dtenedor commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4593852722


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,463 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import java.util.Locale
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.SqlScriptingContextManager
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util.{toPrettySQL, MetadataColumnHelper}
+import org.apache.spark.sql.connector.catalog.CatalogManager
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{DataType, NullType, StringType}
+
+/**
+ * Optional references: a `?` after an identifier of a column, field, or 
variable reference, or
+ * after a named parameter marker, makes that identifier optional. When name 
resolution finds no
+ * match for an optional identifier, the reference resolves to a static NULL 
of type VOID instead
+ * of raising a not-found error. Ambiguity and type errors are still raised.
+ *
+ * {{{
+ *   -- `t` has a column `id` but no column `name`:
+ *   SELECT id?, name? FROM t;
+ *   -- Project [id#1, null AS name#2]
+ * }}}
+ */
+object OptionalReferences {
+
+  /**
+   * Indices of the name parts of an unresolved multipart name (an 
`UnresolvedAttribute` or an
+   * `UnresolvedNamedLambdaVariable`) that are followed by `?`.
+   */
+  val OPTIONAL_NAME_PART_INDICES: TreeNodeTag[Set[Int]] =
+    TreeNodeTag[Set[Int]]("optionalNamePartIndices")
+
+  /**
+   * Marks an [[UnresolvedExtractValue]] field, a named parameter marker, or 
an IDENTIFIER clause
+   * followed by `?`.
+   */
+  val OPTIONAL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReference")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   *
+   * The two tags that the parser sets, [[OPTIONAL_NAME_PART_INDICES]] and 
[[OPTIONAL_REFERENCE]],
+   * describe the statement: they are facts about the reference as written, 
which stay true in
+   * every analysis of the plan. The generic transforms of a tree copy them to 
the nodes that
+   * replace a tagged node. A rule that rebuilds a reference in another way 
forwards them itself:
+   * the optional name parts of a multipart name with 
[[withOptionalNamePartsOf]], and the marker
+   * of a field extraction, a named parameter marker, or an IDENTIFIER clause 
with `copyTagsFrom`.
+   * This tag records a decision of one analysis, that a reference matched 
nothing, on the NULL
+   * and the alias that this analysis creates. Only the analyzer sets it, and 
only on these nodes:
+   * the plan that the analyzer receives can be analyzed again later, e.g. 
from a plan cache,
+   * against a relation that has the column by then. The other decision of an 
analysis, that no
+   * resolution step of an operator can resolve a field extraction, is a node 
of the plan that the
+   * analysis builds, see [[LastResortExtractValue]].
+   */
+  val NULL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReferenceNull")
+
+  /** Qualifiers of session variables, which are valid prefixes of a variable 
reference. */
+  private val SESSION_VARIABLE_QUALIFIERS = Seq(
+    Seq(CatalogManager.SYSTEM_CATALOG_NAME, CatalogManager.SESSION_NAMESPACE),
+    Seq(CatalogManager.SESSION_NAMESPACE)
+  )
+
+  /** Returns the indices of the optional name parts of `expression`. */
+  def optionalNamePartIndices(expression: Expression): Set[Int] =
+    expression.getTagValue(OPTIONAL_NAME_PART_INDICES).getOrElse(Set.empty)
+
+  /** Marks the name parts at `indices` of the multipart name `expression` as 
optional. */
+  def markNamePartsOptional(expression: Expression, indices: Set[Int]): Unit = 
{
+    if (indices.nonEmpty) {
+      expression.setTagValue(
+        OPTIONAL_NAME_PART_INDICES,
+        optionalNamePartIndices(expression) ++ indices
+      )
+    }
+  }
+
+  /** Marks `expression` as a whole as optional. */
+  def markOptional(expression: Expression): Unit =
+    expression.setTagValue(OPTIONAL_REFERENCE, ())
+
+  /** Returns true if `expression` as a whole is marked optional. */
+  def isOptional(expression: Expression): Boolean =
+    expression.getTagValue(OPTIONAL_REFERENCE).isDefined
+
+  /** Returns true if `expression` or any of its name parts is marked 
optional. */
+  def hasOptionalMarker(expression: Expression): Boolean =
+    isOptional(expression) || optionalNamePartIndices(expression).nonEmpty
+
+  /**
+   * Gives `expression`, a multipart name that a rule rebuilt from `source`, 
the optional name
+   * parts of `source`, which a case class copy or a constructor does not keep.
+   */
+  def withOptionalNamePartsOf[T <: Expression](expression: T, source: 
Expression): T = {
+    markNamePartsOptional(expression, optionalNamePartIndices(source))
+    expression
+  }
+
+  /**
+   * Returns the first unresolved expression in `expression` that is an 
optional reference or has
+   * an optional name part, including in the plans of its subquery 
expressions, or None.
+   */
+  def unresolvedOptionalReference(expression: Expression): Option[Expression] 
= {
+    expression.find(e => !e.resolved && hasOptionalMarker(e)).orElse {
+      expression
+        .collect { case subquery: SubqueryExpression => subquery.plan }
+        .iterator
+        .flatMap(plan => unresolvedOptionalReference(plan))
+        .nextOption()
+    }
+  }
+
+  /**
+   * Returns true if the parsed `plan` has an optional reference, including in 
the plans of its
+   * subquery expressions and in its common table expressions. Before the 
analysis, every optional
+   * reference of the statement is unresolved, so the answer does not depend 
on the data that the
+   * statement is analyzed against.
+   */
+  def hasOptionalReferences(plan: LogicalPlan): Boolean =

Review Comment:
   Done: `OptionalReferences.unresolvedOptionalReference(plan)` now also 
searches:
   - the plan of a `SupervisingCommand`, the catalyst trait of `ExplainCommand` 
and `DescribeQueryCommand`, read through `withTransformedSupervisedPlan` 
because the trait has no getter;
   - the window specifications of `WithWindowDefinition`.
   
   In the legacy-binding test of `ParametersSuite`, given two values, `DESCRIBE 
QUERY` of the statement and a statement whose only `?` is in `WINDOW w AS 
(PARTITION BY region?)` fail with UNUSED_SQL_PARAMETER_VALUES. EXPLAIN reports 
the errors of the plan it explains, so its output now contains 
UNUSED_SQL_PARAMETER_VALUES. The same three forms without optional references 
still ignore the extra value. I checked locally that removing the new cases 
fails the test, and that it also fails with only the WINDOW case removed.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/Command.scala:
##########
@@ -69,6 +69,13 @@ trait AnalysisOnlyCommand extends Command {
   def markAsAnalyzed(analysisContext: AnalysisContext): LogicalPlan
 }
 
+/**
+ * A command that defines a view: it stores the text of a query, which is 
analyzed again whenever
+ * the view is read. CREATE VIEW, ALTER VIEW ... AS, and CACHE TABLE ... AS 
SELECT define views.
+ * See `AnalysisContext.isViewDefinition`.
+ */
+trait DefinesView extends Command

Review Comment:
   Done. `AnalysisContext.definesView` now also covers a 
`MetricViewPlaceholder` with `isCreate`, the placeholder that CREATE VIEW ... 
WITH METRICS analyzes, in the session catalog and in a v2 view catalog alike 
(both go through `MetricViewHelper.analyzeMetricViewText`). 
`executeAndCheckReferredTempVariablesUnderIdentifier`, which metric-view 
creation uses, now goes through the same `executeSameContextAsDefinition` 
helper as `execute`. The docs of `isViewDefinition` and `DefinesView` mention 
metric views.
   
   A new test in `OptionalReferencesSuite` checks both sides:
   - Inside `BEGIN lbl: BEGIN ... END; END`, creating a metric view whose 
dimension is `lbl.missing?` fails with UNRESOLVED_COLUMN for `lbl`.`missing`, 
and the view is not created.
   - A metric view whose dimension is `missing?`, over a source without that 
column, is created and reads NULL for it.
   
   Metric-view creation runs the fixed-point analyzer except when the 
single-pass resolver is forced on, which does not support the placeholder (the 
existing forced single-pass test). So the dual-run and tentative modes take 
this path too. With the placeholder case removed locally, the test fails.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala:
##########
@@ -771,6 +791,57 @@ class NameScope(
     }
   }
 
+  /**
+   * Resolves the optional name `multipartName` that 
[[tryResolveMultipartNameByOutput]] could not
+   * resolve, if it matches columns of the output and none of them has the 
nested fields of the
+   * name. This mirrors the fixed-point analyzer, for which the error of the 
same name without `?`
+   * is final in that case, except in ORDER BY: the result is NULL if the 
field that the only

Review Comment:
   Done: the doc now describes the result outside of ORDER BY, and says 
separately that the method returns None in ORDER BY, which falls back from the 
SELECT list to the columns of the FROM clause.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8550,6 +8561,34 @@ object SQLConf {
       .booleanConf
       .createWithDefault(true)
 
+  val OPTIONAL_REFERENCES_ENABLED =
+    buildConf("spark.sql.optionalReferences.enabled")
+      .internal()
+      .doc("When true, a `?` after an identifier of a column, field, or 
variable reference, or " +
+        "after a named parameter marker, makes that identifier optional: when 
no name matches " +
+        "the identifier, the reference evaluates to a NULL of type VOID 
instead of raising a " +
+        "not-found error. Ambiguous references and type errors are still 
raised. UPDATE, " +
+        "DELETE, MERGE, the REPLACE condition of INSERT, AUTO CDC flows, 
partition " +
+        "specifications, and the DEFAULT, GENERATED ALWAYS AS, CHECK, and 
OPTIONS clauses of " +
+        "table and function definitions reject optional references.")
+      .version("4.4.0")
+      .withBindingPolicy(ConfigBindingPolicy.SESSION)

Review Comment:
   Done. `SessionCatalog.makeSQLFunctionPlan` still parses a scalar function 
body with its captured configs, except for 
`spark.sql.optionalReferences.enabled`: an explicit value from the caller now 
replaces the captured one. The override uses the same gate as views and SQL 
table functions, `spark.sql.analyzer.sqlFunctionResolution.applyConfOverrides`. 
I did not switch scalar bodies to `applySessionOverrides = true`, which would 
change how they parse under every other SESSION-bound config.
   
   The golden file's disabled block now calls `captured_fn()` and 
`captured_table_fn()`, both created while optional references were enabled. 
With the conf explicitly false, both fail with PARSE_SYNTAX_ERROR inside the 
function, and after RESET both return 10. Without the override, `captured_fn()` 
returns 10 in the disabled block.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to