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


##########
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:
   Done. Both comments now describe the boundary by the kind of statement, and 
they name dynamic partition overwrite and `INSERT ... REPLACE ON/USING` with 
the treatment that the code applies to them: the query of an INSERT may use 
`?`, including where the written rows decide which partitions or target rows 
are replaced, and only the REPLACE condition, a predicate on the target table, 
rejects it. The decision itself is in the top-level comment, together with the 
reasoning.



##########
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:
   Done.



##########
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:
   Done. `SubstituteParamsParser` checks `parser.optional_references_enabled` 
before it collects the `?` tokens, with `restartWithOptionalReferences` still 
last. The count of positional markers moved into `UnclosedCommentProcessor`, 
which `configureParser` registers for every parse, so the only parse listeners 
during a parse are `PostProcessor` and `UnclosedCommentProcessor` whether the 
conf is on or off; `executeWithTwoStageStrategy` reads the count from that 
listener after a failed parse. The count is reset when a rule without a parent 
is entered, so each attempt of SLL-then-LL starts from zero, as before. 
`OptionalReferencesParserSuite` still covers `SELECT ?, a? FROM t`, `SELECT ? 
FROM t WHERE`, and the `SET` free-text cases.



##########
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:
   Done. The label now counts for any name of two or more parts, so 
`lbl.missing?.f` and `r.missing?.city` are NULL, and it does not count while 
the body of a view is resolved (`resolvingView` is threaded through 
`OptionalReferences.resolvesToNull` from both analyzers), matching variable 
lookup. New golden cases: `SELECT lbl.missing?.f, LBL.y?, r.missing?.city, 
r.addr.state?.code` inside a labeled block with a FOR statement returns four 
NULLs in both analyzers, and a temporary view created inside a labeled block 
with `lbl.missing? AS m` fails with `UNRESOLVED_COLUMN` for `lbl.missing` both 
when it is read inside the block and after it.
   
   One nuance I checked while writing the case: a view body does see the script 
variables that it referenced when it was created (`CREATE TEMPORARY VIEW vv AS 
SELECT lbl.y AS y` inside the block, then `SELECT * FROM vv` inside it, returns 
1), because they are in `referredTempVariableNames`; it fails after the block, 
with or without `?`. A missing variable is never captured, so for 
`lbl.missing?` the label-free rule gives the same error inside and outside, as 
you asked for.



##########
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:
   Done. `ResolveOptionalReferences.hasUnresolvedOptionalReferences`, and so 
`isUnfinishedSubqueryPlan`, now counts only the unresolved nodes that the rule 
can still replace or wrap: an `UnresolvedAttribute` with optional name parts, 
an optional `NamedParameter`, and an optional `UnresolvedExtractValue`. A tried 
`TempResolvedColumn` holds a reference that was found and no longer keeps the 
gate, so `RemoveTempResolvedColumn` turns it back into an `UnresolvedAttribute` 
as at the top level. New golden cases: `SELECT (SELECT max(v) FROM VALUES (1, 
2, 3) AS t(k, v, x) GROUP BY k HAVING x? > 0) AS m FROM people` and the `ORDER 
BY x? LIMIT 1` form fail with `UNRESOLVED_COLUMN.WITH_SUGGESTION` for `x`, the 
same error as the same statements without `?` and as the same references 
outside a subquery. The existing HAVING and ORDER BY subquery cases with 
missing optional references keep their results.



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