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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala:
##########
@@ -155,7 +156,13 @@ trait ColumnResolutionHelper extends Logging with 
DataTypeErrorsBase {
             // Real columns from relations -- which don't carry the
             // SQL_FUNCTION_PARAMETER_ALIAS_METADATA_KEY -- continue to win as 
before.
             // Gated by a legacy kill-switch conf so the pre-fix behavior can 
be restored.
-            val column = resolveColumnByName(nameParts)
+            // A missing optional field is only NULL here if the error of the 
same name without
+            // `?` is final. Otherwise another resolution step can still 
resolve the name, e.g. as
+            // a column from below the SELECT list in ORDER BY, and 
`ResolveOptionalReferences`
+            // decides if none does.
+            val optionalNamePartIndices =
+              if (throws) OptionalReferences.optionalNamePartIndices(u) else 
Set.empty[Int]

Review Comment:
   **Non-blocking (P2):** In HAVING, the fixed-point analyzer reaches this line 
with a rebuilt attribute that has lost its optional name parts. 
`ResolveAggregateFunctions` marks a `TempResolvedColumn` that is neither 
grouped nor aggregated with `t.copy(hasTried = true)` (`Analyzer.scala:3366` 
and `3376`), which drops tags, and line 191 re-resolves it as a fresh 
`UnresolvedAttribute(t.nameParts)`, which has none. So 
`optionalNamePartIndices(u)` is empty even where the error is final, and a 
missing optional field raises `FIELD_NOT_FOUND` before 
`ResolveOptionalReferences` can run.
   
   Following the code with optional references on and the golden view 
`people(id INT, addr STRUCT<city STRING, zip STRING>)`: `SELECT 
named_struct('state', 'CA') AS addr FROM people GROUP BY id HAVING addr.city? 
IS NULL` first resolves `addr.city?` against `people.addr`. Because 
`people.addr` is not grouped, the column is marked as tried and re-resolved 
against the SELECT-list alias `addr STRUCT<state>`, and that final step throws 
`FIELD_NOT_FOUND` for `city`. The single-pass resolver returns NULL for the 
same query, so a dual run reports that the fixed-point analyzer failed where 
the single-pass resolver succeeded. The golden HAVING cases cover only the 
opposite shape, where the FROM column lacks the field.
   
   Forwarding the optional name-part indices through both rebuilds fixes it: 
copy the `TempResolvedColumn`'s tags at the two `t.copy(hasTried = true)` 
sites, and give the attribute built on line 191 the column's indices through a 
helper in `OptionalReferences`.
   
   **Verification:**
   - **Regression:** With optional references on, a HAVING condition names an 
optional field that exists in a non-grouped FROM column but is missing from the 
SELECT-list alias of the same name. In the default analyzer the field evaluates 
as NULL and the query returns the groups. The single-pass resolver produces the 
same result, so a dual run reports no mismatch.
   - **Compatibility:** The same HAVING condition without '?' still fails with 
FIELD_NOT_FOUND.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,301 @@
+/*
+ * 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
+}
+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.TreePattern.{PARAMETERIZED_QUERY, 
PLAN_EXPRESSION}
+
+/**
+ * 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]].
+ */
+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 if (markOptionalFieldsAsLastResort(plan)) {
+      resolveAgain(plan)
+    } else {
+      plan
+    }
+  }
+
+  /**
+   * 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
+        ) =>
+      val nullReference = OptionalReferences.nullReference()
+      if (isTopLevel) {
+        OptionalReferences.implicitAlias(nullReference, 
unresolvedAttribute.nameParts.last)
+      } else {
+        nullReference
+      }
+    case namedParameter: NamedParameter if 
OptionalReferences.isOptional(namedParameter) =>
+      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
+        }
+    }
+  }
+
+  /**
+   * Marks the optional field extractions of the lowest operators of `plan` 
that are not resolved
+   * as a last resort, and returns whether it marked any. See
+   * [[OptionalReferences.markLastResort]].
+   */
+  private def markOptionalFieldsAsLastResort(plan: LogicalPlan): Boolean = {
+    var marked = false
+    plan.foreach { operator =>
+      if (operator.childrenResolved && !operator.resolved) {
+        operator.expressions.foreach(_.foreach {
+          case extractValue: UnresolvedExtractValue
+              if OptionalReferences.isOptional(extractValue) &&
+              !OptionalReferences.isLastResort(extractValue) =>
+            OptionalReferences.markLastResort(extractValue)

Review Comment:
   **Blocking (P1):** `markLastResort` sets the tag on the extraction nodes of 
the plan this rule was given, not on copies, and those nodes belong to the 
caller's unresolved plan: a failed non-final resolution step returns the 
original expression (`ColumnResolutionHelper.scala:256-259`), and 
`QueryExecution` analyzes the logical plan without cloning it. The tag 
therefore outlives this analysis, and `ColumnResolutionHelper` treats a tagged 
extraction as final in every later step (`throws || 
OptionalReferences.isLastResort(u)`, line 205), including the first ORDER BY 
step, which resolves against the SELECT list with `throws = false` 
(`ResolveReferencesInSort.scala:78`).
   
   Spark Connect analyzes the same unresolved plan again from the session plan 
cache, which is on by default. Following the code with optional references on 
and `t.arr ARRAY<STRUCT<a INT>>`: for `df = 
spark.table('t').select(expr("array(named_struct('a', 1)) AS 
arr")).orderBy(expr('arr[0].b?'))`, `df.schema` analyzes the cached plan, and 
because `b` is missing from both the SELECT-list alias and `t.arr`, the cached 
extraction node is tagged and resolves to NULL, which is right at that point. 
If the element struct of `t.arr` then gains `b`, `df.collect()` reuses the 
tagged plan, the SELECT-list step resolves `arr[0].b?` to NULL instead of 
falling through to `t.arr[0].b`, and the rows are not sorted by the field that 
now exists, with no error. A newly built DataFrame sorts by the field, as the 
example in `markLastResort`'s own doc says it should.
   
   The same applies to any optional field of a non-name expression 
(`arr[0].b?`, `f(x).b?`) whose operator has an earlier resolution step that 
resolves the base but lacks the field, and to other re-analysis of captured 
plans, such as pipeline flow functions. Concurrent requests that analyze one 
cached plan also write the node's lazily created, unsynchronized tag map.
   
   **Recommended change:** Replace the LAST_RESORT tree-node tag with a marker 
expression in the plan that the analysis builds. When ResolveOptionalReferences 
replaces no optional reference, wrap each optional UnresolvedExtractValue of 
the lowest unresolved operators that is not already wrapped in a new unresolved 
expression, for example LastResortExtractValue(extraction), and rerun the 
Resolution batch on the rewritten plan. ColumnResolutionHelper resolves a 
wrapped extraction with final semantics: a missing optional field becomes NULL 
at the first step that resolves its base, and an extraction whose base is still 
unresolved stays wrapped. After the rerun, unwrap the wrappers that remain, as 
the rule already does for wrapped subquery plans. Remove LAST_RESORT, 
markLastResort, and isLastResort. Add analyzer tests that analyze the same 
unresolved plan again after the referenced struct gains the field, directly and 
through the Spark Connect plan cache.
   
   **Why this works:** The wrapper is a different node from the extraction, so 
the rewrite enters the analysis's own copy of the operator and leaves the 
caller's unresolved plan unchanged. Resolution copies the wrapper together with 
the extraction it holds, so the decision reaches the step that resolves the 
base even when an earlier step rebuilds the extraction. A later analysis of the 
same unresolved plan starts from nodes without wrappers and resolves the field 
as a newly built plan does. Concurrent analyses never write to the shared 
nodes. TempResolvedColumn carries the per-analysis state of a HAVING column 
across Resolution rounds in the same way.
   
   **Scope:** Make the last-resort decision for optional field extractions a 
marker node of the analyzed plan instead of a tag on the caller's plan nodes.
   
   **Compatibility:** Within one analysis, an optional field that no resolution 
step finds still becomes NULL at the first step that resolves its base. ORDER 
BY arr[0].b? sorts by the FROM column's field b when it exists, and by NULL 
when neither the SELECT list nor the FROM column has it.
   
   **Risks:** A new unresolved expression appears in plans during the 
optional-reference batch. A rule added later to the Resolution batch that 
matches UnresolvedExtractValue must look through it. Today only 
ColumnResolutionHelper matches user extractions there. An extraction whose base 
never resolves is wrapped and unwrapped in each round of the optional-reference 
batch, so the batch still ends as it does today. The change is contained in the 
rule, OptionalReferences, and ColumnResolutionHelper, and it can be reverted on 
its own.
   
   **Constraints:** Never write the decision on nodes of the plan that the 
analysis received. Rewrite only the plan that the rule returns. Within one 
analysis, do not change where a missing optional field becomes NULL.
   
   **Exclusions:**
   - Moving the markers the parser sets for optional name parts and optional 
references out of tree-node tags. They describe the statement and are correct 
on the nodes across analyses.
   
   **Success:** Analyzing the same unresolved plan again after the referenced 
struct gains the optional field resolves the field from the FROM column, as a 
newly built plan does. No analysis writes a last-resort decision on nodes of 
the caller's unresolved plan, and no wrapper remains in an analyzed plan or in 
an error message. Every optional field extraction that the golden files cover 
resolves as before, including ORDER BY items[0].price?.
   
   **Verification:**
   - **Regression:** With optional references on, take an unresolved plan that 
orders by arr[0].b? over a relation whose array elements lack b, beneath a 
SELECT-list alias arr that also lacks it. Analyzed once, it sorts by NULL. 
Redefine the relation so its elements have b and analyze the same unresolved 
plan instance again: it sorts by the relation's field b, matching a newly built 
plan.
   - **Regression:** Through Spark Connect with optional references on, request 
the schema of such a DataFrame, then collect it after the relation gains the 
field. The rows come back sorted by the field, as with a newly built DataFrame.
   - **Behavior:** The optional-references golden files give the same analyzed 
plans and results in both analyzers, including the ORDER BY cases over optional 
fields of array elements. A query whose optional extraction cannot resolve its 
base fails with the same error as before, and that error shows the extraction 
as written.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -313,6 +313,9 @@ object AnalysisContext {
         } else {
           mutable.LinkedHashSet.empty
         },
+      // The body of a SQL function is not a part of the query that calls it. 
If the call is in a
+      // subquery, the body must not resolve its names as outer references of 
that query.
+      outerPlan = None,

Review Comment:
   **Non-blocking (P2):** This changes query results whatever the confs: a SQL 
function body called inside a scalar, EXISTS, IN, or LATERAL subquery no longer 
resolves names as outer references of the calling query. On the base branch the 
body's context is a copy of the caller's, including its outer plan, and 
`resolveColsLastResort` tries `resolveOuterRef` before `resolveVariables`. So 
with default confs, `DECLARE VARIABLE v INT DEFAULT 100; CREATE TEMPORARY 
FUNCTION f() RETURNS INT RETURN v; SELECT (SELECT f()) FROM VALUES (5) AS t(v)` 
returns 5 on the base branch and 100 with this change, as the new 
`SQLFunctionSuite` test and the golden `variable_fn` case assert.
   
   The new result is the correct one: it matches a direct call and view bodies. 
The problem is that users whose function bodies rely on the old binding get 
different results after upgrading, with no `spark.sql.legacy.*` conf to restore 
the old resolution while they adapt and no entry in 
`docs/sql-migration-guide.md`. SQL functions are part of the 4.0 and 4.1 
releases, and comparable SQL-function name-resolution fixes in this repository 
ship behind such a conf, for example 
`spark.sql.legacy.allowUdfParameterToShadowParameterlessFunction`.
   
   **Recommended change:** Add an internal legacy conf, for example 
spark.sql.legacy.sqlFunctionBodyResolvesOuterReferences. It defaults to false, 
has version 4.4.0 like spark.sql.optionalReferences.enabled, and has SESSION 
binding like spark.sql.legacy.allowUdfParameterToShadowParameterlessFunction. 
When the conf is true and spark.sql.optionalReferences.enabled is off in the 
body's conf, AnalysisContext.withAnalysisContext(function) keeps the caller's 
outer plan for the body, as the base branch did. Otherwise it drops the outer 
plan, as this PR does. The conf doc states this exception. Add an entry to the 
'Upgrading from Spark SQL 4.3 to 4.4' section of docs/sql-migration-guide.md: 
since Spark 4.4, a name in the body of a SQL function called inside a subquery 
no longer resolves to a column of the calling query, and the conf restores the 
old behavior. Add SQL function tests for both settings. The reset came in the 
PR's second commit, 2bb6e4513b0, together with the two-stage parse.
   
   **Why this works:** The method reads both confs from the body conf that both 
callers install, so a value the caller sets in the session also applies to 
functions created earlier. With the legacy conf on and optional references off, 
the body context copies the caller's outer plan. resolveOuterRef then binds a 
body name to a column of the query around the calling subquery again, before 
session variables are tried, which restores the base branch's results. In every 
other case the body has no outer plan. That keeps this PR's results, and it is 
what ResolveOptionalReferences relies on to tell a subquery plan from a 
function body.
   
   **Scope:** A legacy conf, documented in the migration guide, that restores 
the base branch's name resolution for SQL function bodies called inside 
subqueries.
   
   **Compatibility:** With the legacy conf at its default, SQL function bodies 
resolve names exactly as in this PR. View bodies are not affected by the conf.
   
   **Risks:** While spark.sql.optionalReferences.enabled is on, the legacy conf 
has no effect, and function bodies called inside subqueries resolve as in this 
PR. The conf doc and the migration note must say so. Turning the conf off again 
returns to the new resolution, so the rollback can itself be undone.
   
   **Constraints:** The conf must have SESSION binding, so that a caller's 
session value replaces the value saved with an existing function: SQL function 
bodies take only SESSION-bound settings from the caller. With the conf at its 
default, every result must match this PR. This includes the session-variable 
result for a body called inside a subquery.
   
   **Exclusions:**
   - Making the legacy setting also take effect while optional references are 
enabled. That would require ResolveOptionalReferences to recognize subquery 
plans without relying on the absence of an outer plan.
   
   **Success:** With default confs, after DECLARE VARIABLE v INT DEFAULT 100 
and CREATE TEMPORARY FUNCTION f() RETURNS INT RETURN v, SELECT (SELECT f()) 
FROM VALUES (5) AS t(v) returns 100, as in this PR. With the legacy conf set in 
the session and optional references off, the same statement returns 5, as on 
the base branch. This also holds for a function created before the conf was 
set. With the legacy conf and optional references both on, function bodies 
resolve as in this PR. The migration guide's Spark 4.4 section describes the 
change and names the conf.
   
   **Verification:**
   - **Compatibility:** A SQL function body names both a session variable and a 
column of the query around a calling scalar subquery. With the legacy conf set 
in the session and optional references off, it returns the column's value, 
including for a function created before the conf was set. With default confs, 
it returns the variable's value. The same holds for a SQL table function 
referenced inside a scalar subquery of the calling query.
   - **Behavior:** With the legacy conf and optional references both on, an 
optional reference in the body of a function called inside a subquery still 
becomes NULL when its name is missing. A body name that matches a column of the 
calling query resolves as it does with default confs.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SubstituteParamsParser.scala:
##########
@@ -184,6 +206,23 @@ class SubstituteParamsParser extends Logging {
     (substitutedText, substitutions.toList)
   }
 
+  /**
+   * Returns the text that replaces the named parameter marker at `location` 
with `value`. Unlike
+   * a parameter name, the `?` of an optional marker can be directly followed 
by a keyword or an
+   * identifier, as in `:x?AND`, which must not become a part of the value.
+   */
+  private def namedReplacement(
+      sqlText: String,
+      location: ParameterLocation,
+      value: String): String = {
+    val nextIndex = sqlText.offsetByCodePoints(0, location.end)
+    val isFollowedByWord = location.optional && nextIndex < sqlText.length && {
+      val nextCodePoint = sqlText.codePointAt(nextIndex)
+      Character.isLetterOrDigit(nextCodePoint) || nextCodePoint == '_'
+    }

Review Comment:
   **Nit (P3):** `nextIndex` is computed before `location.optional` is tested, 
and `substituteAtLocations` calls this for every occurrence of every bound 
named parameter, so each bound marker walks the SQL prefix once more, on top of 
the two walks that `applySubstitutions` already makes per substitution. That 
happens for every named-parameter statement (`spark.sql(sqlText, args)`, 
`EXECUTE IMMEDIATE ... USING ... AS name`, Spark Connect named arguments), 
whether or not the marker is optional and whether or not optional references 
are enabled, although only optional markers use the result. The extra work 
grows with the number of markers times the statement length: negligible for a 
few markers, but it adds up for generated statements with thousands of them, 
such as large IN lists or multi-row VALUES. Computing the offset inside the 
conjunction gives the same result:
   
   ```suggestion
       val isFollowedByWord = location.optional && {
         val nextIndex = sqlText.offsetByCodePoints(0, location.end)
         nextIndex < sqlText.length && {
           val nextCodePoint = sqlText.codePointAt(nextIndex)
           Character.isLetterOrDigit(nextCodePoint) || nextCodePoint == '_'
         }
       }
   ```
   
   **Verification:**
   - **Inspection:** When a bound named parameter marker is substituted, the 
offset after the marker is computed only if the marker is optional, and the 
text that replaces each marker is the same as before.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -7039,6 +7039,24 @@
     ],
     "sqlState" : "HY008"
   },
+  "OPTIONAL_COLUMN_REFERENCE_NOT_SUPPORTED" : {

Review Comment:
   **Nit (P3):** This condition is raised for every kind of optional reference, 
not only columns: for optional named parameter markers (`:v?` in UPDATE and 
DELETE, `:p?` in partition specifications, both in the golden file) and for 
field and variable references. Its `IN_DML` message, "Statements that modify 
table data must not contain optional references.", is also what statements that 
only read a partition get: `OptionalReferenceValidation.scala:88-91` rejects 
every partition specification with context `PARTITION`, so by the code, 
`EXECUTE IMMEDIATE 'SHOW PARTITIONS target PARTITION (id = :p?)'` and a 
`DESCRIBE TABLE` with such a `PARTITION` clause fail with a message about 
statements that modify table data. The golden-file comment "Statements that 
modify table data reject `?`." has the same imprecision, since INSERT ... 
SELECT and CTAS write table data and accept `?`.
   
   A new error condition is a contract that callers match on, so this is 
cheapest to fix before it is released: rename it to something like 
`OPTIONAL_REFERENCE_NOT_SUPPORTED`, keeping SQLSTATE `0A000` and the sorted 
order of `error-conditions.json`, and give partition specifications their own 
subclass, such as `IN_PARTITION_SPEC` with "Partition specifications must not 
contain optional references."
   
   **Verification:**
   - **Behavior:** With optional references on, an optional named marker in a 
partition specification raises the partition subclass. This holds both for a 
statement that only reads the partition, such as SHOW PARTITIONS or DESCRIBE 
TABLE with a PARTITION clause, and for one that writes it, such as TRUNCATE 
TABLE or INSERT with a PARTITION clause. UPDATE, DELETE, MERGE, INSERT ... 
REPLACE WHERE, AUTO CDC, and table-definition cases raise the renamed condition 
with their current subclasses and contexts.
   - **Inspection:** No occurrence of the old condition name remains in the 
error definitions, the error helpers, the tests, or the regenerated expected 
outputs.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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
+}
+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.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ * }}}
+ */
+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))
+        }
+      }
+    }
+    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.
+    case _: OverwriteByExpression => Some("INSERT")
+    case _ => None
+  }
+
+  private def checkExpression(expression: Expression, statement: String): Unit 
= {
+    expression.foreach {
+      case reference if !reference.resolved && 
OptionalReferences.hasOptionalMarker(reference) =>
+        throw QueryCompilationErrors.optionalReferenceInDmlNotSupportedError(
+          statement,
+          reference.origin
+        )
+      case subquery: SubqueryExpression =>

Review Comment:
   **Nit (P3):** No test reaches this case: `DataFrameWriterV2Suite` and 
`MergeIntoDataFrameSuite` put only a top-level optional reference in a 
condition, and `Expression.foreach` does not descend into subquery plans, so 
nothing else covers it. If the case were removed, an optional reference in a 
scalar subquery of a DataFrame- or Connect-built MERGE assignment, such as 
`whenMatched().update(Map("salary" -> expr("(SELECT max(bonus?) FROM src)")))`, 
would no longer be rejected with IN_DML and would silently become NULL 
(`RewriteMergeIntoTable` rejects subqueries only in merge conditions), and both 
suites would stay green.
   
   A `MergeIntoDataFrameSuite` case with that assignment, asserting the DML 
error with the MERGE context, closes the gap.
   
   **Verification:**
   - **Regression:** A MERGE built with the DataFrame API whose matched-update 
assignment is a scalar subquery containing an optional reference fails, before 
it runs, with the DML subclass and the MERGE context. Removing the subquery 
branch of the check fails the test.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -4746,22 +4746,34 @@ class AstBuilder extends DataTypeAstBuilder
    * it can be [[UnresolvedExtractValue]].
    */
   override def visitDereference(ctx: DereferenceContext): Expression = 
withOrigin(ctx) {
+    val optionalMarker = ctx.fieldName.optionalMarker
     // Use getIdentifierText to handle both regular identifiers and 
IDENTIFIER('literal')
-    val attr = getIdentifierText(ctx.fieldName)
+    val attr = getIdentifierText(ctx.fieldName.identifier)
     expression(ctx.base) match {
       case unresolved_attr @ UnresolvedAttribute(nameParts) =>
         // For regex check, we need the original text before identifier-lite 
resolution
         ctx.fieldName.getStart.getText match {
           case escapedIdentifier(columnNameRegex)
             if conf.supportQuotedRegexColumnName &&
               isRegex(columnNameRegex) && canApplyRegex(ctx) =>
+            firstOptionalMarker(ctx).foreach { marker =>
+              throw 
QueryParsingErrors.unexpectedOptionalReferenceMarkerError(ctx, marker)
+            }
             UnresolvedRegex(columnNameRegex, Some(unresolved_attr.name),
               conf.caseSensitiveAnalysis)
           case _ =>
-            UnresolvedAttribute(nameParts :+ attr)
+            val dereference = UnresolvedAttribute(nameParts :+ attr)
+            OptionalReferences.markNamePartsOptional(
+              dereference, 
OptionalReferences.optionalNamePartIndices(unresolved_attr))
+            withOptionalNamePart(dereference, nameParts.length, 
optionalMarker, ctx)
         }
       case e =>
-        UnresolvedExtractValue(e, Literal(attr))
+        val extractValue = UnresolvedExtractValue(e, Literal(attr))
+        if (optionalMarker != null) {
+          OptionalReferenceValidation.validate(ctx)

Review Comment:
   **Nit (P3):** Neither this call nor the one in the `IDENTIFIER(expr)?` 
branch of `visitColumnReference` (line 4818) has a negative test: the IN_DML 
and IN_DDL cases in `OptionalReferencesParserSuite` and 
`optional-references.sql` use only names (`a?`, `t.c?`, `s.b?`) and `:v?`. 
Removing either call would leave every test green, and in table definitions, 
partition specifications, and AUTO CDC flows nothing else rejects the marker, 
because `CheckOptionalReferencesInDml` covers only DML plans, so a missing name 
would silently become a NULL default, generated value, or CHECK.
   
   Parser tests for `CHECK (arr[0].b? > 0)` and `GENERATED ALWAYS AS 
(IDENTIFIER('a' || '')? + 1)` that assert the IN_DDL subclass and the context 
of the clause would cover both.
   
   **Verification:**
   - **Regression:** With optional references on, a CHECK constraint on an 
optional field of a non-name expression fails to parse, and so does a generated 
column built on an optional IDENTIFIER clause reference. Each fails with the 
table-definition subclass and the context of its clause, so removing either 
validation call fails a test.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala:
##########
@@ -0,0 +1,103 @@
+/*
+ * 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 condition of INSERT ... REPLACE, of a partition 
specification, or of an
+   * expression that defines a table object.
+   *
+   * {{{
+   *   UPDATE t SET a = b?;                                  -- IN_DML
+   *   WITH s AS (SELECT a? FROM u) DELETE FROM t WHERE ...; -- IN_DML
+   *   CREATE TABLE t (a INT, b INT DEFAULT a?);             -- IN_DDL
+   *   INSERT INTO t SELECT a? FROM s;                       -- allowed: the 
query only reads data
+   * }}}
+   */
+  def validate(ctx: ParserRuleContext): Unit = {
+    Iterator
+      .iterate(ctx.getParent)(_.getParent)
+      .takeWhile(_ != null)
+      .flatMap(unsupportedContextError(_, ctx))
+      .nextOption()
+      .foreach(error => throw error)
+  }
+
+  /**
+   * Validates the optional named parameter markers in the parse tree `tree` 
with [[validate]].
+   * This is for the markers that are substituted in `sqlText`, the text that 
`tree` was parsed
+   * from, before the statement is parsed into a plan.
+   */
+  def validateNamedParameterMarkers(tree: ParseTree, sqlText: String): Unit = 
tree match {
+    case namedParameter: NamedParameterLiteralContext if 
namedParameter.optionalMarker != null =>
+      SparkParserUtils.withOrigin(namedParameter, Some(sqlText)) {
+        validate(namedParameter)
+      }
+    case _ =>
+      (0 until tree.getChildCount).foreach { index =>
+        validateNamedParameterMarkers(tree.getChild(index), sqlText)
+      }
+  }
+
+  /**
+   * Returns the error for the optional reference `ctx` if its ancestor 
`ancestor` is a statement
+   * or a clause that does not support optional references.
+   */
+  private def unsupportedContextError(
+      ancestor: ParserRuleContext,
+      ctx: ParserRuleContext): Option[Throwable] = ancestor match {
+    case _: DeleteFromTableContext =>
+      
Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("DELETE", ctx))
+    case _: UpdateTableContext =>
+      
Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("UPDATE", ctx))
+    case _: MergeIntoTableContext =>
+      Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("MERGE", 
ctx))
+    case _: InsertIntoReplaceBooleanCondContext =>
+      
Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("INSERT", ctx))
+    case dmlStatement: DmlStatementContext =>
+      // The common table expressions of a statement are siblings of its 
DELETE, UPDATE, or MERGE.
+      unsupportedContextError(dmlStatement.dmlStatementNoWith, ctx)
+    case _: AutoCdcParametersContext =>

Review Comment:
   **Non-blocking (P2):** This case only covers AUTO CDC flows written in SQL. 
The Python pipelines API sends `apply_as_deletes` and `sequence_by` of 
`create_auto_cdc_flow` as Spark Connect expression strings, which the server 
parses with `parser.parseExpression` 
(`SparkConnectPlanner.transformExpressionString`) outside any DML parse 
context, and `PipelinesHandler.buildAutoCdcFlow` stores them in `ChangeArgs` 
without a check. `CheckOptionalReferencesInDml` looks only at 
`DeleteFromTable`, `UpdateTable`, `MergeIntoTable`, and `OverwriteByExpression` 
plans, so it does not see them either.
   
   Following the code, with `spark.sql.optionalReferences.enabled` set in the 
Connect session, `create_auto_cdc_flow(target='sink', source='src', 
keys=['id'], sequence_by='ts', apply_as_deletes='deleted? = true')` over a 
source without a `deleted` column is registered, and each microbatch evaluates 
the delete condition as NULL. No row is treated as a delete, so delete events 
are applied as upserts: an SCD1 target keeps the rows the feed deleted, and an 
SCD2 target never ends their history records. That is the silent change of 
modified rows that IN_DML exists to prevent, while the SQL form of the same 
flow fails with IN_DML, as the streaming golden file records. An optional 
reference in `sequence_by` fails later instead, at the null-sequence check.
   
   **Recommended change:** In PipelinesHandler.buildAutoCdcFlow, check every 
change argument the handler receives as an expression for optional references 
before building ChangeArgs: sequence_by, apply_as_deletes, keys, and the column 
lists. Raise the same IN_DML error, with the AUTO CDC context, that the SQL 
form of the flow raises. Move the expression walk of 
CheckOptionalReferencesInDml into a helper in OptionalReferences that both the 
DML check and the handler call. The walk finds an unresolved node with an 
optional marker, including inside the plans of subquery expressions. Add 
pipelines handler tests for the rejected arguments.
   
   **Why this works:** The handler works on the catalyst expressions that the 
Spark Connect planner produced, which still carry the parser's 
optional-reference markers. Walking them with the shared helper finds exactly 
what the parser rejects in SQL text, so the flow is never registered. Keys and 
column-list expressions are checked before they are reduced to names, which 
would drop the marker.
   
   **Scope:** Reject optional references in AUTO CDC change arguments defined 
through the pipelines API, with the error the SQL form raises.
   
   **Compatibility:** SQL-defined AUTO CDC flows and AUTO CDC flows without 
optional references behave as before. DataFrame-built DML statements are still 
rejected when they contain an optional reference.
   
   **Risks:** With the conf on, an AUTO CDC flow defined through the pipelines 
API with '?' in a change argument now fails at definition. Such a flow could 
not exist on the base branch, where '?' after a name was a syntax error.
   
   **Constraints:** Raise the same condition, subclass, and AUTO CDC context as 
the SQL form, through the same error helper, so the two forms stay 
interchangeable, also if the condition is renamed.
   
   **Exclusions:**
   - Optional references in the queries of other flow types. Those queries only 
read data, and '?' stays allowed there.
   
   **Success:** With the conf on, create_auto_cdc_flow with 
apply_as_deletes='deleted? = true' or sequence_by='ts?' fails at flow 
definition with the error and AUTO CDC context of the equivalent SQL flow, and 
no flow is registered. A key or column-list argument built with expr() that 
contains '?' is rejected the same way, instead of being treated as a required 
name. AUTO CDC flows without optional references, and the DML check for 
DataFrame-built statements, behave as before.
   
   **Verification:**
   - **Regression:** With optional references on, define an AUTO CDC flow 
through the pipelines API whose delete condition, or whose sequencing 
expression, contains an optional reference to a column the source lacks. 
Defining the flow fails with the same error condition, subclass, and AUTO CDC 
context as the equivalent SQL flow, and no flow is registered. An optional 
reference nested in a subquery or a function call of a change argument is 
rejected the same way.
   - **Behavior:** A key or column-list entry passed as an expression that 
contains an optional reference is rejected with the same error. The same flow 
without '?' is accepted.



##########
sql/core/src/test/resources/sql-tests/inputs/optional-references.sql:
##########
@@ -0,0 +1,398 @@
+-- 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('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;
+-- A column that is out of scope is not found.
+SELECT DISTINCT id FROM people ORDER BY addr?, id DESC;
+
+-- 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;
+
+-- 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;
+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;
+
+-- An optional reference to an existing column is still subject to the usual 
rules.
+SELECT addr.zip? FROM people GROUP BY id;
+
+-- 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;
+-- A SET VAR statement outside of a SQL script.
+SET VAR known = unknown?;
+SELECT known;
+SET VAR known = (SELECT max(id) + coalesce(max(bonus?), 10) FROM people);
+SELECT known;
+EXECUTE IMMEDIATE 'SET VAR known = :p?' USING 5 AS p;
+SELECT known;
+EXECUTE IMMEDIATE 'SET VAR known = coalesce(unknown?, :p?, ?)' USING 7;
+EXECUTE IMMEDIATE 'SET VAR known = coalesce(unknown?, ?)' USING 7;
+SELECT known;
+DROP TEMPORARY VARIABLE known;
+DROP TEMPORARY VARIABLE known_struct;
+
+-- SQL scripting variables resolve as usual.
+--QUERY-DELIMITER-START
+BEGIN
+  DECLARE local_known INT DEFAULT 5;
+  SELECT local_known?, local_unknown?;
+END;
+--QUERY-DELIMITER-END
+
+-- Correlated subqueries resolve against the same scopes as without `?`.
+SELECT id, (SELECT max(o.missing?) FROM people i WHERE i.id = o.id) AS m FROM 
people o ORDER BY id;
+SELECT id, (SELECT max(i.id) FROM people i WHERE i.id = o.id?) AS m FROM 
people o ORDER BY id;
+SELECT id, (SELECT max(i.id) FROM people i WHERE i.id = o.id AND o.addr.state? 
IS NULL) AS m
+FROM people o ORDER BY id;
+SELECT id, (SELECT max(o.addr.state?) FROM people i WHERE i.id = o.id) AS m 
FROM people o
+ORDER BY id;
+SELECT id FROM people o WHERE EXISTS (
+  SELECT 1 FROM people i WHERE i.id = o.id AND o.ghost? IS NULL) ORDER BY id;
+SELECT id FROM people GROUP BY id
+HAVING (SELECT max(i.id) FROM people i WHERE i.id = people.id AND 
people.ghost? IS NULL) > 0
+ORDER BY id;
+SELECT p.id, l.next_id, l.m FROM people p, LATERAL (SELECT p.id + 1 AS 
next_id, p.missing? AS m) l
+ORDER BY p.id;
+SELECT p.id, l.x FROM people p JOIN LATERAL (SELECT p.id AS x) l ON l.missing? 
IS NULL
+ORDER BY p.id;
+SELECT p.id, l.x, l.g
+FROM people p
+JOIN LATERAL (SELECT q.id AS x, q.ghost? AS g FROM people q WHERE q.id = p.id) 
l
+  ON l.x = p.missing? OR l.g IS NULL
+ORDER BY p.id;
+SELECT id, (SELECT named_struct('id', p.id, 'missing', p.missing?) AS s) AS s 
FROM people p
+ORDER BY id;
+SELECT (SELECT (SELECT missing? AS a) AS b) AS c;
+SELECT id, (SELECT max(i.id) AS id FROM people i WHERE i.id = o.id GROUP BY 
i.addr
+  HAVING id > 0 AND missing? IS NULL) AS m
+FROM people o ORDER BY id;
+-- A field that the column of the subquery does not have is not looked up in 
the outer query.
+SELECT id, (SELECT addr.zip? FROM (SELECT named_struct('city', 'x') AS addr)) 
AS zip FROM people
+ORDER BY id;
+-- A subquery can reference the alias of a generator of the query around it.
+SELECT explode(array(1, 2)) AS e, (SELECT max(id) FROM people WHERE id = e?) 
AS m;
+
+-- Lambda functions.
+SELECT transform(array(named_struct('a', 1)), x -> x.a?) AS a,
+  transform(array(named_struct('a', 1)), x -> x.b?) AS b;
+SELECT transform(array(1, 2), x -> x + missing?) AS t FROM people LIMIT 1;
+SELECT filter(array(1, 2), x -> x? > 1) AS f;
+SELECT transform(array(NULL), x -> x?.a) AS t;
+
+-- Optional fields of expressions other than column references.
+SELECT array(named_struct('a', 1))[0].a?, array(named_struct('a', 1))[0].b?;
+SELECT missing?[0], missing?['key'] FROM people LIMIT 1;
+SELECT id, items[0].qty?, items[0].price? FROM orders ORDER BY items[0].qty? 
DESC;
+SELECT id FROM orders ORDER BY items[0].price?, id DESC;
+SELECT id FROM orders ORDER BY items?[0].price, id DESC;
+
+-- IDENTIFIER clause.
+SELECT IDENTIFIER('id')?, IDENTIFIER('name')? FROM people;
+SELECT IDENTIFIER('people.name')? FROM people;
+SELECT IDENTIFIER('i' || 'd')?, IDENTIFIER('na' || 'me')? FROM people;
+SELECT IDENTIFIER('ghost')?.city, addr.IDENTIFIER('state')? FROM people;
+SELECT addr.IDENTIFIER('sta' || 'te')? FROM people;
+DECLARE OR REPLACE VARIABLE column_name STRING DEFAULT 'name';
+SELECT IDENTIFIER(column_name)? FROM people;
+DROP TEMPORARY VARIABLE column_name;
+
+-- SQL user-defined functions.
+CREATE TEMPORARY FUNCTION optional_fn(a INT) RETURNS INT RETURN a? + 
coalesce(b?, 10);
+SELECT optional_fn(1);
+CREATE TEMPORARY FUNCTION optional_qualified_fn(a INT) RETURNS INT
+  RETURN optional_qualified_fn.a? + coalesce(optional_qualified_fn.b?, 10);
+SELECT optional_qualified_fn(1);
+-- The body of a SQL function does not see the columns of the query that calls 
it, with or
+-- without `?`.
+SELECT (SELECT optional_fn(1)) AS r;
+SELECT (SELECT optional_fn(1)) AS r FROM VALUES (5) AS t(b);
+CREATE TEMPORARY FUNCTION optional_table_fn(a INT) RETURNS TABLE (x INT, y INT)
+  RETURN SELECT a, coalesce(b?, 10);
+SELECT p.id, f.x, f.y FROM people p, LATERAL optional_table_fn(p.id) f ORDER 
BY p.id;
+DECLARE OR REPLACE VARIABLE fn_variable INT DEFAULT 100;
+CREATE TEMPORARY FUNCTION variable_fn() RETURNS INT RETURN fn_variable;
+SELECT (SELECT variable_fn()) AS r FROM VALUES (5) AS t(fn_variable);
+DROP TEMPORARY FUNCTION optional_fn;
+DROP TEMPORARY FUNCTION optional_qualified_fn;
+DROP TEMPORARY FUNCTION optional_table_fn;
+DROP TEMPORARY FUNCTION variable_fn;
+DROP TEMPORARY VARIABLE fn_variable;
+
+-- SQL pipe syntax.
+FROM people |> SELECT id, missing?;
+FROM people |> WHERE missing? IS NULL |> EXTEND missing? AS m |> AGGREGATE 
count(m) AS cnt;
+
+-- Spark has no try-cast operator, so `?` followed by `::` is an optional 
reference that is cast.
+SELECT id?::STRING FROM people;
+SELECT name?::STRING FROM people;
+SELECT name? ::STRING, (name?)::STRING, CAST(name? AS STRING) FROM people 
LIMIT 1;
+
+-- Optional named parameter markers: `:name?` is NULL if no value is bound to 
`name`.
+EXECUTE IMMEDIATE 'SELECT id?, ? FROM people' USING 10;
+EXECUTE IMMEDIATE 'SELECT :x?, :y?' USING 1 AS x;
+EXECUTE IMMEDIATE 'SELECT id FROM people WHERE :city? IS NULL OR addr.city = 
:city? ORDER BY id';
+EXECUTE IMMEDIATE 'SELECT id FROM people WHERE :city? IS NULL OR addr.city = 
:city? ORDER BY id'
+  USING 'SF' AS city;
+EXECUTE IMMEDIATE 'SELECT :x ?, :x /* comment */ ?' USING 5 AS x;
+EXECUTE IMMEDIATE 'SELECT :x?::INT' USING '5' AS x;
+EXECUTE IMMEDIATE 'SELECT :x?AS v, :y?IS NULL AS w' USING 5 AS x;
+EXECUTE IMMEDIATE 'SELECT :y?, :y';
+EXECUTE IMMEDIATE 'SELECT :x?, ?' USING 1;
+SELECT :x?;
+SELECT :x;
+
+-- Positional parameter markers are unchanged.
+EXECUTE IMMEDIATE 'SELECT TRIM(BOTH ? FROM ?)' USING 'x', 'xabcx';
+EXECUTE IMMEDIATE 'SELECT INTERVAL ? DAY' USING '1';
+EXECUTE IMMEDIATE 'SELECT DISTINCT ? FROM people' USING 5;
+EXECUTE IMMEDIATE 'SELECT id FROM people WHERE id IN (SELECT ?) ORDER BY id' 
USING 2;
+EXECUTE IMMEDIATE 'SELECT id FROM people WHERE id IN (VALUES ?, ?) ORDER BY 
id' USING 1, 2;
+EXECUTE IMMEDIATE 'SELECT ? ? FROM people' USING 'a', 'b';
+EXECUTE IMMEDIATE 'SELECT id FROM people WHERE id = ? ORDER BY id' USING 2;
+EXECUTE IMMEDIATE 'SELECT ?::INT' USING '5';
+EXECUTE IMMEDIATE 'SELECT ALL ? FROM people LIMIT ?' USING 5, 1;
+EXECUTE IMMEDIATE 'SELECT NOT ?, CASE ? WHEN 1 THEN ? ELSE ? END' USING true, 
1, 'a', 'b';
+EXECUTE IMMEDIATE
+  'SELECT id FROM people WHERE id BETWEEN ? AND ? AND addr.city LIKE ? ORDER 
BY id'
+  USING 1, 2, '%F';
+-- A statement that is valid without optional references keeps its meaning: 
the `?` is a
+-- parameter marker, although `distinct?` is also a reference to a column 
named `distinct`.
+EXECUTE IMMEDIATE 'SELECT first(DISTINCT ?) AS f FROM people' USING 5;
+-- Parameter markers in a statement with optional references.
+EXECUTE IMMEDIATE
+  'SELECT missing?, id FROM people WHERE id IN (SELECT ?) AND id BETWEEN ? AND 
? LIMIT ?'
+  USING 2, 1, 2, 1;
+-- In a statement that is not valid without optional references, a `?` after a 
keyword marks a
+-- reference to a column with the name of the keyword where the syntax allows 
a reference, so
+-- `distinct?` is NULL here.
+EXECUTE IMMEDIATE 'SELECT missing?, first(DISTINCT ?) AS f FROM people' USING 
5;
+
+-- Views are the primary use case: a view stays valid while its source table 
evolves.
+CREATE OR REPLACE TEMPORARY VIEW people_v AS SELECT id, addr, deleted_at? FROM 
people;
+SELECT * FROM people_v ORDER BY id;
+DESCRIBE people_v;
+
+CREATE TABLE evolving (id INT) USING parquet;
+INSERT INTO evolving VALUES (1);
+CREATE VIEW evolving_v WITH SCHEMA EVOLUTION AS SELECT id, deleted_at? FROM 
evolving;
+CREATE VIEW evolving_cast_v AS SELECT id, CAST(deleted_at? AS STRING) AS 
deleted_at FROM evolving;
+CREATE VIEW evolving_void_v AS SELECT id, deleted_at? FROM evolving;
+SELECT * FROM evolving_v;
+ALTER TABLE evolving ADD COLUMNS (deleted_at STRING);
+INSERT INTO evolving VALUES (2, 'yesterday');
+SELECT * FROM evolving_v ORDER BY id;
+-- A view that is not created WITH SCHEMA EVOLUTION keeps the types of its 
columns. A missing
+-- optional reference has the type VOID, which the column that appears later 
cannot be cast to,
+-- so such a view should cast the reference to the type of that column.

Review Comment:
   **Nit (P3):** `WITH SCHEMA TYPE EVOLUTION` also takes the new column's type: 
`SessionCatalog.castColToType` keeps the column as it is for that mode (`case 
SchemaTypeEvolution => col`), so by the code `CREATE VIEW v WITH SCHEMA TYPE 
EVOLUTION AS SELECT id, deleted_at? FROM evolving` keeps working after 
`deleted_at STRING` is added, like `evolving_v`, without a cast. Only BINDING 
and the default COMPENSATION keep the types of their columns. Suggested wording:
   
   ```suggestion
   -- A view WITH SCHEMA BINDING or COMPENSATION, the default, keeps the types 
of its columns, and a
   -- missing optional reference has the type VOID, which a column that appears 
later cannot be cast
   -- to, so such a view should cast the reference. WITH SCHEMA [TYPE] 
EVOLUTION takes the new type.
   ```
   
   **Verification:**
   - **Inspection:** The comment names BINDING and the default COMPENSATION as 
the modes that keep a view's column types. It names WITH SCHEMA EVOLUTION and 
WITH SCHEMA TYPE EVOLUTION as the modes that take the type of a column that 
appears later.



##########
sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4:
##########
@@ -1727,8 +1778,8 @@ primaryExpression
     | identifier ARROW expression                                              
                #lambda
     | LEFT_PAREN identifier (COMMA identifier)+ RIGHT_PAREN ARROW expression   
                #lambda
     | value=primaryExpression LEFT_BRACKET index=valueExpression RIGHT_BRACKET 
                #subscript
-    | identifier                                                               
                #columnReference
-    | base=primaryExpression DOT fieldName=identifier                          
                #dereference
+    | leadingReferenceNamePart                                                 
                #columnReference

Review Comment:
   **Non-blocking (P2):** With `spark.sql.optionalReferences.enabled` off, the 
default, every column reference now enters `leadingReferenceNamePart` and every 
dereference field enters `referenceNamePart`, and the generated parser also 
carries the new `QUESTION_WITH_OPTIONAL_REFERENCES` alternatives and the two 
semantic predicates (on the IN-list alternative of `predicate` and in the 
`stringLit` loop). The PR measured the bytecode size of `primaryExpression` but 
not parse time, so this review measured the generated parser alone.
   
   Setup: the lexer and parser grammars of the merge base and of this PR, 
generated with ANTLR 4.13.1 (Spark's version), compiled with ECJ 3.44 for Java 
21, and run on a Temurin 25 HotSpot with Spark's parse setup: the upper-casing 
char stream, two no-op parse listeners in place of `PostProcessor` and 
`UnclosedCommentProcessor`, SLL with a bail strategy and then LL, and the 
`compoundOrSingleStatement` rule, with optional references off. Each JVM parsed 
six workloads 300 times to warm up and then 300 times measured; base and head 
JVMs alternated, 13 runs each over three sessions. Medians of the per-run 
medians, head against base:
   
   | Workload | Head vs. base |
   |---|---|
   | 103 TPC-DS queries | +2.9% to +4.2% |
   | 500 short statements | +4% to +5% |
   | WHERE clause with 500 predicates | +4.5% to +5.8% |
   | 2,000 column references | +9% to +11.5% |
   | 2,000 qualified columns | +13% to +14% |
   | 1,000 nested fields | +13% to +14% |
   
   Run-to-run spreads were 1-5%, there was no LL fallback, and every variant 
produced identical parse trees. That is a few microseconds per TPC-DS query 
and, for the column-heavy statements, roughly 0.05-0.1 microseconds per 
reference.
   
   A control grammar with the marker inlined into `#columnReference` and 
`#dereference`, so with no extra rule frames, measured about +3% on TPC-DS and 
+6% to +7% on the column-heavy workloads: the rule frames cause about half of 
the column-heavy overhead, and the rest is the cost of the marker alternatives 
and predicates. Its `primaryExpression` is 7,997 bytes with ECJ, against 7,844 
at head and 7,843 at the merge base; javac's output is 8 bytes larger in the 
PR's own numbers, so this control would likely exceed the 8,000-byte limit that 
the separate rules exist to avoid. All of this is grammar parse time only: 
`parsePlan` also builds the plan, and parsing is a small part of query 
compilation, so the end-to-end share is smaller.
   
   **Recommended change:** Inline identifier 
optionalMarker=QUESTION_WITH_OPTIONAL_REFERENCES? into the #columnReference 
alternative and into the field of #dereference. A reference without '?' then 
enters no rule that the base grammar did not enter. Keep the IDENTIFIER(expr)? 
form as its own alternative or rule. Move a rarely used alternative of 
primaryExpression, for example #overlay or #extract, into a rule of its own, so 
that the generated primaryExpression stays under 8,000 bytes of javac bytecode. 
Update the AstBuilder visitors, keeping the optional-reference validation at 
the sites that build references. Measure the parse time of the TPC-DS queries 
and of statements with thousands of column references on the base branch and at 
head, report it in the PR, and note the remaining cost of the marker 
alternatives in the grammar comment.
   
   **Why this works:** Without the frames, a reference without '?' costs one 
lookahead check for the absent marker token. With them, it costs an extra rule 
invocation, a context object, two listener events, and, for 
leadingReferenceNamePart, a prediction between its alternatives. In the 
review's measurement, inlining cut the overhead on statements with thousands of 
column references from 9-14% to 6-7% of grammar parse time.
   
   **Scope:** Remove the per-reference rule frames that every parse pays for 
the optional-marker syntax, keeping primaryExpression under the JIT size limit.
   
   **Compatibility:** The plans and errors of every statement, with optional 
references on or off.
   
   **Risks:** The construct whose alternative moves out of primaryExpression 
pays one rule frame per occurrence instead. Even without the frames, the 
review's measurement kept about 3% of grammar parse time on the TPC-DS queries. 
That is the cost of the marker alternatives and predicates that the feature 
needs, and the grammar comment records it.
   
   **Constraints:** The generated primaryExpression method must stay under 
8,000 bytes of javac bytecode, or HotSpot does not compile it. Every statement, 
with optional references on or off, must produce the same plan and errors as 
before the change.
   
   **Exclusions:**
   - Removing the parse cost of the optional-marker alternatives and of the two 
semantic predicates, which the feature needs; the change documents that cost 
instead.
   
   **Success:** A column reference or field without '?' enters no grammar rule 
that the base grammar did not enter. The generated primaryExpression method is 
under 8,000 bytes of javac bytecode. The PR reports a parse-time comparison of 
the base branch and head for the TPC-DS queries and column-heavy statements, 
and the grammar comment states the remaining cost.
   
   **Verification:**
   - **Behavior:** With optional references on and off, the optional-reference 
parser suite and golden files give the same plans and errors as before the 
change, including the IN_DML and IN_DDL rejections.
   - **Inspection:** javap on the generated SqlBaseParser shows 
primaryExpression under 8,000 bytes of bytecode.
   - **Regression:** A parse-time measurement with optional references off, 
base branch against head, over the TPC-DS queries and statements with thousands 
of column references, shows the column-heavy overhead reduced to the cost of 
the marker alternatives.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8550,6 +8561,17 @@ 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 
it cannot be " +
+        "resolved, the reference evaluates to a NULL of type VOID instead of 
raising an error.")

Review Comment:
   **Nit (P3):** "when it cannot be resolved, ... instead of raising an error" 
promises more than the conf does. Only a name that matches nothing becomes 
NULL: the `OptionalReferences` object doc says ambiguity and type errors are 
still raised, and with the conf on the golden files record 
`AMBIGUOUS_REFERENCE`, `INVALID_EXTRACT_BASE_FIELD_TYPE`, and 
`MISSING_AGGREGATION` for optional references, as well as 
`OPTIONAL_COLUMN_REFERENCE_NOT_SUPPORTED` in DML, partition, and 
table-definition contexts. A reader of this doc would expect every resolution 
error to become NULL. The doc should say that the reference is NULL when no 
name matches the identifier, that ambiguous references and type errors are 
still raised, and which statements and clauses reject `?`: UPDATE, DELETE, 
MERGE, the condition of INSERT ... REPLACE, AUTO CDC flows, partition 
specifications, and table definitions.
   
   **Verification:**
   - **Inspection:** The conf doc limits the NULL result to identifiers that 
match no name. It names the statements and clauses that reject '?', consistent 
with the errors those contexts raise.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,377 @@
+/*
+ * 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 scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral
+}
+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.types.{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 an optional [[UnresolvedExtractValue]] as a last resort, see 
[[markLastResort]]. */
+  val LAST_RESORT: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReferenceLastResort")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   */
+  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
+
+  /**
+   * Marks the optional field extraction `extractValue` as one that no name 
resolution step of its
+   * operator could resolve, so that its missing field is NULL in the next 
step that resolves its
+   * child. Until then, a step whose errors are not final leaves it 
unresolved, like the same
+   * extraction without `?`, because a later step can still resolve it. For 
example, ORDER BY
+   * resolves names against the SELECT list before the columns of the FROM 
clause:
+   *
+   * {{{
+   *   -- `t.arr` is an ARRAY<STRUCT<a INT, b INT>>, so ORDER BY sorts by its 
field `b`.
+   *   SELECT array(named_struct('a', 1)) AS arr FROM t ORDER BY arr[0].b?;
+   * }}}
+   */
+  def markLastResort(extractValue: UnresolvedExtractValue): Unit =
+    extractValue.setTagValue(LAST_RESORT, ())
+
+  /** Returns true if `extractValue` is marked as a last resort, see 
[[markLastResort]]. */
+  def isLastResort(extractValue: UnresolvedExtractValue): Boolean =
+    extractValue.getTagValue(LAST_RESORT).isDefined
+
+  /** The static NULL of type VOID that an unresolvable optional reference 
resolves to. */
+  def nullReference(): Literal = {
+    val nullReference = Literal(null, NullType)
+    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.
+   */
+  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): Boolean = {
+    optionalNamePartIndices.nonEmpty &&
+    firstUnmatchedNamePartIndex(nameParts, attributes, resolver).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. Session variable qualifiers are 
valid paths too. 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): Option[Int] = {
+    val matchedNamePartCounts =
+      attributes.iterator.map(matchedNamePartCount(nameParts, _, resolver)) ++
+      
SESSION_VARIABLE_QUALIFIERS.iterator.map(matchedQualifierPartCount(nameParts, 
_, resolver))

Review Comment:
   **Nit (P3):** Only attribute paths and `system.session` / `session` count as 
matched qualifiers here, but SQL scripting variables can also be qualified by a 
compound label or a FOR variable: `VariableResolution.lookupVariable` resolves 
`label.var` through the scripting variable manager, and `ForStatementExec` 
declares each column of the current row in a scope labeled with the FOR 
variable name. Such a label counts as the first unmatched part (index 0, not 
optional), so the reference is not replaced with NULL.
   
   By the review's reading of the code, with optional references on, `BEGIN 
lbl: BEGIN DECLARE x INT DEFAULT 1; SELECT lbl.x?, lbl.y?; END; END` fails with 
`UNRESOLVED_COLUMN` for `lbl.y?`, and so does `FOR r AS SELECT id FROM people 
DO SELECT r.missing?; END FOR`, while the unqualified `local_unknown?` in the 
golden script and the session-qualified `session.unknown?` resolve to NULL. The 
same applies to `r.deleted_at?` in a FOR loop over `SELECT *` of a table that 
lacks the column. The failure is loud, and the unqualified form works.
   
   The fix is to count the label of an active scripting scope as a matched 
qualifier, the way `system.session` and `session` count; active scopes include 
the one a FOR statement labels with its variable name. Because 
`NameScopeStack.tryResolveOptionalReferenceAsNull` uses this helper too, that 
makes both references NULL in both analyzers.
   
   **Verification:**
   - **Behavior:** In a SQL script with optional references on, two optional 
references name something that does not exist: one is qualified by the label of 
an enclosing block and names an undeclared variable, the other is qualified by 
a FOR variable and names a column the loop query lacks. Both return NULL named 
after the last name part, while the same references to a declared variable and 
a present column return their values. With an active label, '?' on the label 
alone does not hide a missing variable.
   - **Compatibility:** A label-qualified reference without '?' to an 
undeclared variable still raises UNRESOLVED_COLUMN. So does other.y? when no 
active block or FOR variable is named other.



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:
##########
@@ -139,6 +140,31 @@ private[parser] class UpperCaseCharStream(wrapped: 
CodePointCharStream) extends
   }
 }
 
+/**
+ * Counts the `?` tokens that a parse uses as positional parameter markers. A 
parse of a statement
+ * that fails, or that uses a `?` in another way, uses fewer of them than the 
statement has.
+ */
+private class PositionalParameterMarkerCounter extends 
SqlBaseParserBaseListener {
+  var count: Int = 0
+
+  override def enterEveryRule(ctx: ParserRuleContext): Unit = {
+    // The parser enters a rule without a parent when it starts to parse the 
statement, which it
+    // does once in each stage of the two-stage parsing strategy.
+    if (ctx.getParent == null) {

Review Comment:
   **Nit (P3):** This reset is what lets a statement with a positional marker 
before an optional reference parse, but no test depends on it. If the count 
carried over from the failed SLL attempt into the LL attempt, `EXECUTE 
IMMEDIATE 'SELECT * FROM people WHERE id = ? AND deleted? IS NULL' USING 1` (or 
`SELECT ?, a? FROM t`) would count 2 of its 2 `?`, would not be parsed again, 
and would fail with `PARSE_SYNTAX_ERROR`, while every test still passed. In 
every test statement that needs the second parse (the parser suite's "stays 
one" cases, `EXECUTE IMMEDIATE 'SELECT id?, ? FROM people'`, `SET VAR known = 
coalesce(unknown?, ?)`, and the others), the first optional reference comes 
before every positional marker, so the failed parse counts no marker in either 
stage and the reset makes no difference.
   
   A parser-suite case such as `SELECT ?, a? FROM t`, asserting a positional 
parameter and an optional reference, and an EXECUTE IMMEDIATE golden case like 
the one above would cover it.
   
   **Verification:**
   - **Regression:** With optional references on, a statement in which a 
positional marker comes before an optional reference parses into a positional 
parameter and an optional reference. Its EXECUTE IMMEDIATE form with one value 
returns the row whose id matches, with the missing column evaluated as NULL. If 
the marker count of the failed SLL attempt carried over into the LL attempt, 
both would fail.



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:
##########
@@ -500,12 +526,17 @@ object AbstractParser extends Logging {
     parser.legacy_identifier_clause_only = conf.legacyIdentifierClauseOnly
     parser.single_character_pipe_operator_enabled = 
conf.singleCharacterPipeOperatorEnabled
     parser.file_type_enabled = conf.isFileTypeEnabled
+    parser.optional_references_enabled = conf.optionalReferencesEnabled
   }
 
   /**
    * Executes a parsing operation using the standard two-stage parsing 
strategy. This ensures
    * consistent error handling and performance optimization across all parsers.
    *
+   * If optional references (`x?`) are enabled, the operation is executed 
again with optional
+   * references if it does not use every `?` of the statement as a positional 
parameter marker
+   * without them, see [[restartWithOptionalReferences]].

Review Comment:
   **Nit (P3):** This doc and the `PositionalParameterMarkerCounter` doc (lines 
144-145) both misstate when the second parse runs. Here, a successful parse 
that consumes a `?` as free text, such as `SET key=a?b`, does not use it as a 
positional marker but is deliberately not executed again; only a successful 
parse that stops before a remaining `?` is (lines 561-567). The counter doc 
says that a parse that fails uses fewer markers than the statement has, but 
`SELECT ? FROM t WHERE` uses its only `?` as a marker and then fails, and the 
`Failure` branch (line 571) relies on exactly that case to rethrow the original 
syntax error. A maintainer who trusts either doc could, for example, parse 
every failed statement that contains a `?` again, which would replace the 
original syntax error of such statements. The `restartWithOptionalReferences` 
doc already states the trigger correctly.
   
   Suggested wording here; the counter doc's second sentence should instead say 
that a parse can use every `?` as a marker and still fail, as `SELECT ? FROM t 
WHERE` does:
   
   ```suggestion
      * If optional references (`x?`) are enabled, the operation is executed 
again with optional
      * references if it fails without using every `?` as a positional 
parameter marker, or if it
      * succeeds but stops before a `?` it did not parse, see 
[[restartWithOptionalReferences]].
   ```
   
   **Verification:**
   - **Inspection:** The method and counter docs describe when the second parse 
runs, including a failed parse that used every '?' as a positional marker and a 
successful parse that consumed a '?' as free text, and they match the branches 
the method implements.



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