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


##########
sql/core/src/test/scala/org/apache/spark/sql/OptionalReferencesSuite.scala:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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
+
+import org.apache.spark.sql.catalyst.expressions.Literal
+import org.apache.spark.sql.catalyst.parser.ParseException
+import org.apache.spark.sql.catalyst.plans.logical.Sort
+import org.apache.spark.sql.classic.Dataset
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+
+/**
+ * Tests of optional references (`x?`) that need more than one analysis of a 
plan. The golden file

Review Comment:
   Done: the class doc now names what the golden file cannot express and the 
suite does: a second analysis of the same unresolved plan, a query that only 
the fixed-point analyzer resolves, an error whose context is relative to text 
parsed apart from the statement, and, new in this round, the definition of a 
metric view.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala:
##########
@@ -0,0 +1,118 @@
+/*
+ * 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 REPLACE condition of INSERT, of a partition 
specification, or of a DEFAULT,
+   * GENERATED ALWAYS AS, CHECK, or OPTIONS clause of a table or function 
definition.
+   *
+   * The boundary is the kind of statement. UPDATE, DELETE, MERGE, and AUTO 
CDC exist to modify
+   * existing rows, so they reject optional references everywhere, including 
in the source query of
+   * MERGE and in common table expressions. INSERT rejects them only in the 
REPLACE condition, a

Review Comment:
   Done: the boundary paragraph now says that INSERT rejects optional 
references in the REPLACE condition and in its PARTITION clause, like every 
partition specification.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,463 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import java.util.Locale
+
+import scala.annotation.tailrec
+import scala.util.{Left => EitherLeft, Right => EitherRight}
+
+import org.apache.spark.SparkThrowable
+import org.apache.spark.sql.catalyst.SqlScriptingContextManager
+import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
+  Attribute,
+  Expression,
+  ExtractValue,
+  Literal,
+  NonNullLiteral,
+  SubqueryExpression
+}
+import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
+import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.util.{toPrettySQL, MetadataColumnHelper}
+import org.apache.spark.sql.connector.catalog.CatalogManager
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{DataType, NullType, StringType}
+
+/**
+ * Optional references: a `?` after an identifier of a column, field, or 
variable reference, or
+ * after a named parameter marker, makes that identifier optional. When name 
resolution finds no
+ * match for an optional identifier, the reference resolves to a static NULL 
of type VOID instead
+ * of raising a not-found error. Ambiguity and type errors are still raised.
+ *
+ * {{{
+ *   -- `t` has a column `id` but no column `name`:
+ *   SELECT id?, name? FROM t;
+ *   -- Project [id#1, null AS name#2]
+ * }}}
+ */
+object OptionalReferences {
+
+  /**
+   * Indices of the name parts of an unresolved multipart name (an 
`UnresolvedAttribute` or an
+   * `UnresolvedNamedLambdaVariable`) that are followed by `?`.
+   */
+  val OPTIONAL_NAME_PART_INDICES: TreeNodeTag[Set[Int]] =
+    TreeNodeTag[Set[Int]]("optionalNamePartIndices")
+
+  /**
+   * Marks an [[UnresolvedExtractValue]] field, a named parameter marker, or 
an IDENTIFIER clause
+   * followed by `?`.
+   */
+  val OPTIONAL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReference")
+
+  /**
+   * Marks the NULL that an unresolvable optional reference resolves to, see 
[[nullReference]], and
+   * the alias that names it, see [[implicitAlias]].
+   *
+   * The two tags that the parser sets, [[OPTIONAL_NAME_PART_INDICES]] and 
[[OPTIONAL_REFERENCE]],
+   * describe the statement: they are facts about the reference as written, 
which stay true in
+   * every analysis of the plan. The generic transforms of a tree copy them to 
the nodes that
+   * replace a tagged node. A rule that rebuilds a reference in another way 
forwards them itself:
+   * the optional name parts of a multipart name with 
[[withOptionalNamePartsOf]], and the marker
+   * of a field extraction, a named parameter marker, or an IDENTIFIER clause 
with `copyTagsFrom`.
+   * This tag records a decision of one analysis, that a reference matched 
nothing, on the NULL
+   * and the alias that this analysis creates. Only the analyzer sets it, and 
only on these nodes:
+   * the plan that the analyzer receives can be analyzed again later, e.g. 
from a plan cache,
+   * against a relation that has the column by then. The other decision of an 
analysis, that no
+   * resolution step of an operator can resolve a field extraction, is a node 
of the plan that the
+   * analysis builds, see [[LastResortExtractValue]].
+   */
+  val NULL_REFERENCE: TreeNodeTag[Unit] = 
TreeNodeTag[Unit]("optionalReferenceNull")
+
+  /** Qualifiers of session variables, which are valid prefixes of a variable 
reference. */
+  private val SESSION_VARIABLE_QUALIFIERS = Seq(
+    Seq(CatalogManager.SYSTEM_CATALOG_NAME, CatalogManager.SESSION_NAMESPACE),
+    Seq(CatalogManager.SESSION_NAMESPACE)
+  )
+
+  /** Returns the indices of the optional name parts of `expression`. */
+  def optionalNamePartIndices(expression: Expression): Set[Int] =
+    expression.getTagValue(OPTIONAL_NAME_PART_INDICES).getOrElse(Set.empty)
+
+  /** Marks the name parts at `indices` of the multipart name `expression` as 
optional. */
+  def markNamePartsOptional(expression: Expression, indices: Set[Int]): Unit = 
{
+    if (indices.nonEmpty) {
+      expression.setTagValue(
+        OPTIONAL_NAME_PART_INDICES,
+        optionalNamePartIndices(expression) ++ indices
+      )
+    }
+  }
+
+  /** Marks `expression` as a whole as optional. */
+  def markOptional(expression: Expression): Unit =
+    expression.setTagValue(OPTIONAL_REFERENCE, ())
+
+  /** Returns true if `expression` as a whole is marked optional. */
+  def isOptional(expression: Expression): Boolean =
+    expression.getTagValue(OPTIONAL_REFERENCE).isDefined
+
+  /** Returns true if `expression` or any of its name parts is marked 
optional. */
+  def hasOptionalMarker(expression: Expression): Boolean =
+    isOptional(expression) || optionalNamePartIndices(expression).nonEmpty
+
+  /**
+   * Gives `expression`, a multipart name that a rule rebuilt from `source`, 
the optional name
+   * parts of `source`, which a case class copy or a constructor does not keep.
+   */
+  def withOptionalNamePartsOf[T <: Expression](expression: T, source: 
Expression): T = {
+    markNamePartsOptional(expression, optionalNamePartIndices(source))
+    expression
+  }
+
+  /**
+   * Returns the first unresolved expression in `expression` that is an 
optional reference or has
+   * an optional name part, including in the plans of its subquery 
expressions, or None.
+   */
+  def unresolvedOptionalReference(expression: Expression): Option[Expression] 
= {
+    expression.find(e => !e.resolved && hasOptionalMarker(e)).orElse {
+      expression
+        .collect { case subquery: SubqueryExpression => subquery.plan }
+        .iterator
+        .flatMap(plan => unresolvedOptionalReference(plan))
+        .nextOption()
+    }
+  }
+
+  /**
+   * Returns true if the parsed `plan` has an optional reference, including in 
the plans of its
+   * subquery expressions and in its common table expressions. Before the 
analysis, every optional
+   * reference of the statement is unresolved, so the answer does not depend 
on the data that the
+   * statement is analyzed against.
+   */
+  def hasOptionalReferences(plan: LogicalPlan): Boolean =
+    unresolvedOptionalReference(plan).isDefined
+
+  /**
+   * Returns the first unresolved optional reference of the operators of 
`plan`, including in the
+   * plans of their subquery expressions and in the plans that an operator 
keeps outside of its
+   * children, such as the common table expressions of `UnresolvedWith`, or 
None.
+   */
+  def unresolvedOptionalReference(plan: LogicalPlan): Option[Expression] = {
+    plan.expressions.iterator
+      .flatMap(expression => unresolvedOptionalReference(expression))
+      .nextOption()
+      .orElse {
+        // The subquery plans of the operator are inner children as well, and 
the search of its
+        // expressions has covered them, so that every plan is searched once.
+        val subqueryPlans = plan.expressions.flatMap(_.collect {
+          case subquery: SubqueryExpression => subquery.plan
+        })
+        plan.innerChildren.iterator
+          .collect {
+            case innerPlan: LogicalPlan if !subqueryPlans.exists(_ eq 
innerPlan) => innerPlan
+          }
+          .flatMap(innerPlan => unresolvedOptionalReference(innerPlan))
+          .nextOption()
+      }
+      .orElse {
+        plan.children.iterator.flatMap(child => 
unresolvedOptionalReference(child)).nextOption()
+      }
+  }
+
+  /**
+   * The static NULL that an unresolvable optional reference resolves to: of 
type VOID, or of type
+   * VARIANT for a path extracted from such a NULL (`missing?:a`).
+   */
+  def nullReference(dataType: DataType = NullType): Literal = {
+    val nullReference = Literal(null, dataType)
+    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, or the 
[[implicitAlias]] that names
+   * one. [[isNullReferenceAlias]] tells the alias apart.
+   */
+  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,
+      isViewQuery: Boolean): Boolean = {
+    optionalNamePartIndices.nonEmpty &&
+    firstUnmatchedNamePartIndex(nameParts, attributes, resolver, 
isViewQuery).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, the latter except in the query of a 
view (`isViewQuery`),
+   * when the view is read or defined: a view cannot see the variables of the 
script, so a
+   * definition that resolves a label is rejected when the view is created 
rather than when it is
+   * read. 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,
+      isViewQuery: Boolean): Option[Int] = {
+    val matchedNamePartCounts =
+      attributes.iterator.map(matchedNamePartCount(nameParts, _, resolver)) ++
+      
SESSION_VARIABLE_QUALIFIERS.iterator.map(matchedQualifierPartCount(nameParts, 
_, resolver)) ++
+      Iterator(if (isViewQuery) 0 else 
matchedScriptingScopeLabelCount(nameParts))
+    val longestMatch = matchedNamePartCounts.max
+    if (longestMatch < nameParts.length) Some(longestMatch) else None
+  }
+
+  /**
+   * Returns 1 if `nameParts` has at least two parts and its first part is the 
label of an active
+   * SQL scripting scope, so that the name can reference a variable of that 
scope and then the
+   * nested fields of that variable, and 0 otherwise.
+   */
+  private def matchedScriptingScopeLabelCount(nameParts: Seq[String]): Int = {
+    val isScopeLabel = nameParts.length >= 2 && {
+      // Scope labels are normalized like variable names, see 
`VariableResolution.lookupVariable`.
+      val label = if (SQLConf.get.caseSensitiveAnalysis) {
+        nameParts.head
+      } else {
+        nameParts.head.toLowerCase(Locale.ROOT)
+      }
+      
SqlScriptingContextManager.get().flatMap(_.getVariableManager).exists(_.isScopeLabel(label))
+    }
+    if (isScopeLabel) 1 else 0
+  }
+
+  /**
+   * Returns the name with which to alias the static NULL of the optional 
field extraction
+   * `unresolvedExtractValue` if `child` is resolved and does not have the 
extracted struct field,
+   * or None otherwise. The name is the one that the extraction has when the 
field exists.
+   */
+  def missingOptionalFieldAliasName(
+      unresolvedExtractValue: UnresolvedExtractValue,
+      child: Expression,
+      extraction: Expression,
+      resolver: Resolver): Option[String] = {
+    extraction match {
+      case NonNullLiteral(fieldName, _: StringType)
+          if isOptional(unresolvedExtractValue) && child.resolved =>
+        ExtractValue.extractValue(child, extraction, resolver) match {
+          case EitherRight(throwable) if isFieldNotFound(throwable) =>
+            Some(s"${toPrettySQL(child)}.$fieldName")
+          case _ =>
+            None
+        }
+      case _ =>
+        None
+    }
+  }
+
+  /**
+   * Extracts `nestedFields` from `expression`, or returns the error of the 
extraction that
+   * failed. See [[extractNestedFields]].
+   */
+  @tailrec
+  private def extractNestedFieldsOrError(
+      expression: Expression,
+      nestedFields: Seq[String],
+      nestedFieldIndex: Int,
+      optionalNamePartIndices: Set[Int],
+      resolver: Resolver,
+      voidBaseIsNull: Boolean): Either[Expression, Throwable] = {
+    if (nestedFields.isEmpty) {
+      EitherLeft(expression)
+    } else if (voidBaseIsNull && expression.dataType == NullType) {
+      // The name is found, so this NULL is not a `nullReference`.
+      EitherLeft(Literal(null, NullType))

Review Comment:
   Done: the golden file now has `SELECT n.a?, a + 1 FROM VALUES (NULL) AS 
t(n)`. It returns two NULLs, because the alias `a` of the found field is a 
lateral column alias. With this branch changed locally to return 
`nullReference()`, the fixed-point analyzer failed the query while the 
single-pass resolver returned it, so the golden run failed with 
HYBRID_ANALYZER_EXCEPTION.



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