cloud-fan commented on code in PR #60660:
URL: https://github.com/apache/spark/pull/60660#discussion_r4626129548


##########
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:
   Fixed in 6fb34b2df99. I reproduced it first: `SELECT explode_outer(array(1, 
2)), v, count(*) FROM range(1)` failed with `UNRESOLVED_COLUMN` for `v`, with 
and without `GROUP BY`, and so did the `posexplode_outer` and `inline_outer` 
versions. `generatorOutputNames` now looks through `GeneratorOuter`, as 
`AliasedGenerator` does, so these queries return `[1,10,1] [2,10,1]` again, the 
same as with the config off.



##########
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:
   Fixed in 6fb34b2df99. `generatorOutputNames` now also looks through 
`PipeExpression`, so `SELECT 1 AS x |> SELECT explode(array('a', 'b')), 
upper(col)` and `SELECT array('a', 'b') AS arr |> EXTEND explode(arr), 
upper(col)` read the generator output, like the standard SELECT list. This also 
holds in a LATERAL subquery, and for an aliased generator with implicit lateral 
column alias resolution off.
   
   One note on the aggregate point: an outer generator inside `|> SELECT` or 
`|> EXTEND`, e.g. `SELECT 1 AS x |> SELECT explode_outer(array(1, 2))`, already 
fails on master with `UNSUPPORTED_GENERATOR.NESTED_IN_EXPRESSIONS`, with the 
config on or off. `PipeExpression` is only stripped once its child is resolved, 
and `GeneratorOuter` never is. That is a separate existing issue, so the pipe 
aggregate hold can't happen today, but the change looks through both wrappers 
anyway.



##########
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:
   Added in 6fb34b2df99: `generator in a SELECT list with aggregation does not 
affect other SQL variables`. It puts a SQL variable that is not a generator 
output after aliased and unaliased `explode` and `explode_outer`, unaliased 
`posexplode_outer` and `inline_outer`, and a `|> SELECT`, without and with 
`GROUP BY`, under both config values. It fails without the fix. It also checks 
that a matching name after an unaliased outer generator still fails in an 
aggregate and resolves without aggregation.



##########
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:
   Done in 6fb34b2df99. The migration note and the config doc now list SQL 
function parameters, with the table function example, and say that the `|> 
SELECT` and `|> EXTEND` lists are covered. I also added a test for the table 
function under both config values, and a bullet to the PR description.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to