spark-test commented on code in PR #60367:
URL: https://github.com/apache/spark/pull/60367#discussion_r4610268423
##########
sql/core/src/test/resources/sql-tests/inputs/optional-references.sql:
##########
@@ -0,0 +1,646 @@
+-- Tests for optional column, field, variable, and named parameter references:
a `?` after an
+-- identifier makes that identifier optional, so that a reference that cannot
be resolved
+-- evaluates to a static NULL of type VOID instead of raising a not-found
error.
+
+--SET spark.sql.optionalReferences.enabled=true
+
+CREATE TEMPORARY VIEW people AS SELECT * FROM VALUES
+ (1, named_struct('city', 'SF', 'zip', '94105')),
+ (2, named_struct('city', 'NYC', 'zip', '10001'))
+ AS t(id, addr);
+
+CREATE TEMPORARY VIEW orgs AS SELECT * FROM VALUES
+ (1, named_struct('addr', named_struct('city', 'SF', 'zip', '94105')))
+ AS t(id, info);
+
+CREATE TEMPORARY VIEW orders AS SELECT * FROM VALUES
+ (1, array(named_struct('sku', 'a', 'qty', 5))),
+ (2, array(named_struct('sku', 'b', 'qty', 9)))
+ AS t(id, items);
+
+-- A missing column resolves to NULL and an existing column resolves normally.
Either way, the
+-- output column of a reference that is a whole SELECT item keeps the name of
the reference, and an
+-- expression over a missing reference is named after NULL.
+SELECT id?, name? FROM people;
+SELECT typeof(id?), typeof(name?) FROM people LIMIT 1;
+SELECT * FROM (SELECT id?, name? FROM people);
+
+-- Whitespace and comments between the identifier and `?` are insignificant.
+SELECT id ?, name /* comment */ ? FROM people;
+
+-- Optional references in expressions, predicates, grouping, ordering, and
function arguments.
+SELECT id, bonus? + 1 AS b FROM people;
+SELECT coalesce(archived?, false) AS archived, count(*) AS cnt
+FROM people
+WHERE archived? IS NULL
+GROUP BY archived?;
+SELECT id FROM people WHERE coalesce(archived?, false) = false ORDER BY id;
+SELECT id FROM people ORDER BY missing?, id DESC;
+SELECT id, sum(id) OVER (PARTITION BY region? ORDER BY id) AS running FROM
people;
+SELECT id FROM people GROUP BY id HAVING max(missing?) IS NULL ORDER BY id;
+SELECT id FROM people GROUP BY id HAVING max(addr.state?) IS NULL ORDER BY id;
+SELECT id FROM people GROUP BY id ORDER BY max(addr.state?), id;
+SELECT id, CASE WHEN missing? IS NULL THEN 'none' ELSE 'some' END AS c FROM
people;
+SELECT a.id FROM people a JOIN people b ON a.id = b.id AND a.missing? IS NULL
ORDER BY a.id;
+SELECT a.id, b.missing?, b.addr.state? FROM people a JOIN people b USING (id)
ORDER BY a.id;
+SELECT id, missing?, count(*) FROM people GROUP BY ALL ORDER BY id;
+SELECT count(*) + missing? AS c FROM people GROUP BY ALL;
+SELECT missing?, count(*) FROM people;
+SELECT count(missing?), max(id?) FROM people;
+SELECT DISTINCT missing?, addr?.city FROM people ORDER BY city;
+SELECT id, row_number() OVER (ORDER BY id) AS rn FROM people QUALIFY rn = 1
AND missing? IS NULL;
+
+-- GROUP BY, HAVING, and ORDER BY can reference aliases of the SELECT list as
usual.
+SELECT coalesce(region?, 'none') AS region, count(*) AS cnt FROM people GROUP
BY region?;
+SELECT coalesce(region?, 'none') AS region, count(*) AS cnt FROM people
+GROUP BY 1 HAVING region? = 'none';
+SELECT coalesce(rank?, id) AS rank FROM people ORDER BY rank? DESC;
+
+-- Where a name can resolve in more than one way, an optional reference
resolves like the same
+-- reference without `?`: ORDER BY falls back from the SELECT list to the
columns of the FROM
+-- clause, and HAVING falls back from those columns to the SELECT list.
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY
addr.zip?;
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY
addr.state?, id DESC;
+SELECT id, named_struct('city', addr.city) AS addr FROM people ORDER BY
addr?.state;
+SELECT named_struct('city', 'x') AS addr FROM people GROUP BY id ORDER BY
addr.zip?;
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY addr HAVING
addr.state? = 'CA';
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY addr
+HAVING addr.country? IS NULL;
+-- `addr.city` exists below the SELECT list but is not grouped, so HAVING
falls back to the alias
+-- `addr` of the SELECT list, which has no `city`.
+SELECT named_struct('state', 'CA') AS addr FROM people GROUP BY id HAVING
addr.city? IS NULL;
+-- A column that is out of scope is not found.
+SELECT DISTINCT id FROM people ORDER BY addr?, id DESC;
+-- ORDER BY and WHERE do not reach below an aliased subquery or a pipe
operator, like without `?`.
+SELECT id FROM (SELECT id FROM people) s ORDER BY addr?, id;
+SELECT id FROM (SELECT id FROM people) s ORDER BY addr, id;
+FROM people |> SELECT id |> WHERE addr? IS NULL;
+FROM people |> SELECT id |> WHERE addr IS NULL;
+
+-- Common table expressions and set operations.
+WITH cte AS (SELECT id, missing? AS m FROM people) SELECT id, m, other? FROM
cte ORDER BY id;
+SELECT id?, missing? FROM people UNION ALL SELECT missing?, id? FROM people
+ORDER BY id NULLS FIRST, missing NULLS FIRST;
+
+-- An optional reference that resolves keeps its type and nullability.
+SELECT id? + 1 AS next_id, addr?.city AS city FROM people;
+
+-- Qualified and nested references: `?` guards only the identifier that it
follows.
+SELECT p.name? FROM people AS p;
+SELECT people.name?, people.addr.state? FROM people;
+SELECT addr?.city FROM people;
+SELECT addr?.state FROM people;
+SELECT addr.state? FROM people;
+SELECT ghost?.city FROM people;
+SELECT ghost.city? FROM people;
+SELECT ghost?.city? FROM people;
+SELECT t.name? FROM people;
+SELECT people?, p? FROM people AS p;
+-- The qualifier of a table can include its namespace and catalog, like
without `?`.
+CREATE TABLE qualified_t (id INT) USING parquet;
+INSERT INTO qualified_t VALUES (1);
+SELECT qualified_t.missing? AS a, default.qualified_t.missing? AS b,
+ spark_catalog.default.qualified_t.missing? AS c
+FROM qualified_t;
+SELECT other.qualified_t.missing? FROM qualified_t;
+DROP TABLE qualified_t;
+
+-- Three-part names: `?` binds to the immediately preceding identifier only.
+SELECT info.addr.zip? FROM orgs;
+SELECT info.addr.geo? FROM orgs;
+SELECT info.loc?.city FROM orgs;
+SELECT info.loc.city? FROM orgs;
+SELECT info?.addr.zip FROM orgs;
+SELECT a?.b?.c? FROM orgs;
+SELECT missing?.a.b, info.addr.geo?.x FROM orgs;
+-- The fields of a column of type VOID are NULL, like without `?`. Such a
field is found, so its
+-- name is a lateral column alias.
+SELECT n.a, n.a? FROM VALUES (NULL) AS t(n);
+SELECT n.a?, a + 1 FROM VALUES (NULL) AS t(n);
+SELECT struct(id?, missing?) AS s FROM orgs;
+
+-- Errors other than not-found are still raised, and so is the not-found error
of an ORDER BY
+-- name that matches more than one column of the FROM clause, which is not a
missing column.
Review Comment:
**Nit (P3):** `SELECT missing? FROM people GROUP BY id;` at line 127 sits
under this heading but raises no error: the golden output records two NULL rows
with schema `struct<missing:void>`
(results/optional-references.sql.out:795-800), because a missing reference is a
constant NULL that needs no grouping. A reader who trusts the heading would
expect MISSING_AGGREGATION for it, the opposite of the recorded result. Either
say so in the heading, or move the statement next to the found `addr.zip?` at
line 132:
```suggestion
-- Errors other than not-found are still raised, and so is the not-found
error of an ORDER BY
-- name that matches more than one column of the FROM clause, which is not a
missing column. A
-- missing reference in the SELECT list of an aggregate is a constant NULL
that needs no grouping,
-- so it raises no error, unlike the found `addr.zip?` below.
```
This extends an [existing
discussion](https://github.com/apache/spark/pull/60367#discussion_r4592555050).
**Verification:**
- **Inspection:** The heading above the statements that still raise errors
in the optional-references golden input names the aggregate case that returns
NULL rows.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala:
##########
@@ -224,6 +219,51 @@ trait ColumnResolutionHelper extends Logging with
DataTypeErrorsBase {
resolved
}
+ def resolveExtractValue(u: UnresolvedExtractValue, isLastResort: Boolean):
Expression = {
+ val newChild = innerResolve(u.child, isTopLevel = false)
+ val resolvedField = if
(conf.getConf(SQLConf.PREFER_COLUMN_OVER_LCA_IN_ARRAY_INDEX)) {
+ innerResolve(u.extraction, isTopLevel = false)
+ } else {
+ u.extraction
+ }
+ // Like a missing optional field of a name, see above.
+ val missingOptionalFieldAliasName = if (throws || isLastResort) {
+ OptionalReferences.missingOptionalFieldAliasName(
+ unresolvedExtractValue = u,
+ child = newChild,
+ extraction = resolvedField,
+ resolver = resolver)
+ } else {
+ None
+ }
+ val resolved = if (missingOptionalFieldAliasName.isDefined) {
+ OptionalReferences.implicitAlias(
Review Comment:
**Nit (P3):** This alias is created wherever the extraction sits, not only
for a top-level SELECT item. In `SELECT coalesce(items[0].price?, 0) FROM
orders`, with `items` an array of structs without `price`, the extraction
reaches this method through the `UnresolvedExtractValue` case at line 199, and
nothing trims the alias in that nested position: `innerResolve` does so only in
the name case at line 179. Alias resolution names the unaliased SELECT item
with `toPrettySQL` before `CleanupAliases` runs, and `usePrettyExpression` has
no `Alias` case (catalyst/util/package.scala:91-160), so by the review's
reading the column is named ``coalesce(NULL AS `items[0].price`, 0)``. For a
struct column `s` without `price`, `coalesce(s.price?, 0)` gets `coalesce(NULL,
0)`, as the PR's rule that an expression over a missing reference is named as
if NULL were written says. Results are unaffected, but a view, an INSERT ... BY
NAME, or a DataFrame lookup by the generated name sees the alias text;
it is reached only with `spark.sql.optionalReferences.enabled` on.
A fix is to treat an extraction as top-level only when it is the expression
being resolved or the child of the top-level `UnresolvedAlias`, since an
unaliased SELECT item such as `items[0].price?` arrives wrapped in one, and to
pass that into `resolveExtractValue` for both the `UnresolvedExtractValue` and
the `LastResortExtractValue` cases. Create the implicit alias only at the top
level, and otherwise return the tagged `nullReference()` itself. The golden
files cover only top-level extractions of a missing optional field, so a case
such as `coalesce(items[0].price?, 0)` would pin the name.
**Verification:**
- **Regression:** An unaliased function over a missing optional field of an
array element or map value is named as if NULL were written.
- **Compatibility:** Unaliased top-level SELECT items that extract a missing
optional field, such as items[0].price? and array(named_struct('a', 1))[0].b?,
keep their implicit alias names, and a DML source with such a nested NULL is
still rejected.
##########
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.
Review Comment:
**Nit (P3):** `validate` is also called with an optional named parameter
marker, by `AstBuilder.visitNamedParameterLiteral` (AstBuilder.scala:8287) and
by `validateNamedParameterMarkers` (lines 72-76), and the examples below use
`:p?` and `:b?`, but this sentence describes only a reference with a `?` after
one of its name parts. A maintainer who adds a call site or changes the
ancestor checks from this doc would miss the named markers, whose IN_DML and
IN_PARTITION_SPEC rejections rely on the same walk.
```suggestion
* Throws an error for the optional reference `ctx`, i.e. the parse tree
of a reference with a
* `?` after one of its name parts or of a named parameter marker followed
by `?`, 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.
```
**Verification:**
- **Inspection:** The validate scaladoc describes its argument as a
reference or a named parameter marker followed by `?`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -313,7 +332,18 @@ object AnalysisContext {
} else {
mutable.LinkedHashSet.empty
},
- collation = function.collation)
+ // The body of a SQL function is not a part of the query that calls it.
If the call is in a
Review Comment:
**Non-blocking (P2):** This context drops the calling subquery's outer plan,
but it still copies the caller's `catalogAndNamespace`, so for a call from a
top-level query or a SQL script `resolveVariables` runs with `resolvingView =
false` (ColumnResolutionHelper.scala:336) and the body resolves names against
every session and script variable of the caller. For a persistent function, an
optional reference that matched nothing at CREATE FUNCTION leaves no variable
in the analyzed body, so `verifyTemporaryObjectsNotExists`
(CreateSQLFunctionCommand.scala:412) accepts it, and at each later call the
Resolution batch tries the caller's variables before
`ResolveOptionalReferences` turns the name into NULL. That contradicts the PR's
statement that an optional reference in a function body should not resolve
differently depending on where the function is called.
By the review's reading of the code: with the conf on, `CREATE FUNCTION pf()
RETURNS INT RETURN coalesce(x?, 0)` is created while no `x` exists. In a later
session that leaves the conf unset, `SELECT pf()` returns 0, but after `DECLARE
VARIABLE x INT DEFAULT 5` it returns 5, and inside `BEGIN DECLARE x INT DEFAULT
7; SELECT pf(); END` it returns 7. `CREATE VIEW pv AS SELECT coalesce(x?, 0) AS
c` returns 0 in all three, and CREATE FUNCTION rejects a body that references
the temporary variable `x` directly. Persistent SQL table functions and
session-qualified or label-qualified references such as `session.x?` and
`lbl.x?` behave the same way. Temporary SQL functions may read their caller's
temporary variables by design, as their other names already do on the base
branch, so they are outside this. Reaching it requires
`spark.sql.optionalReferences.enabled` to have been on when the function was
created.
**Recommended change:** Analyze the body of a SQL function stored in the
catalog so that its optional references, plain, session-qualified, or
label-qualified, never resolve to a session or SQL-script variable of the
caller: withAnalysisContext(function) records, for a non-temporary function,
that variable lookup for optional references is closed, as a persistent view
body sees no temporary variable, and the variable resolution of optional
references honors it, so the reference becomes the NULL it was at creation.
Temporary functions and every name without `?` keep their current lookup. SQL
function tests cover a persistent function whose body uses x? called with and
without a session or script variable x, and one whose body uses lbl.x? called
inside a block labeled lbl that declares x.
**Why this works:** A persistent function cannot reference a temporary
object, so no name in its body may resolve to one; closing the lookup for its
optional references at each call gives them the NULL they had at creation in
every calling session, the same result a persistent view gives.
**Compatibility:** Temporary SQL functions and every name without `?` in
persistent function bodies resolve as before.
**Risks:** A persistent function whose body has an optional reference that a
session or script variable satisfied at call time returns NULL there instead;
the syntax is unreleased and behind the internal conf.
**Constraints:** Temporary SQL functions keep resolving the session and
script variables of their caller. Names without `?` in persistent function
bodies keep their current resolution.
**Exclusions:**
- Names without `?` in persistent function bodies that fall back to a caller
temporary variable after a table drops a column, which the base branch already
allows.
- Temporary SQL functions, which may read the temporary variables of their
caller, as their other names already do on the base branch.
- Whether a label-qualified optional reference of a persistent function body
is NULL or raises UNRESOLVED_COLUMN for its label, which still depends on
whether the caller runs inside a block with that label; outside such a block
the call fails loudly instead of reading a variable.
**Verification:**
- **Regression:** A persistent SQL function whose body uses a plain or
session-qualified optional reference that matched nothing at creation returns
NULL-based results when called with no variable, after DECLARE VARIABLE of that
name, and inside a script that declares it, and so does a persistent table
function; inside a block labeled lbl that declares x, a body reference lbl.x?
is NULL rather than that variable.
- **Compatibility:** A temporary SQL function still reads a session variable
named by its body, with or without `?`, and a persistent function body without
`?` resolves as before.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -548,7 +596,13 @@ class Analyzer(
override def execute(plan: LogicalPlan): LogicalPlan = {
AnalysisContext.withNewAnalysisContext {
- executeSameContext(plan)
+ val analyzed = if (conf.optionalReferencesEnabled &&
AnalysisContext.definesView(plan)) {
Review Comment:
**Nit (P3):** This gate reads the session conf, but a SQL function created
while `spark.sql.optionalReferences.enabled` was on keeps it:
`SessionCatalog.makeSQLFunctionPlan` parses the body with the captured configs
unless the caller sets the key (SessionCatalog.scala:1902-1914), and
`ResolveOptionalReferences` does not check the conf. So in a session that
leaves the conf unset, a view definition that calls such a function is analyzed
with `isViewDefinition` false, and a label still qualifies names in the
function body (ResolveOptionalReferences.scala:170).
By the review's reading of the code: inside a script labeled `lbl` with the
conf on, `CREATE TEMPORARY FUNCTION lbl_fn() RETURNS INT RETURN lbl.missing?`
creates a function whose body is NULL. After `RESET
spark.sql.optionalReferences.enabled`, `CREATE TEMPORARY VIEW lbl_fv AS SELECT
lbl_fn() AS m` inside another script labeled `lbl` succeeds, and every read of
`lbl_fv` then fails with UNRESOLVED_COLUMN for `` `lbl`.`missing` ``, because a
view read ignores labels. With the conf set to true in the session, the golden
file shows the same definition rejected at creation. A persistent view would be
stored unreadable and have to be dropped and created again, and ALTER VIEW ...
AS and CACHE TABLE ... AS SELECT behave the same way. The field doc at lines
206-207 states the same conf condition, and no test covers a session that
leaves the conf unset. The failure stays loud, and reaching it needs a function
created with the conf on that a view defined in a labeled block or FOR loop
calls.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60367#discussion_r4576517552).
**Recommended change:** Set isViewDefinition for every plan that defines a
view, whether or not the session enables optional references, by dropping the
conf condition at Analyzer.scala line 599, and correct the field doc at
Analyzer.scala lines 206-207, which says the flag is only set while optional
references are enabled because nothing else reads it. Golden or suite cases
cover a view defined in a labeled block that calls a SQL function created with
optional references enabled after the session resets the conf, for CREATE
TEMPORARY VIEW, a persistent CREATE VIEW, ALTER VIEW ... AS, and CACHE TABLE
... AS SELECT.
**Why this works:** The view-definition context then reaches every function
body that a view definition calls, so a label never qualifies a name that
matches no captured variable there, and such a definition fails at creation, as
it already does when the session enables the conf.
**Risks:** With the conf off, the analysis of every plan that contains a
command or an unresolved IDENTIFIER plan now walks it once to look for a view
definition, a linear walk that the tree-pattern check limits to those plans;
restoring the condition rolls it back.
**Constraints:** Plans that define no view keep isViewDefinition false, so
labels outside view definitions qualify names as before.
**Verification:**
- **Regression:** With the session conf reset, a temporary view, a
persistent view, an ALTER VIEW ... AS, and a CACHE TABLE ... AS SELECT defined
in a labeled block that call a SQL function created with optional references
enabled, whose body uses a label-qualified optional reference that matches no
variable, fail at creation with UNRESOLVED_COLUMN.
- **Compatibility:** A view in a labeled block whose query reads a captured
label-qualified variable still returns its value, and labeled-block queries
outside view definitions still resolve label-qualified optional references to
NULL.
- **Inspection:** The isViewDefinition field doc no longer limits the flag
to sessions that enable optional references.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/OptionalReferences.scala:
##########
@@ -0,0 +1,544 @@
+/*
+ * 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,
+ SupervisingCommand,
+ WithWindowDefinition
+}
+import org.apache.spark.sql.catalyst.trees.{Origin, 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, like [[RESOLVED_NULL_REFERENCE]] on the plan
that it returns. Only
+ * the analyzer sets them, 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")
+
+ /**
+ * Marks the root of the plan that an analysis returned, with the origin of
the first optional
+ * reference of the analyzed plan that the analysis resolved to a
[[nullReference]], see
+ * [[markResolvedNullReference]]. The rest of the analysis can replace that
NULL, e.g. by folding
+ * an extraction from it, the IF whose condition it is, or the row of an
inline table that holds
+ * it, so the mark is what keeps the decision for
`CheckOptionalReferencesInDml`, which reads it
+ * in the analyzed operations of a MERGE source. The optional references of
the body of a view
+ * or SQL function that the plan reads do not count: that body is analyzed
in an analysis
+ * context of its own.
+ *
+ * A later analysis keeps the mark, because its rules copy the tags of a
node to the node that
+ * replaces it. A rewrite outside of the analyzer that replaces an analyzed
plan, such as the
+ * union flattening and the self-join rewrite of `Dataset`, must keep the
mark of the plan that
+ * it replaces, see [[withResolvedNullReferenceOf]].
+ */
+ val RESOLVED_NULL_REFERENCE: TreeNodeTag[Origin] =
+ TreeNodeTag[Origin]("optionalReferenceResolvedNull")
+
+ /** 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 anywhere, see
+ * [[unresolvedOptionalReference]]. 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 and expressions that
an operator keeps
+ * outside of its children and expressions, or None: the common table
expressions of
+ * `UnresolvedWith`, the query of a command such as EXPLAIN or DESCRIBE
QUERY, and the window
+ * specifications of a WINDOW clause.
+ */
+ def unresolvedOptionalReference(plan: LogicalPlan): Option[Expression] = {
+ val expressions = plan match {
+ case withWindows: WithWindowDefinition =>
+ plan.expressions ++ withWindows.windowDefinitions.values
+ case _ =>
+ plan.expressions
+ }
+ val supervisedPlans = plan match {
+ case command: SupervisingCommand => Seq(supervisedPlan(command))
+ case _ => Nil
+ }
+ 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 ++ supervisedPlans).iterator
+ .flatMap(child => unresolvedOptionalReference(child))
+ .nextOption()
+ }
+ }
+
+ /** Returns the plan that `command` supervises, which is not a child of the
command. */
+ private def supervisedPlan(command: SupervisingCommand): LogicalPlan = {
+ var supervisedPlan: LogicalPlan = null
+ command.withTransformedSupervisedPlan { plan =>
+ supervisedPlan = plan
+ plan
+ }
+ supervisedPlan
+ }
+
+ /**
+ * 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, ())
+ AnalysisContext.get.nullReferenceOrigins += nullReference.origin
+ nullReference
+ }
+
+ /**
+ * Marks `analyzed`, the plan that an analysis of `plan` returned, with
+ * [[RESOLVED_NULL_REFERENCE]] if the analysis resolved an optional
reference of `plan` to a
+ * [[nullReference]] and built `analyzed`. A node of `plan` is never marked:
`plan` can be
+ * analyzed again later, e.g. from a plan cache, and its analyzed nodes
belong to other plans as
+ * well, such as the plan of the Dataset that a drop returns when it drops
nothing. The NULL is
+ * not a part of such a node.
+ */
+ def markResolvedNullReference(plan: LogicalPlan, analyzed: LogicalPlan):
Unit = {
+ AnalysisContext.get.nullReferenceOrigins.headOption.foreach { origin =>
+ if (!plan.exists(_ eq analyzed)) {
+ analyzed.setTagValue(RESOLVED_NULL_REFERENCE, origin)
+ }
+ }
+ }
+
+ /**
+ * Gives `plan`, which a rewrite outside of the analyzer built to replace
the analyzed plans
+ * `replaced`, the first [[RESOLVED_NULL_REFERENCE]] mark of them, unless
`plan` has one. Other
+ * tags stay where they are, e.g. the ids of the Datasets that the self-join
detection reads.
+ */
+ def withResolvedNullReferenceOf[T <: LogicalPlan](plan: T, replaced:
LogicalPlan*): T = {
+ if (resolvedNullReferenceOrigin(plan).isEmpty) {
+
replaced.iterator.flatMap(resolvedNullReferenceOrigin).nextOption().foreach {
origin =>
+ plan.setTagValue(RESOLVED_NULL_REFERENCE, origin)
+ }
+ }
+ plan
+ }
+
+ /** Returns the origin of the [[RESOLVED_NULL_REFERENCE]] mark of `plan`, or
None. */
+ def resolvedNullReferenceOrigin(plan: LogicalPlan): Option[Origin] =
+ plan.getTagValue(RESOLVED_NULL_REFERENCE)
+
+ /**
+ * 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))
+ } else {
+ ExtractValue.extractValue(expression, Literal(nestedFields.head),
resolver) match {
+ case EitherLeft(extracted) =>
+ extractNestedFieldsOrError(
+ expression = extracted,
+ nestedFields = nestedFields.tail,
+ nestedFieldIndex = nestedFieldIndex + 1,
+ optionalNamePartIndices = optionalNamePartIndices,
+ resolver = resolver,
+ voidBaseIsNull = voidBaseIsNull
+ )
+ case EitherRight(throwable)
+ if isFieldNotFound(throwable) &&
+ optionalNamePartIndices.contains(nestedFieldIndex) =>
+ EitherLeft(nullReference())
+ case error =>
+ error
+ }
+ }
+ }
+
+ private def isFieldNotFound(throwable: Throwable): Boolean = throwable match
{
+ case sparkThrowable: SparkThrowable => sparkThrowable.getCondition ==
"FIELD_NOT_FOUND"
+ case _ => false
+ }
+
+ /**
+ * Returns the number of leading name parts of `nameParts` that match the
longest reference path
+ * to `attribute`. A qualified-access-only attribute requires at least one
qualifier part.
+ */
+ private def matchedNamePartCount(
+ nameParts: Seq[String],
+ attribute: Attribute,
+ resolver: Resolver): Int = {
+ val minQualifierLength = if (attribute.qualifiedAccessOnly) 1 else 0
+ (minQualifierLength to attribute.qualifier.length).iterator
+ .map { qualifierLength =>
+ val qualifier = attribute.qualifier.takeRight(qualifierLength)
+ val matchedQualifierParts = matchedQualifierPartCount(nameParts,
qualifier, resolver)
+ if (matchedQualifierParts < qualifier.length) {
Review Comment:
**Non-blocking (P2):** When a name matches only the leading parts of a
qualifier suffix, this returns that partial count, and
`firstUnmatchedNamePartIndex` then reports the next name part as the one that
matched nothing. For `default.deleted_at?` against a column `deleted_at` whose
qualifier is `[spark_catalog, default, events]`, the suffix `[default, events]`
counts `default`, so the optional `deleted_at` is taken as missing. Column
resolution accepts only a whole qualifier suffix (table, db.table, or
catalog.db.table) before the column name, so by the review's reading `SELECT
default.deleted_at FROM default.events` fails with UNRESOLVED_COLUMN while
`SELECT default.deleted_at? FROM default.events` returns NULL for every row,
although the column exists. `spark_catalog.deleted_at?` and
`spark_catalog.default.deleted_at?` behave the same way, and an unknown
qualifier such as `other.qualified_t.missing?` still fails, as the golden file
expects. The session-variable qualifiers at lin
e 385 take the same partial count, so after `DECLARE VARIABLE x INT DEFAULT
5`, `SELECT system.x` fails while `SELECT system.x?` returns NULL. Both
analyzers use this rule. This goes against the PR's rule that `?` suppresses
only the not-found error of the optional part, and it hides a typo in a
qualifier; it is reached only with `spark.sql.optionalReferences.enabled` on.
A fix is to count a qualifier that the name matches only partly, here and
for the session-variable qualifiers, only when the first name part that does
not match is followed by further name parts. When the name's qualifier parts
run out first, as for `default.deleted_at?` against `[spark_catalog, default,
events]` or `system.x?` against `[system, session]`, that qualifier matches
nothing. The golden case `system.session?` then raises the UNRESOLVED_COLUMN
error of `system.session`, and golden cases for a database or catalog prefix
without the table and for `system.x?` with and without a session variable `x`
would pin the behavior.
**Verification:**
- **Regression:** A database or catalog prefix without the table name before
an optional column part, and `system` without `session` before an optional
variable name, fail with the same error as without `?`, for a column or
variable that exists and for one that does not, in both analyzers.
- **Compatibility:** References whose qualifier is a whole table, database
and table, or catalog, database, and table suffix, or the whole session or
system.session qualifier, keep their current NULL or error.
--
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]