This is an automated email from the ASF dual-hosted git repository.

cloud-fan pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 013e5613eff8 [SPARK-59243][SQL][FOLLOWUP] Drop the alias of a spliced 
JSON constructor value in its SQL
013e5613eff8 is described below

commit 013e5613eff8986171cb3a284307a2c675c1396c
Author: Ganesha S <[email protected]>
AuthorDate: Wed Nov 11 10:50:54 2026 +0000

    [SPARK-59243][SQL][FOLLOWUP] Drop the alias of a spliced JSON constructor 
value in its SQL
    
    ### What changes were proposed in this pull request?
    
    Follow-up to #59828. When an aliased JSON value is spliced into JSON_ARRAY 
/ JSON_OBJECT, drop the alias from the rendered SQL:
    
    ```
    JSON_ARRAY(JSON_ARRAY(1) AS x FORMAT JSON)   -- before (invalid SQL)
    JSON_ARRAY(JSON_ARRAY(1))                    -- after
    ```
    
    Aliased arguments of other functions (e.g. `upper(a AS y)`) keep their 
existing rendering; that is pre-existing and out of scope here.
    
    ### Why are the changes needed?
    
    The old text is invalid SQL and leaks into auto-generated column names.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Only vs. unreleased master / branch-4.x: such column names no longer 
contain `AS x FORMAT JSON`. Results don't change.
    
    ### How was this patch tested?
    
    New tests in `JsonArraySuite` and `JsonObjectSuite` (rendered SQL, column 
names, user `CAST` still quoted). They fail without the fix.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Code (Opus 5.5)
    
    Closes #60303 from ganeshashree/SPARK-59243-followup.
    
    Lead-authored-by: Ganesha S <[email protected]>
    Co-authored-by: Ganesha S <[email protected]>
    Signed-off-by: Wenchen Fan <[email protected]>
    
    (cherry picked from commit e3689df67867403f9b4a5a352263cbc380c3ae29)
    Signed-off-by: Wenchen Fan <[email protected]>
    
    
    skip-checks: true
---
 .../sql/catalyst/expressions/jsonExpressions.scala | 19 +++++++++++--
 .../org/apache/spark/sql/JsonArraySuite.scala      | 27 ++++++++++++++++++
 .../org/apache/spark/sql/JsonObjectSuite.scala     | 33 ++++++++++++++++++++++
 3 files changed, 76 insertions(+), 3 deletions(-)

diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
index 0c004a363167..cec67b808936 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala
@@ -1356,6 +1356,13 @@ object ImplicitlyFormattedAsJson {
     case _ => false
   }
 
+  /** Drops the `Alias`es that [[splicesThroughCollationCast]] sees through, 
for SQL rendering. */
+  private[sql] def stripAliases(e: Expression): Expression = e match {
+    case a: Alias => stripAliases(a.child)
+    case c: Collate => c.copy(child = stripAliases(c.child))
+    case _ => e
+  }
+
   private def isAnalyzerCollationCast(c: Cast): Boolean = {
     // The default-collation rules only recolor a string producer of the 
default `StringType`, and
     // never mark the cast user-specified or recolored. `string(...)` has no 
user mark, but it wraps
@@ -1672,7 +1679,11 @@ case class JsonArray(
       case i: ImplicitlyFormattedAsJson => i.emitsImplicitJsonText
       case _ => false
     }
-    val valuesSQL = values.zip(formatJson).map { case (v, isJson) =>
+    // `Alias.sql` renders `AS name`, which cannot precede `FORMAT JSON`.
+    val rendered = values.zip(formatJson).map { case (v, isJson) =>
+      (if (isJson) ImplicitlyFormattedAsJson.stripAliases(v) else v, isJson)
+    }
+    val valuesSQL = rendered.map { case (v, isJson) =>
       // Emit SQL that reparses to the same splice/quote decision as the 
frozen `formatJson` flag.
       // The parser splices a value iff it is an explicit `FORMAT JSON` or a 
lexically-nested JSON
       // constructor (see `AstBuilder.visitJsonArray`), so the rendering 
depends on the flag and the
@@ -1711,7 +1722,7 @@ case class JsonArray(
     // Add `RETURNING STRING` so a clause-free render still means the built-in 
when reparsed (a
     // clause-free call, even a nested one, could bind a shadow). A rendered 
FORMAT JSON, null, or
     // RETURNING clause already does that.
-    val rendersFormatJson = values.zip(formatJson).exists {
+    val rendersFormatJson = rendered.exists {
       case (v, isJson) => isJson && !directlyImplicit(v)
     }
     val ownershipClause =
@@ -2783,7 +2794,9 @@ case class JsonObjectExpr(
   private[sql] def sqlString(
       forceBuiltinOwnership: Boolean,
       renderChild: Expression => String): String = {
-    val membersSQL = members.zip(rawJson).map { case ((k, v), raw) =>
+    val membersSQL = members.zip(rawJson).map { case ((k, child), raw) =>
+      // `Alias.sql` renders `AS name`, which cannot precede `FORMAT JSON`.
+      val v = if (raw) ImplicitlyFormattedAsJson.stripAliases(child) else child
       // Render SQL that reparses to the frozen `raw` flag, regardless of 
optimizer rewrites of the
       // child:
       //  - raw + child still a bare implicit producer (bare, or under a 
pass-through COLLATE):
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala
index ef3e978443b3..451f24b04367 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/JsonArraySuite.scala
@@ -24,6 +24,7 @@ import 
org.apache.spark.sql.catalyst.analysis.{AnalysisContext, NoSuchFunctionEx
 import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
 import 
org.apache.spark.sql.catalyst.analysis.resolver.ExplicitlyUnsupportedResolverFeature
 import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
   ApplyFunctionExpression,
   Cast,
   Collate,
@@ -386,6 +387,32 @@ class JsonArraySuite extends QueryTest with 
SharedSparkSession {
       "JSON_ARRAY(CAST(JSON_ARRAY(1 RETURNING STRING) AS STRING) RETURNING 
STRING)")
   }
 
+  test("SPARK-59243: SQL of a spliced aliased child drops the alias") {
+    val inner = JsonArray(
+      Seq(Literal(1)), Seq(false), Seq(false), 
JsonConstructorNullBehavior.Absent, StringType)
+    val aliased = JsonArray(
+      Seq(Alias(inner, "x")()), Seq(true), Seq(false), 
JsonConstructorNullBehavior.Absent,
+      StringType)
+    assert(aliased.sql == "JSON_ARRAY(JSON_ARRAY(1 RETURNING STRING) RETURNING 
STRING)")
+    checkAnswer(sql(s"SELECT ${aliased.sql}"), Row("[[1]]"))
+    val literal = JsonArray(
+      Seq(Alias(Literal("[1]"), "x")()), Seq(true), Seq(true), 
JsonConstructorNullBehavior.Absent,
+      StringType)
+    assert(literal.sql == "JSON_ARRAY('[1]' FORMAT JSON)")
+    val collated = JsonArray(
+      Seq(Collate(Alias(inner, "x")(), ResolvedCollation("UTF8_LCASE"))), 
Seq(true), Seq(false),
+      JsonConstructorNullBehavior.Absent, StringType)
+    assert(collated.sql ==
+      "JSON_ARRAY(collate(JSON_ARRAY(1 RETURNING STRING), UTF8_LCASE) FORMAT 
JSON)")
+    // The column name drops the alias too; a user cast still quotes and keeps 
it.
+    val df = spark.range(1).select(call_function("json_array", 
expr("json_array(1)").as("x")))
+    assert(df.columns.toSeq == Seq("JSON_ARRAY(JSON_ARRAY(1))"))
+    val quoted = spark.range(1).select(
+      call_function("json_array", expr("CAST(json_array(1) AS 
STRING)").as("x")))
+    assert(quoted.columns.toSeq == Seq("JSON_ARRAY(CAST(JSON_ARRAY(1) AS 
STRING) AS x)"))
+    checkAnswer(quoted, Row("""["[1]"]"""))
+  }
+
   test("emitted SQL reparses and evaluates with raw-vs-quoted semantics 
preserved") {
     // The .sql renderings above are round-trip contracts: reparsing and 
evaluating the actual
     // emitted SQL -- including any default RETURNING STRING clauses it 
carries -- must reproduce
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/JsonObjectSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/JsonObjectSuite.scala
index af336e66f973..874f4796997c 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/JsonObjectSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/JsonObjectSuite.scala
@@ -25,6 +25,7 @@ import org.apache.spark.sql.catalyst.analysis.Star
 import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.DataTypeMismatch
 import 
org.apache.spark.sql.catalyst.analysis.resolver.ExplicitlyUnsupportedResolverFeature
 import org.apache.spark.sql.catalyst.expressions.{
+  Alias,
   Cast,
   CodegenObjectFactoryMode,
   Collate,
@@ -39,6 +40,7 @@ import org.apache.spark.sql.catalyst.plans.logical.{Filter, 
Join}
 import org.apache.spark.sql.connector.ConstantStringOfAnyArity
 import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryCatalog}
 import org.apache.spark.sql.execution.{ProjectExec, WholeStageCodegenExec}
+import org.apache.spark.sql.functions.{call_function, expr, lit}
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.test.SharedSparkSession
 import org.apache.spark.sql.types.{ArrayType, CharType, GeographyType, 
GeometryType, IntegerType, MapType, StringType, StructType, VarcharType}
@@ -696,6 +698,37 @@ world'))"""))
     assert(default.sql == "JSON_OBJECT('k' VALUE 1 NULL ON NULL)")
   }
 
+  test("SPARK-59243: SQL of a raw aliased value drops the alias") {
+    val inner = JsonObjectExpr(
+      Seq((Literal("b"), Literal(1))), Seq(false), Seq(false), 
JsonConstructorNullBehavior.Null,
+      StringType)
+    val aliased = JsonObjectExpr(
+      Seq((Literal("a"), Alias(inner, "x")())), Seq(true), Seq(false),
+      JsonConstructorNullBehavior.Null, StringType)
+    assert(aliased.sql ==
+      "JSON_OBJECT('a' VALUE JSON_OBJECT('b' VALUE 1 NULL ON NULL) NULL ON 
NULL)")
+    checkAnswer(sql(s"SELECT ${aliased.sql}"), Row("""{"a":{"b":1}}"""))
+    val literal = JsonObjectExpr(
+      Seq((Literal("a"), Alias(Literal("[1]"), "x")())), Seq(true), Seq(true),
+      JsonConstructorNullBehavior.Null, StringType)
+    assert(literal.sql == "JSON_OBJECT('a' VALUE '[1]' FORMAT JSON NULL ON 
NULL)")
+    checkAnswer(sql(s"SELECT ${literal.sql}"), Row("""{"a":[1]}"""))
+    val collated = JsonObjectExpr(
+      Seq((Literal("a"), Collate(Alias(inner, "x")(), 
Literal("UTF8_BINARY")))), Seq(true),
+      Seq(false), JsonConstructorNullBehavior.Null, StringType)
+    assert(collated.sql == aliased.sql)
+    // The column name drops the alias too; a user cast still quotes and keeps 
it.
+    val df = spark.range(1).select(
+      call_function("json_object", lit("a"), expr("json_object('b', 
1)").as("x")))
+    assert(!df.columns.head.contains(" AS ") && 
!df.columns.head.contains("FORMAT JSON"),
+      df.columns.head)
+    checkAnswer(df, Row("""{"a":{"b":1}}"""))
+    val quoted = spark.range(1).select(call_function(
+      "json_object", lit("a"), expr("CAST(json_object('b', 1) AS 
STRING)").as("x")))
+    assert(quoted.columns.head.contains(" AS x"), quoted.columns.head)
+    checkAnswer(quoted, Row("""{"a":"{\"b\":1}"}"""))
+  }
+
   test("SQL renders a raw nested value spliced back to raw even after 
collation wrapping") {
     val inner = JsonObjectExpr(
       Seq((Literal("b"), Literal(1))), Seq(false), Seq(false),


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

Reply via email to