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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8550,6 +8561,17 @@ object SQLConf {
       .booleanConf
       .createWithDefault(true)
 
+  val OPTIONAL_REFERENCES_ENABLED =
+    buildConf("spark.sql.optionalReferences.enabled")
+      .internal()
+      .doc("When true, a `?` after an identifier of a column, field, or 
variable reference, or " +
+        "after a named parameter marker, makes that identifier optional: when 
it cannot be " +
+        "resolved, the reference evaluates to a NULL of type VOID instead of 
raising an error.")

Review Comment:
   Done. The doc now limits the NULL to an identifier that no name matches, 
says that ambiguous references and type errors are still raised, and lists the 
statements and clauses that reject `?`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,377 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral
+}
+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.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 an optional [[UnresolvedExtractValue]] as a last resort, see 
[[markLastResort]]. */
+  val LAST_RESORT: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReferenceLastResort")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   */
+  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
+
+  /**
+   * Marks the optional field extraction `extractValue` as one that no name 
resolution step of its
+   * operator could resolve, so that its missing field is NULL in the next 
step that resolves its
+   * child. Until then, a step whose errors are not final leaves it 
unresolved, like the same
+   * extraction without `?`, because a later step can still resolve it. For 
example, ORDER BY
+   * resolves names against the SELECT list before the columns of the FROM 
clause:
+   *
+   * {{{
+   *   -- `t.arr` is an ARRAY<STRUCT<a INT, b INT>>, so ORDER BY sorts by its 
field `b`.
+   *   SELECT array(named_struct('a', 1)) AS arr FROM t ORDER BY arr[0].b?;
+   * }}}
+   */
+  def markLastResort(extractValue: UnresolvedExtractValue): Unit =
+    extractValue.setTagValue(LAST_RESORT, ())
+
+  /** Returns true if `extractValue` is marked as a last resort, see 
[[markLastResort]]. */
+  def isLastResort(extractValue: UnresolvedExtractValue): Boolean =
+    extractValue.getTagValue(LAST_RESORT).isDefined
+
+  /** 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. Session variable qualifiers 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))

Review Comment:
   Fixed. `VariableManager` has `isScopeLabel(label)`, which the scripting 
manager implements with the same frame search as variable lookup, and 
`firstUnmatchedNamePartIndex` counts such a label as a matched qualifier of a 
two-part name, so both analyzers return NULL. Golden cases: `lbl.y?`, 
`r.missing?`, and `r.addr.state?` are NULL and `lbl.x?`, `r.id?`, and 
`r.addr.city?` return their values inside a labeled block and a FOR loop; 
`other.x?` still fails with `UNRESOLVED_COLUMN`.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SubstituteParamsParser.scala:
##########
@@ -184,6 +206,23 @@ class SubstituteParamsParser extends Logging {
     (substitutedText, substitutions.toList)
   }
 
+  /**
+   * Returns the text that replaces the named parameter marker at `location` 
with `value`. Unlike
+   * a parameter name, the `?` of an optional marker can be directly followed 
by a keyword or an
+   * identifier, as in `:x?AND`, which must not become a part of the value.
+   */
+  private def namedReplacement(
+      sqlText: String,
+      location: ParameterLocation,
+      value: String): String = {
+    val nextIndex = sqlText.offsetByCodePoints(0, location.end)
+    val isFollowedByWord = location.optional && nextIndex < sqlText.length && {
+      val nextCodePoint = sqlText.codePointAt(nextIndex)
+      Character.isLetterOrDigit(nextCodePoint) || nextCodePoint == '_'
+    }

Review Comment:
   Applied.



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:
##########
@@ -139,6 +140,31 @@ private[parser] class UpperCaseCharStream(wrapped: 
CodePointCharStream) extends
   }
 }
 
+/**
+ * Counts the `?` tokens that a parse uses as positional parameter markers. A 
parse of a statement
+ * that fails, or that uses a `?` in another way, uses fewer of them than the 
statement has.
+ */
+private class PositionalParameterMarkerCounter extends 
SqlBaseParserBaseListener {
+  var count: Int = 0
+
+  override def enterEveryRule(ctx: ParserRuleContext): Unit = {
+    // The parser enters a rule without a parent when it starts to parse the 
statement, which it
+    // does once in each stage of the two-stage parsing strategy.
+    if (ctx.getParent == null) {

Review Comment:
   Added: `SELECT ?, a? FROM t` and `SELECT a FROM t WHERE b = ? AND c? IS 
NULL` in the parser suite (one positional parameter and one optional reference 
each), and `EXECUTE IMMEDIATE 'SELECT id FROM people WHERE id = ? AND deleted? 
IS NULL' USING 1` in the golden file.



##########
sql/api/src/main/scala/org/apache/spark/sql/catalyst/parser/parsers.scala:
##########
@@ -500,12 +526,17 @@ object AbstractParser extends Logging {
     parser.legacy_identifier_clause_only = conf.legacyIdentifierClauseOnly
     parser.single_character_pipe_operator_enabled = 
conf.singleCharacterPipeOperatorEnabled
     parser.file_type_enabled = conf.isFileTypeEnabled
+    parser.optional_references_enabled = conf.optionalReferencesEnabled
   }
 
   /**
    * Executes a parsing operation using the standard two-stage parsing 
strategy. This ensures
    * consistent error handling and performance optimization across all parsers.
    *
+   * If optional references (`x?`) are enabled, the operation is executed 
again with optional
+   * references if it does not use every `?` of the statement as a positional 
parameter marker
+   * without them, see [[restartWithOptionalReferences]].

Review Comment:
   Applied both wordings.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -4746,22 +4746,34 @@ class AstBuilder extends DataTypeAstBuilder
    * it can be [[UnresolvedExtractValue]].
    */
   override def visitDereference(ctx: DereferenceContext): Expression = 
withOrigin(ctx) {
+    val optionalMarker = ctx.fieldName.optionalMarker
     // Use getIdentifierText to handle both regular identifiers and 
IDENTIFIER('literal')
-    val attr = getIdentifierText(ctx.fieldName)
+    val attr = getIdentifierText(ctx.fieldName.identifier)
     expression(ctx.base) match {
       case unresolved_attr @ UnresolvedAttribute(nameParts) =>
         // For regex check, we need the original text before identifier-lite 
resolution
         ctx.fieldName.getStart.getText match {
           case escapedIdentifier(columnNameRegex)
             if conf.supportQuotedRegexColumnName &&
               isRegex(columnNameRegex) && canApplyRegex(ctx) =>
+            firstOptionalMarker(ctx).foreach { marker =>
+              throw 
QueryParsingErrors.unexpectedOptionalReferenceMarkerError(ctx, marker)
+            }
             UnresolvedRegex(columnNameRegex, Some(unresolved_attr.name),
               conf.caseSensitiveAnalysis)
           case _ =>
-            UnresolvedAttribute(nameParts :+ attr)
+            val dereference = UnresolvedAttribute(nameParts :+ attr)
+            OptionalReferences.markNamePartsOptional(
+              dereference, 
OptionalReferences.optionalNamePartIndices(unresolved_attr))
+            withOptionalNamePart(dereference, nameParts.length, 
optionalMarker, ctx)
         }
       case e =>
-        UnresolvedExtractValue(e, Literal(attr))
+        val extractValue = UnresolvedExtractValue(e, Literal(attr))
+        if (optionalMarker != null) {
+          OptionalReferenceValidation.validate(ctx)

Review Comment:
   Added `CREATE TABLE t (a ARRAY<STRUCT<b: INT>>, CONSTRAINT c CHECK (a[0].b? 
> 0))` and `CREATE TABLE t (a INT, b INT GENERATED ALWAYS AS (IDENTIFIER('a' || 
'')? + 1))` to the parser suite, each asserting `IN_DDL` with the context of 
its clause and the fragment of the reference.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CheckOptionalReferencesInDml.scala:
##########
@@ -0,0 +1,76 @@
+/*
+ * 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, 
SubqueryExpression}
+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))
+        }
+      }
+    }
+    plan
+  }
+
+  private def statementName(operator: LogicalPlan): Option[String] = operator 
match {
+    case _: DeleteFromTable => Some("DELETE")
+    case _: UpdateTable => Some("UPDATE")
+    case _: MergeIntoTable => Some("MERGE")
+    // The plan of INSERT ... REPLACE WHERE.
+    case _: OverwriteByExpression => Some("INSERT")
+    case _ => None
+  }
+
+  private def checkExpression(expression: Expression, statement: String): Unit 
= {
+    expression.foreach {
+      case reference if !reference.resolved && 
OptionalReferences.hasOptionalMarker(reference) =>
+        throw QueryCompilationErrors.optionalReferenceInDmlNotSupportedError(
+          statement,
+          reference.origin
+        )
+      case subquery: SubqueryExpression =>

Review Comment:
   Added a `MergeIntoDataFrameSuite` case whose matched-update assignment is 
`expr("(SELECT max(bonus?) FROM source)")`, asserting `IN_DML` with the `MERGE` 
context. The walk now lives in 
`OptionalReferences.unresolvedOptionalReference`, which the AUTO CDC check 
shares.



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