spark-test commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4576517538
##########
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" : [
+ "Definitions of tables and functions must not contain optional
references."
Review Comment:
**Nit (P3):** This message tells users that table and function definitions
cannot use `?`, but the PR accepts `?` in SQL function bodies, view queries,
and CTAS queries, as the golden file shows; only DEFAULT (of columns and of SQL
function parameters), GENERATED ALWAYS AS, CHECK, and OPTIONS reject it. The
same overstatement is in the `spark.sql.optionalReferences.enabled` doc, whose
list ends with "table definitions" and leaves out function parameter defaults,
and in the `OptionalReferenceValidation` doc, which also says that CREATE OR
REPLACE TABLE AS SELECT rejects `?` only in a REPLACE condition, a clause RTAS
does not have. The wording of this message came from the previous review's
suggestion, which was too broad.
Suggested fix: name the rejected clauses, for example "Defaults, generation
expressions, CHECK constraints, and options of tables and functions must not
contain optional references.", and describe the same clauses in both docs.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60367#discussion_r4559147444),
[2](https://github.com/apache/spark/pull/60367#discussion_r4570588641),
[3](https://github.com/apache/spark/pull/60367#discussion_r4570588675).
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/SubstituteParamsParser.scala:
##########
@@ -73,12 +73,39 @@ 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 >
+ locations.positionalParameterLocations.length &&
+ AbstractParser.restartWithOptionalReferences(parser, tokenStream)
=>
+ parseParameterLocations()
+ case parsed =>
+ parsed
+ }
+ // In a statement with optional references, a `?` after an identifier or a
non-reserved keyword
+ // is an optional reference where the syntax allows a reference. The
remaining markers must
+ // not take the values of such a `?` silently, so a value without a marker
is an error.
+ val numPositionalMarkers =
parameterLocations.positionalParameterLocations.length
+ if (parameterLocations.hasOptionalReferences &&
Review Comment:
**Non-blocking (P2):** For `EXECUTE IMMEDIATE ... USING`,
`ParameterHandler.handleHybridParameters` passes every USING value as
`positionalParams`, the named ones included, next to the named map. By the
review's reading of the code, `EXECUTE IMMEDIATE 'SELECT id FROM people WHERE
id = :x AND deleted? IS NULL' USING 1 AS x` therefore reaches this check with 0
positional markers and 1 positional value and fails with
UNUSED_SQL_PARAMETER_VALUES, although its only value is bound by name. The same
statement runs through `spark.sql(text, Map("x" -> 1))`, which supplies no
positional values, and in the legacy binding mode, whose named branch of
BindParameters does not apply the check. Named parameters together with
optional references are the natural way to write such a statement over an
evolving schema.
Suggested fix: apply the check only when the statement has no named markers.
Then every value can bind to a `?` marker, while with named markers every value
binds by name, and unnamed values or `?` markers are already errors.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60367#issuecomment-6866045584).
**Verification:**
- **Regression:** With optional references on, `EXECUTE IMMEDIATE 'SELECT id
FROM people WHERE id = :x AND deleted? IS NULL' USING 1 AS x` over a relation
without `deleted` returns the rows with id 1 instead of failing with
UNUSED_SQL_PARAMETER_VALUES.
- **Compatibility:** With optional references on, an EXECUTE IMMEDIATE
statement with `?` markers and an optional reference that is given more values
than markers, passed as named USING values, still fails with
UNUSED_SQL_PARAMETER_VALUES with the counts of markers and values.
##########
sql/core/src/main/scala/org/apache/spark/sql/classic/SparkSession.scala:
##########
@@ -552,7 +552,10 @@ class SparkSession private(
}
// In legacy mode, wrap with PosParameterizedQuery for analyzer
binding
if (args.nonEmpty &&
sessionState.conf.legacyParameterSubstitutionConstantsOnly) {
- PosParameterizedQuery(parsed, paramContext.params)
+ PosParameterizedQuery(
+ parsed,
+ paramContext.params,
+ hasOptionalReferences =
OptionalReferences.hasOptionalReferences(parsed))
Review Comment:
**Nit (P3):** With `spark.sql.legacy.parameterSubstitution.constantsOnly`
on, this `PosParameterizedQuery` and the `GeneralParameterizedQuery` built for
`parseParameterizedPlan` (also reached from EXECUTE IMMEDIATE ... USING) run
`OptionalReferences.hasOptionalReferences(parsed)` whether or not
`spark.sql.optionalReferences.enabled` is on. With the conf off the parser
never produces an optional reference, so the walk over every operator,
expression, subquery plan, and CTE of the parsed plan always returns false. The
cost is small next to analysis, but it falls on statements outside the feature.
Suggested fix: compute the flag as
`sessionState.conf.optionalReferencesEnabled &&
OptionalReferences.hasOptionalReferences(parsed)` at both sites, which gives
the same value.
**Verification:**
- **Inspection:** Both legacy parameterized-query constructions in
SparkSession evaluate the optional-reference search only when
spark.sql.optionalReferences.enabled is on and pass false otherwise.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala:
##########
@@ -4755,13 +4757,24 @@ class AstBuilder extends DataTypeAstBuilder
case escapedIdentifier(columnNameRegex)
if conf.supportQuotedRegexColumnName &&
isRegex(columnNameRegex) && canApplyRegex(ctx) =>
+ firstOptionalMarker(ctx).foreach { marker =>
Review Comment:
**Nit (P3):** `firstOptionalMarker` looks only through
`ColumnReferenceContext` and `DereferenceContext`, but `expression(ctx.base)`
also returns the marked attribute through parentheses. By the review's reading
of the code, with `spark.sql.parser.quotedRegexColumnNames` on, ``SELECT
(t?).`(a|b)` FROM t`` therefore builds the same `UnresolvedRegex` as ``SELECT
t.`(a|b)` FROM t``, and the `?` disappears without an error, while ``SELECT
t?.`(a|b)` FROM t`` fails with the unexpected-marker error. There is no wrong
result, since the statement behaves as without `?`, but the user's marker is
accepted and ignored.
Suggested fix: let `firstOptionalMarker` look through
`ParenthesizedExpressionContext`, so every spelling of the qualifier gets the
same error.
**Verification:**
- **Regression:** With optional references and quoted regex column names on,
`SELECT (t?).`(a|b)` FROM t` and `SELECT ((t?)).`(a|b)` FROM t` fail with the
same unexpected-marker parse error as `SELECT t?.`(a|b)` FROM t`.
- **Compatibility:** With quoted regex column names on, `SELECT (t).`(a|b)`
FROM t` without a marker still selects the matching columns of t.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,433 @@
+/*
+ * 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.{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 with
+ * [[withOptionalNamePartsOf]]. 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(_.flatMap(_.expressions).iterator.flatMap(unresolvedOptionalReference))
+ .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, which are not
children of the
+ * operator that defines them. 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 = plan.exists {
operator =>
+ operator.expressions.exists(unresolvedOptionalReference(_).isDefined) ||
+ operator.innerChildren.exists {
+ case innerPlan: LogicalPlan => hasOptionalReferences(innerPlan)
+ case _ => false
+ }
+ }
+
+ /** 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,
+ resolvingView: Boolean): Boolean = {
+ optionalNamePartIndices.nonEmpty &&
+ firstUnmatchedNamePartIndex(nameParts, attributes, resolver,
resolvingView).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 while the body of a
view is resolved
+ * (`resolvingView`), where variable lookup hides the variables of the
script. 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,
+ resolvingView: Boolean): Option[Int] = {
+ val matchedNamePartCounts =
+ attributes.iterator.map(matchedNamePartCount(nameParts, _, resolver)) ++
+
SESSION_VARIABLE_QUALIFIERS.iterator.map(matchedQualifierPartCount(nameParts,
_, resolver)) ++
+ Iterator(if (resolvingView) 0 else
matchedScriptingScopeLabelCount(nameParts))
Review Comment:
**Nit (P3):** `resolvingView` is true only while a stored view body is
resolved, not while CREATE VIEW analyzes the same query, so the two analyses
disagree on whether `lbl` qualifies `lbl.missing?`. In the golden file, `CREATE
TEMPORARY VIEW lbl_v AS SELECT lbl.missing? AS m` inside `lbl: BEGIN ... END`
succeeds, and both reads of `lbl_v`, inside the block and after it, fail with
UNRESOLVED_COLUMN for `lbl.missing`. The same applies to FOR-variable
qualifiers, to subqueries of the view's query, to ALTER VIEW ... AS, and to a
persistent CREATE VIEW, which is then stored unreadable; without `?`, the same
definition fails at creation. The golden comment before the case also says that
a label does not qualify a reference in a view body, but a view body does
resolve a label-qualified variable that it captured when it was created; only a
name that matches no captured variable loses the label.
Suggested fix: apply the view-body label rule while a view definition's
query is analyzed, including the plans of its subqueries, which the analyzer
resolves in nested analyses (for example through a field of AnalysisContext),
so that such a definition fails at creation, and correct the golden comment.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60367#discussion_r4570588694).
**Verification:**
- **Regression:** With optional references on, inside `lbl: BEGIN DECLARE y
INT DEFAULT 1; ... END`, `CREATE TEMPORARY VIEW v AS SELECT lbl.missing? AS m`,
`CREATE TEMPORARY VIEW v AS SELECT (SELECT lbl.missing?) AS m`, and a
persistent `CREATE VIEW` with the first body fail at creation with
UNRESOLVED_COLUMN for `lbl.missing`, and inside `FOR r AS SELECT id FROM people
DO ... END FOR` a view whose body has `r.missing?` fails the same way.
- **Compatibility:** With optional references on, a temporary view created
inside a labeled block with `SELECT lbl.y AS y` returns 1 when read inside the
block, and `SELECT lbl.missing?` as a query inside the block still returns NULL.
- **Inspection:** The golden-file comment before the labeled-block view case
says that a view body resolves the label-qualified variables it captured when
it was created, and that only a name that matches no captured variable loses
the label.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/OptionalReferenceValidation.scala:
##########
@@ -0,0 +1,115 @@
+/*
+ * 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 is stored in the definition of a table or a function.
+ *
+ * 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 and CREATE OR REPLACE TABLE
AS SELECT reject them
+ * only in the REPLACE condition, a predicate on the target table: their
queries produce the rows
+ * to write, and a missing column in such a query makes the written rows
differ in the same way as
+ * in any other query. This holds where the written rows also decide which
existing rows are
+ * replaced: an INSERT OVERWRITE with dynamic partition overwrite replaces
the partitions of the
+ * written rows, and INSERT ... REPLACE ON or REPLACE USING deletes the
target rows that match
+ * them.
+ *
+ * {{{
+ * UPDATE t SET a = b?; -- IN_DML
+ * WITH s AS (SELECT a? FROM u) DELETE FROM t WHERE ...; -- IN_DML
+ * INSERT INTO t REPLACE WHERE a? IS NULL SELECT ...; -- IN_DML
+ * TRUNCATE TABLE t PARTITION (p = :p?); --
IN_PARTITION_SPEC
+ * CREATE TABLE t (a INT, b INT DEFAULT a?); -- IN_DDL
+ * INSERT OVERWRITE t SELECT a? FROM s; -- allowed
+ * }}}
+ */
+ def validate(ctx: ParserRuleContext): Unit = {
+ Iterator
+ .iterate(ctx.getParent)(_.getParent)
+ .takeWhile(_ != null)
+ .flatMap(unsupportedContextError(_, ctx))
+ .nextOption()
+ .foreach(error => throw error)
+ }
+
+ /**
+ * Validates the optional named parameter markers in the parse tree `tree`
with [[validate]].
+ * This is for the markers that are substituted in `sqlText`, the text that
`tree` was parsed
+ * from, before the statement is parsed into a plan.
+ */
+ def validateNamedParameterMarkers(tree: ParseTree, sqlText: String): Unit =
tree match {
+ case namedParameter: NamedParameterLiteralContext if
namedParameter.optionalMarker != null =>
+ SparkParserUtils.withOrigin(namedParameter, Some(sqlText)) {
+ validate(namedParameter)
+ }
+ case _ =>
+ (0 until tree.getChildCount).foreach { index =>
+ validateNamedParameterMarkers(tree.getChild(index), sqlText)
+ }
+ }
+
+ /**
+ * Returns the error for the optional reference `ctx` if its ancestor
`ancestor` is a statement
+ * or a clause that does not support optional references.
+ */
+ private def unsupportedContextError(
+ ancestor: ParserRuleContext,
+ ctx: ParserRuleContext): Option[Throwable] = ancestor match {
+ case _: DeleteFromTableContext =>
+
Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("DELETE", ctx))
+ case _: UpdateTableContext =>
+
Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("UPDATE", ctx))
+ case _: MergeIntoTableContext =>
+ Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("MERGE",
ctx))
+ case _: InsertIntoReplaceBooleanCondContext =>
+
Some(QueryParsingErrors.optionalReferenceInDmlNotSupportedError("INSERT", ctx))
Review Comment:
**Nit (P3):** With the context `INSERT`, `INSERT INTO target REPLACE WHERE
missing? IS NULL SELECT * FROM target` fails with "The `?` optional-reference
operator is not supported in INSERT. Statements that modify table data must not
contain optional references.", and `CheckOptionalReferencesInDml` gives
`df.writeTo("t").overwrite(expr("deleted_at? IS NULL"))` the same message. Both
sentences point the user away from the clause that is rejected: the queries of
INSERT, INSERT OVERWRITE, and INSERT ... REPLACE ON/USING also modify table
data, and they accept `?`.
Suggested fix: pass a context that names the condition, for example `INSERT
... REPLACE` here and a matching one for the overwrite condition, and word the
IN_DML subclass for statements that modify existing rows and for conditions
that select the rows to replace.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,433 @@
+/*
+ * 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.{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 with
+ * [[withOptionalNamePartsOf]]. 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(_.flatMap(_.expressions).iterator.flatMap(unresolvedOptionalReference))
Review Comment:
**Non-blocking (P2):** `subquery.plan.flatMap(_.expressions)` visits only
the children of the subquery plan, and `UnresolvedWith` keeps its common table
expressions as `innerChildren`, so a CTE defined inside a subquery is never
searched. `PipelinesHandler` runs this search on the change arguments before
CTE substitution, so by the review's reading of the code, an AUTO CDC flow
defined through the pipelines API with `apply_as_deletes` set to `(WITH c AS
(SELECT max(deleted?) AS d FROM src) SELECT d FROM c) = true` is registered,
while `(SELECT max(deleted?) FROM src) = true`, the case
SparkDeclarativePipelinesServerSuite covers, and the SQL form of the flow fail
with IN_DML. A source without `deleted` then silently gets no deletes applied,
the outcome the rejection exists to prevent; it needs the conf on and an
unusual change argument. `CheckOptionalReferencesInDml` runs after CTE
substitution and is not affected, and neither is the legacy binding flag:
`hasOptionalReferences` als
o follows `operator.innerChildren`, which for an ordinary operator is the
plans of its subquery expressions and for `UnresolvedWith` its CTE plans.
Suggested fix: search a subquery plan here the way `hasOptionalReferences`
searches a plan, including the plans an operator keeps outside its children,
and add a handler test for this shape.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60367#discussion_r4559147418).
**Verification:**
- **Regression:** With optional references on, defining an AUTO CDC flow
through the pipelines API whose delete condition is `(WITH c AS (SELECT
max(deleted?) AS d FROM src) SELECT d FROM c) = true`, and one whose delete
condition has `?` in a CTE of a subquery nested inside another subquery, fails
with the IN_DML error and the AUTO CDC context, and the flow is not registered.
- **Compatibility:** With optional references on, the same flows with
`deleted` in place of `deleted?` are accepted.
--
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]