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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,402 @@
+/*
+ * 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,
+  SubqueryExpression,
+  UnaryExpression,
+  Unevaluable
+}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  Aggregate,
+  DefaultValueExpression,
+  Filter,
+  GeneratedColumnExpression,
+  LateralJoin,
+  LogicalPlan,
+  RepartitionByExpression,
+  Sort,
+  UnaryNode
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.CurrentOrigin
+import org.apache.spark.sql.catalyst.trees.TreePattern.{PARAMETERIZED_QUERY, 
PLAN_EXPRESSION}
+import org.apache.spark.sql.errors.QueryCompilationErrors
+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,
+    variableResolution: VariableResolution)
+    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 attributeGroups = visibleAttributeGroups(operator)
+        operator.mapExpressions(replace(_, attributeGroups, 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 attributeGroups = visibleAttributeGroups(aggregate)
+    aggregate.copy(aggregateExpressions = aggregate.aggregateExpressions.map { 
expression =>
+      replace(expression, attributeGroups, isTopLevel = 
true).asInstanceOf[NamedExpression]
+    })
+  }
+
+  /**
+   * Replaces the optional references of `expression` that resolve to NULL 
against
+   * `attributeGroups`.
+   * A top-level reference keeps its name through an [[Alias]] of its last 
name part.
+   */
+  private def replace(
+      expression: Expression,
+      attributeGroups: => Seq[Seq[Attribute]],
+      isTopLevel: Boolean): Expression = expression match {
+    // The parser rejects optional references in these clauses of SQL text, 
but a column definition
+    // of an API, such as `Catalog.createTable`, parses its expressions on its 
own.
+    case default: DefaultValueExpression =>
+      rejectInDdl(default, "DEFAULT")
+    case generation: GeneratedColumnExpression =>
+      rejectInDdl(generation, "GENERATED ALWAYS AS")
+    case unresolvedAttribute: UnresolvedAttribute
+        if 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute).nonEmpty &&
+        OptionalReferences.resolvesToNull(
+          nameParts = unresolvedAttribute.nameParts,
+          optionalNamePartIndices = 
OptionalReferences.optionalNamePartIndices(unresolvedAttribute),
+          attributeGroups = attributeGroups,
+          resolver = conf.resolver,
+          isVariableQualifier = variableResolution.isVariableQualifier(
+            _,
+            includeScopeLabels = !isViewQuery)

Review Comment:
   **[P2] Persistent SQL function body still treats the caller's script labels 
as qualifiers**
   
   `includeScopeLabels = !isViewQuery` never looks at 
`AnalysisContext.isPersistentSQLFunctionBody`. A label-qualified optional 
reference in a persistent function body is therefore resolved against the scope 
labels of whoever calls the function. The PR description says a persistent 
function body "keeps the NULL it was when the function was created, as in a 
persistent view". A view rejects a label dependency at CREATE VIEW, but a 
persistent function becomes call-site dependent. SQLFunctionSuite only calls 
`persistent_label_var_fn` inside a block labeled `lbl`, so the inconsistency is 
not tested. Fix: also pass `includeScopeLabels = false` in a persistent 
function body, so the dependency fails at CREATE FUNCTION as it does for views.
   
   **Failure scenario:** With the conf on, run `BEGIN lbl: BEGIN CREATE 
FUNCTION f() RETURNS INT RETURN coalesce(lbl.x?, 0); END; END` with no variable 
`x`. Creation succeeds because `lbl` is an active label. Later, `SELECT f()` 
from a plain session, or from a block without label `lbl`, fails with 
UNRESOLVED_COLUMN `lbl`.`x`: `lbl` is no longer a qualifier and name part 0 is 
not optional. The same call inside `lbl:` returns 0.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SubstituteParamsParser.scala:
##########
@@ -134,11 +200,16 @@ class SubstituteParamsParser extends Logging {
         case Some(value) =>
           // Substitute all occurrences of this parameter
           locationList.foreach { location =>
-            substitutions += Substitution(location, value)
+            substitutions += Substitution(location, namedReplacement(sqlText, 
location, value))
+          }
+        case None if locationList.forall(_.optional) =>
+          // An optional named parameter marker (`:name?`) without a value is 
NULL.
+          locationList.foreach { location =>
+            substitutions += Substitution(location, namedReplacement(sqlText, 
location, "NULL"))

Review Comment:
   **[P2] Unbound `:name?` becomes the text NULL, so extracting from it fails, 
unlike `missing?`**
   
   With a parameter context, an unbound optional named marker is replaced by 
the text `NULL` before parsing. The result is a plain NULL literal, not a 
tagged null reference. Without a parameter context, or in legacy binding mode, 
the same marker stays a NamedParameter, ResolveOptionalReferences replaces it 
with `OptionalReferences.nullReference()`, and extracting from it is NULL. The 
PR says an extraction from a missing reference is NULL (`missing?:a`), but the 
result for `:p?:a` now depends on whether other parameters were passed. The 
golden file confirms that `SELECT NULL:a` raises COLUMN_IS_NOT_VARIANT_TYPE. 
The MERGE-source gap that the text substitution also causes is explicitly 
documented as not covered, so it is not part of this finding.
   
   **Failure scenario:** `EXECUTE IMMEDIATE 'SELECT :p?:a, :q' USING 1 AS q` 
(or `spark.sql("SELECT :p?:a, :q", Map("q" -> 1))`) is rewritten to `SELECT 
NULL:a, 1` and fails with COLUMN_IS_NOT_VARIANT_TYPE. `SELECT :p?:a` with no 
parameter context, or in legacy mode, returns a VARIANT NULL.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveOptionalReferences.scala:
##########
@@ -0,0 +1,402 @@
+/*
+ * 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,
+  SubqueryExpression,
+  UnaryExpression,
+  Unevaluable
+}
+import org.apache.spark.sql.catalyst.plans.logical.{
+  Aggregate,
+  DefaultValueExpression,
+  Filter,
+  GeneratedColumnExpression,
+  LateralJoin,
+  LogicalPlan,
+  RepartitionByExpression,
+  Sort,
+  UnaryNode
+}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.CurrentOrigin
+import org.apache.spark.sql.catalyst.trees.TreePattern.{PARAMETERIZED_QUERY, 
PLAN_EXPRESSION}
+import org.apache.spark.sql.errors.QueryCompilationErrors
+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,
+    variableResolution: VariableResolution)
+    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 attributeGroups = visibleAttributeGroups(operator)
+        operator.mapExpressions(replace(_, attributeGroups, 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 attributeGroups = visibleAttributeGroups(aggregate)
+    aggregate.copy(aggregateExpressions = aggregate.aggregateExpressions.map { 
expression =>
+      replace(expression, attributeGroups, isTopLevel = 
true).asInstanceOf[NamedExpression]
+    })
+  }
+
+  /**
+   * Replaces the optional references of `expression` that resolve to NULL 
against
+   * `attributeGroups`.
+   * A top-level reference keeps its name through an [[Alias]] of its last 
name part.
+   */
+  private def replace(
+      expression: Expression,
+      attributeGroups: => Seq[Seq[Attribute]],
+      isTopLevel: Boolean): Expression = expression match {
+    // The parser rejects optional references in these clauses of SQL text, 
but a column definition
+    // of an API, such as `Catalog.createTable`, parses its expressions on its 
own.
+    case default: DefaultValueExpression =>

Review Comment:
   **[P2] Design: DDL rejection for API-built column definitions lives in the 
resolution rule, not in the existing rejection rule**
   
   `replace` now matches `DefaultValueExpression` and 
`GeneratedColumnExpression` and calls `rejectInDdl` (lines 167-170 and 
205-210). `rejectInDdl` runs 
`OptionalReferences.unresolvedOptionalReference(expression)` and throws 
`optionalReferenceInDdlNotSupportedError`. Its comment gives the reason: a 
column definition built through an API, such as `Catalog.createTable` 
(`ColumnDefinition.fromV1Column`, `ColumnDefinition.scala:165-170`), skips the 
parser check.
   
   The PR already has a rule for exactly this case. 
`CheckOptionalReferencesInDml` (`CheckOptionalReferencesInDml.scala:34-38`) 
"rejects optional references in the expressions of a statement ... that was 
built without the SQL parser, which rejects them in SQL text (see 
`OptionalReferenceValidation`)". It runs in the early "Simple Sanity Check" 
batch (`Analyzer.scala:810-812`), before resolution. It walks command plans 
(`CreateTable` is a `UnaryCommand`, so it carries `COMMAND`) and uses the same 
`unresolvedOptionalReference` and throw pattern (`checkExpression`, lines 
152-160).
   
   As written, "reject `?` in plans built outside the parser" is split across 
two rules. The DDL half is also nested inside the traversal of the resolution 
rule, so it fires only when `ResolveOptionalReferences` visits that operator. 
That requires `childrenResolved && !resolved`, no `PARAMETERIZED_QUERY`, and a 
plan that is not a subquery plan.
   
   Fix: move the DEFAULT and GENERATED ALWAYS AS cases into the sanity-check 
rule, for example by generalizing it to `CheckOptionalReferences` with a 
`V2CreateTablePlan` case over `columns`. `ResolveOptionalReferences` then only 
resolves.
   
   **Why it matters:** Each new kind of plan built through an API, such as 
ALTER COLUMN SET DEFAULT or CHECK through an API, has to choose which rule gets 
its rejection. The two rules have different preconditions, so a later change to 
how `ResolveOptionalReferences` traverses plans can silently stop the DDL 
rejection while the DML one keeps working.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SubstituteParamsParser.scala:
##########
@@ -73,12 +108,42 @@ class SubstituteParamsParser extends Logging {
     // Use shared parser configuration to ensure consistency with main parser.
     AbstractParser.configureParser(parser, sqlText, tokenStream, SQLConf.get)
 
-    val astBuilder = new SubstituteParmsAstBuilder()
-
     // Use shared two-stage parsing strategy for consistent error handling.
-    val ctx = AbstractParser.executeWithTwoStageStrategy(parser, tokenStream,
-      _.compoundOrSingleStatement())
-    val parameterLocations = astBuilder.extractParameterLocations(ctx)
+    def parseParameterLocations(): (ParserRuleContext, ParameterLocationInfo) 
= {
+      val ctx = AbstractParser.executeWithTwoStageStrategy(parser, tokenStream,
+        _.compoundOrSingleStatement())
+      (ctx, new SubstituteParmsAstBuilder().extractParameterLocations(ctx))
+    }
+    val (ctx, parameterLocations) = parseParameterLocations() match {
+      // A rule that accepts any tokens, such as `SET .*?`, parses a statement 
such as
+      // `SET VAR v = :p?`, which is not valid without optional references. 
Only the parser that
+      // builds the plan can tell, so parse a statement with a `?` that is not 
a parameter marker
+      // again with optional references.
+      case (_, locations)
+          if parser.optional_references_enabled &&
+            AbstractParser.questions(tokenStream).length >

Review Comment:
   **[P2] A `?` in a DECLARE CURSOR query forces optional-reference mode on a 
script that has no optional references**
   
   The re-parse condition compares 
`AbstractParser.questions(tokenStream).length`, which counts every `?` token, 
with `positionalParameterLocations.length`. SubstituteParmsAstBuilder 
deliberately skips DECLARE CURSOR queries (their markers are bound at OPEN), so 
with the conf on, any parameterized script whose cursor query uses `?` meets 
the condition. That script is re-parsed with QUESTION_WITH_OPTIONAL_REFERENCES 
and reported as `parsedWithOptionalReferences`. SparkSqlParser then parses the 
substituted text directly in optional-reference mode. This breaks the PR's rule 
that a statement valid without optional references keeps its normal parse: 
every remaining `?` after an identifier or non-reserved keyword can become an 
optional reference. Fix: count only the `?` tokens outside the skipped cursor 
queries, or compare against all `?` tokens that the first parse accepted.
   
   **Failure scenario:** With `spark.sql.optionalReferences.enabled=true`, run 
`spark.sql("BEGIN DECLARE c CURSOR FOR SELECT * FROM t WHERE id = ?; SELECT 
first(DISTINCT ?) FROM t; END", Array(1))`. The script contains no optional 
references. The cursor's `?` makes the substitution re-parse in optional mode, 
where `DISTINCT ?` becomes an optional reference to a column `distinct`. The 
valid script then fails with UNUSED_SQL_PARAMETER_VALUES, or the `?` reads as a 
NULL column, instead of binding 1.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/ParameterHandler.scala:
##########
@@ -156,6 +158,17 @@ object ParameterHandler {
   def substituteParameters(
       sqlText: String,
       context: ParameterContext): (String, PositionMapper) = {
+    val substitution = substituteParametersForParsing(sqlText, context)
+    (substitution.sqlText, substitution.positionMapper)
+  }
+
+  /**
+   * Same as [[substituteParameters]], but returns the whole 
[[ParameterSubstitution]], whose SQL
+   * text the parser has to parse with the optional references that the 
substitution chose.
+   */
+  def substituteParametersForParsing(

Review Comment:
   **[P2] Design: Parallel substitution entry points; the tuple variants drop 
the flag that parsing now needs**
   
   The PR keeps both forms of each substitution method instead of changing 
their return type.
   - `ParameterHandler`: the tuple-returning `substituteParameters` (line 158) 
stays, and `substituteParametersForParsing` (line 169) is added to return 
`ParameterSubstitution`.
   - `SubstituteParamsParser`: the tuple-returning `substitute` (line 69) 
stays, and `substituteParameters` (line 86) is added to return 
`ParameterSubstitution`.
   
   So `substituteParameters` returns a tuple on `ParameterHandler` and the case 
class on `SubstituteParamsParser`. The `ParameterSubstitution` scaladoc says 
"The parser must parse `sqlText` with them too", but every tuple variant drops 
`parsedWithOptionalReferences`. That includes `substituteNamedParameters` and 
`substitutePositionalParameters` (lines 234-268) and `object 
SubstituteParamsParser.substitute` (line 312).
   
   The only production caller that parses the substituted text is 
`SparkSqlParser.scala:167`. Every other call site of 
`ParameterHandler.substituteParameters` is in tests 
(`ParameterSubstitutionSuite`). Changing the return type of the existing 
methods to `ParameterSubstitution` and updating the tests would leave one entry 
point that cannot lose the flag.
   
   Also, `case class ParameterSubstitution` was inserted between the scaladoc 
of `SubstituteParamsParser` and the class 
(`SubstituteParamsParser.scala:35-57`). The class lost its doc, and an orphaned 
`/** */` block was left behind.
   
   **Why it matters:** The next caller that substitutes parameters and then 
parses the result, for example a scripting or Connect path, can pick the 
familiar tuple method. It then silently parses `:x?` substitutions without 
optional references, which is the bug this commit fixes in `SparkSqlParser`.



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