spark-test commented on code in PR #60660:
URL: https://github.com/apache/spark/pull/60660#discussion_r4625468069
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala:
##########
@@ -509,6 +514,107 @@ trait ColumnResolutionHelper extends Logging with
DataTypeErrorsBase {
resolveVariables(resolveOuterRef(e))
}
+ /**
+ * Applies [[resolveColsLastResort]] to a SELECT list (the project list of a
`Project` or the
+ * aggregate expressions of an `Aggregate`), but keeps the columns that
reference the output of
+ * a preceding generator in the same SELECT list unresolved, such as `tag` in
+ * `SELECT explode(tags) AS tag, upper(tag)`, or `col` in `SELECT
explode(tags), upper(col)`.
+ * In a `Project`, the rule `ExtractGenerator` will pull the generator out
into a `Generate`
+ * node below the `Project`, and then these columns are resolved to the
generator output. In an
+ * `Aggregate`, the generator output can not be referenced, as
`ExtractGenerator` puts the
+ * generator in a `Project` above the `Aggregate`. These columns stay
unresolved, and the query
+ * fails with `UNRESOLVED_COLUMN` instead of reading an outer query column
or a SQL variable.
+ *
+ * This follows the lateral column alias rule: the output of a generator has
higher priority
+ * than outer references and SQL variables only for the SELECT items after
the generator. A
+ * reference that comes before the generator, or in the arguments of the
generator, keeps its
+ * current resolution.
+ *
+ * The output names of a generator are its alias names, or the field names
of its element schema
+ * if it has no alias. As this runs before the rule `ResolveFunctions` in an
analyzer iteration,
+ * the function call of a generator is not resolved yet in the first
iteration, and a call to a
+ * built-in generator function is recognized by its name. If such a call has
no alias, its
+ * output names are not known until it is resolved, so all the columns after
it are kept
+ * unresolved in this iteration.
+ *
+ * TODO: A generator call that [[isBuiltinGeneratorCall]] can not recognize,
such as a call to a
+ * temporary or persistent function, or a call with a qualified function
name, is not protected
+ * before it is resolved. With an alias, the lateral column alias resolution
still keeps the
+ * references to the alias from being resolved as outer references or SQL
variables, unless
+ * `spark.sql.lateralColumnAlias.enableImplicitResolution` is false. Without
an alias, the
+ * references to its output names can still be resolved as outer references
or SQL variables in
+ * the first analyzer iteration.
+ */
+ protected def resolveSelectListColsLastResort(selectList: Seq[Expression]):
Seq[Expression] = {
+ if
(!conf.getConf(SQLConf.PREFER_GENERATOR_ALIAS_OVER_OUTER_REFERENCE_AND_VARIABLE))
{
+ return selectList.map(resolveColsLastResort)
+ }
+ // The output names of the generators before the current SELECT item.
+ val precedingGeneratorOutputNames = mutable.ArrayBuffer.empty[String]
+ // Whether a generator before the current SELECT item has output names
that are not known yet.
+ var hasPrecedingGeneratorWithUnknownOutputNames = false
+ selectList.map { e =>
+ val result = if (hasPrecedingGeneratorWithUnknownOutputNames) {
+ // Any column may reference the output of that generator. Keep them
all unresolved until
+ // the generator is resolved in this analyzer iteration, and its
output names are known
+ // in the next one.
+ val skipAll = (_: UnresolvedAttribute) => true
+ resolveVariables(resolveOuterRef(e, skipAll), skipAll)
+ } else if (precedingGeneratorOutputNames.isEmpty) {
+ resolveColsLastResort(e)
+ } else {
+ val names = precedingGeneratorOutputNames.toSeq
+ // Like lateral column alias, only the first name part is used to look
up the generator
+ // output, as the generator output does not have qualifiers.
+ val isGeneratorOutputRef = (u: UnresolvedAttribute) =>
+ names.exists(name => conf.resolver(name, u.nameParts.head))
+ resolveVariables(resolveOuterRef(e, isGeneratorOutputRef),
isGeneratorOutputRef)
+ }
+ generatorOutputNames(e) match {
+ case Some(names) => precedingGeneratorOutputNames ++= names
+ case None => hasPrecedingGeneratorWithUnknownOutputNames = true
+ }
+ result
+ }
+ }
+
+ /**
+ * Returns the output names of the generator in a SELECT item, or `None` if
the SELECT item has
+ * a generator whose output names are not known yet. Returns an empty
sequence if the SELECT
+ * item does not have a generator.
+ */
+ private def generatorOutputNames(selectItem: Expression):
Option[Seq[String]] = {
+ selectItem match {
+ case Alias(_: Generator, name) => Some(Seq(name))
+ // `MultiAlias` is only allowed for generators, even if its child is not
resolved yet.
+ case MultiAlias(_, names) if names.nonEmpty => Some(names)
+ // Without an alias, the rule `ExtractGenerator` names the generator
output with the field
+ // names of the element schema. See
`GeneratorResolution.makeGeneratorOutput`.
+ case UnresolvedAlias(g: Generator, _) if g.resolved =>
Some(g.elementSchema.fieldNames.toSeq)
+ case MultiAlias(g: Generator, _) if g.resolved =>
Some(g.elementSchema.fieldNames.toSeq)
+ case UnresolvedAlias(_: Generator, _) | MultiAlias(_, _) => None
+ // The function call of a generator is not resolved yet in the first
analyzer iteration.
+ case Alias(f: UnresolvedFunction, name) if isBuiltinGeneratorCall(f) =>
Some(Seq(name))
+ case UnresolvedAlias(f: UnresolvedFunction, _) if
isBuiltinGeneratorCall(f) => None
+ case _ => Some(Nil)
Review Comment:
**Non-blocking (P2):** In `|> SELECT` and `|> EXTEND` lists the parser wraps
each item's expression in `PipeExpression` (AstBuilder.scala:1960-1975,
8460-8473), and `ValidateAndStripPipeExpressions` removes the wrapper only
after the call inside resolves, later in the iteration. While the call is still
wrapped, an item such as
`UnresolvedAlias(PipeExpression(UnresolvedFunction(explode, ...)))` reaches
this fallback, so the helper sees no generator, and the later columns bind to a
same-named SQL variable or outer column for good.
Tracing the analyzer rules, with `DECLARE VARIABLE col STRING DEFAULT
'var'`, `SELECT 1 AS x |> SELECT explode(array('a', 'b')), upper(col)` still
yields `VAR` for both rows, while the same query without the pipe now yields
`A` and `B`. The same applies to `SELECT array('a', 'b') AS arr |> EXTEND
explode(arr), upper(col)`, to a LATERAL outer column named `col`, and, with
implicit lateral column alias resolution off, to `|> SELECT explode(arr) AS
tag, upper(tag)`. An `EXTEND` call with only constant arguments happens to be
protected, because the `EXTEND` star is expanded in a pass of its own and the
call resolves before `col` is first looked up. Pipe syntax is on by default,
and the migration note states the new precedence for every SELECT list.
Because `|> SELECT` allows aggregate functions, stripping the wrapper here
has to come together with looking through `GeneratorOuter`; otherwise a newly
recognized unaliased outer generator would hit the same permanent hold in a
pipe SELECT list with aggregation.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala:
##########
@@ -509,6 +514,107 @@ trait ColumnResolutionHelper extends Logging with
DataTypeErrorsBase {
resolveVariables(resolveOuterRef(e))
}
+ /**
+ * Applies [[resolveColsLastResort]] to a SELECT list (the project list of a
`Project` or the
+ * aggregate expressions of an `Aggregate`), but keeps the columns that
reference the output of
+ * a preceding generator in the same SELECT list unresolved, such as `tag` in
+ * `SELECT explode(tags) AS tag, upper(tag)`, or `col` in `SELECT
explode(tags), upper(col)`.
+ * In a `Project`, the rule `ExtractGenerator` will pull the generator out
into a `Generate`
+ * node below the `Project`, and then these columns are resolved to the
generator output. In an
+ * `Aggregate`, the generator output can not be referenced, as
`ExtractGenerator` puts the
+ * generator in a `Project` above the `Aggregate`. These columns stay
unresolved, and the query
+ * fails with `UNRESOLVED_COLUMN` instead of reading an outer query column
or a SQL variable.
+ *
+ * This follows the lateral column alias rule: the output of a generator has
higher priority
+ * than outer references and SQL variables only for the SELECT items after
the generator. A
+ * reference that comes before the generator, or in the arguments of the
generator, keeps its
+ * current resolution.
+ *
+ * The output names of a generator are its alias names, or the field names
of its element schema
+ * if it has no alias. As this runs before the rule `ResolveFunctions` in an
analyzer iteration,
+ * the function call of a generator is not resolved yet in the first
iteration, and a call to a
+ * built-in generator function is recognized by its name. If such a call has
no alias, its
+ * output names are not known until it is resolved, so all the columns after
it are kept
+ * unresolved in this iteration.
+ *
+ * TODO: A generator call that [[isBuiltinGeneratorCall]] can not recognize,
such as a call to a
+ * temporary or persistent function, or a call with a qualified function
name, is not protected
+ * before it is resolved. With an alias, the lateral column alias resolution
still keeps the
+ * references to the alias from being resolved as outer references or SQL
variables, unless
+ * `spark.sql.lateralColumnAlias.enableImplicitResolution` is false. Without
an alias, the
+ * references to its output names can still be resolved as outer references
or SQL variables in
+ * the first analyzer iteration.
+ */
+ protected def resolveSelectListColsLastResort(selectList: Seq[Expression]):
Seq[Expression] = {
+ if
(!conf.getConf(SQLConf.PREFER_GENERATOR_ALIAS_OVER_OUTER_REFERENCE_AND_VARIABLE))
{
+ return selectList.map(resolveColsLastResort)
+ }
+ // The output names of the generators before the current SELECT item.
+ val precedingGeneratorOutputNames = mutable.ArrayBuffer.empty[String]
+ // Whether a generator before the current SELECT item has output names
that are not known yet.
+ var hasPrecedingGeneratorWithUnknownOutputNames = false
+ selectList.map { e =>
+ val result = if (hasPrecedingGeneratorWithUnknownOutputNames) {
+ // Any column may reference the output of that generator. Keep them
all unresolved until
+ // the generator is resolved in this analyzer iteration, and its
output names are known
+ // in the next one.
+ val skipAll = (_: UnresolvedAttribute) => true
+ resolveVariables(resolveOuterRef(e, skipAll), skipAll)
+ } else if (precedingGeneratorOutputNames.isEmpty) {
+ resolveColsLastResort(e)
+ } else {
+ val names = precedingGeneratorOutputNames.toSeq
+ // Like lateral column alias, only the first name part is used to look
up the generator
+ // output, as the generator output does not have qualifiers.
+ val isGeneratorOutputRef = (u: UnresolvedAttribute) =>
+ names.exists(name => conf.resolver(name, u.nameParts.head))
+ resolveVariables(resolveOuterRef(e, isGeneratorOutputRef),
isGeneratorOutputRef)
+ }
+ generatorOutputNames(e) match {
+ case Some(names) => precedingGeneratorOutputNames ++= names
+ case None => hasPrecedingGeneratorWithUnknownOutputNames = true
+ }
+ result
+ }
+ }
+
+ /**
+ * Returns the output names of the generator in a SELECT item, or `None` if
the SELECT item has
+ * a generator whose output names are not known yet. Returns an empty
sequence if the SELECT
+ * item does not have a generator.
+ */
+ private def generatorOutputNames(selectItem: Expression):
Option[Seq[String]] = {
+ selectItem match {
+ case Alias(_: Generator, name) => Some(Seq(name))
+ // `MultiAlias` is only allowed for generators, even if its child is not
resolved yet.
+ case MultiAlias(_, names) if names.nonEmpty => Some(names)
+ // Without an alias, the rule `ExtractGenerator` names the generator
output with the field
+ // names of the element schema. See
`GeneratorResolution.makeGeneratorOutput`.
+ case UnresolvedAlias(g: Generator, _) if g.resolved =>
Some(g.elementSchema.fieldNames.toSeq)
+ case MultiAlias(g: Generator, _) if g.resolved =>
Some(g.elementSchema.fieldNames.toSeq)
Review Comment:
**Blocking (P1):** `GeneratorOuter.resolved` is hard-coded to `false`
(generators.scala:344). For an unaliased `explode_outer`, `posexplode_outer` or
`inline_outer` call, which `ResolveAliases` turns into
`MultiAlias(GeneratorOuter(g), Nil)`, this guard never matches, and the next
case returns `None` on every pass. `resolveSelectListColsLastResort` then keeps
every later column away from variable and outer-reference resolution. In a
`Project` the hold ends once `ExtractGenerator` extracts the generator, but in
an `Aggregate` `ExtractGenerator` first waits for every other item to resolve
(Analyzer.scala:3465-3469), so the two wait on each other until the fixed point.
Tracing the analyzer rules, with `DECLARE VARIABLE v INT DEFAULT 10`,
`SELECT explode_outer(array(1, 2)), v, count(*) FROM range(1)` returns `(1, 10,
1)` and `(2, 10, 1)` on the base branch but now fails with `UNRESOLVED_COLUMN`
for `v`, although `v` is not a generator output. The same holds with an
explicit `GROUP BY`, for session and SQL-script local variables, and in the
DataFrame API, all with default settings. A later outer column is held back the
same way, but there only the error changes, because an `Aggregate` cannot host
an outer reference on the base branch either.
Treating `GeneratorOuter(g)` as `g` here, as `ExtractGenerator`'s
`AliasedGenerator` already does (Analyzer.scala:3439-3440), would report `col`
(or `pos` and `col`) once `g` is resolved, and keeps every decision of the PR.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala:
##########
@@ -509,6 +514,107 @@ trait ColumnResolutionHelper extends Logging with
DataTypeErrorsBase {
resolveVariables(resolveOuterRef(e))
}
+ /**
+ * Applies [[resolveColsLastResort]] to a SELECT list (the project list of a
`Project` or the
+ * aggregate expressions of an `Aggregate`), but keeps the columns that
reference the output of
+ * a preceding generator in the same SELECT list unresolved, such as `tag` in
+ * `SELECT explode(tags) AS tag, upper(tag)`, or `col` in `SELECT
explode(tags), upper(col)`.
+ * In a `Project`, the rule `ExtractGenerator` will pull the generator out
into a `Generate`
+ * node below the `Project`, and then these columns are resolved to the
generator output. In an
+ * `Aggregate`, the generator output can not be referenced, as
`ExtractGenerator` puts the
+ * generator in a `Project` above the `Aggregate`. These columns stay
unresolved, and the query
+ * fails with `UNRESOLVED_COLUMN` instead of reading an outer query column
or a SQL variable.
+ *
+ * This follows the lateral column alias rule: the output of a generator has
higher priority
+ * than outer references and SQL variables only for the SELECT items after
the generator. A
+ * reference that comes before the generator, or in the arguments of the
generator, keeps its
+ * current resolution.
+ *
+ * The output names of a generator are its alias names, or the field names
of its element schema
+ * if it has no alias. As this runs before the rule `ResolveFunctions` in an
analyzer iteration,
+ * the function call of a generator is not resolved yet in the first
iteration, and a call to a
+ * built-in generator function is recognized by its name. If such a call has
no alias, its
+ * output names are not known until it is resolved, so all the columns after
it are kept
+ * unresolved in this iteration.
+ *
+ * TODO: A generator call that [[isBuiltinGeneratorCall]] can not recognize,
such as a call to a
+ * temporary or persistent function, or a call with a qualified function
name, is not protected
+ * before it is resolved. With an alias, the lateral column alias resolution
still keeps the
+ * references to the alias from being resolved as outer references or SQL
variables, unless
+ * `spark.sql.lateralColumnAlias.enableImplicitResolution` is false. Without
an alias, the
+ * references to its output names can still be resolved as outer references
or SQL variables in
+ * the first analyzer iteration.
+ */
+ protected def resolveSelectListColsLastResort(selectList: Seq[Expression]):
Seq[Expression] = {
+ if
(!conf.getConf(SQLConf.PREFER_GENERATOR_ALIAS_OVER_OUTER_REFERENCE_AND_VARIABLE))
{
+ return selectList.map(resolveColsLastResort)
+ }
+ // The output names of the generators before the current SELECT item.
+ val precedingGeneratorOutputNames = mutable.ArrayBuffer.empty[String]
+ // Whether a generator before the current SELECT item has output names
that are not known yet.
+ var hasPrecedingGeneratorWithUnknownOutputNames = false
+ selectList.map { e =>
+ val result = if (hasPrecedingGeneratorWithUnknownOutputNames) {
+ // Any column may reference the output of that generator. Keep them
all unresolved until
+ // the generator is resolved in this analyzer iteration, and its
output names are known
+ // in the next one.
+ val skipAll = (_: UnresolvedAttribute) => true
+ resolveVariables(resolveOuterRef(e, skipAll), skipAll)
+ } else if (precedingGeneratorOutputNames.isEmpty) {
+ resolveColsLastResort(e)
+ } else {
+ val names = precedingGeneratorOutputNames.toSeq
Review Comment:
**Nit (P3):** This copies the accumulated names into a new immutable
collection (`toSeq` on an `ArrayBuffer` under Scala 2.13) and builds a new
predicate for every SELECT item after a generator, although the names only
change at line 574, when an item adds generator names. `resolveOuterRef` and
`resolveVariables` apply the predicate eagerly and do not keep it, so the names
and the predicate can be built once each time the buffer grows, or the
predicate can read the buffer directly, with the same result. The extra work is
analysis-time only and negligible at typical widths, but it grows with the
number of later items times the number of names, for example for `inline` over
a wide struct followed by many columns.
**Verification:**
- **Inspection:** The names and predicate used for the items after a
generator are created only when a SELECT item contributes generator output
names, and the predicate still compares a column's first name part, using
conf.resolver, against every name accumulated so far.
##########
docs/sql-migration-guide.md:
##########
@@ -104,6 +104,7 @@ license: |
- Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'`
whose class implements
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends
either a Hive UDF class (such as `UDF` or `GenericUDF`) or
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions
created in earlier versions. Its result type, argument coercion, and null
handling are defined by the V2 implementation selected by
`UnboundFunction.bind`. Hive's `@UDFType` and Spark UDAF's `deterministic`
property do not control the V2 path. For scalar functions, determinism uses
`BoundFunction.isDeterministic()` (default `true`) and the arguments'
determinism. A call with constant arguments can therefore become eligible for
constant folding during query planning instead of being evaluated per row.
- Since Spark 4.4, `next_day` and `last_day` fail with `DATETIME_OVERFLOW`
when the result is later than the maximum `DATE`, `+5881580-07-11`, and `trunc`
fails with it when the result is earlier than the minimum `DATE`,
`-5877641-06-23`, regardless of `spark.sql.ansi.enabled`. Previously, these
functions silently returned a wrong date, in most cases one at the other end of
the `DATE` range; for example, `last_day(DATE'+5881580-07-11')` returned
`-5877641-07-12` and `trunc(DATE'-5877641-06-23', 'MONTH')` returned
`+5881580-06-20`, while `trunc` to `QUARTER` failed with `ARITHMETIC_OVERFLOW`.
`next_day` and `trunc` to `WEEK` also returned a wrong date for the first days
of the `DATE` range; for example, `next_day(DATE'-5877641-06-23', 'MO')` and
`trunc(DATE'-5877641-07-01', 'WEEK')` returned `-5877641-06-25`, a Thursday,
and now return `-5877641-06-29`.
- Since Spark 4.4, a Variant `TIMESTAMP` value is rendered in the session time
zone (`spark.sql.session.timeZone`) when it is nested in an array, map, or
struct that is cast to `STRING`, in `Dataset.show()`, and in the output of the
spark-sql CLI and the Thrift server, as a top-level `CAST(v AS STRING)` already
does. Previously, these paths rendered it in UTC. For example, with
`spark.sql.session.timeZone` set to `America/Los_Angeles`,
`CAST(named_struct('a', CAST(TIMESTAMP'2020-01-01 00:00:00Z' AS VARIANT)) AS
STRING)` returns `{"2019-12-31 16:00:00-08:00"}` instead of `{"2020-01-01
00:00:00+00:00"}`. The rendered text carries an explicit offset, so it still
denotes the same instant. Sessions in UTC are not affected.
+- Since Spark 4.4, a column in a SELECT list that references the output of a
preceding generator in the same SELECT list, such as `tag` in `SELECT
explode(tags) AS tag, upper(tag)`, or `col`, the default output name of
`explode` without an alias, in `SELECT explode(tags), upper(col)`, resolves to
the generator output even if an outer query column or a SQL variable has the
same name. Previously, it resolved to the outer query column or the SQL
variable. Such a reference in a SELECT list with aggregation is not supported,
and now fails with `UNRESOLVED_COLUMN` instead of resolving to the outer query
column or the SQL variable. To restore the previous behavior, set
`spark.sql.analyzer.preferGeneratorAliasOverOuterReferenceAndVariable` to
`false`.
Review Comment:
**Nit (P3):** SQL function parameters are rebound too: a SQL table function
body, and the body of a query-bodied scalar function, read their parameters as
outer references (SessionCatalog.scala:1950-1966, 2048-2061), so the new helper
holds them back like an outer column. For example, with `CREATE FUNCTION
words(col STRING) RETURNS TABLE (word STRING, src STRING) RETURN SELECT
explode(split(col, ' ')), col`, the second `col` now reads the `explode` output
instead of the parameter, so `src` becomes each word. Persisted SQL functions
are re-analyzed on use, so their results change after an upgrade, yet this note
and the config description (SQLConf.scala:381-388) only name outer query
columns and SQL variables. The rebinding itself follows the documented order,
which ranks a preceding SELECT-list alias above routine parameters; only the
disclosure is missing. A possible wording, which the config description could
mirror:
```suggestion
- Since Spark 4.4, a column in a SELECT list that references the output of a
preceding generator in the same SELECT list, such as `tag` in `SELECT
explode(tags) AS tag, upper(tag)`, or `col`, the default output name of
`explode` without an alias, in `SELECT explode(tags), upper(col)`, resolves to
the generator output even if an outer query column, a SQL function parameter,
or a SQL variable has the same name. Previously, it resolved to the outer query
column, the SQL function parameter, or the SQL variable. Such a reference in a
SELECT list with aggregation is not supported, and now fails with
`UNRESOLVED_COLUMN` instead of resolving to the outer query column or the SQL
variable. To restore the previous behavior, set
`spark.sql.analyzer.preferGeneratorAliasOverOuterReferenceAndVariable` to
`false`.
```
**Verification:**
- **Inspection:** Both texts list SQL function parameters alongside outer
query columns and SQL variables, both in the statement of the new precedence
and in the statement of the previous behavior.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ColumnResolutionHelper.scala:
##########
@@ -509,6 +514,107 @@ trait ColumnResolutionHelper extends Logging with
DataTypeErrorsBase {
resolveVariables(resolveOuterRef(e))
}
+ /**
+ * Applies [[resolveColsLastResort]] to a SELECT list (the project list of a
`Project` or the
+ * aggregate expressions of an `Aggregate`), but keeps the columns that
reference the output of
+ * a preceding generator in the same SELECT list unresolved, such as `tag` in
+ * `SELECT explode(tags) AS tag, upper(tag)`, or `col` in `SELECT
explode(tags), upper(col)`.
+ * In a `Project`, the rule `ExtractGenerator` will pull the generator out
into a `Generate`
+ * node below the `Project`, and then these columns are resolved to the
generator output. In an
+ * `Aggregate`, the generator output can not be referenced, as
`ExtractGenerator` puts the
+ * generator in a `Project` above the `Aggregate`. These columns stay
unresolved, and the query
+ * fails with `UNRESOLVED_COLUMN` instead of reading an outer query column
or a SQL variable.
+ *
+ * This follows the lateral column alias rule: the output of a generator has
higher priority
+ * than outer references and SQL variables only for the SELECT items after
the generator. A
+ * reference that comes before the generator, or in the arguments of the
generator, keeps its
+ * current resolution.
+ *
+ * The output names of a generator are its alias names, or the field names
of its element schema
+ * if it has no alias. As this runs before the rule `ResolveFunctions` in an
analyzer iteration,
+ * the function call of a generator is not resolved yet in the first
iteration, and a call to a
+ * built-in generator function is recognized by its name. If such a call has
no alias, its
+ * output names are not known until it is resolved, so all the columns after
it are kept
+ * unresolved in this iteration.
+ *
+ * TODO: A generator call that [[isBuiltinGeneratorCall]] can not recognize,
such as a call to a
+ * temporary or persistent function, or a call with a qualified function
name, is not protected
+ * before it is resolved. With an alias, the lateral column alias resolution
still keeps the
+ * references to the alias from being resolved as outer references or SQL
variables, unless
+ * `spark.sql.lateralColumnAlias.enableImplicitResolution` is false. Without
an alias, the
+ * references to its output names can still be resolved as outer references
or SQL variables in
+ * the first analyzer iteration.
Review Comment:
**Nit (P3):** `generatorOutputNames` returns the names of any `MultiAlias`
(line 590) before it checks `isBuiltinGeneratorCall`, and the lateral column
alias resolution records only single `Alias` items, so a multi-alias call such
as `builtin.explode(m) AS (k, v)`, or a temporary UDTF called with `AS (a, b)`,
is protected in the first iteration under either lateral column alias setting.
What this TODO actually tracks is a call without an alias, or with a single
alias while implicit lateral column alias resolution is off. A possible wording:
```suggestion
* TODO: A generator call that [[isBuiltinGeneratorCall]] can not
recognize, such as a call to a
* temporary or persistent function, or a call with a qualified function
name, is protected
* before it is resolved only through its alias names. A multi-alias is
always protected by
* `generatorOutputNames`, and a single alias only by the lateral column
alias resolution, while
* `spark.sql.lateralColumnAlias.enableImplicitResolution` is true.
Without an alias, the
* references to its output names can still be resolved as outer
references or SQL variables in
* the first analyzer iteration.
```
**Verification:**
- **Inspection:** The TODO's description of the unprotected cases matches
generatorOutputNames, which reports a multi-alias item's names before any
built-in check, and lateral column alias resolution, which covers only single
aliases.
##########
sql/core/src/test/scala/org/apache/spark/sql/GeneratorFunctionSuite.scala:
##########
@@ -818,6 +818,233 @@ class GeneratorFunctionSuite extends SharedSparkSession {
""".stripMargin),
Row(10, "hello") :: Nil)
}
+
+ test("generator output alias in the same SELECT list has higher priority
than outer reference") {
+ withTempView("users", "struct_users", "sessions") {
+ Seq(("ann", "vip", 1), ("bob", "new", 2)).toDF("user_name", "tag", "ms")
+ .createOrReplaceTempView("users")
+ sql(
+ """
+ |CREATE TEMPORARY VIEW struct_users AS SELECT * FROM VALUES
+ | ('ann', named_struct('f', 'vip')), ('bob', named_struct('f',
'new'))
+ | AS t(user_name, tag)
+ |""".stripMargin)
+ Seq(
+ ("ann", Seq("mobile", "promo"), Map("home" -> 120), "mobile,promo"),
+ ("bob", Seq("repeat"), Map("shop" -> 60), "repeat")
+ ).toDF("user_name", "tags", "page_ms",
"csv").createOrReplaceTempView("sessions")
+
+ val singleAlias =
+ """
+ |SELECT u.user_name, x.tag, x.tag_uc
+ |FROM users u, LATERAL (
+ | SELECT explode(s.tags) AS tag, upper(tag) AS tag_uc
+ | FROM sessions s WHERE s.user_name = u.user_name) x
+ |""".stripMargin
+ val multiAlias =
+ """
+ |SELECT u.user_name, x.page, x.ms, x.ms10
+ |FROM users u, LATERAL (
+ | SELECT explode(s.page_ms) AS (page, ms), ms * 10 AS ms10
+ | FROM sessions s WHERE s.user_name = u.user_name) x
+ |""".stripMargin
+ checkAnswer(
+ sql(singleAlias),
+ Row("ann", "mobile", "MOBILE") :: Row("ann", "promo", "PROMO") ::
+ Row("bob", "repeat", "REPEAT") :: Nil)
+ checkAnswer(
+ sql(multiAlias),
+ Row("ann", "home", 120, 1200) :: Row("bob", "shop", 60, 600) :: Nil)
+
+ // The generator may have function calls in its arguments.
+ checkAnswer(
+ sql(
+ """
+ |SELECT u.user_name, x.tag, x.tag_uc
+ |FROM users u, LATERAL (
+ | SELECT explode(split(s.csv, ',')) AS tag, upper(tag) AS tag_uc
+ | FROM sessions s WHERE s.user_name = u.user_name) x
+ |""".stripMargin),
+ Row("ann", "mobile", "MOBILE") :: Row("ann", "promo", "PROMO") ::
+ Row("bob", "repeat", "REPEAT") :: Nil)
+
+ // A struct field of the generator output: like lateral column alias,
only the first name
+ // part is used to look up the generator output.
+ checkAnswer(
+ sql(
+ """
+ |SELECT u.user_name, x.f
+ |FROM struct_users u, LATERAL (
+ | SELECT explode(array(named_struct('f', 'x'), named_struct('f',
'y'))) AS tag,
+ | upper(tag.f) AS f) x
+ |""".stripMargin),
+ Row("ann", "X") :: Row("ann", "Y") :: Row("bob", "X") :: Row("bob",
"Y") :: Nil)
+
+ // Lateral column alias baselines without a generator: a forward
reference to a lateral
+ // column alias resolves to the outer column.
+ checkAnswer(
+ sql(
+ """
+ |SELECT u.user_name, x.tag_uc
+ |FROM users u, LATERAL (
+ | SELECT upper(tag) AS tag_uc, lower(s.user_name) AS tag
+ | FROM sessions s WHERE s.user_name = u.user_name) x
+ |""".stripMargin),
+ Row("ann", "VIP") :: Row("bob", "NEW") :: Nil)
+ // The same for a forward reference that a later alias depends on
through lateral column
+ // alias.
+ checkAnswer(
+ sql(
+ """
+ |SELECT u.user_name, x.a, x.tag
+ |FROM users u, LATERAL (
+ | SELECT upper(tag) AS a, lower(a) AS tag
+ | FROM sessions s WHERE s.user_name = u.user_name) x
+ |""".stripMargin),
+ Row("ann", "VIP", "vip") :: Row("bob", "NEW", "new") :: Nil)
+ // Like lateral column alias, only the generators before the reference
are considered. A
+ // forward reference to the output of a later generator still resolves
to the outer column.
+ checkAnswer(
+ sql(
+ """
+ |SELECT u.user_name, x.a, x.pos, x.tag
+ |FROM users u, LATERAL (
+ | SELECT upper(tag) AS a, posexplode(s.tags) AS (pos, tag)
+ | FROM sessions s WHERE s.user_name = u.user_name) x
+ |""".stripMargin),
+ Row("ann", "VIP", 0, "mobile") :: Row("ann", "VIP", 1, "promo") ::
+ Row("bob", "NEW", 0, "repeat") :: Nil)
+
+ // The output of a generator does not precede its own arguments, so they
can still
+ // reference an outer column of the same name.
+ checkAnswer(
+ sql("SELECT u.user_name, x.tag " +
+ "FROM users u, LATERAL (SELECT explode(array(tag)) AS tag) x"),
+ Row("ann", "vip") :: Row("bob", "new") :: Nil)
+ checkAnswer(
+ sql("SELECT u.user_name, x.pos, x.tag " +
+ "FROM users u, LATERAL (SELECT posexplode(array(tag)) AS (pos, tag))
x"),
+ Row("ann", 0, "vip") :: Row("bob", 0, "new") :: Nil)
+
+ // Without implicit lateral column alias resolution, a single alias is
protected too.
+ withSQLConf(SQLConf.LATERAL_COLUMN_ALIAS_IMPLICIT_ENABLED.key ->
"false") {
+ checkAnswer(
+ sql(singleAlias),
+ Row("ann", "mobile", "MOBILE") :: Row("ann", "promo", "PROMO") ::
+ Row("bob", "repeat", "REPEAT") :: Nil)
+ }
+
+ withSQLConf(
+ SQLConf.PREFER_GENERATOR_ALIAS_OVER_OUTER_REFERENCE_AND_VARIABLE.key
-> "false") {
+ checkAnswer(
+ sql(singleAlias),
+ Row("ann", "mobile", "VIP") :: Row("ann", "promo", "VIP") ::
+ Row("bob", "repeat", "NEW") :: Nil)
+ checkAnswer(
+ sql(multiAlias),
+ Row("ann", "home", 120, 10) :: Row("bob", "shop", 60, 20) :: Nil)
+ }
+ }
+ }
+
+ test("generator output alias in the same SELECT list has higher priority
than SQL variable") {
+ val singleAlias = "SELECT explode(array('a', 'b')) AS tag, upper(tag)"
+ val aggregate = "SELECT explode(array('a', 'b')) AS tag, upper(tag),
count(*) FROM range(1)"
Review Comment:
**Non-blocking (P2):** All of the new aggregate checks, here and at
GeneratorFunctionSuite.scala:983-984, 1006-1008 and 1021-1022, reference a name
that matches the generator's output and expect the query to fail. In a
`Project`, a column the helper holds back by mistake still resolves once
`ExtractGenerator` pulls the generator out, so the `Project` tests cannot tell.
Only a SELECT list with aggregation, where `ExtractGenerator` waits for every
other item, makes an over-broad hold visible, and no test has one with a later
column that must still resolve. As a result the suite passes although, by the
review's reading of the analyzer, `SELECT explode_outer(array('a', 'b')),
upper(v), count(*) FROM range(1)` with a variable `v` fails with this PR, and
it would also pass if the predicate at ColumnResolutionHelper.scala:570 matched
every name.
A case for each generator shape (aliased, unaliased, unaliased outer),
without and with `GROUP BY`, followed by a SQL variable that is not a generator
output and must resolve to it, would catch this. A LATERAL outer column cannot
serve here, because an `Aggregate` cannot host an outer reference on the base
branch either.
See **Shared repair plan 1** in the review body.
--
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]