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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,80 @@
+/*
+ * 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
+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. The source of a MERGE is checked too, like 
the source query of
+ * the SQL statement: `Dataset.mergeInto` and the Spark Connect MERGE command 
put the unanalyzed
+ * plan of the source DataFrame there, so its references are resolved as part 
of the MERGE.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ *   spark.sql("SELECT pk, is_deleted? FROM s").mergeInto("t", $"s.pk" === 
$"t.pk")...
+ * }}}
+ */
+object CheckOptionalReferencesInDml extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (plan.containsPattern(COMMAND)) {
+      plan.foreach { operator =>
+        statementName(operator).foreach { statement =>
+          operator.expressions.foreach(checkExpression(_, statement))
+        }
+        operator match {
+          case merge: MergeIntoTable =>
+            merge.sourceTable.foreach(_.expressions.foreach(checkExpression(_, 
"MERGE")))

Review Comment:
   Done, thanks for catching this. `CheckOptionalReferencesInDml` now also 
rejects, in the source of a `MergeIntoTable`, the NULL that an optional 
reference resolved to in a source operation that was analyzed before the MERGE 
was built (`OptionalReferences.isNullReference`: the `NULL_REFERENCE` tag on 
the NULL and on its implicit alias). The search does not enter a `View`, a 
`SQLFunctionNode`, or the body of a `SQLScalarFunction`, which resolve their 
own references, and it searches each subquery plan once. The class doc now says 
that only the last operation of a source DataFrame is sure to be unanalyzed, 
and why. So that the error points at the reference instead of the enclosing 
operator, `ResolveOptionalReferences` now creates the NULL and its implicit 
alias with the origin of the reference. No existing golden context changed.
   
   Two related holes turned up while doing this, and both are closed now:
   - Both analyzers created the VARIANT NULL of `missing?:a` without the tag, 
so `CAST(missing?:a AS BOOLEAN)` in an analyzed source operation would have 
passed. They now use `OptionalReferences.nullReference(VariantType)`.
   - The unresolved-reference search of the source used `foreach`, which does 
not visit the CTE plans that an unanalyzed `UnresolvedWith` keeps outside its 
children, so `spark.sql("WITH s AS (SELECT pk, archived? AS archived FROM 
source) SELECT * FROM s").mergeInto(...)` ran. It now uses the shared plan 
search, which visits them.
   
   Tests: in `MergeIntoDataFrameSuite`, a source with `archived?` in a 
`selectExpr` followed by `.as("s")`, or by `filter` and `.as("s")`, fails with 
IN_DML/MERGE and the fragment `archived?`, and so do the VARIANT path (fragment 
`missing?:a`) and the CTE source. Sources that read a view, a SQL scalar 
function, and a SQL table function whose bodies use `?`, each followed by 
`.as("s")`, still merge. The new `OptionalReferencesConnectSuite` (in-process 
Connect server and Scala client) checks that a source built with 
`withColumn("archived", expr("archived?"))` fails with IN_DML/MERGE and that 
the target keeps its row.
   
   One more case leaves no trace, beside the two the review excluded: in the 
default substitution mode, an unbound `:p?` in the SQL text of a source 
DataFrame becomes the text `NULL` before that text is parsed, so this check 
cannot tell it from a written NULL. The SQL MERGE statement still rejects `:p?`.



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

Review Comment:
   Done. `OptionalReferences.unresolvedOptionalReference(plan)` now skips the 
inner children that are the operator's own subquery plans (compared by 
identity), because the search of its expressions has covered them. The CTE 
plans of `UnresolvedWith` and the analyzed children of an `AnalysisOnlyCommand` 
are still searched, each once. The new `OptionalReferencesAnalysisSuite` builds 
20 levels of nested IN subqueries over a relation that counts its visits, and 
checks that `hasOptionalReferences` and `CheckOptionalReferencesInDml` on a 
`DeleteFromTable` visit every level once. With the double search, the deepest 
level would be visited 2^19 times. The CTE-in-subquery cases of the AUTO CDC 
handler test and the legacy binding cases in `ParametersSuite` still pass.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,360 @@
+/*
+ * 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.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
+        ) =>
+      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
+        }
+    }
+  }
+
+  /**
+   * Wraps the optional field extractions of the lowest operators of `plan` 
that are not resolved
+   * in [[LastResortExtractValue]].
+   */
+  private def wrapOptionalFieldsAsLastResort(plan: LogicalPlan): LogicalPlan = 
{
+    plan.resolveOperatorsDown {
+      case operator if operator.childrenResolved && !operator.resolved =>
+        operator.mapExpressions(wrapOptionalFields)
+    }
+  }
+
+  private def wrapOptionalFields(expression: Expression): Expression = 
expression match {
+    case lastResort: LastResortExtractValue =>
+      lastResort
+    case extractValue: UnresolvedExtractValue if 
OptionalReferences.isOptional(extractValue) =>
+      // The children are wrapped first, so the wrapped extraction is still an 
extraction.
+      LastResortExtractValue(
+        
extractValue.mapChildren(wrapOptionalFields).asInstanceOf[UnresolvedExtractValue])
+    case other if !other.resolved =>
+      other.mapChildren(wrapOptionalFields)
+    case other =>
+      other
+  }
+
+  /** Unwraps the extractions of `plan` that the analyzer did not resolve. */
+  private def unwrapLastResortExtractValues(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveExpressions {
+      case LastResortExtractValue(extractValue) => extractValue
+    }
+  }
+
+  /**
+   * Returns the attributes that the name resolution of `operator` can match a 
multipart name
+   * against: the output of its children, the attributes that `Sort`, 
`Filter`, HAVING, and
+   * QUALIFY can reference from below their child, the output of the subquery 
of a lateral join,
+   * and the attributes of the outer query of a subquery.
+   */
+  private def visibleAttributes(operator: LogicalPlan): Seq[Attribute] = {
+    val localAttributes = operator.children.flatMap(namedAttributes)
+    val attributesFromBelow = operator match {
+      case sort: Sort => attributesForMissingReferences(sort.child)
+      case filter: Filter => attributesForMissingReferences(filter.child)
+      case repartition: RepartitionByExpression =>
+        attributesForMissingReferences(repartition.child)
+      case qualify: UnresolvedQualify => 
attributesForMissingReferences(qualify.child)
+      case UnresolvedHaving(_, aggregate: Aggregate) => 
namedAttributes(aggregate.child)
+      case lateralJoin: LateralJoin => namedAttributes(lateralJoin.right.plan)
+      case _ => Seq.empty
+    }
+    val outerAttributes = AnalysisContext.get.outerPlan.toSeq.flatMap {
+      case having @ UnresolvedHaving(_, aggregate: Aggregate) =>
+        having.children.flatMap(namedAttributes) ++ 
namedAttributes(aggregate.child)
+      case outerPlan =>
+        outerPlan.children.flatMap(namedAttributes)
+    }
+    localAttributes ++ attributesFromBelow ++ outerAttributes
+  }
+
+  private def namedAttributes(plan: LogicalPlan): Seq[Attribute] =
+    plan.output ++ plan.metadataOutput
+
+  /**
+   * Returns the attributes below `plan` that a `Sort` or a `Filter` on top of 
`plan` can reference
+   * as missing attributes, mirroring 
`ColumnResolutionHelper.resolveExprsAndAddMissingAttrs`.
+   */
+  private def attributesForMissingReferences(plan: LogicalPlan): 
Seq[Attribute] = plan match {
+    case unary: UnaryNode
+        if !unary.isInstanceOf[Distinct] && !unary.isInstanceOf[SubqueryAlias] 
&&
+        !unary.isInstanceOf[PipeOperator] =>
+      namedAttributes(unary.child) ++ 
attributesForMissingReferences(unary.child)
+    case _ =>
+      Seq.empty
+  }
+}
+
+object ResolveOptionalReferences {
+
+  /**
+   * Returns true if `plan` or the plan of one of its subquery expressions has 
an optional
+   * reference that is not resolved and that the rule can still replace or 
wrap: an attribute, a
+   * named parameter marker, or a field extraction. Other unresolved nodes 
with an optional marker,
+   * such as a [[TempResolvedColumn]] that HAVING or ORDER BY tried, hold a 
reference that was
+   * found, and the rule leaves them to the rules that report their errors.
+   */
+  private def hasUnresolvedOptionalReferences(plan: LogicalPlan): Boolean = 
plan.exists {

Review Comment:
   Done. `hasUnresolvedOptionalReferences` now returns false for a resolved 
operator, and the new `isOrHasUnresolvedOptionalReference` returns false for a 
resolved expression or subquery expression, so the walk enters only unresolved 
operators, expressions, and subquery plans. For a V1 INSERT or CTAS, it stops 
at the resolved query instead of walking its whole analyzed lineage. The golden 
INSERT cases keep their results, and a new one, `INSERT OVERWRITE target SELECT 
id, addr FROM people WHERE id IN (SELECT id FROM people WHERE id = 1 AND 
missing? IS NULL)`, checks a missing optional reference in a subquery of the 
query of an INSERT into a V1 table.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,448 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import java.util.Locale
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.SqlScriptingContextManager
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util.{toPrettySQL, MetadataColumnHelper}
+import org.apache.spark.sql.connector.catalog.CatalogManager
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{NullType, StringType}
+
+/**
+ * Optional references: a `?` after an identifier of a column, field, or 
variable reference, or
+ * after a named parameter marker, makes that identifier optional. When name 
resolution finds no
+ * match for an optional identifier, the reference resolves to a static NULL 
of type VOID instead
+ * of raising a not-found error. Ambiguity and type errors are still raised.
+ *
+ * {{{
+ *   -- `t` has a column `id` but no column `name`:
+ *   SELECT id?, name? FROM t;
+ *   -- Project [id#1, null AS name#2]
+ * }}}
+ */
+object OptionalReferences {
+
+  /**
+   * Indices of the name parts of an unresolved multipart name (an 
`UnresolvedAttribute` or an
+   * `UnresolvedNamedLambdaVariable`) that are followed by `?`.
+   */
+  val OPTIONAL_NAME_PART_INDICES: TreeNodeTag[Set[Int]] =
+    TreeNodeTag[Set[Int]]("optionalNamePartIndices")
+
+  /**
+   * Marks an [[UnresolvedExtractValue]] field, a named parameter marker, or 
an IDENTIFIER clause
+   * followed by `?`.
+   */
+  val OPTIONAL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReference")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   *
+   * The two tags that the parser sets, [[OPTIONAL_NAME_PART_INDICES]] and 
[[OPTIONAL_REFERENCE]],
+   * describe the statement: they are facts about the reference as written, 
which stay true in
+   * every analysis of the plan. The generic transforms of a tree copy them to 
the nodes that
+   * replace a tagged node; a rule that rebuilds a reference in another way 
forwards them with

Review Comment:
   Done. The paragraph now says that a rule that rebuilds a reference in 
another way forwards 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`. The PR 
description's Tags paragraph says the same.



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

Review Comment:
   Done. The doc now says that the implicit alias that names such a NULL 
matches too, and that `isNullReferenceAlias` tells the alias apart. The new 
MERGE source check relies on both and rejects whichever of the two it reaches 
first.



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

Review Comment:
   Done. The optional-field comment now sits directly above 
`optionalNamePartIndices`, and the UDF precedence comment is back directly 
above `resolveColumnByName` and the match on SQL function parameter aliases, 
where it is on master, so this block's diff is only the two added statements.



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