spark-test commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4592554975


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Expression, 
SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  DeleteFromTable,
+  LogicalPlan,
+  MergeIntoTable,
+  OverwriteByExpression,
+  UpdateTable,
+  View
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
+import org.apache.spark.sql.errors.QueryCompilationErrors
+
+/**
+ * Rejects optional references in the expressions of a statement that modifies 
table data and
+ * that was built without the SQL parser, which rejects them in SQL text (see
+ * `OptionalReferenceValidation`). A missing column must not silently change 
which rows a
+ * statement deletes or updates.
+ *
+ * The source of a MERGE is checked too, like the source query of the SQL 
statement.
+ * `Dataset.mergeInto` and the Spark Connect MERGE command put the plan of the 
source DataFrame
+ * there, in which only the last operation is sure to be unanalyzed: a Dataset 
operation builds on
+ * the analyzed plan of the one before, and Spark Connect analyzes some 
relations, such as
+ * `withColumns`, when it plans them. In an analyzed operation, an optional 
reference that matched
+ * nothing is the NULL that it resolved to, which is rejected as well.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ *   spark.table("s").selectExpr("pk", "archived? AS 
archived").as("s").mergeInto("t", ...)
+ * }}}
+ */
+object CheckOptionalReferencesInDml extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (plan.containsPattern(COMMAND)) {
+      plan.foreach { operator =>
+        statementName(operator).foreach { statement =>
+          operator.expressions.foreach(checkExpression(_, statement))
+        }
+        operator match {
+          case merge: MergeIntoTable =>
+            OptionalReferences
+              .unresolvedOptionalReference(merge.sourceTable)
+              .orElse(firstNullReference(merge.sourceTable))
+              .foreach { reference =>
+                throw 
QueryCompilationErrors.optionalReferenceInDmlNotSupportedError(
+                  "MERGE",
+                  reference.origin
+                )
+              }
+          case _ =>
+        }
+      }
+    }
+    plan
+  }
+
+  private def statementName(operator: LogicalPlan): Option[String] = operator 
match {
+    case _: DeleteFromTable => Some("DELETE")
+    case _: UpdateTable => Some("UPDATE")
+    case _: MergeIntoTable => Some("MERGE")
+    // The plan of INSERT ... REPLACE WHERE and of 
`DataFrameWriterV2.overwrite(condition)`.
+    case _: OverwriteByExpression => Some("INSERT ... REPLACE")
+    case _ => None
+  }
+
+  /**
+   * Returns the first NULL that an optional reference of `plan` resolved to 
in an analysis of an
+   * operation of `plan`, see [[OptionalReferences.isNullReference]], or None. 
Views and SQL
+   * functions resolve their own optional references, so the search does not 
enter a view, a SQL
+   * table function, or the body of a SQL scalar function.
+   */
+  private def firstNullReference(plan: LogicalPlan): Option[Expression] = plan 
match {

Review Comment:
   **Blocking (P1):** This search finds an optional reference of an analyzed 
source operation only through the NULL_REFERENCE tag, but the rest of the 
analysis of that operation often replaces the tagged NULL with an untagged node 
or hides it. By the review's reading of the code:
   
   - In `attrs?['active']`, `tags?[0]`, or `items?[0].sku`, the Resolution 
batch that ResolveOptionalReferences runs again replaces the extraction with a 
fresh `Literal(null, NullType)` from `ExtractValue.applyOrNull` under a plain 
Alias (ColumnResolutionHelper.scala:244-257, complexTypeExtractors.scala:63-72).
   - In `IF(is_active?, 'keep', 'drop')`, IfTypeCoercion replaces the NULL 
condition with `Literal.create(null, BooleanType)` 
(TypeCoercionHelper.scala:723-724).
   - In `SELECT * FROM VALUES (1, flag?) AS t(pk, archived)` with no variable 
`flag`, ResolveInlineTables evaluates the row into the constants of a 
LocalRelation, so no expression is left.
   - In `tvf(s.missing?)` for a SQL table function, the NULL is in the 
projection of the caller's arguments under SQLFunctionNode, which line 93 does 
not enter.
   
   So with spark.sql.optionalReferences.enabled on and a table `source(pk INT)` 
without `attrs`, `spark.table("source").selectExpr("pk", "attrs?['active'] AS 
active").as("s").mergeInto("t", $"s.pk" === 
col("t.pk")).whenMatched(expr("s.active IS NULL")).delete().merge()` passes 
this check, and the MERGE deletes every matched row of `t` instead of failing 
with OPTIONAL_REFERENCE_NOT_SUPPORTED.IN_DML, as the same source query does in 
a SQL MERGE statement. This affects DataFrame and Spark Connect MERGE sources; 
the MERGE tests use only shapes that keep the tagged NULL, such as `archived? 
AS archived`.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4580318547).
   
   **Recommended change:** Record on the analyzed plan, not only on the NULL 
node, that an analysis resolved one of the plan's own optional references to 
NULL, and make the MERGE source check of CheckOptionalReferencesInDml reject a 
source that carries the record outside views and SQL function bodies, raising 
IN_DML at the position of the reference; update the class doc, and add 
DataFrame MERGE tests and a Spark Connect MERGE test for an extraction from a 
missing optional reference, for one used as an IF condition, for one in an 
inline VALUES row, and for one passed to a SQL table function.
   
   **Why this works:** OptionalReferences.nullReference, the single constructor 
both analyzers use, records the origin of the first such NULL in the analysis 
context, as the context already collects the temporary variables an analysis 
refers to, unless the NULL belongs to the body of a view or SQL function. When 
the analysis returns, the analyzer sets a plan tag with that origin on the root 
of the plan it returns, as Dataset sets its dataset-id tag on its analyzed 
plan; that root is a node the analysis created, because replacing a reference 
rebuilt it. The record no longer depends on the NULL node surviving the rest of 
the analysis. Dataset and Spark Connect composition wrap analyzed plans 
unchanged, so the tagged root reaches the MERGE, where the source search treats 
a tagged node like a tagged NULL, and a SQL table function's arguments count 
because their NULL was created by the caller's own analysis.
   
   **Scope:** The analyzer records, per analysis and on the plan it returns, 
that it resolved one of the plan's own optional references to NULL, and the 
MERGE source check reads that record, with tests for the shapes that now escape 
the check.
   
   **Compatibility:** MERGE sources that read views and SQL functions whose 
bodies use `?` keep merging, and every source that the check rejects today 
keeps failing with the same error at the same fragment.
   
   **Risks:** A DataFrame or Spark Connect MERGE whose source resolved an 
optional reference to NULL in any analyzed operation now fails with IN_DML, 
including shapes that run today; the behavior is unreleased and behind an 
internal conf, and removing the record rolls the change back. If a NULL of a 
view or SQL function body were recorded for the caller's plan, a source that 
reads such a view or function would start failing; the view and function cases 
of the tests guard it.
   
   **Constraints:** Record only NULLs that belong to the analyzed plan itself, 
in both analyzers: the NULLs of view and SQL function bodies must not mark the 
plan of a source that reads them. Set the tag only on a node the analysis 
created, never on the plan the analyzer receives, so that re-analysis of a 
cached unresolved plan is unaffected. Keep the expression-level NULL_REFERENCE 
tag and its implicit-alias handling unchanged, and keep the existing 
unresolved-marker search of the source.
   
   **Exclusions:**
   - An unbound `:name?` in the SQL text of a source DataFrame, which becomes 
the text NULL before parsing and is the declared deferral that a separate 
comment documents.
   - A source materialized before the MERGE, such as a checkpoint, whose plan 
keeps no analysis of the operations that produced its rows.
   
   **Success:** With optional references on, a DataFrame or Spark Connect MERGE 
whose source resolved an optional reference to NULL in an analyzed operation, 
including an extraction from it, an IF over it, a value of an inline VALUES 
row, or a SQL table function argument, fails with 
OPTIONAL_REFERENCE_NOT_SUPPORTED.IN_DML at the reference and leaves the target 
unchanged. MERGE sources that only read views or SQL functions whose bodies use 
`?` still merge.
   
   **Verification:**
   - **Regression:** With optional references on and a source table without the 
column, a DataFrame MERGE whose source applies `.as` after a selectExpr that 
extracts a field, a subscript, or a map key from a missing optional reference 
fails with IN_DML, with the MERGE context and the fragment of the reference, 
and the target keeps its rows.
   - **Regression:** The same holds for a source whose missing optional 
reference is the condition of IF and for a source that passes a missing 
optional reference to a SQL table function in a LATERAL join.
   - **Regression:** The same holds for a source built from `SELECT * FROM 
VALUES (1, flag?) AS t(pk, archived)` followed by `.as`, with no variable 
`flag`, whose row the analysis turns into constants.
   - **Regression:** With optional references on in a Spark Connect session, a 
MERGE whose source extracts a field from a missing optional reference in a 
withColumn step fails with IN_DML and the target keeps its row.
   - **Compatibility:** DataFrame MERGE sources that read a view, a SQL scalar 
function, or a SQL table function whose body uses `?`, without an optional 
reference of their own, still merge, also when aliased; a source built while 
optional references were on still fails a MERGE that runs after the conf is 
turned off; and the existing MERGE source cases still fail with IN_DML at the 
fragment of the reference.



##########
sql/core/src/test/resources/sql-tests/inputs/optional-references.sql:
##########
@@ -0,0 +1,575 @@
+-- Tests for optional column, field, variable, and named parameter references: 
a `?` after an
+-- identifier makes that identifier optional, so that a reference that cannot 
be resolved
+-- evaluates to a static NULL of type VOID instead of raising a not-found 
error.
+
+--SET spark.sql.optionalReferences.enabled=true
+
+CREATE TEMPORARY VIEW people AS SELECT * FROM VALUES
+  (1, named_struct('city', 'SF', 'zip', '94105')),
+  (2, named_struct('city', 'NYC', 'zip', '10001'))
+  AS t(id, addr);
+
+CREATE TEMPORARY VIEW orgs AS SELECT * FROM VALUES
+  (1, named_struct('addr', named_struct('city', 'SF', 'zip', '94105')))
+  AS t(id, info);
+
+CREATE TEMPORARY VIEW orders AS SELECT * FROM VALUES
+  (1, array(named_struct('sku', 'a', 'qty', 5))),
+  (2, array(named_struct('sku', 'b', 'qty', 9)))
+  AS t(id, items);
+
+-- A missing column resolves to NULL and an existing column resolves normally. 
Either way, the

Review Comment:
   **Nit (P3):** This comment and two others in this file say more than the 
results recorded under them, so a reader who takes them as the contract is 
misled:
   
   - Lines 21-22 say that the output column keeps the name of the reference, 
but the query at line 24 names `typeof(name?)` for the missing column 
`typeof(NULL)` (line 46 of the results file). Only a top-level reference keeps 
its name, as lines 471-472 say.
   - Line 119 says that errors other than not-found are still raised, but `... 
JOIN (SELECT 2 AS x) b ORDER BY x?` at line 124 fails with UNRESOLVED_COLUMN, 
the same not-found error as without `?`.
   - Lines 559-561 say that `?` is a syntax error while optional references are 
disabled, including in a view that was created while they were enabled. That 
holds only while the session sets the conf to false: after RESET at line 573 
the conf is off by default and people_v is still read at line 575, as lines 
571-572 say.
   
   **Verification:**
   - **Inspection:** The comments above the naming queries, the errors that are 
still raised, and the disabled block match their recorded results: only a 
top-level reference keeps its name, the ORDER BY case raises the error of the 
statement without `?`, and a view fails only when the conf is set to false.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,376 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{
+  Attribute,
+  Expression,
+  LambdaFunction,
+  LateralColumnAliasReference,
+  NamedExpression,
+  PipeOperator,
+  SubqueryExpression,
+  UnaryExpression,
+  Unevaluable
+}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  Aggregate,
+  Distinct,
+  Filter,
+  LateralJoin,
+  LogicalPlan,
+  RepartitionByExpression,
+  Sort,
+  SubqueryAlias,
+  UnaryNode
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.CurrentOrigin
+import org.apache.spark.sql.catalyst.trees.TreePattern.{PARAMETERIZED_QUERY, 
PLAN_EXPRESSION}
+import org.apache.spark.sql.types.DataType
+
+/**
+ * Replaces the optional references that the fixed-point "Resolution" batch 
could not resolve
+ * with a static NULL, and then resolves the plan again with `resolveAgain`.
+ *
+ * {{{
+ *   -- `t` has no column `name`:
+ *   SELECT id, name? FROM t;
+ *   -- Project [id#1, 'name] becomes Project [id#1, null AS name#2]
+ * }}}
+ *
+ * Only the expressions of operators with resolved children are replaced, 
because a reference in
+ * an operator with unresolved children can still resolve once the children 
are resolved. The
+ * rule is meant to run in a fixed-point batch: every application replaces the 
references of the
+ * lowest operators that cannot be resolved, which can make the operators 
above them resolvable.
+ * References that a later resolution step is still waiting for, such as the 
body of an unbound
+ * lambda function or a lateral column alias reference, are left in place.
+ *
+ * The analyzer resolves the plan of a subquery expression on its own, while 
the operator of the
+ * subquery expression is still being resolved. A reference of the subquery 
that is unresolved at
+ * the end of that can still resolve later, e.g. once the outer query binds 
its parameter markers
+ * or resolves the alias of a generator. The rule therefore only replaces the 
references of a
+ * subquery plan after it could not resolve the operator of the subquery 
expression, which it
+ * signals by wrapping the subquery plan in 
[[ResolveOptionalReferencesInSubquery]].
+ *
+ * The rule never changes the plan that it is given, which can be analyzed 
again later, e.g. from a
+ * plan cache: its decisions are nodes of the plan that it returns.
+ */
+class ResolveOptionalReferences(resolveAgain: LogicalPlan => LogicalPlan)
+    extends Rule[LogicalPlan] {
+  import ResolveOptionalReferences._
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan match {
+    case subquery: ResolveOptionalReferencesInSubquery =>
+      val resolvedPlan = replaceAndResolveAgain(subquery.child)
+      if (resolvedPlan.fastEquals(subquery.child)) subquery.child else 
subquery.copy(resolvedPlan)
+    case _ if plan.resolved || isPlanOfSubquery || 
plan.containsPattern(PARAMETERIZED_QUERY) =>
+      plan
+    case _ if hasUnresolvedOptionalReferences(plan) =>
+      replaceAndResolveAgain(plan)
+    case _ =>
+      plan
+  }
+
+  private def replaceAndResolveAgain(plan: LogicalPlan): LogicalPlan = {
+    val replacedPlan = replaceUnresolvableOptionalReferences(plan)
+    val resolvedPlan = if (replacedPlan.fastEquals(plan)) {
+      plan
+    } else {
+      unwrapSubqueryPlans(resolveAgain(replacedPlan))
+    }
+    if (!resolvedPlan.fastEquals(plan)) {
+      resolvedPlan
+    } else {
+      val wrappedPlan = wrapOptionalFieldsAsLastResort(plan)
+      if (wrappedPlan.fastEquals(plan)) {
+        plan
+      } else {
+        unwrapLastResortExtractValues(resolveAgain(wrappedPlan))
+      }
+    }
+  }
+
+  /**
+   * Replaces the optional references of the lowest operators of `plan` that 
are not resolved, and
+   * wraps the unresolved plans of their subquery expressions for the analysis 
of these plans.
+   *
+   * The traversal is top-down so that an operator is only considered while 
its children are the
+   * ones that the "Resolution" batch resolved its references against. An 
operator above a
+   * replaced one waits for `resolveAgain`, which can still resolve its 
references in other ways,
+   * for example as lateral column aliases or as variables.
+   */
+  private def replaceUnresolvableOptionalReferences(plan: LogicalPlan): 
LogicalPlan = {
+    plan.resolveOperatorsDown {
+      case aggregate: Aggregate
+          if aggregate.childrenResolved && 
!aggregate.aggregateExpressions.forall(_.resolved) =>
+        replaceInAggregateExpressions(aggregate)
+      case lateralJoin: LateralJoin
+          if lateralJoin.left.resolved && !lateralJoin.right.plan.resolved =>
+        // The join condition can reference the output of the subquery, which 
is not known yet.
+        if (hasUnresolvedOptionalReferences(lateralJoin.right.plan)) {
+          lateralJoin.copy(right = wrapSubqueryPlan(lateralJoin.right))
+        } else {
+          lateralJoin
+        }
+      case operator if operator.childrenResolved && !operator.resolved =>
+        lazy val attributes = visibleAttributes(operator)
+        operator.mapExpressions(replace(_, attributes, isTopLevel = true))
+    }
+  }
+
+  /**
+   * Replaces the optional references in the aggregate expressions of 
`aggregate` only, because
+   * its grouping expressions can reference aliases of the aggregate 
expressions, which can only
+   * be resolved once all the aggregate expressions are resolved.
+   *
+   * {{{
+   *   -- `archived` in GROUP BY resolves to the alias `archived` of the 
SELECT list.
+   *   SELECT coalesce(archived?, false) AS archived FROM t GROUP BY archived?;
+   * }}}
+   */
+  private def replaceInAggregateExpressions(aggregate: Aggregate): Aggregate = 
{
+    lazy val attributes = visibleAttributes(aggregate)
+    aggregate.copy(aggregateExpressions = aggregate.aggregateExpressions.map { 
expression =>
+      replace(expression, attributes, isTopLevel = 
true).asInstanceOf[NamedExpression]
+    })
+  }
+
+  /**
+   * Replaces the optional references of `expression` that resolve to NULL 
against `attributes`.
+   * A top-level reference keeps its name through an [[Alias]] of its last 
name part.
+   */
+  private def replace(
+      expression: Expression,
+      attributes: => Seq[Attribute],
+      isTopLevel: Boolean): Expression = expression match {
+    case unresolvedAttribute: UnresolvedAttribute
+        if 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute).nonEmpty &&
+        OptionalReferences.resolvesToNull(
+          nameParts = unresolvedAttribute.nameParts,
+          optionalNamePartIndices = 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute),
+          attributes = attributes,
+          resolver = conf.resolver,
+          isViewQuery = AnalysisContext.get.catalogAndNamespace.nonEmpty ||
+            AnalysisContext.get.isViewDefinition
+        ) =>
+      // The NULL keeps the position of the reference, e.g. for 
`CheckOptionalReferencesInDml`.
+      CurrentOrigin.withOrigin(unresolvedAttribute.origin) {
+        val nullReference = OptionalReferences.nullReference()
+        if (isTopLevel) {
+          OptionalReferences.implicitAlias(nullReference, 
unresolvedAttribute.nameParts.last)
+        } else {
+          nullReference
+        }
+      }
+    case namedParameter: NamedParameter if 
OptionalReferences.isOptional(namedParameter) =>
+      
CurrentOrigin.withOrigin(namedParameter.origin)(OptionalReferences.nullReference())
+    case lambdaFunction: LambdaFunction if !lambdaFunction.bound =>
+      lambdaFunction
+    case lateralColumnAliasReference: LateralColumnAliasReference =>
+      lateralColumnAliasReference
+    case subquery: SubqueryExpression if 
hasUnresolvedOptionalReferences(subquery.plan) =>
+      wrapSubqueryPlan(subquery)
+    case other if !other.resolved =>
+      other.mapChildren(replace(_, attributes, isTopLevel = false))
+    case other =>
+      other
+  }
+
+  private def wrapSubqueryPlan[T <: SubqueryExpression](subquery: T): T = 
subquery.plan match {
+    case _: ResolveOptionalReferencesInSubquery => subquery
+    case plan => 
subquery.withNewPlan(ResolveOptionalReferencesInSubquery(plan)).asInstanceOf[T]
+  }
+
+  /**
+   * Unwraps the subquery plans of `plan` that are still wrapped because the 
analyzer did not
+   * resolve them again.
+   */
+  private def unwrapSubqueryPlans(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
+      case subquery: SubqueryExpression =>
+        subquery.plan match {
+          case wrapped: ResolveOptionalReferencesInSubquery => 
subquery.withNewPlan(wrapped.child)
+          case _ => subquery
+        }
+    }
+  }
+
+  /**
+   * Wraps the optional field extractions of the lowest operators of `plan` 
that are not resolved
+   * in [[LastResortExtractValue]].
+   */
+  private def wrapOptionalFieldsAsLastResort(plan: LogicalPlan): LogicalPlan = 
{
+    plan.resolveOperatorsDown {
+      case operator if operator.childrenResolved && !operator.resolved =>
+        operator.mapExpressions(wrapOptionalFields)
+    }
+  }
+
+  private def wrapOptionalFields(expression: Expression): Expression = 
expression match {
+    case lastResort: LastResortExtractValue =>
+      lastResort
+    case extractValue: UnresolvedExtractValue if 
OptionalReferences.isOptional(extractValue) =>
+      // The children are wrapped first, so the wrapped extraction is still an 
extraction.
+      LastResortExtractValue(
+        
extractValue.mapChildren(wrapOptionalFields).asInstanceOf[UnresolvedExtractValue])
+    case other if !other.resolved =>
+      other.mapChildren(wrapOptionalFields)
+    case other =>
+      other
+  }
+
+  /** Unwraps the extractions of `plan` that the analyzer did not resolve. */
+  private def unwrapLastResortExtractValues(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveExpressions {
+      case LastResortExtractValue(extractValue) => extractValue
+    }
+  }
+
+  /**
+   * Returns the attributes that the name resolution of `operator` can match a 
multipart name
+   * against: the output of its children, the attributes that `Sort`, 
`Filter`, HAVING, and
+   * QUALIFY can reference from below their child, the output of the subquery 
of a lateral join,
+   * and the attributes of the outer query of a subquery.
+   */
+  private def visibleAttributes(operator: LogicalPlan): Seq[Attribute] = {
+    val localAttributes = operator.children.flatMap(namedAttributes)
+    val attributesFromBelow = operator match {
+      case sort: Sort => attributesForMissingReferences(sort.child)
+      case filter: Filter => attributesForMissingReferences(filter.child)

Review Comment:
   **Nit (P3):** No test reaches this case with a column that exists below the 
child of the Filter but that the filter cannot use: a SQL WHERE sits below the 
SELECT list, the search for the `|> WHERE` case stops at the PipeOperator, and 
DataFrameSuite filters only on the base relation. The DataFrame API reaches it, 
as in `df.groupBy("k").count().select("k").filter("v? > 0")` where `v` is a 
column of `df`. By the review's reading of the code, deleting this line makes 
that filter test NULL and return no rows instead of failing with 
UNRESOLVED_COLUMN, and every suite still passes. The Sort case on the line 
above has such a test, `ORDER BY x?` at line 124 of optional-references.sql.
   
   **Verification:**
   - **Regression:** A DataFrame filter on an optional reference to a column 
below an aggregate that the filter cannot use fails with UNRESOLVED_COLUMN, 
like the same filter without `?`, and the test fails if the Filter case of the 
attributes from below is removed.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Expression, 
SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  DeleteFromTable,
+  LogicalPlan,
+  MergeIntoTable,
+  OverwriteByExpression,
+  UpdateTable,
+  View
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
+import org.apache.spark.sql.errors.QueryCompilationErrors
+
+/**
+ * Rejects optional references in the expressions of a statement that modifies 
table data and
+ * that was built without the SQL parser, which rejects them in SQL text (see
+ * `OptionalReferenceValidation`). A missing column must not silently change 
which rows a
+ * statement deletes or updates.
+ *
+ * The source of a MERGE is checked too, like the source query of the SQL 
statement.
+ * `Dataset.mergeInto` and the Spark Connect MERGE command put the plan of the 
source DataFrame
+ * there, in which only the last operation is sure to be unanalyzed: a Dataset 
operation builds on
+ * the analyzed plan of the one before, and Spark Connect analyzes some 
relations, such as
+ * `withColumns`, when it plans them. In an analyzed operation, an optional 
reference that matched
+ * nothing is the NULL that it resolved to, which is rejected as well.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ *   spark.table("s").selectExpr("pk", "archived? AS 
archived").as("s").mergeInto("t", ...)
+ * }}}
+ */
+object CheckOptionalReferencesInDml extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (plan.containsPattern(COMMAND)) {
+      plan.foreach { operator =>
+        statementName(operator).foreach { statement =>
+          operator.expressions.foreach(checkExpression(_, statement))
+        }
+        operator match {
+          case merge: MergeIntoTable =>

Review Comment:
   **Nit (P3):** This check does not catch an unbound `:name?` in the SQL text 
of a source DataFrame, and nothing here says so. In the default parameter mode, 
`SubstituteParamsParser` replaces it with the text NULL before the text is 
parsed (SubstituteParamsParser.scala:169-173), so `spark.sql("SELECT pk, :flag? 
AS archived FROM source")` is parsed as `SELECT pk, NULL AS archived FROM 
source`. By the review's reading of the code, a DataFrame or Spark Connect 
MERGE built from it with `whenMatched(expr("archived IS NULL")).delete()` is 
not rejected and deletes every matched row, while a SQL MERGE statement with 
the same source query fails with OPTIONAL_REFERENCE_NOT_SUPPORTED.IN_DML. The 
latest reply in the MERGE source thread defers this case, but the code does not 
record it: the class doc reads as if every optional reference of a MERGE source 
were rejected, and neither this check nor the substitution mentions the gap.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4580318547).
   
   See **Shared repair plan 1** in the review body.



##########
sql/core/src/test/scala/org/apache/spark/sql/OptionalReferencesSuite.scala:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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
+
+import org.apache.spark.sql.catalyst.expressions.Literal
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.Sort
+import org.apache.spark.sql.classic.Dataset
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+
+/**
+ * Tests of optional references (`x?`) that need more than one analysis of a 
plan. The golden file

Review Comment:
   **Nit (P3):** Only the first test of this suite analyzes a plan more than 
once. 'a HAVING column that is not grouped keeps its optional name parts' (line 
64) analyzes each statement once and is here to run the fixed-point analyzer 
alone, because the single-pass resolver does not resolve that shape, and 
'optional references are not supported in the parameters of a SQL function' 
(line 80) only checks that `CREATE TEMPORARY FUNCTION f(x INT DEFAULT a?) ...` 
raises a ParseException whose context is relative to the separately parsed 
parameter list, without analyzing a plan. A maintainer who follows this doc 
would move or misplace such tests.
   
   **Verification:**
   - **Inspection:** Every test kept in OptionalReferencesSuite matches the 
reason its class doc gives.



##########
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:
   **Nit (P3):** In the legacy binding mode, this search decides from the 
parsed plan whether extra positional values are an error 
(SparkSession.scala:555-559 and 705-707), but it does not see three places that 
can hold optional references. `ExplainCommand` (commands.scala:160-163) and 
`DescribeQueryCommand` (tables.scala:805-806) are leaf commands that keep their 
plan in a plain field, neither a child nor an inner child, and 
`WithWindowDefinition` keeps its specs in a `Map[String, 
WindowSpecDefinition]`, whose pairs `QueryPlan.expressions` does not collect. 
`MoveParameterizedQueriesDown` then moves the parameterized query into the 
explained or described plan with the flag unchanged (parameters.scala:155-174). 
By the review's reading of the code, with spark.sql.optionalReferences.enabled 
and spark.sql.legacy.parameterSubstitution.constantsOnly on, `spark.sql("SELECT 
missing?, first(DISTINCT ?) AS f, ? AS g FROM people", Array(5, 6))` fails with 
UNUSED_SQL_PARAMETER_VALUES, but with E
 XPLAIN in front it explains a plan in which `g` is bound to 5, the value meant 
for the `?` that became a reference, and with DESCRIBE QUERY in front it 
describes the schema of that binding. A statement whose only optional reference 
is in a named WINDOW clause likewise ignores extra positional values. The 
effect is limited to diagnostic output and to that combination of an internal 
and a legacy conf.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4576517549).
   
   **Verification:**
   - **Regression:** With optional references and legacy parameter binding on, 
EXPLAIN and DESCRIBE QUERY of `SELECT missing?, first(DISTINCT ?) AS f, ? AS g 
FROM people`, each given two positional values, fail with 
UNUSED_SQL_PARAMETER_VALUES, like the statement without them.
   - **Regression:** In the legacy binding mode, a statement whose only 
optional reference is in a named WINDOW clause and that is given more 
positional values than markers fails with UNUSED_SQL_PARAMETER_VALUES.
   - **Compatibility:** Statements without optional references, with or without 
EXPLAIN, DESCRIBE QUERY, and named WINDOW clauses, keep ignoring extra 
positional values in the legacy binding mode.



##########
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:
   **Nit (P3):** The colon after 'except in ORDER BY' makes the rest of the 
sentence, 'the result is NULL if the field that the only matching column does 
not have is optional, and all the matching columns, for the ambiguity error, if 
there are several', read as what the method returns in ORDER BY. Line 810 
returns None when `parameters.resolvingSortOrder` is set, so in ORDER BY the 
method returns neither.
   
   **Verification:**
   - **Inspection:** The doc of tryResolveMissingOptionalFieldByOutput 
separates the ORDER BY exception from the description of the result.



##########
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 =
+    unresolvedOptionalReference(plan).isDefined
+
+  /**
+   * Returns the first unresolved optional reference of the operators of 
`plan`, including in the
+   * plans of their subquery expressions and in the plans that an operator 
keeps outside of its
+   * children, such as the common table expressions of `UnresolvedWith`, or 
None.
+   */
+  def unresolvedOptionalReference(plan: LogicalPlan): Option[Expression] = {
+    plan.expressions.iterator
+      .flatMap(expression => unresolvedOptionalReference(expression))
+      .nextOption()
+      .orElse {
+        // The subquery plans of the operator are inner children as well, and 
the search of its
+        // expressions has covered them, so that every plan is searched once.
+        val subqueryPlans = plan.expressions.flatMap(_.collect {
+          case subquery: SubqueryExpression => subquery.plan
+        })
+        plan.innerChildren.iterator
+          .collect {
+            case innerPlan: LogicalPlan if !subqueryPlans.exists(_ eq 
innerPlan) => innerPlan
+          }
+          .flatMap(innerPlan => unresolvedOptionalReference(innerPlan))
+          .nextOption()
+      }
+      .orElse {
+        plan.children.iterator.flatMap(child => 
unresolvedOptionalReference(child)).nextOption()
+      }
+  }
+
+  /**
+   * The static NULL that an unresolvable optional reference resolves to: of 
type VOID, or of type
+   * VARIANT for a path extracted from such a NULL (`missing?:a`).
+   */
+  def nullReference(dataType: DataType = NullType): Literal = {
+    val nullReference = Literal(null, dataType)
+    nullReference.setTagValue(NULL_REFERENCE, ())
+    nullReference
+  }
+
+  /**
+   * Returns true if `expression` is a [[nullReference]], i.e. the result of 
an optional reference
+   * that did not resolve to a column, field, or variable, or the 
[[implicitAlias]] that names
+   * one. [[isNullReferenceAlias]] tells the alias apart.
+   */
+  def isNullReference(expression: Expression): Boolean =
+    expression.getTagValue(NULL_REFERENCE).isDefined
+
+  /**
+   * Returns the alias that gives `child`, the result of a top-level 
reference, the name `name` of
+   * the reference, see [[markImplicitAlias]].
+   */
+  def implicitAlias(child: Expression, name: String): Alias =
+    markImplicitAlias(Alias(child, name)())
+
+  /**
+   * Marks `alias`, which gives the result of a top-level reference the name 
of the reference, if
+   * that result is a [[nullReference]]. Such an alias is only there for the 
name of the output
+   * column, which ORDER BY and HAVING can reference. Unlike other aliases of 
a SELECT list,
+   * including `missing? AS m`, it is neither a lateral column alias nor an 
alias that GROUP BY
+   * can reference, so that a reference without `?` is not found, see 
[[isNullReferenceAlias]].
+   *
+   * {{{
+   *   SELECT missing?, missing? IS NULL, missing + 1 FROM t;
+   *   -- NULL, true, and UNRESOLVED_COLUMN for the `missing` without `?`
+   * }}}
+   */
+  def markImplicitAlias(alias: Alias): Alias = {
+    if (isNullReference(alias.child)) {
+      alias.setTagValue(NULL_REFERENCE, ())
+    }
+    alias
+  }
+
+  /** Returns true if `expression` is the [[implicitAlias]] of a 
[[nullReference]]. */
+  def isNullReferenceAlias(expression: Expression): Boolean = expression match 
{
+    case alias: Alias => alias.getTagValue(NULL_REFERENCE).isDefined
+    case _ => false
+  }
+
+  /**
+   * Extracts `nestedFields` from `base` in the same way as the `ExtractValue` 
chain of a multipart
+   * name, where the first nested field is the name part at 
`firstNestedFieldIndex`. A struct field
+   * that does not exist turns the whole chain into [[nullReference]] if its 
name part is optional,
+   * without extracting the remaining fields. Any other extraction error is 
thrown.
+   *
+   * @param voidBaseIsNull Whether the fields of a NULL of type VOID are NULL, 
as they are for a
+   *   column, or an error, as they are for a variable.
+   */
+  def extractNestedFields(
+      base: Expression,
+      nestedFields: Seq[String],
+      firstNestedFieldIndex: Int,
+      optionalNamePartIndices: Set[Int],
+      resolver: Resolver,
+      voidBaseIsNull: Boolean): Expression = {
+    extractNestedFieldsOrError(
+      expression = base,
+      nestedFields = nestedFields,
+      nestedFieldIndex = firstNestedFieldIndex,
+      optionalNamePartIndices = optionalNamePartIndices,
+      resolver = resolver,
+      voidBaseIsNull = voidBaseIsNull
+    ) match {
+      case EitherLeft(extracted) => extracted
+      case EitherRight(throwable) => throw throwable
+    }
+  }
+
+  /**
+   * Returns true if the optional multipart name `nameParts` resolves to 
[[nullReference]] after
+   * it failed to resolve against `attributes`, i.e. if its first name part 
that matches no
+   * reference path to `attributes` is optional. See 
[[firstUnmatchedNamePartIndex]].
+   */
+  def resolvesToNull(
+      nameParts: Seq[String],
+      optionalNamePartIndices: Set[Int],
+      attributes: Seq[Attribute],
+      resolver: Resolver,
+      isViewQuery: Boolean): Boolean = {
+    optionalNamePartIndices.nonEmpty &&
+    firstUnmatchedNamePartIndex(nameParts, attributes, resolver, 
isViewQuery).exists(
+      optionalNamePartIndices.contains
+    )
+  }
+
+  /**
+   * Returns the index of the first name part of `nameParts` that does not 
continue any reference
+   * path to `attributes`, where a path is a suffix of the attribute 
qualifier, the attribute name,
+   * and then the names of nested fields. The qualifiers of session variables 
and of the variables
+   * of an active SQL scripting scope, i.e. the label of a compound statement 
or the variable of a
+   * FOR statement, are valid paths too, the latter except in the query of a 
view (`isViewQuery`),
+   * when the view is read or defined: a view cannot see the variables of the 
script, so a
+   * definition that resolves a label is rejected when the view is created 
rather than when it is
+   * read. A qualifier is not a reference by itself, so the last name part 
never matches a
+   * qualifier.
+   * Returns None if the whole name matches a path, which means that the name 
was found but was not
+   * usable, e.g. because it references a column that is not grouped.
+   *
+   * {{{
+   *   -- `t` has the columns `id` and `addr STRUCT<city STRING>`:
+   *   t.name    -- 1: `t` matches the qualifier of `id`, `name` matches 
nothing
+   *   ghost.id  -- 0
+   *   addr.zip  -- 1
+   *   t         -- 0: `t` is not a column
+   * }}}
+   */
+  def firstUnmatchedNamePartIndex(
+      nameParts: Seq[String],
+      attributes: Seq[Attribute],
+      resolver: Resolver,
+      isViewQuery: Boolean): Option[Int] = {
+    val matchedNamePartCounts =
+      attributes.iterator.map(matchedNamePartCount(nameParts, _, resolver)) ++
+      
SESSION_VARIABLE_QUALIFIERS.iterator.map(matchedQualifierPartCount(nameParts, 
_, resolver)) ++
+      Iterator(if (isViewQuery) 0 else 
matchedScriptingScopeLabelCount(nameParts))
+    val longestMatch = matchedNamePartCounts.max
+    if (longestMatch < nameParts.length) Some(longestMatch) else None
+  }
+
+  /**
+   * Returns 1 if `nameParts` has at least two parts and its first part is the 
label of an active
+   * SQL scripting scope, so that the name can reference a variable of that 
scope and then the
+   * nested fields of that variable, and 0 otherwise.
+   */
+  private def matchedScriptingScopeLabelCount(nameParts: Seq[String]): Int = {
+    val isScopeLabel = nameParts.length >= 2 && {
+      // Scope labels are normalized like variable names, see 
`VariableResolution.lookupVariable`.
+      val label = if (SQLConf.get.caseSensitiveAnalysis) {
+        nameParts.head
+      } else {
+        nameParts.head.toLowerCase(Locale.ROOT)
+      }
+      
SqlScriptingContextManager.get().flatMap(_.getVariableManager).exists(_.isScopeLabel(label))
+    }
+    if (isScopeLabel) 1 else 0
+  }
+
+  /**
+   * Returns the name with which to alias the static NULL of the optional 
field extraction
+   * `unresolvedExtractValue` if `child` is resolved and does not have the 
extracted struct field,
+   * or None otherwise. The name is the one that the extraction has when the 
field exists.
+   */
+  def missingOptionalFieldAliasName(
+      unresolvedExtractValue: UnresolvedExtractValue,
+      child: Expression,
+      extraction: Expression,
+      resolver: Resolver): Option[String] = {
+    extraction match {
+      case NonNullLiteral(fieldName, _: StringType)
+          if isOptional(unresolvedExtractValue) && child.resolved =>
+        ExtractValue.extractValue(child, extraction, resolver) match {
+          case EitherRight(throwable) if isFieldNotFound(throwable) =>
+            Some(s"${toPrettySQL(child)}.$fieldName")
+          case _ =>
+            None
+        }
+      case _ =>
+        None
+    }
+  }
+
+  /**
+   * Extracts `nestedFields` from `expression`, or returns the error of the 
extraction that
+   * failed. See [[extractNestedFields]].
+   */
+  @tailrec
+  private def extractNestedFieldsOrError(
+      expression: Expression,
+      nestedFields: Seq[String],
+      nestedFieldIndex: Int,
+      optionalNamePartIndices: Set[Int],
+      resolver: Resolver,
+      voidBaseIsNull: Boolean): Either[Expression, Throwable] = {
+    if (nestedFields.isEmpty) {
+      EitherLeft(expression)
+    } else if (voidBaseIsNull && expression.dataType == NullType) {
+      // The name is found, so this NULL is not a `nullReference`.
+      EitherLeft(Literal(null, NullType))

Review Comment:
   **Nit (P3):** The only test of this branch, `SELECT n.a, n.a? FROM VALUES 
(NULL) AS t(n)`, checks values and column names, which are the same whether or 
not this NULL carries the missing-reference tag. The distinction that the 
comment above draws is what keeps `n.a?` behaving like `n.a`: its alias `a` 
stays a lateral column alias and a GROUP BY alias, a VARIANT path on it fails 
like `NULL:a`, and the MERGE source check does not reject it. By the review's 
reading of the code, returning `nullReference()` here would make `SELECT n.a?, 
a + 1 FROM VALUES (NULL) AS t(n)` fail with UNRESOLVED_COLUMN for `a`, and no 
test would fail.
   
   **Verification:**
   - **Regression:** `SELECT n.a?, a + 1 FROM VALUES (NULL) AS t(n)` returns 
two NULLs, and the case fails with UNRESOLVED_COLUMN for `a` if an optional 
field of a VOID column becomes a missing-reference NULL.



##########
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:
   **Nit (P3):** CREATE METRIC VIEW also stores text that is analyzed again on 
every read, but it does not get the view-definition context that this trait 
gives CREATE VIEW, ALTER VIEW ... AS, and CACHE TABLE ... AS SELECT. 
`CreateMetricViewCommand` analyzes its YAML dimension and measure expressions 
in `run()` through `MetricViewHelper.analyzeMetricViewText` 
(metricViewCommands.scala:164-210), a separate analysis of a 
`MetricViewPlaceholder` with `isViewDefinition` false and an empty 
`catalogAndNamespace`. By the review's reading of the code, with 
spark.sql.optionalReferences.enabled on, inside `lbl: BEGIN ... END` a metric 
view with a dimension `lbl.missing?` is created, because the label qualifies 
the reference and it resolves to NULL, but every read plans the YAML again as a 
view, where the label does not count, and fails with UNRESOLVED_COLUMN for 
`lbl.missing`. In the same block, `CREATE TEMPORARY VIEW v AS SELECT 
lbl.missing? AS m` fails when it is created, as the golden file 
 shows.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4576517552).
   
   **Verification:**
   - **Regression:** With optional references on, inside a labeled SQL script, 
CREATE METRIC VIEW with a dimension `lbl.missing?` fails at creation with 
UNRESOLVED_COLUMN for `lbl.missing`, like CREATE TEMPORARY VIEW with the same 
reference, also with the single-pass resolver enabled.
   - **Compatibility:** A metric view whose optional reference names a missing 
column of its source is still created, and reading it returns NULL for that 
dimension.



##########
sql/core/src/test/resources/sql-tests/inputs/optional-references.sql:
##########
@@ -0,0 +1,575 @@
+-- Tests for optional column, field, variable, and named parameter references: 
a `?` after an
+-- identifier makes that identifier optional, so that a reference that cannot 
be resolved
+-- evaluates to a static NULL of type VOID instead of raising a not-found 
error.
+
+--SET spark.sql.optionalReferences.enabled=true
+
+CREATE TEMPORARY VIEW people AS SELECT * FROM VALUES
+  (1, named_struct('city', 'SF', 'zip', '94105')),
+  (2, named_struct('city', 'NYC', 'zip', '10001'))
+  AS t(id, addr);
+
+CREATE TEMPORARY VIEW orgs AS SELECT * FROM VALUES
+  (1, named_struct('addr', named_struct('city', 'SF', 'zip', '94105')))
+  AS t(id, info);
+
+CREATE TEMPORARY VIEW orders AS SELECT * FROM VALUES
+  (1, array(named_struct('sku', 'a', 'qty', 5))),
+  (2, array(named_struct('sku', 'b', 'qty', 9)))
+  AS t(id, items);
+
+-- A missing column resolves to NULL and an existing column resolves normally. 
Either way, the
+-- output column keeps the name of the reference.
+SELECT id?, name? FROM people;
+SELECT typeof(id?), typeof(name?) FROM people LIMIT 1;
+SELECT * FROM (SELECT id?, name? FROM people);
+
+-- Whitespace and comments between the identifier and `?` are insignificant.
+SELECT id ?, name /* comment */ ? FROM people;
+
+-- Optional references in expressions, predicates, grouping, ordering, and 
function arguments.
+SELECT id, bonus? + 1 AS b FROM people;
+SELECT coalesce(archived?, false) AS archived, count(*) AS cnt
+FROM people
+WHERE archived? IS NULL
+GROUP BY archived?;
+SELECT id FROM people WHERE coalesce(archived?, false) = false ORDER BY id;
+SELECT id FROM people ORDER BY missing?, id DESC;
+SELECT id, sum(id) OVER (PARTITION BY region? ORDER BY id) AS running FROM 
people;
+SELECT id FROM people GROUP BY id HAVING max(missing?) IS NULL ORDER BY id;
+SELECT id FROM people GROUP BY id HAVING max(addr.state?) IS NULL ORDER BY id;
+SELECT id FROM people GROUP BY id ORDER BY max(addr.state?), id;
+SELECT id, CASE WHEN missing? IS NULL THEN 'none' ELSE 'some' END AS c FROM 
people;
+SELECT a.id FROM people a JOIN people b ON a.id = b.id AND a.missing? IS NULL 
ORDER BY a.id;
+SELECT a.id, b.missing?, b.addr.state? FROM people a JOIN people b USING (id) 
ORDER BY a.id;
+SELECT id, missing?, count(*) FROM people GROUP BY ALL ORDER BY id;
+SELECT count(*) + missing? AS c FROM people GROUP BY ALL;
+SELECT missing?, count(*) FROM people;
+SELECT count(missing?), max(id?) FROM people;
+SELECT DISTINCT missing?, addr?.city FROM people ORDER BY city;
+SELECT id, row_number() OVER (ORDER BY id) AS rn FROM people QUALIFY rn = 1 
AND missing? IS NULL;
+
+-- GROUP BY, HAVING, and ORDER BY can reference aliases of the SELECT list as 
usual.
+SELECT coalesce(region?, 'none') AS region, count(*) AS cnt FROM people GROUP 
BY region?;
+SELECT coalesce(region?, 'none') AS region, count(*) AS cnt FROM people
+GROUP BY 1 HAVING region? = 'none';
+SELECT coalesce(rank?, id) AS rank FROM people ORDER BY rank? DESC;
+
+-- Where a name can resolve in more than one way, an optional reference 
resolves like the same
+-- reference without `?`: ORDER BY falls back from the SELECT list to the 
columns of the FROM
+-- clause, and HAVING falls back from those columns to the SELECT list.
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY 
addr.zip?;
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY 
addr.state?, id DESC;
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY 
addr?.state;
+SELECT named_struct('city', 'x') AS addr FROM people GROUP BY id ORDER BY 
addr.zip?;
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY addr HAVING 
addr.state? = 'CA';
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY addr
+HAVING addr.country? IS NULL;
+-- `addr.city` exists below the SELECT list but is not grouped, so HAVING 
falls back to the alias
+-- `addr` of the SELECT list, which has no `city`.
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY id HAVING 
addr.city? IS NULL;
+-- A column that is out of scope is not found.
+SELECT DISTINCT id FROM people ORDER BY addr?, id DESC;
+-- ORDER BY and WHERE do not reach below an aliased subquery or a pipe 
operator, like without `?`.
+SELECT id FROM (SELECT id FROM people) s ORDER BY addr?, id;
+SELECT id FROM (SELECT id FROM people) s ORDER BY addr, id;
+FROM people |> SELECT id |> WHERE addr? IS NULL;
+FROM people |> SELECT id |> WHERE addr IS NULL;
+
+-- Common table expressions and set operations.
+WITH cte AS (SELECT id, missing? AS m FROM people) SELECT id, m, other? FROM 
cte ORDER BY id;
+SELECT id?, missing? FROM people UNION ALL SELECT missing?, id? FROM people
+ORDER BY id NULLS FIRST, missing NULLS FIRST;
+
+-- An optional reference that resolves keeps its type and nullability.
+SELECT id? + 1 AS next_id, addr?.city AS city FROM people;
+
+-- Qualified and nested references: `?` guards only the identifier that it 
follows.
+SELECT p.name? FROM people AS p;
+SELECT people.name?, people.addr.state? FROM people;
+SELECT addr?.city FROM people;
+SELECT addr?.state FROM people;
+SELECT addr.state? FROM people;
+SELECT ghost?.city FROM people;
+SELECT ghost.city? FROM people;
+SELECT ghost?.city? FROM people;
+SELECT t.name? FROM people;
+SELECT people?, p? FROM people AS p;
+-- The qualifier of a table can include its namespace and catalog, like 
without `?`.
+CREATE TABLE qualified_t (id INT) USING parquet;
+INSERT INTO qualified_t VALUES (1);
+SELECT qualified_t.missing? AS a, default.qualified_t.missing? AS b,
+  spark_catalog.default.qualified_t.missing? AS c
+FROM qualified_t;
+SELECT other.qualified_t.missing? FROM qualified_t;
+DROP TABLE qualified_t;
+
+-- Three-part names: `?` binds to the immediately preceding identifier only.
+SELECT info.addr.zip? FROM orgs;
+SELECT info.addr.geo? FROM orgs;
+SELECT info.loc?.city FROM orgs;
+SELECT info.loc.city? FROM orgs;
+SELECT info?.addr.zip FROM orgs;
+SELECT a?.b?.c? FROM orgs;
+SELECT missing?.a.b, info.addr.geo?.x FROM orgs;
+-- The fields of a column of type VOID are NULL, like without `?`.
+SELECT n.a, n.a? FROM VALUES (NULL) AS t(n);
+SELECT struct(id?, missing?) AS s FROM orgs;
+
+-- Errors other than not-found are still raised.
+SELECT x? FROM (SELECT 1 AS x) a JOIN (SELECT 2 AS x) b;
+SELECT addr.state? FROM people a JOIN people b ON a.id = b.id;
+SELECT id.missing? FROM people;
+SELECT missing? FROM people GROUP BY id;
+SELECT 1 AS c FROM (SELECT 1 AS x) a JOIN (SELECT 2 AS x) b ORDER BY x?;
+
+-- An optional reference to an existing column is still subject to the usual 
rules, also where
+-- the column is below the operator that references it, and in a subquery.
+SELECT addr.zip? FROM people GROUP BY id;
+SELECT id FROM people GROUP BY id DISTRIBUTE BY addr?;
+SELECT (SELECT max(v) FROM VALUES (1, 2, 3) AS t(k, v, x) GROUP BY k HAVING x? 
> 0) AS m
+FROM people;
+SELECT (SELECT max(v) FROM VALUES (1, 2, 3) AS t(k, v, x) GROUP BY k ORDER BY 
x? LIMIT 1) AS m
+FROM people;
+
+-- Lateral column aliases resolve as usual.
+SELECT id AS a, a? + 1 AS b, c? FROM people;
+SELECT named_struct('x', 1) AS s, s.x?, s.y? FROM people;
+SELECT missing? AS a, a? AS b FROM people;
+SELECT missing? AS a, a + 1 AS b FROM people;
+SELECT id AS a, a? + 1 AS b FROM people WHERE missing? IS NULL;
+-- A missing optional reference is NULL under its own name, but unlike the 
name of `addr.city`,
+-- that name is not a lateral column alias and not a GROUP BY alias, so a 
reference to it
+-- without `?` is not found. ORDER BY and HAVING can reference it as a column 
of the SELECT list.
+SELECT missing?, missing? IS NULL AS m, addr.city, upper(city) AS c FROM 
people;
+SELECT missing?, missing + 1 AS m FROM people;
+SELECT missing + 1 AS m, missing? FROM people;
+SELECT addr.state?, upper(state) AS s FROM people;
+SELECT missing?, count(*) AS c FROM people GROUP BY missing;
+SELECT addr.state?, count(*) AS c FROM people GROUP BY state;
+SELECT addr.city, count(*) AS c FROM people GROUP BY city ORDER BY city;
+SELECT missing?, count(*) AS c FROM people GROUP BY missing?;
+SELECT missing? AS m, count(*) AS c FROM people GROUP BY m;
+SELECT missing?, id FROM people ORDER BY missing, id;
+SELECT missing?, count(*) AS c FROM people GROUP BY ALL HAVING missing IS NULL;
+-- A field that the column does not have is not looked up in a lateral column 
alias of the same
+-- name, like without `?`.
+SELECT named_struct('state', 'CA') AS addr, addr.state? FROM people;
+
+-- Session variables resolve as usual.
+DECLARE OR REPLACE VARIABLE known INT DEFAULT 7;
+SELECT known?, unknown?;
+SELECT known? FROM people WHERE missing? IS NULL LIMIT 1;
+DECLARE OR REPLACE VARIABLE known_struct STRUCT<a: INT> DEFAULT 
named_struct('a', 1);
+SELECT known_struct.a?, known_struct.b?;
+SELECT session.known?, session.unknown?, system.session.unknown?;
+SELECT session?, system.session?;
+SELECT known_struct.b;
+-- The name of a missing field of a variable is not a lateral column alias 
either.
+SELECT known_struct.b?, b + 1;
+-- The fields of a variable of type VOID are an error, like without `?`, 
unlike those of a column.
+DECLARE OR REPLACE VARIABLE void_var DEFAULT NULL;

Review Comment:
   **Non-blocking (P2):** `void_var` is never dropped, unlike `known` and 
`known_struct` at lines 184-185. While any temporary variable exists, 
ResolverGuard sends every plan to the fixed-point analyzer only 
(`checkTempVariables`, ResolverGuard.scala:80-83 and 714-716), so by the 
review's reading of the code, no query from line 160 to the end of the file 
runs in the single-pass resolver, and the golden run compares no plans of the 
two analyzers there. That includes the correlated cases at lines 303-331, the 
only tests of the outer-scope part of 
`NameScopeStack.tryResolveOptionalReferenceAsNull`, and the view, DML, INSERT, 
scripting, and parameter cases, although the PR description says that the 
golden files run with both analyzers on every query that the single-pass 
resolver supports. For example, removing the outer scopes from the attributes 
in `tryResolveOptionalReferenceAsNull` (NameScope.scala:1440-1443) would make 
the single-pass resolver fail `SELECT id, (SELECT max(o.missing?)
  FROM people i WHERE i.id = o.id) AS m FROM people o` with UNRESOLVED_COLUMN 
where the fixed-point analyzer returns NULL, and no test would fail. The 
single-pass resolver is not the default analyzer, so this loses test signal 
rather than changing default query results.
   
   **Verification:**
   - **Behavior:** The golden queries after the session-variable section that 
the single-pass resolver supports, including the correlated optional references 
in scalar, EXISTS, and HAVING subqueries, run in both analyzers with matching 
plans, and the regenerated results differ from the current ones only by the 
added DROP statement; the LATERAL cases stay with the fixed-point analyzer, 
which ResolverGuard picks for any LATERAL join.
   - **Regression:** Removing the outer scopes from the single-pass resolution 
of an optional reference to NULL makes the golden run fail on the correlated 
scalar-subquery cases.



##########
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:
   **Nit (P3):** With this binding, a session that sets the conf overrides the 
value that a stored definition captured, and views and SQL table functions 
follow that: after `SET spark.sql.optionalReferences.enabled=false`, reading a 
view or calling a SQL table function whose body uses `missing?` fails with 
PARSE_SYNTAX_ERROR, because their text is parsed with the caller's explicit 
values overlaid (Analyzer.scala:3222-3231 for table functions). A scalar SQL 
function does not follow it: `SessionCatalog.makeSQLFunctionPlan` parses its 
body under `buildSQLFunctionConf(applySessionOverrides = false)`, with the 
captured configs only (SessionCatalog.scala:1903-1909), and no analyzer rule 
checks the conf before its optional references resolve. By the review's reading 
of the code, in that session a scalar function created with `missing?` in its 
body still parses and returns NULL for `missing`, so setting the conf to false 
switches the feature off for views and table functions but not for scal
 ar functions. The disabled block of the golden file (lines 559-575) covers 
only `people_v`.
   
   **Verification:**
   - **Regression:** In a session that sets 
spark.sql.optionalReferences.enabled to false, calling a scalar SQL function 
created with `?` in its body fails with PARSE_SYNTAX_ERROR inside the function, 
like reading a view and calling a SQL table function created with `?`.
   - **Compatibility:** In a session that leaves the conf unset, the scalar 
function, the SQL table function, and the view created with `?` keep working 
with their captured value, and scalar SQL functions without `?` behave as 
before in both sessions.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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 org.apache.spark.sql.catalyst.expressions.{Expression, 
SubqueryExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  DeleteFromTable,
+  LogicalPlan,
+  MergeIntoTable,
+  OverwriteByExpression,
+  UpdateTable,
+  View
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
+import org.apache.spark.sql.errors.QueryCompilationErrors
+
+/**
+ * Rejects optional references in the expressions of a statement that modifies 
table data and
+ * that was built without the SQL parser, which rejects them in SQL text (see
+ * `OptionalReferenceValidation`). A missing column must not silently change 
which rows a
+ * statement deletes or updates.
+ *
+ * The source of a MERGE is checked too, like the source query of the SQL 
statement.
+ * `Dataset.mergeInto` and the Spark Connect MERGE command put the plan of the 
source DataFrame
+ * there, in which only the last operation is sure to be unanalyzed: a Dataset 
operation builds on
+ * the analyzed plan of the one before, and Spark Connect analyzes some 
relations, such as
+ * `withColumns`, when it plans them. In an analyzed operation, an optional 
reference that matched
+ * nothing is the NULL that it resolved to, which is rejected as well.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ *   spark.table("s").selectExpr("pk", "archived? AS 
archived").as("s").mergeInto("t", ...)
+ * }}}
+ */
+object CheckOptionalReferencesInDml extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (plan.containsPattern(COMMAND)) {

Review Comment:
   **Nit (P3):** This pass runs for every DELETE, UPDATE, MERGE, and 
`overwrite(condition)` analysis whatever spark.sql.optionalReferences.enabled 
is, and nothing here or in the class doc says why it has to. The reason is not 
obvious: a source DataFrame built while the conf was on, such as 
`spark.table("s").selectExpr("pk", "archived? AS archived").as("s")`, keeps its 
tagged NULL when the MERGE is analyzed after the conf is turned off, and only 
this rule rejects it. By the review's reading of the code, a later cleanup that 
wraps `apply` in `if (conf.optionalReferencesEnabled)` to save the pass on 
every DML statement would let that MERGE with `whenMatched(expr("s.archived IS 
NULL")).delete()` delete every matched row.
   
   See **Shared repair plan 1** in the review body.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala:
##########
@@ -0,0 +1,118 @@
+/*
+ * 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.parser
+
+import org.antlr.v4.runtime.ParserRuleContext
+import org.antlr.v4.runtime.tree.ParseTree
+
+import org.apache.spark.sql.catalyst.parser.SqlBaseParser._
+import org.apache.spark.sql.catalyst.util.SparkParserUtils
+import org.apache.spark.sql.errors.QueryParsingErrors
+
+/** Checks where the `?` optional-reference operator can appear in a SQL 
statement. */
+object OptionalReferenceValidation {
+
+  /**
+   * Throws an error for the optional reference `ctx`, i.e. the parse tree of 
a reference with a
+   * `?` after one of its name parts, if `ctx` is part of an UPDATE, DELETE, 
MERGE, or AUTO CDC
+   * statement, of the REPLACE condition of INSERT, of a partition 
specification, or of a DEFAULT,
+   * GENERATED ALWAYS AS, CHECK, or OPTIONS clause of a table or function 
definition.
+   *
+   * The boundary is the kind of statement. UPDATE, DELETE, MERGE, and AUTO 
CDC exist to modify
+   * existing rows, so they reject optional references everywhere, including 
in the source query of
+   * MERGE and in common table expressions. INSERT rejects them only in the 
REPLACE condition, a

Review Comment:
   **Nit (P3):** 'INSERT rejects them only in the REPLACE condition' leaves out 
the PARTITION clause: the PartitionSpecContext case at line 103 raises 
IN_PARTITION_SPEC for `INSERT INTO t PARTITION (p = :v?) SELECT a FROM s`, as 
OptionalReferencesParserSuite asserts. The first paragraph of this doc lists 
partition specifications, but a reader of this paragraph would conclude that a 
partition spec of an INSERT accepts `:v?`.
   
   **Verification:**
   - **Inspection:** The boundary paragraph of the validator doc names 
partition specifications as well as the REPLACE condition for INSERT.



-- 
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