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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SubstituteParamsParser.scala:
##########
@@ -134,11 +164,16 @@ class SubstituteParamsParser extends Logging {
         case Some(value) =>
           // Substitute all occurrences of this parameter
           locationList.foreach { location =>
-            substitutions += Substitution(location, value)
+            substitutions += Substitution(location, namedReplacement(sqlText, 
location, value))

Review Comment:
   **[P1] Preserve the selected interpretation after parameter substitution**
   
   The substitution parse selects optional-reference mode, interpreting 
DISTINCT? as a column reference. Replacing :x? removes the syntax that forced 
that mode. SparkSqlParser.parseInternal subsequently calls super.parse on the 
resulting text independently, so first(DISTINCT ?) now parses with a positional 
parameter. That marker was never substituted, and CheckAnalysis raises 
UNBOUND_SQL_PARAMETER. Preserve the original parse decisions through 
substitution and final parsing.
   
   **Failure scenario:** With optional references enabled and default parameter 
substitution, spark.sql("SELECT :x? AS a, first(DISTINCT ?) AS f FROM VALUES 
(2) AS t(`distinct`)", Map("x" -> 1)) fails with UNBOUND_SQL_PARAMETER instead 
of returning (1, 2).



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,557 @@
+/*
+ * 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,
+  SupervisingCommand,
+  WithWindowDefinition
+}
+import org.apache.spark.sql.catalyst.trees.{Origin, 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 the tags of a 
node to the node that
+   * replaces it, but only if that node has no tags of its own, see 
`TreeNode.copyTagsFrom`. 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` into the 
new node. This tag
+   * records a decision of one analysis, that a reference matched nothing, on 
the NULL and the alias
+   * that this analysis creates, like [[RESOLVED_NULL_REFERENCE]] on the plan 
that it returns. Only
+   * the analyzer sets them, 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")
+
+  /**
+   * Marks the root of the plan that an analysis returned, with the origin of 
the first optional
+   * reference of the analyzed plan that the analysis resolved to a 
[[nullReference]], see
+   * [[markResolvedNullReference]]. The rest of the analysis can replace that 
NULL, e.g. by folding
+   * an extraction from it, the IF whose condition it is, or the row of an 
inline table that holds
+   * it, so the mark is what keeps the decision for 
`CheckOptionalReferencesInDml`, which reads it
+   * in the analyzed operations of a MERGE source. The optional references of 
the body of a view
+   * or SQL function that the plan reads do not count: that body is analyzed 
in an analysis
+   * context of its own.
+   *
+   * The generic transforms of a later analysis copy the mark to the node that 
replaces a marked
+   * one only if that node has no tags of its own, see 
`TreeNode.copyTagsFrom`; a node with a
+   * Dataset id or a Spark Connect plan id has some. So code outside of the 
analyzer that replaces
+   * or rebuilds an analyzed node, e.g. with a case class copy, must keep the 
mark of the node that
+   * it replaces with [[withResolvedNullReferenceOf]], which also sets it on a 
node with other tags,
+   * as the union flattening and the join rewrites of `Dataset` do.
+   */
+  val RESOLVED_NULL_REFERENCE: TreeNodeTag[Origin] =
+    TreeNodeTag[Origin]("optionalReferenceResolvedNull")
+
+  /** 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 anywhere, see
+   * [[unresolvedOptionalReference]]. 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 and expressions that 
an operator keeps
+   * outside of its children and expressions, or None: the common table 
expressions of
+   * `UnresolvedWith`, the query of a command such as EXPLAIN or DESCRIBE 
QUERY, and the window
+   * specifications of a WINDOW clause.
+   */
+  def unresolvedOptionalReference(plan: LogicalPlan): Option[Expression] = {
+    val expressions = plan match {
+      case withWindows: WithWindowDefinition =>
+        plan.expressions ++ withWindows.windowDefinitions.values
+      case _ =>
+        plan.expressions
+    }
+    val supervisedPlans = plan match {
+      case command: SupervisingCommand => Seq(supervisedPlan(command))
+      case _ => Nil
+    }
+    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 ++ supervisedPlans).iterator
+          .flatMap(child => unresolvedOptionalReference(child))
+          .nextOption()
+      }
+  }
+
+  /** Returns the plan that `command` supervises, which is not a child of the 
command. */
+  private def supervisedPlan(command: SupervisingCommand): LogicalPlan = {
+    var supervisedPlan: LogicalPlan = null
+    command.withTransformedSupervisedPlan { plan =>
+      supervisedPlan = plan
+      plan
+    }
+    supervisedPlan
+  }
+
+  /**
+   * 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, ())
+    AnalysisContext.get.nullReferenceOrigins += nullReference.origin
+    nullReference
+  }
+
+  /**
+   * Marks `analyzed`, the plan that an analysis of `plan` returned, with
+   * [[RESOLVED_NULL_REFERENCE]] if the analysis resolved an optional 
reference of `plan` to a
+   * [[nullReference]] and built `analyzed`. A node of `plan` is never marked: 
`plan` can be
+   * analyzed again later, e.g. from a plan cache, and its analyzed nodes 
belong to other plans as
+   * well, such as the plan of the Dataset that a drop returns when it drops 
nothing. The NULL is
+   * not a part of such a node.
+   */
+  def markResolvedNullReference(plan: LogicalPlan, analyzed: LogicalPlan): 
Unit = {
+    AnalysisContext.get.nullReferenceOrigins.headOption.foreach { origin =>
+      if (!plan.exists(_ eq analyzed)) {
+        analyzed.setTagValue(RESOLVED_NULL_REFERENCE, origin)
+      }
+    }
+  }
+
+  /**
+   * Gives `plan`, which a rewrite outside of the analyzer built to replace 
the analyzed plans
+   * `replaced`, the first [[RESOLVED_NULL_REFERENCE]] mark of them, unless 
`plan` has one. Other
+   * tags stay where they are, e.g. the ids of the Datasets that the self-join 
detection reads.
+   */
+  def withResolvedNullReferenceOf[T <: LogicalPlan](plan: T, replaced: 
LogicalPlan*): T = {
+    if (resolvedNullReferenceOrigin(plan).isEmpty) {
+      
replaced.iterator.flatMap(resolvedNullReferenceOrigin).nextOption().foreach { 
origin =>
+        plan.setTagValue(RESOLVED_NULL_REFERENCE, origin)
+      }
+    }
+    plan
+  }
+
+  /** Returns the origin of the [[RESOLVED_NULL_REFERENCE]] mark of `plan`, or 
None. */
+  def resolvedNullReferenceOrigin(plan: LogicalPlan): Option[Origin] =
+    plan.getTagValue(RESOLVED_NULL_REFERENCE)
+
+  /**
+   * 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 a name is on the path 
of a qualifier only
+   * if it has a name part after the whole qualifier. Otherwise `?` would turn 
a column or variable
+   * that exists into NULL, as in `default.id?` or `system.v?`, which fail 
without `?` because
+   * `default` and `system` alone are not qualifiers.
+   * 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` is the table `spark_catalog.default.t` with the columns `id` and
+   *   -- `addr STRUCT<city STRING>`:
+   *   t.name          -- 1: `t` matches the qualifier of `id`, `name` matches 
nothing
+   *   default.t.name  -- 2
+   *   ghost.id        -- 0
+   *   default.id      -- 0: `default` is not a qualifier without `t`
+   *   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

Review Comment:
   **[P1] Reject ambiguous bases before replacing nested references with NULL**
   
   The longest-prefix calculation checks attributes independently without 
preserving ambiguity between matching base columns. ORDER BY resolution uses 
resolveExpressionByPlanOutput with throws=false, which catches the ambiguous 
lookup and leaves the reference unresolved. visibleAttributes then supplies 
both structs here; each matches s but lacks y, so resolvesToNull accepts 
optional index 1 and replaces the ambiguous reference with NULL. The 
single-pass fallback reaches the same decision. Check ambiguity before allowing 
this fallback.
   
   **Failure scenario:** With optional references enabled, SELECT 1 FROM 
VALUES(named_struct('x', 1)) AS l(s) CROSS JOIN VALUES(named_struct('x', 2)) AS 
r(s) ORDER BY s.y? succeeds with a NULL sort key instead of rejecting the 
ambiguous s reference.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.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 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))

Review Comment:
   **[P1] Validate API-created defaults before resolving optional references**
   
   Catalog.createTable constructs ColumnDefinition through fromV1Column, which 
parses the default using parseExpression. Consequently, the parser validator 
never sees a DefaultExpressionContext. This generic replacement traverses 
DefaultValueExpression and converts missing? to NULL; type coercion and 
CreateTableHelper.constantFoldDefaultValue then accept it as a constant. Add 
analyzer-level validation so API-created defaults receive the same IN_DDL 
rejection as SQL defaults.
   
   **Failure scenario:** With optional references enabled, construct 
StructField("v", 
IntegerType).withCurrentDefaultValue("missing?").withExistenceDefaultValue("NULL")
 and pass its StructType to spark.catalog.createTable("t", "parquet", schema, 
Map.empty[String, String]). The table is created with a NULL default instead of 
OPTIONAL_REFERENCE_NOT_SUPPORTED.IN_DDL.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/SemiStructuredExtract.scala:
##########
@@ -50,7 +51,11 @@ case object ExtractSemiStructuredFields extends 
Rule[LogicalPlan] {
   override def apply(plan: LogicalPlan): LogicalPlan = 
plan.resolveExpressionsWithPruning(
     _.containsPattern(SEMI_STRUCTURED_EXTRACT), ruleId) {
     case SemiStructuredExtract(column, field) if column.resolved =>
-      if (column.dataType.isInstanceOf[VariantType]) {
+      if (OptionalReferences.isNullReference(column)) {

Review Comment:
   **[P1] Preserve optional NULL provenance through intermediate extraction**
   
   An intermediate subscript loses the NULL_REFERENCE marker required by this 
check. After arr? becomes a tagged NULL, ExtractValue.applyOrNull creates a 
fresh, untagged NULL. ColumnResolutionHelper.resolveExtractValue wraps it in an 
unmarked alias, so this rule reaches COLUMN_IS_NOT_VARIANT_TYPE. 
ExtractValueResolver and SemiStructuredExtractResolver have the same problem in 
single-pass analysis. Preserve the optional origin through NULL-propagating 
extraction.
   
   **Failure scenario:** With optional references enabled, SELECT arr?[0]:a 
FROM VALUES (1) AS t(id) raises COLUMN_IS_NOT_VARIANT_TYPE instead of returning 
NULL when the optional ARRAY<VARIANT> column is absent.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.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 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,
+   * DISTRIBUTE BY, 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] = {

Review Comment:
   **[P2] Design: visibleAttributes keeps a hand-copied list of the analyzer's 
name sources**
   
   `visibleAttributes` and `attributesForMissingReferences` (:251-288) rebuild 
by hand which attributes each operator's name resolution can reach:
   - the descent stop condition `UnaryNode && !Distinct && !SubqueryAlias && 
!PipeOperator` is copied from 
`ColumnResolutionHelper.resolveExprsAndAddMissingAttrs` 
(ColumnResolutionHelper.scala:57-61); the scaladoc at :277 says it is mirroring 
that method;
   - the Sort, Filter, RepartitionByExpression, UnresolvedQualify and 
UnresolvedHaving sources repeat the cases of ResolveReferences 
(Analyzer.scala:2016-2061);
   - the outer-plan special case for `UnresolvedHaving` (:263-268) repeats 
`resolveOuterRef` (ColumnResolutionHelper.scala:315-328).
   
   Nothing ties the copy to the originals. Fix: move the descent predicate into 
a shared helper in ColumnResolutionHelper (for example 
`canAddMissingAttrsThrough(plan)`) that both `resolveExprsAndAddMissingAttrs` 
and this rule call. Ideally, get the candidate attributes from the same code 
ResolveReferences and resolveOuterRef use to resolve names.
   
   **Why it matters:** These attributes decide between "not found" (NULL) and 
"found but unusable" (error kept, e.g. MISSING_AGGREGATION). Suppose a later 
change lets one more operator resolve names from below, or changes the HAVING 
or outer-reference sources, and this list is not updated. Then `?` hides real 
errors behind a NULL, against the PR's stated rule that only not-found errors 
are suppressed.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8749,6 +8714,33 @@ 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, metric view definitions, and the DEFAULT, GENERATED 
ALWAYS AS, CHECK, " +
+        "and OPTIONS clauses of table and function definitions reject optional 
references.")
+      .version("4.4.0")

Review Comment:
   **[P2] New confs and migration note use 4.4.0, but the first release is 
4.5.0**
   
   The three new confs use `.version("4.4.0")`: the single-pass analyzer 
optional-references conf (line 642), spark.sql.optionalReferences.enabled (line 
8727), and spark.sql.legacy.sqlFunctionBodyResolvesOuterReferences (line 8739). 
The migration guide entry for the default-on SQL function behavior change is 
under 'Upgrading from Spark SQL 4.3 to 4.4'. branch-4.4 has already been cut, 
and `dev/next_version_candidates.py` prints `branch-4.x 4.5.0` (branch-4.x pom 
is 4.5.0-SNAPSHOT). The repo's CLAUDE.md rule says a master PR that is not 
master-only should use the branch-<N>.x version. So this feature and its 
behavior change first ship in 4.5.0, and the conf metadata and the migration 
guide give the wrong version.
   
   **Failure scenario:** After merge to master and branch-4.x, users upgrading 
from 4.4 to 4.5 find the change to SQL function outer-reference resolution, and 
its legacy conf, listed under the 4.3 to 4.4 section. They upgrade from 4.3 to 
4.4 expecting the change, and it is not there.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,557 @@
+/*
+ * 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,
+  SupervisingCommand,
+  WithWindowDefinition
+}
+import org.apache.spark.sql.catalyst.trees.{Origin, 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 the tags of a 
node to the node that
+   * replaces it, but only if that node has no tags of its own, see 
`TreeNode.copyTagsFrom`. 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` into the 
new node. This tag
+   * records a decision of one analysis, that a reference matched nothing, on 
the NULL and the alias
+   * that this analysis creates, like [[RESOLVED_NULL_REFERENCE]] on the plan 
that it returns. Only
+   * the analyzer sets them, 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")
+
+  /**
+   * Marks the root of the plan that an analysis returned, with the origin of 
the first optional
+   * reference of the analyzed plan that the analysis resolved to a 
[[nullReference]], see
+   * [[markResolvedNullReference]]. The rest of the analysis can replace that 
NULL, e.g. by folding
+   * an extraction from it, the IF whose condition it is, or the row of an 
inline table that holds
+   * it, so the mark is what keeps the decision for 
`CheckOptionalReferencesInDml`, which reads it
+   * in the analyzed operations of a MERGE source. The optional references of 
the body of a view
+   * or SQL function that the plan reads do not count: that body is analyzed 
in an analysis
+   * context of its own.
+   *
+   * The generic transforms of a later analysis copy the mark to the node that 
replaces a marked
+   * one only if that node has no tags of its own, see 
`TreeNode.copyTagsFrom`; a node with a
+   * Dataset id or a Spark Connect plan id has some. So code outside of the 
analyzer that replaces
+   * or rebuilds an analyzed node, e.g. with a case class copy, must keep the 
mark of the node that
+   * it replaces with [[withResolvedNullReferenceOf]], which also sets it on a 
node with other tags,
+   * as the union flattening and the join rewrites of `Dataset` do.
+   */
+  val RESOLVED_NULL_REFERENCE: TreeNodeTag[Origin] =
+    TreeNodeTag[Origin]("optionalReferenceResolvedNull")
+
+  /** 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 anywhere, see
+   * [[unresolvedOptionalReference]]. 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 and expressions that 
an operator keeps
+   * outside of its children and expressions, or None: the common table 
expressions of
+   * `UnresolvedWith`, the query of a command such as EXPLAIN or DESCRIBE 
QUERY, and the window
+   * specifications of a WINDOW clause.
+   */
+  def unresolvedOptionalReference(plan: LogicalPlan): Option[Expression] = {
+    val expressions = plan match {
+      case withWindows: WithWindowDefinition =>
+        plan.expressions ++ withWindows.windowDefinitions.values
+      case _ =>
+        plan.expressions
+    }
+    val supervisedPlans = plan match {
+      case command: SupervisingCommand => Seq(supervisedPlan(command))
+      case _ => Nil
+    }
+    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 ++ supervisedPlans).iterator
+          .flatMap(child => unresolvedOptionalReference(child))
+          .nextOption()
+      }
+  }
+
+  /** Returns the plan that `command` supervises, which is not a child of the 
command. */
+  private def supervisedPlan(command: SupervisingCommand): LogicalPlan = {
+    var supervisedPlan: LogicalPlan = null
+    command.withTransformedSupervisedPlan { plan =>
+      supervisedPlan = plan
+      plan
+    }
+    supervisedPlan
+  }
+
+  /**
+   * 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, ())
+    AnalysisContext.get.nullReferenceOrigins += nullReference.origin
+    nullReference
+  }
+
+  /**
+   * Marks `analyzed`, the plan that an analysis of `plan` returned, with
+   * [[RESOLVED_NULL_REFERENCE]] if the analysis resolved an optional 
reference of `plan` to a
+   * [[nullReference]] and built `analyzed`. A node of `plan` is never marked: 
`plan` can be
+   * analyzed again later, e.g. from a plan cache, and its analyzed nodes 
belong to other plans as
+   * well, such as the plan of the Dataset that a drop returns when it drops 
nothing. The NULL is
+   * not a part of such a node.
+   */
+  def markResolvedNullReference(plan: LogicalPlan, analyzed: LogicalPlan): 
Unit = {
+    AnalysisContext.get.nullReferenceOrigins.headOption.foreach { origin =>
+      if (!plan.exists(_ eq analyzed)) {
+        analyzed.setTagValue(RESOLVED_NULL_REFERENCE, origin)
+      }
+    }
+  }
+
+  /**
+   * Gives `plan`, which a rewrite outside of the analyzer built to replace 
the analyzed plans
+   * `replaced`, the first [[RESOLVED_NULL_REFERENCE]] mark of them, unless 
`plan` has one. Other
+   * tags stay where they are, e.g. the ids of the Datasets that the self-join 
detection reads.
+   */
+  def withResolvedNullReferenceOf[T <: LogicalPlan](plan: T, replaced: 
LogicalPlan*): T = {
+    if (resolvedNullReferenceOrigin(plan).isEmpty) {
+      
replaced.iterator.flatMap(resolvedNullReferenceOrigin).nextOption().foreach { 
origin =>
+        plan.setTagValue(RESOLVED_NULL_REFERENCE, origin)
+      }
+    }
+    plan
+  }
+
+  /** Returns the origin of the [[RESOLVED_NULL_REFERENCE]] mark of `plan`, or 
None. */
+  def resolvedNullReferenceOrigin(plan: LogicalPlan): Option[Origin] =
+    plan.getTagValue(RESOLVED_NULL_REFERENCE)
+
+  /**
+   * 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 a name is on the path 
of a qualifier only
+   * if it has a name part after the whole qualifier. Otherwise `?` would turn 
a column or variable
+   * that exists into NULL, as in `default.id?` or `system.v?`, which fail 
without `?` because
+   * `default` and `system` alone are not qualifiers.
+   * 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` is the table `spark_catalog.default.t` with the columns `id` and
+   *   -- `addr STRUCT<city STRING>`:
+   *   t.name          -- 1: `t` matches the qualifier of `id`, `name` matches 
nothing
+   *   default.t.name  -- 2
+   *   ghost.id        -- 0
+   *   default.id      -- 0: `default` is not a qualifier without `t`
+   *   addr.zip        -- 1
+   *   t               -- 0: `t` is not a column
+   * }}}
+   */
+  def firstUnmatchedNamePartIndex(

Review Comment:
   **[P1] Design: firstUnmatchedNamePartIndex reimplements attribute and 
variable name matching, and already disagrees with VariableResolution**
   
   `firstUnmatchedNamePartIndex` and its helpers (`matchedNamePartCount` :488, 
`matchedQualifierPartCount` :515, `SESSION_VARIABLE_QUALIFIERS` :115, 
`matchedScriptingScopeLabelCount` :404) are a second implementation of the 
rules that decide which name parts of a multipart name match a reference:
   - qualifier-suffix matching and `qualifiedAccessOnly` filtering duplicate 
`AttributeSeq.matchWithThreeOrLessQualifierParts` and 
`matchWithFourOrMoreQualifierParts` (expressions/package.scala:191, :285);
   - the `system.session` / `session` qualifier check duplicates 
`VariableResolution.maybeTempVariableName` (VariableResolution.scala:219);
   - the scope-label normalization duplicates `lookupVariable`, as the comment 
at :406 says.
   
   The copies already disagree. `maybeTempVariableName` compares `system` and 
`session` with `equalsIgnoreCase`, and `TempVariableManager.get` only looks at 
`nameParts.last` (VariableManager.scala:155). So with 
`spark.sql.caseSensitive=true`, `SESSION.v` resolves to variable `v`. The new 
code compares those qualifiers with `conf.resolver`. So in that mode 
`session.undeclared?` gives NULL, but `SESSION.undeclared?` raises 
UNRESOLVED_COLUMN, because index 0 is the unmatched part and it is not 
optional. The single-pass resolver 
(`NameScopeStack.tryResolveOptionalReferenceAsNull`) inherits the same rule.
   
   Fix: compute the index from the existing resolvers instead of a parallel 
matcher. For example, take the longest prefix of `nameParts` that 
`AttributeSeq.getCandidatesForResolution` or 
`VariableResolution.lookupVariable` resolves. Have `VariableResolution` expose 
its qualifier and label check (for example `isVariableQualifier(prefix)`) so 
the session and scripting qualifier rules live in one place.
   
   **Why it matters:** The PR's main promise is that `?` changes only not-found 
errors and that a name that resolves without `?` resolves the same way with it. 
With these rules copied, any later change to qualifier, variable or label 
resolution has to be made twice. If it isn't, `?` quietly turns a reference 
into NULL, or fails to. The case-sensitivity mismatch above shows this has 
already happened.



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