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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,301 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.expressions.{
+  Attribute,
+  Expression,
+  LambdaFunction,
+  LateralColumnAliasReference,
+  NamedExpression,
+  PipeOperator,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  Aggregate,
+  Distinct,
+  Filter,
+  LateralJoin,
+  LogicalPlan,
+  RepartitionByExpression,
+  Sort,
+  SubqueryAlias,
+  UnaryNode
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{PARAMETERIZED_QUERY, 
PLAN_EXPRESSION}
+
+/**
+ * Replaces the optional references that the fixed-point "Resolution" batch 
could not resolve
+ * with a static NULL, and then resolves the plan again with `resolveAgain`.
+ *
+ * {{{
+ *   -- `t` has no column `name`:
+ *   SELECT id, name? FROM t;
+ *   -- Project [id#1, 'name] becomes Project [id#1, null AS name#2]
+ * }}}
+ *
+ * Only the expressions of operators with resolved children are replaced, 
because a reference in
+ * an operator with unresolved children can still resolve once the children 
are resolved. The
+ * rule is meant to run in a fixed-point batch: every application replaces the 
references of the
+ * lowest operators that cannot be resolved, which can make the operators 
above them resolvable.
+ * References that a later resolution step is still waiting for, such as the 
body of an unbound
+ * lambda function or a lateral column alias reference, are left in place.
+ *
+ * The analyzer resolves the plan of a subquery expression on its own, while 
the operator of the
+ * subquery expression is still being resolved. A reference of the subquery 
that is unresolved at
+ * the end of that can still resolve later, e.g. once the outer query binds 
its parameter markers
+ * or resolves the alias of a generator. The rule therefore only replaces the 
references of a
+ * subquery plan after it could not resolve the operator of the subquery 
expression, which it
+ * signals by wrapping the subquery plan in 
[[ResolveOptionalReferencesInSubquery]].
+ */
+class ResolveOptionalReferences(resolveAgain: LogicalPlan => LogicalPlan)
+    extends Rule[LogicalPlan] {
+  import ResolveOptionalReferences._
+
+  override def apply(plan: LogicalPlan): LogicalPlan = plan match {
+    case subquery: ResolveOptionalReferencesInSubquery =>
+      val resolvedPlan = replaceAndResolveAgain(subquery.child)
+      if (resolvedPlan.fastEquals(subquery.child)) subquery.child else 
subquery.copy(resolvedPlan)
+    case _ if plan.resolved || isPlanOfSubquery || 
plan.containsPattern(PARAMETERIZED_QUERY) =>
+      plan
+    case _ if hasUnresolvedOptionalReferences(plan) =>
+      replaceAndResolveAgain(plan)
+    case _ =>
+      plan
+  }
+
+  private def replaceAndResolveAgain(plan: LogicalPlan): LogicalPlan = {
+    val replacedPlan = replaceUnresolvableOptionalReferences(plan)
+    val resolvedPlan = if (replacedPlan.fastEquals(plan)) {
+      plan
+    } else {
+      unwrapSubqueryPlans(resolveAgain(replacedPlan))
+    }
+    if (!resolvedPlan.fastEquals(plan)) {
+      resolvedPlan
+    } else if (markOptionalFieldsAsLastResort(plan)) {
+      resolveAgain(plan)
+    } else {
+      plan
+    }
+  }
+
+  /**
+   * Replaces the optional references of the lowest operators of `plan` that 
are not resolved, and
+   * wraps the unresolved plans of their subquery expressions for the analysis 
of these plans.
+   *
+   * The traversal is top-down so that an operator is only considered while 
its children are the
+   * ones that the "Resolution" batch resolved its references against. An 
operator above a
+   * replaced one waits for `resolveAgain`, which can still resolve its 
references in other ways,
+   * for example as lateral column aliases or as variables.
+   */
+  private def replaceUnresolvableOptionalReferences(plan: LogicalPlan): 
LogicalPlan = {
+    plan.resolveOperatorsDown {
+      case aggregate: Aggregate
+          if aggregate.childrenResolved && 
!aggregate.aggregateExpressions.forall(_.resolved) =>
+        replaceInAggregateExpressions(aggregate)
+      case lateralJoin: LateralJoin
+          if lateralJoin.left.resolved && !lateralJoin.right.plan.resolved =>
+        // The join condition can reference the output of the subquery, which 
is not known yet.
+        if (hasUnresolvedOptionalReferences(lateralJoin.right.plan)) {
+          lateralJoin.copy(right = wrapSubqueryPlan(lateralJoin.right))
+        } else {
+          lateralJoin
+        }
+      case operator if operator.childrenResolved && !operator.resolved =>
+        lazy val attributes = visibleAttributes(operator)
+        operator.mapExpressions(replace(_, attributes, isTopLevel = true))
+    }
+  }
+
+  /**
+   * Replaces the optional references in the aggregate expressions of 
`aggregate` only, because
+   * its grouping expressions can reference aliases of the aggregate 
expressions, which can only
+   * be resolved once all the aggregate expressions are resolved.
+   *
+   * {{{
+   *   -- `archived` in GROUP BY resolves to the alias `archived` of the 
SELECT list.
+   *   SELECT coalesce(archived?, false) AS archived FROM t GROUP BY archived?;
+   * }}}
+   */
+  private def replaceInAggregateExpressions(aggregate: Aggregate): Aggregate = 
{
+    lazy val attributes = visibleAttributes(aggregate)
+    aggregate.copy(aggregateExpressions = aggregate.aggregateExpressions.map { 
expression =>
+      replace(expression, attributes, isTopLevel = 
true).asInstanceOf[NamedExpression]
+    })
+  }
+
+  /**
+   * Replaces the optional references of `expression` that resolve to NULL 
against `attributes`.
+   * A top-level reference keeps its name through an [[Alias]] of its last 
name part.
+   */
+  private def replace(
+      expression: Expression,
+      attributes: => Seq[Attribute],
+      isTopLevel: Boolean): Expression = expression match {
+    case unresolvedAttribute: UnresolvedAttribute
+        if 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute).nonEmpty &&
+        OptionalReferences.resolvesToNull(
+          nameParts = unresolvedAttribute.nameParts,
+          optionalNamePartIndices = 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute),
+          attributes = attributes,
+          resolver = conf.resolver
+        ) =>
+      val nullReference = OptionalReferences.nullReference()
+      if (isTopLevel) {
+        OptionalReferences.implicitAlias(nullReference, 
unresolvedAttribute.nameParts.last)
+      } else {
+        nullReference
+      }
+    case namedParameter: NamedParameter if 
OptionalReferences.isOptional(namedParameter) =>
+      OptionalReferences.nullReference()
+    case lambdaFunction: LambdaFunction if !lambdaFunction.bound =>
+      lambdaFunction
+    case lateralColumnAliasReference: LateralColumnAliasReference =>
+      lateralColumnAliasReference
+    case subquery: SubqueryExpression if 
hasUnresolvedOptionalReferences(subquery.plan) =>
+      wrapSubqueryPlan(subquery)
+    case other if !other.resolved =>
+      other.mapChildren(replace(_, attributes, isTopLevel = false))
+    case other =>
+      other
+  }
+
+  private def wrapSubqueryPlan[T <: SubqueryExpression](subquery: T): T = 
subquery.plan match {
+    case _: ResolveOptionalReferencesInSubquery => subquery
+    case plan => 
subquery.withNewPlan(ResolveOptionalReferencesInSubquery(plan)).asInstanceOf[T]
+  }
+
+  /**
+   * Unwraps the subquery plans of `plan` that are still wrapped because the 
analyzer did not
+   * resolve them again.
+   */
+  private def unwrapSubqueryPlans(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveExpressionsWithPruning(_.containsPattern(PLAN_EXPRESSION)) {
+      case subquery: SubqueryExpression =>
+        subquery.plan match {
+          case wrapped: ResolveOptionalReferencesInSubquery => 
subquery.withNewPlan(wrapped.child)
+          case _ => subquery
+        }
+    }
+  }
+
+  /**
+   * Marks the optional field extractions of the lowest operators of `plan` 
that are not resolved
+   * as a last resort, and returns whether it marked any. See
+   * [[OptionalReferences.markLastResort]].
+   */
+  private def markOptionalFieldsAsLastResort(plan: LogicalPlan): Boolean = {
+    var marked = false
+    plan.foreach { operator =>
+      if (operator.childrenResolved && !operator.resolved) {
+        operator.expressions.foreach(_.foreach {
+          case extractValue: UnresolvedExtractValue
+              if OptionalReferences.isOptional(extractValue) &&
+              !OptionalReferences.isLastResort(extractValue) =>
+            OptionalReferences.markLastResort(extractValue)

Review Comment:
   Thanks, the fix looks right, and no Spark Connect-level test is needed. The 
Connect plan cache hands back the same unresolved `LogicalPlan` object for a 
repeated relation (`SessionHolder.usePlanCache` stores what 
`SparkConnectPlanner.transformRelation` builds), and the server analyzes that 
object again through a new `QueryExecution`, the same path that 
`Dataset.ofRows` takes in the new `OptionalReferencesSuite` test when it 
analyzes one unresolved plan instance twice. A Connect-level test would analyze 
the same object the same way, so it would not catch anything that test misses.
   
   <!-- SPARK_DEV_REVIEW_REPLY 
{"feedback_id":"inline:4559147404","thread_id":"inline:4559147404","verdict_sha256":"1c8581c81fca34f7503580e0ea5580ec71d3d050c813e1b6b52cea00909d8c5e"}
 -->



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

Review Comment:
   **Non-blocking (P2):** Thanks for inlining the marker and measuring it. The 
remaining cost is still paid by every parse, with the conf on or off and for 
statements that never use `?`: the marker alternatives after `#columnReference` 
and `#dereference`, the `#optionalIdentifierClause` alternative in 
`primaryExpression`'s prediction, and the predicates on the IN-list alternative 
and in the `stringLit` loop. Your numbers put it at +2.1% on the TPC-DS 
queries, about 1.8 microseconds per query, and up to +8.6% on 1,000 nested 
fields, growing with the number of references. Parsing is a small part of query 
compilation, but this cost lands on statements outside the feature, and the 
comment above `overlayExpression` records that the alternatives cost a 
lookahead check without saying why the cost has to stay: removing it would take 
a separate generated parser for the second stage, which `AstBuilder` cannot 
visit and whose grammar would have to accept every statement without `?` 
exactly as t
 his one does.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4559147424).
   
   **Recommended change:** Keep the marker alternatives and the two predicates 
in the shared generated parser, and extend the grammar comment above 
overlayExpression so it says why their cost stays: AstBuilder visits the same 
generated contexts in both parse stages, and keeping the syntax out of 
first-stage and conf-off parses would need a second generated parser for the 
second stage, which AstBuilder cannot visit and whose grammar would have to 
accept every statement without `?` exactly as this one does. State the measured 
cost with the conf off, from +2.1% on the TPC-DS queries to +8.6% on 1,000 
nested fields of grammar parse time.
   
   **Why this works:** The comment records the cost and the reason it is kept 
where the next change to these alternatives is made, so a later cleanup does 
not trade it for a second grammar, or add rule frames back, without seeing the 
measured trade-off.
   
   **Scope:** Document in the grammar why the optional-reference parse cost 
stays in the shared parser.
   
   **Risks:** Every statement keeps the measured parse cost with the conf on or 
off; a parser used only by the second stage can still remove it later.
   
   **Constraints:** The generated primaryExpression method stays under 8,000 
bytes of bytecode.
   
   **Exclusions:**
   - Removing the parse cost of the marker alternatives and predicates, which 
would need a separate generated parser for the second parse stage.
   
   **Success:** The grammar comment states the measured parse cost of the 
optional-reference alternatives with the conf off and why they stay in the 
shared parser.
   
   **Verification:**
   - **Inspection:** The grammar comment above overlayExpression names the 
measured parse cost with the conf off and explains that removing it would need 
a separate generated parser for the second parse stage.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ *
+ * {{{
+ *   df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))
+ * }}}
+ */
+object CheckOptionalReferencesInDml extends Rule[LogicalPlan] {
+
+  override def apply(plan: LogicalPlan): LogicalPlan = {
+    if (plan.containsPattern(COMMAND)) {
+      plan.foreach { operator =>
+        statementName(operator).foreach { statement =>
+          operator.expressions.foreach(checkExpression(_, statement))

Review Comment:
   **Non-blocking (P2):** This rule checks only `operator.expressions` of the 
DML node. For a `MergeIntoTable` that is the merge condition and the actions, 
not the source plan, and `MergeIntoWriter` puts the source DataFrame's 
unanalyzed plan (`df.queryExecution.logical`) there for both 
`Dataset.mergeInto` and the Spark Connect MERGE command. By the review's 
reading of the code, with optional references on and a `source` table without 
`is_deleted`, this merge runs, the merge's own analysis turns `is_deleted?` 
into NULL, and no matched row is deleted:
   
   ```scala
   spark.sql("SELECT pk, is_deleted? AS is_deleted FROM source")
     .mergeInto("target", expr("source.pk = target.pk"))
     .whenMatched(expr("is_deleted = true")).delete()
     .merge()
   ```
   
   The SQL form, `MERGE INTO target USING (SELECT pk, is_deleted? AS is_deleted 
FROM source) s ON s.pk = target.pk WHEN MATCHED AND s.is_deleted = true THEN 
DELETE`, fails with `IN_DML`. In Connect, any `?` in the source relation takes 
this path; in classic Spark, the `?` of the source DataFrame's last step does. 
`MergeIntoDataFrameSuite` covers only conditions and a subquery in an 
assignment.
   
   Suggested fix: also walk the source plan of a `MergeIntoTable` here, 
applying `OptionalReferences.unresolvedOptionalReference` to its operators' 
expressions, and raise `IN_DML` with the `MERGE` context. A source that reads a 
view with `?`, or a classic DataFrame step that was analyzed before the merge 
was built, keeps working, because its `?` is already resolved by then.
   
   **Verification:**
   - **Regression:** With optional references on, a DataFrame MERGE whose 
source is `spark.sql("SELECT pk, is_deleted? AS is_deleted FROM source")` fails 
with IN_DML and the MERGE context, as the SQL statement `MERGE INTO target 
USING (SELECT pk, is_deleted? AS is_deleted FROM source) s ...` does.
   - **Behavior:** With optional references on, a DataFrame MERGE whose source 
uses selectExpr with an optional reference fails with IN_DML and the MERGE 
context.
   - **Compatibility:** A DataFrame MERGE whose source reads a view created 
with an optional reference still runs and uses the view's NULL.



##########
common/utils/src/main/resources/error/error-conditions.json:
##########
@@ -7039,6 +7039,29 @@
     ],
     "sqlState" : "HY008"
   },
+  "OPTIONAL_REFERENCE_NOT_SUPPORTED" : {
+    "message" : [
+      "The `?` optional-reference operator is not supported in <context>."
+    ],
+    "subClass" : {
+      "IN_DDL" : {
+        "message" : [
+          "Table definitions must not contain optional references."

Review Comment:
   **Nit (P3):** `OptionalReferenceValidation`'s `DefaultExpressionContext` 
case matches every `DEFAULT` of a `colDefinition`, and SQL function parameters 
use `colDefinitionList`, so `CREATE TEMPORARY FUNCTION f(x INT DEFAULT v?) 
RETURNS INT RETURN x` fails with this message about table definitions when the 
function's parameters are parsed. Rejecting `?` in a stored default is 
consistent with the other definitions; only the wording is off, and the 
validator's scaladoc ("an expression that defines a table object") has the same 
scope. The new `UNUSED_SQL_PARAMETER_VALUES` message (line 10458) is broader 
than the behavior: it says that in a statement with optional references, a `?` 
after an identifier or a non-reserved keyword is an optional reference, but 
that holds only where the syntax allows a reference, and a `?` right after 
`SELECT` or `VALUES` at the start of an `IN` subquery stays a marker. For 
`EXECUTE IMMEDIATE 'SELECT missing?, id FROM people WHERE id IN (SELECT ?)' 
USING 1, 
 2`, the message suggests that the statement's one marker is a reference.
   
   Suggested fix: word IN_DDL for every definition it covers, for example 
"Definitions of tables and functions must not contain optional references.", 
give the scaladoc the same scope, and limit the unused-values message to a `?` 
where the syntax allows a reference.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4559147438).
   
   **Verification:**
   - **Behavior:** With optional references on, `CREATE TEMPORARY FUNCTION f(x 
INT DEFAULT v?) RETURNS INT RETURN x` fails with IN_DDL and a message that fits 
a function definition.
   - **Inspection:** The UNUSED_SQL_PARAMETER_VALUES message limits the reading 
of `?` as an optional reference to places where the syntax allows a reference.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/parameters.scala:
##########
@@ -174,6 +174,22 @@ object MoveParameterizedQueriesDown extends 
Rule[LogicalPlan] {
  */
 object BindParameters extends Rule[LogicalPlan] with QueryErrorsBase {
 
+  /**
+   * Fails if a statement with optional references has fewer positional 
parameter markers than
+   * values. In such a statement, a `?` after an identifier or a non-reserved 
keyword is an
+   * optional reference where the syntax allows a reference, and the remaining 
markers must not
+   * take its value silently. See `SubstituteParamsParser` for the statements 
that are not bound
+   * here.
+   */
+  private def checkUnusedPositionalArgs(plan: LogicalPlan, numMarkers: Int, 
numArgs: Int): Unit = {
+    def hasOptionalReferences: Boolean = plan.exists { operator =>
+      
operator.expressions.exists(OptionalReferences.unresolvedOptionalReference(_).isDefined)

Review Comment:
   **Non-blocking (P2):** `OptionalReferences.unresolvedOptionalReference` 
finds only references that are still unresolved, but `BindParameters` runs 
after `ResolveRelations` and `ResolveReferences` in the same Resolution 
iteration, so a `?` reference that resolves against the relation is already an 
attribute when this check runs. By the review's reading of the code, with 
optional references and `spark.sql.legacy.parameterSubstitution.constantsOnly` 
on and a view `v` with columns `id` and `distinct`, `spark.sql("SELECT id?, 
first(DISTINCT ?) AS f, ? AS g FROM v", Array(5, 6))` reads `DISTINCT ?` as the 
reference `distinct?`, binds 5 to `g`, and drops 6 without an error. The same 
call fails with `UNUSED_SQL_PARAMETER_VALUES` when `v` lacks either column, and 
always in the default mode, which decides from the parse tree. `EXECUTE 
IMMEDIATE ... USING` takes the same path through the 
`GeneralParameterizedQuery` arm. The `ParametersSuite` cases run the legacy 
mode only with references tha
 t stay unresolved, and none covers legacy `EXECUTE IMMEDIATE` or a legacy 
statement without optional references that is given extra values.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#issuecomment-6866045584).
   
   **Recommended change:** When SparkSession builds a legacy 
PosParameterizedQuery or GeneralParameterizedQuery, record whether the parsed 
statement has optional references, searching the parsed plan, its subquery 
plans, and its common table expressions before any analysis, and carry that 
fact on the node; checkUnusedPositionalArgs uses it instead of searching for 
references that are still unresolved. Add legacy-mode parameter tests for a 
statement whose optional references resolve, for EXECUTE IMMEDIATE ... USING, 
and for a statement without optional references that is given extra values.
   
   **Why this works:** Before analysis every optional reference of the 
statement is unresolved, so the recorded fact is the same whatever the schema, 
and BindParameters applies the declared rule to the statement as written, like 
the default mode's parse-time check.
   
   **Scope:** Carry a parse-time fact about optional references on the legacy 
parameterized plan and use it when binding.
   
   **Compatibility:** Statements without optional references keep ignoring 
extra positional values in both binding modes.
   
   **Risks:** Every construction of and pattern match on the two parameterized 
query nodes must carry the new fact; the compiler reports each one, and inside 
Spark they are built only in SparkSession.
   
   **Constraints:** A statement without optional references keeps ignoring 
extra positional values in the legacy mode. The default substitution mode keeps 
its current check.
   
   **Success:** In the legacy binding mode, a statement with optional 
references that is given more positional values than it has positional markers 
fails with UNUSED_SQL_PARAMETER_VALUES whether or not its optional references 
resolve, through spark.sql(text, args) and through EXECUTE IMMEDIATE ... USING. 
In the legacy binding mode, a statement without optional references still 
ignores extra positional values.
   
   **Verification:**
   - **Regression:** With optional references on and the legacy binding mode, 
`SELECT id?, first(DISTINCT ?) AS f, ? AS g FROM v` over a view with columns 
`id` and `distinct`, given two values, fails with UNUSED_SQL_PARAMETER_VALUES 
for one marker and two values, both through spark.sql and through EXECUTE 
IMMEDIATE.
   - **Compatibility:** With the legacy binding mode, a statement without 
optional references that is given more values than markers runs and ignores the 
extra values, as on the base branch.
   - **Behavior:** With the legacy binding mode, a statement whose optional 
references are all missing still fails with UNUSED_SQL_PARAMETER_VALUES when it 
is given extra values.



##########
sql/core/src/test/scala/org/apache/spark/sql/ParametersSuite.scala:
##########
@@ -1385,6 +1385,73 @@ class ParametersSuite extends SharedSparkSession {
     }
   }
 
+  test("optional named parameter markers") {
+    val optionalFilterQuery = "SELECT id FROM range(3) WHERE :low? IS NULL OR 
id >= :low?"
+    Seq(false, true).foreach { constantsOnly =>
+      withSQLConf(
+        SQLConf.OPTIONAL_REFERENCES_ENABLED.key -> "true",
+        SQLConf.LEGACY_PARAMETER_SUBSTITUTION_CONSTANTS_ONLY.key -> 
constantsOnly.toString
+      ) {
+        // A marker with a value is bound, and a marker without a value is 
NULL.
+        checkAnswer(spark.sql("SELECT :x?, :y?", Map("x" -> 1)), Row(1, null))
+        checkAnswer(spark.sql("SELECT :x ?, :x? + 1", Map("x" -> 1)), Row(1, 
2))
+        checkAnswer(spark.sql(optionalFilterQuery, Map("low" -> 2L)), Row(2))
+        checkAnswer(
+          spark.sql(optionalFilterQuery, Map("unused" -> 1)),
+          Row(0) :: Row(1) :: Row(2) :: Nil)
+
+        // A marker in a subquery is bound like a marker in the query around 
it.
+        checkAnswer(spark.sql("SELECT (SELECT :x?) AS a, (SELECT :y?) AS b", 
Map("x" -> 1)),
+          Row(1, null))
+        checkAnswer(
+          spark.sql("SELECT id FROM range(3) WHERE id IN (SELECT :low? AS 
low)", Map("low" -> 2L)),
+          Row(2))
+        checkAnswer(
+          spark.sql(
+            "SELECT id FROM range(3) t WHERE EXISTS (SELECT 1 WHERE t.id >= 
:low?)",
+            Map("low" -> 1L)),
+          Row(1) :: Row(2) :: Nil)
+
+        // Each occurrence is independent: the occurrence without `?` still 
requires a value.
+        checkError(
+          exception = intercept[AnalysisException] {
+            spark.sql("SELECT :y?, :y", Map("x" -> 1))
+          },
+          condition = "UNBOUND_SQL_PARAMETER",
+          parameters = Map("name" -> "y"),
+          context = ExpectedContext(fragment = ":y", start = 12, stop = 13))
+      }
+    }
+  }
+
+  test("positional parameter values that a statement with optional references 
does not use") {
+    Seq(false, true).foreach { constantsOnly =>
+      withSQLConf(
+        SQLConf.OPTIONAL_REFERENCES_ENABLED.key -> "true",
+        SQLConf.LEGACY_PARAMETER_SUBSTITUTION_CONSTANTS_ONLY.key -> 
constantsOnly.toString
+      ) {
+        // A statement that is valid without optional references keeps its 
markers.
+        checkAnswer(spark.sql("SELECT first(DISTINCT ?) AS f, ? AS g", 
Array(5, 6)), Row(5, 6))
+        // In a statement with optional references, a `?` after a non-reserved 
keyword where the
+        // syntax allows a reference is an optional reference, so the 
remaining markers would
+        // take the values of the following ones silently.

Review Comment:
   **Nit (P3):** With values `(5, 6)`, `? AS g` would take 5, the value meant 
for the reinterpreted `DISTINCT ?` before it, so the markers would take the 
values of the preceding ones, as `optional-references.sql` and 
`SubstituteParamsParser` put it:
   
   ```suggestion
           // take the values of the preceding ones silently.
   ```
   
   **Verification:**
   - **Inspection:** The test comment says that without the check the remaining 
markers would take the values of the preceding markers, as the golden file and 
SubstituteParamsParser say.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala:
##########
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.parser
+
+import org.antlr.v4.runtime.ParserRuleContext
+import org.antlr.v4.runtime.tree.ParseTree
+
+import org.apache.spark.sql.catalyst.parser.SqlBaseParser._
+import org.apache.spark.sql.catalyst.util.SparkParserUtils
+import org.apache.spark.sql.errors.QueryParsingErrors
+
+/** Checks where the `?` optional-reference operator can appear in a SQL 
statement. */
+object OptionalReferenceValidation {
+
+  /**
+   * Throws an error for the optional reference `ctx`, i.e. the parse tree of 
a reference with a
+   * `?` after one of its name parts, if `ctx` is part of an UPDATE, DELETE, 
MERGE, or AUTO CDC
+   * statement, of the condition of INSERT ... REPLACE, of a partition 
specification, or of an
+   * expression that defines a table object.
+   *
+   * The query of an INSERT, including INSERT OVERWRITE, and of a CREATE OR 
REPLACE TABLE AS
+   * SELECT is allowed to have optional references: like any query, it only 
reads data, and the
+   * rows that these statements replace do not depend on it.

Review Comment:
   **Nit (P3):** In dynamic partition overwrite mode 
(`spark.sql.sources.partitionOverwriteMode=dynamic` or the per-write option), 
`InsertionResolution` turns a V2 `INSERT OVERWRITE` into 
`OverwritePartitionsDynamic`, and `InsertIntoHadoopFsRelationCommand` does the 
same for file sources, so only the partitions that the query writes are 
replaced. For example, with `t` partitioned by `p`, `INSERT OVERWRITE t SELECT 
v, p FROM src WHERE deleted_at? IS NULL` keeps every row once `src` loses 
`deleted_at` and so replaces more partitions. In `INSERT ... REPLACE ON` and 
`REPLACE USING`, the query's rows select the target rows that are deleted. The 
golden-file comment before the INSERT cases (`optional-references.sql`, lines 
370-372) gives the same reason. Whatever is decided about these forms (see the 
question under Decision challenges), both comments should say which INSERT 
forms' queries select the replaced rows and how those forms treat `?`.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#issuecomment-6866045584).
   
   **Verification:**
   - **Inspection:** Neither comment says that the replaced rows never depend 
on the query, and both name dynamic partition overwrite and INSERT ... REPLACE 
ON/USING with the treatment that the code applies to them.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,410 @@
+/*
+ * 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.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 three tags 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]]. The one decision that an analysis 
makes about an
+   * optional reference, that no resolution step of its 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(_.flatMap(_.expressions).iterator.flatMap(unresolvedOptionalReference))
+        .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
+   * that did not resolve to a column, field, or variable.
+   */
+  def isNullReference(expression: Expression): Boolean =
+    expression.getTagValue(NULL_REFERENCE).isDefined
+
+  /**
+   * Returns the alias that gives `child`, the result of a top-level 
reference, the name `name` of
+   * the reference, see [[markImplicitAlias]].
+   */
+  def implicitAlias(child: Expression, name: String): Alias =
+    markImplicitAlias(Alias(child, name)())
+
+  /**
+   * Marks `alias`, which gives the result of a top-level reference the name 
of the reference, if
+   * that result is a [[nullReference]]. Such an alias is only there for the 
name of the output
+   * column, which ORDER BY and HAVING can reference. Unlike other aliases of 
a SELECT list,
+   * including `missing? AS m`, it is neither a lateral column alias nor an 
alias that GROUP BY
+   * can reference, so that a reference without `?` is not found, see 
[[isNullReferenceAlias]].
+   *
+   * {{{
+   *   SELECT missing?, missing? IS NULL, missing + 1 FROM t;
+   *   -- NULL, true, and UNRESOLVED_COLUMN for the `missing` without `?`
+   * }}}
+   */
+  def markImplicitAlias(alias: Alias): Alias = {
+    if (isNullReference(alias.child)) {
+      alias.setTagValue(NULL_REFERENCE, ())
+    }
+    alias
+  }
+
+  /** Returns true if `expression` is the [[implicitAlias]] of a 
[[nullReference]]. */
+  def isNullReferenceAlias(expression: Expression): Boolean = expression match 
{
+    case alias: Alias => alias.getTagValue(NULL_REFERENCE).isDefined
+    case _ => false
+  }
+
+  /**
+   * Extracts `nestedFields` from `base` in the same way as the `ExtractValue` 
chain of a multipart
+   * name, where the first nested field is the name part at 
`firstNestedFieldIndex`. A struct field
+   * that does not exist turns the whole chain into [[nullReference]] if its 
name part is optional,
+   * without extracting the remaining fields. Any other extraction error is 
thrown.
+   *
+   * @param voidBaseIsNull Whether the fields of a NULL of type VOID are NULL, 
as they are for a
+   *   column, or an error, as they are for a variable.
+   */
+  def extractNestedFields(
+      base: Expression,
+      nestedFields: Seq[String],
+      firstNestedFieldIndex: Int,
+      optionalNamePartIndices: Set[Int],
+      resolver: Resolver,
+      voidBaseIsNull: Boolean): Expression = {
+    extractNestedFieldsOrError(
+      expression = base,
+      nestedFields = nestedFields,
+      nestedFieldIndex = firstNestedFieldIndex,
+      optionalNamePartIndices = optionalNamePartIndices,
+      resolver = resolver,
+      voidBaseIsNull = voidBaseIsNull
+    ) match {
+      case EitherLeft(extracted) => extracted
+      case EitherRight(throwable) => throw throwable
+    }
+  }
+
+  /**
+   * Returns true if the optional multipart name `nameParts` resolves to 
[[nullReference]] after
+   * it failed to resolve against `attributes`, i.e. if its first name part 
that matches no
+   * reference path to `attributes` is optional. See 
[[firstUnmatchedNamePartIndex]].
+   */
+  def resolvesToNull(
+      nameParts: Seq[String],
+      optionalNamePartIndices: Set[Int],
+      attributes: Seq[Attribute],
+      resolver: Resolver): Boolean = {
+    optionalNamePartIndices.nonEmpty &&
+    firstUnmatchedNamePartIndex(nameParts, attributes, resolver).exists(
+      optionalNamePartIndices.contains
+    )
+  }
+
+  /**
+   * Returns the index of the first name part of `nameParts` that does not 
continue any reference
+   * path to `attributes`, where a path is a suffix of the attribute 
qualifier, the attribute name,
+   * and then the names of nested fields. 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. A qualifier is not a reference by 
itself, so the last name
+   * part never matches a qualifier.
+   * Returns None if the whole name matches a path, which means that the name 
was found but was not
+   * usable, e.g. because it references a column that is not grouped.
+   *
+   * {{{
+   *   -- `t` has the columns `id` and `addr STRUCT<city STRING>`:
+   *   t.name    -- 1: `t` matches the qualifier of `id`, `name` matches 
nothing
+   *   ghost.id  -- 0
+   *   addr.zip  -- 1
+   *   t         -- 0: `t` is not a column
+   * }}}
+   */
+  def firstUnmatchedNamePartIndex(
+      nameParts: Seq[String],
+      attributes: Seq[Attribute],
+      resolver: Resolver): Option[Int] = {
+    val matchedNamePartCounts =
+      attributes.iterator.map(matchedNamePartCount(nameParts, _, resolver)) ++
+      
SESSION_VARIABLE_QUALIFIERS.iterator.map(matchedQualifierPartCount(nameParts, 
_, resolver)) ++
+      Iterator(matchedScriptingScopeLabelCount(nameParts))
+    val longestMatch = matchedNamePartCounts.max
+    if (longestMatch < nameParts.length) Some(longestMatch) else None
+  }
+
+  /**
+   * Returns 1 if `nameParts` is a two-part name whose first part is the label 
of an active SQL
+   * scripting scope, so that the name can reference a variable of that scope, 
and 0 otherwise.
+   */
+  private def matchedScriptingScopeLabelCount(nameParts: Seq[String]): Int = {
+    val isScopeLabel = nameParts.length == 2 && {

Review Comment:
   **Nit (P3):** Thanks for adding the label qualifier. Because of 
`nameParts.length == 2`, the label counts only for two-part names, while 
`VariableResolution` resolves a label-qualified variable with nested fields, 
`lbl.v.f`, as `lbl.v` plus field `f`, and session qualifiers count for names of 
any length (line 252). By the review's reading of the code, inside `lbl: BEGIN 
DECLARE x INT DEFAULT 1; SELECT lbl.missing?.f; END` or `FOR r AS SELECT id 
FROM people DO SELECT r.missing?.city; END FOR`, the first unmatched part is 
the label itself, which is not optional, so both fail with `UNRESOLVED_COLUMN`. 
The count also consults the active script while a view body is resolved, where 
`VariableResolution.resolveVariable` hides script variables that the view did 
not capture, so a temporary view whose body has `lbl.y?` is NULL when read 
inside the script and fails after it. No case has a nested field after a label, 
a view inside a script, or a qualifier written in another case, such as `LBL.
 y?`.
   
   Suggested fix: count the label for every name of two or more parts, and not 
while a view body is resolved, matching variable lookup.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4559147447).
   
   **Verification:**
   - **Regression:** With optional references on, `SELECT lbl.missing?.f` 
inside `lbl: BEGIN ... END` and `SELECT r.missing?.city` inside `FOR r AS 
SELECT id FROM people DO ... END FOR` return NULL in both analyzers.
   - **Behavior:** With optional references on, `SELECT LBL.y?` inside `lbl: 
BEGIN ... END` returns NULL.
   - **Regression:** A temporary view whose body has `lbl.y?`, created inside a 
labeled block, gives the same result when it is read inside the block and after 
it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -4675,13 +4724,19 @@ object UpdateOuterReferences extends Rule[LogicalPlan] {
  */
 object RemoveTempResolvedColumn extends Rule[LogicalPlan] {
   override def apply(plan: LogicalPlan): LogicalPlan = {
-    
plan.resolveExpressionsWithPruning(_.containsPattern(TEMP_RESOLVED_COLUMN)) {
-      case t: TempResolvedColumn =>
-        if (t.hasTried) {
-          UnresolvedAttribute(t.nameParts)
-        } else {
-          t.child
-        }
+    if (ResolveOptionalReferences.isUnfinishedSubqueryPlan(plan)) {

Review Comment:
   **Non-blocking (P2):** The tried `TempResolvedColumn` that 
`ResolveAggregateFunctions` builds for a column that is neither grouped nor 
aggregated now keeps the optional marker, since `markTried` copies it, and a 
tried column is unresolved, so `isUnfinishedSubqueryPlan` holds for the 
subquery plan in every analysis and this gate never lets 
`RemoveTempResolvedColumn` turn the column back into an `UnresolvedAttribute`. 
`ResolveOptionalReferences.replace` handles only `UnresolvedAttribute` and 
`NamedParameter`, so nothing else removes it. By the review's reading of the 
code, with `t(k INT, v INT, x INT)` and a table `u` without `x`, `SELECT 
(SELECT max(v) FROM t GROUP BY k HAVING x? > 0) FROM u`, and the same subquery 
with `ORDER BY x? LIMIT 1`, fail with `INTERNAL_ERROR` "Found the unresolved 
operator", while the same query without `?`, and the `?` query outside a 
subquery, fail with the usual error for the not-grouped `x`. When the outer 
query has a column `x` or a variable has that
  name, the tried column resolves to it first, as without `?`.
   
   Suggested fix: make `isUnfinishedSubqueryPlan` count only the optional 
references that `ResolveOptionalReferences` can still replace or wrap, so a 
tried `TempResolvedColumn` no longer holds the gate.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4559147412).
   
   **Verification:**
   - **Regression:** With optional references on, `SELECT (SELECT max(v) FROM t 
GROUP BY k HAVING x? > 0) FROM u` and the same subquery with `ORDER BY x? LIMIT 
1`, where `t.x` is neither grouped nor aggregated and `u` has no `x`, fail with 
the error that the same reference gets outside a subquery.
   - **Compatibility:** The existing golden cases for HAVING and ORDER BY in 
subqueries with missing optional references keep their results.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,410 @@
+/*
+ * 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.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 three tags describe the statement: they are facts about the reference 
as written, which

Review Comment:
   **Nit (P3):** Only `nullReference` and `markImplicitAlias` set this tag, on 
the NULL literal and the implicit alias that one analysis creates when a 
reference matches nothing; no parsed node carries it. For `SELECT missing? FROM 
t`, the tag exists only in the analyzed plan, and after `t` gains `missing`, a 
new analysis of the same unresolved plan resolves the column and creates no 
tagged node. Since this doc is the tag-lifetime contract that later rules 
follow, it would help to say that the parser's two tags, the optional name 
parts and the optional marker, are facts about the reference as written, while 
`NULL_REFERENCE` records a decision of one analysis on nodes that analysis 
creates, and must not be set on or forwarded to the nodes of the plan that the 
analyzer receives.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#issuecomment-6866045584).
   
   **Verification:**
   - **Inspection:** The OptionalReferences doc no longer describes 
NULL_REFERENCE as a fact of the statement as written, and it states that only 
analysis sets it, on the nodes that the analysis creates.



##########
docs/sql-migration-guide.md:
##########
@@ -99,6 +99,7 @@ license: |
 - Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda function or one that passes a column to `datediff`, `year` 
or `upper` (SPARK-60032). Such a constraint is stored without a predicate, so 
each write parses and analyzes its SQL text under the session of the write, as 
it does for a constraint without a predicate that `CREATE TABLE` adds. A 
setting of the write such as `spark.sql.ansi.enforceReservedKeywords`, which 
reserves `TIME`, or `spark.sql.ansi.doubleQuotedIdentifiers` can then make it 
fail to parse the text or read it differently. A row-level operation
  that copies unchanged rows, such as a `DELETE` or `UPDATE` on a copy-on-write 
table, fails with `CHECK_CONSTRAINT_VIOLATION` on a copied row that no longer 
satisfies the condition. For example, `ts >= current_timestamp() - INTERVAL 30 
DAYS` now fails such a `DELETE` once a copied row is older than 30 days. A 
condition that Spark detects a write could resolve differently is stored as 
before, so a write accepts and rejects the same rows for it as before. Examples 
are conditions that also read a variable, a `CHAR` column, a name with more 
than one part such as a column qualified by the table name, or a constant that 
depends on the session time zone, such as `'2024-01-01 00:00:00'` cast to a 
timestamp. So are conditions with a name such as `current_date` or `user` 
without parentheses, which a write can read as a column name, and conditions 
whose text the parser settings of the `ALTER TABLE`, such as 
`spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, r
 ead differently from their default values. ANSI mode, 
`spark.sql.timestampType` and the session time zone are taken from the session 
for this comparison, as for a generation expression. A condition that reads the 
current date or time only through a typed literal such as `DATE 'today'` is 
also stored as before. An existing constraint keeps its stored predicate until 
it is dropped and added again. `Check.predicate()` is null for a constraint 
stored without a predicate, so a connector that validates or enforces it itself 
has to evaluate `Check.predicateSql()`. To restore the previous behavior, set 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
the constraint. A constraint added without it is not changed.
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V2 implementation selected by 
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic` 
property do not control the V2 path. For scalar functions, determinism uses 
`BoundFunction.isDeterministic()` (default `true`) and the arguments' 
determinism. A call with constant arguments can therefore become eligible for 
constant folding during query planning instead of being evaluated per row.
 - Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW` 
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc` 
fails with it when the result is earlier than the minimum `DATE`, 
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these 
functions silently returned a wrong date, in most cases one at the other end of 
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned 
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned 
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`. 
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days 
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and 
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday, 
and now return `-5877641-06-29`.
+- Since Spark 4.4, a name in the body of a SQL function that is called in a 
subquery no longer resolves to a column of the query around the subquery. It 
resolves like a name in the body of a function that is called directly: to a 
parameter or a column of the body, or else to a session variable. For example, 
after `DECLARE VARIABLE v INT DEFAULT 100` and `CREATE FUNCTION f() RETURNS INT 
RETURN v`, `SELECT (SELECT f()) FROM VALUES (5) AS t(v)` returns 100 instead of 
5. To restore the previous behavior, set 
`spark.sql.legacy.sqlFunctionBodyResolvesOuterReferences` to `true`.

Review Comment:
   **Nit (P3):** `CREATE FUNCTION` without `TEMPORARY` creates a permanent 
function, and a permanent function's body must not reference the temporary 
variable `v`: `CreateSQLFunctionCommand` rejects it with 
`INVALID_TEMP_OBJ_REFERENCE`, as the existing `sql-udf.sql.out` case `CREATE 
FUNCTION foo3_5d(x INT) RETURNS INT RETURN x + length(foo3_5_col)` records. A 
reader who runs the example in order never reaches the `SELECT` that returns 
100 instead of 5. `CREATE TEMPORARY FUNCTION`, which the PR description and 
`SQLFunctionSuite` use, makes it runnable:
   
   ```suggestion
   - Since Spark 4.4, a name in the body of a SQL function that is called in a 
subquery no longer resolves to a column of the query around the subquery. It 
resolves like a name in the body of a function that is called directly: to a 
parameter or a column of the body, or else to a session variable. For example, 
after `DECLARE VARIABLE v INT DEFAULT 100` and `CREATE TEMPORARY FUNCTION f() 
RETURNS INT RETURN v`, `SELECT (SELECT f()) FROM VALUES (5) AS t(v)` returns 
100 instead of 5. To restore the previous behavior, set 
`spark.sql.legacy.sqlFunctionBodyResolvesOuterReferences` to `true`.
   ```
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60367#discussion_r4559147430).
   
   **Verification:**
   - **Inspection:** The example creates a temporary function, which may read 
the session variable, so each statement is accepted as written and the SELECT 
shows 100 where the base branch shows 5.



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:
##########
@@ -519,6 +552,73 @@ object AbstractParser extends Logging {
       parser: SqlBaseParser,
       tokenStream: CommonTokenStream,
       parseOperation: SqlBaseParser => T): T = {
+    if (!parser.optional_references_enabled) {
+      executeWithSllThenLl(parser, tokenStream, parseOperation)
+    } else {
+      val parameterMarkers = new PositionalParameterMarkerCounter
+      parser.addParseListener(parameterMarkers)

Review Comment:
   **Nit (P3):** With the conf on, this registers a third parse listener on 
every parse, including view text and internal `parseDataType` or 
`parseMultipartIdentifier` calls, and its `enterEveryRule` runs for every rule, 
although the count is read only after a failed parse. A third listener class 
can also make ANTLR's listener-dispatch call sites megamorphic for later parses 
in the same JVM, which nobody has measured. Separately, with the conf off, the 
default, `SubstituteParamsParser` evaluates 
`AbstractParser.questions(tokenStream).length > ...` before 
`restartWithOptionalReferences`, which then returns false without looking at 
the tokens, so every parameterized statement pays an extra pass over its tokens.
   
   Suggested fix: in `SubstituteParamsParser`, check that optional references 
are enabled before collecting the `?` tokens, keeping 
`restartWithOptionalReferences` last because it retypes them; and count the 
positional markers in `UnclosedCommentProcessor`, which `configureParser` 
already registers, resetting the count when a root rule is entered, instead of 
adding a listener.
   
   **Verification:**
   - **Compatibility:** With the conf on, statements that need the second 
parse, including a positional marker before an optional reference such as 
`SELECT ?, a? FROM t` and a statement that uses every `?` as a marker and still 
fails such as `SELECT ? FROM t WHERE`, keep their plans and errors.
   - **Compatibility:** With the conf off, parameterized statements with 
positional and named markers keep their substitutions and errors.
   - **Inspection:** With the conf on, the only parse listeners registered 
during a parse are PostProcessor and UnclosedCommentProcessor.



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