You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by we...@apache.org on 2025/09/16 08:19:38 UTC

(spark) branch master updated: [SPARK-53582][SQL] Extend `isExtractable` so it can be applied on `UnresolvedExtractValue`

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

wenchen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new dbbb54db214d [SPARK-53582][SQL] Extend `isExtractable` so it can be applied on `UnresolvedExtractValue`
dbbb54db214d is described below

commit dbbb54db214ded281dfa8d424ddbb61783f22eae
Author: Mihailo Timotic <mi...@databricks.com>
AuthorDate: Tue Sep 16 16:19:25 2025 +0800

    [SPARK-53582][SQL] Extend `isExtractable` so it can be applied on `UnresolvedExtractValue`
    
    ### What changes were proposed in this pull request?
    Extend isExtractable so it can be applied on UnresolvedExtractValue. Additionally, fix the error context for `UNSUPPORTED_CORRELATED_REFERENCE_DATA_TYPE` error
    
    ### Why are the changes needed?
    The extension to `ExtractValue.isExtractable` is necessary in order to implement `UnresolvedExtractValue` in single-pass analyzer.
    
    We are also fixing the context, because current context is inconsistent and often doesn't make sense. This is makes it hard for single-pass analyzer to be compatible with fixed-point. For example, query like:
    ```
    select * from x where (select sum(y2) from y where xm[y2] = ym[1]) > 2
    ```
    will show the error on relation `y`, which has nothing to do with actual issue. This PR fixed that
    
    ### How was this patch tested?
    Existing tests.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    No
    
    Closes #52341 from mihailotim-db/mihailo-timotic_data/fix_extract_value.
    
    Authored-by: Mihailo Timotic <mi...@databricks.com>
    Signed-off-by: Wenchen Fan <we...@databricks.com>
---
 .../sql/catalyst/analysis/resolver/NameScope.scala |   6 +-
 .../expressions/complexTypeExtractors.scala        |  33 +++++-
 .../catalyst/optimizer/DecorrelateInnerQuery.scala |   5 +-
 ...order-by-recursive-type-name-resolution.sql.out | 129 +++++++++++++++++++++
 ...and-order-by-recursive-type-name-resolution.sql |  55 +++++++++
 ...order-by-recursive-type-name-resolution.sql.out | 103 ++++++++++++++++
 .../results/subquery/subquery-nested-data.sql.out  |  12 +-
 .../scala/org/apache/spark/sql/SubquerySuite.scala |   6 +-
 8 files changed, 333 insertions(+), 16 deletions(-)

diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala
index ed731432e2a3..b9b98f497ae1 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/NameScope.scala
@@ -700,7 +700,11 @@ class NameScope(
 
     val filteredCandidates = if (nestedFields.nonEmpty) {
       candidates.filter { attribute =>
-        ExtractValue.isExtractable(attribute, nestedFields, nameComparator)
+        ExtractValue.isExtractable(
+          attribute = attribute,
+          nestedFields = nestedFields,
+          resolver = nameComparator
+        )
       }
     } else {
       candidates
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeExtractors.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeExtractors.scala
index 30e71f7a3e36..dba061eeb870 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeExtractors.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/complexTypeExtractors.scala
@@ -106,21 +106,44 @@ object ExtractValue {
   }
 
   /**
-   * Check that [[attribute]] can be fully extracted using the given [[nestedFields]].
+   * Check that `attribute` can be fully extracted using the given nestedFields and `extractorKey`.
+   * This method first tries to extract the innermost nested field using `nestedFields`. If such
+   * nested field is found, try to extract the value using `extractorKey`, if it exists. This
+   * method returns true if all attempted extractions are successful.
    */
   def isExtractable(
-      attribute: Attribute, nestedFields: Seq[String], resolver: Resolver): Boolean = {
-    nestedFields
+      attribute: Attribute,
+      nestedFields: Seq[String],
+      extractorKey: Option[Expression] = None,
+      resolver: Resolver): Boolean = {
+    val withExtractedNestedFields = nestedFields
       .foldLeft(Some(attribute): Option[Expression]) {
         case (Some(expression), field) =>
-          ExtractValue.extractValue(expression, Literal(field), resolver) match {
+          ExtractValue.extractValue(
+            child = expression,
+            extraction = Literal(field),
+            resolver = resolver
+          ) match {
             case Left(e) => Some(e)
             case Right(_) => None
           }
         case _ =>
           None
       }
-      .isDefined
+
+    withExtractedNestedFields match {
+      case Some(nestedField) if extractorKey.isDefined =>
+        ExtractValue.extractValue(
+          child = nestedField,
+          extraction = extractorKey.get,
+          resolver = resolver
+        ) match {
+          case Left(e) => true
+          case Right(_) => false
+        }
+      case Some(_) => true
+      case None => false
+    }
   }
 
   /**
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala
index 47cee2e789c7..c6a7940b93aa 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala
@@ -532,7 +532,10 @@ object DecorrelateInnerQuery extends PredicateHelper {
               if (!cond.resolved) {
                 if (!RowOrdering.isOrderable(a.dataType)) {
                   throw QueryCompilationErrors.unsupportedCorrelatedReferenceDataTypeError(
-                    o, a.dataType, plan.origin)
+                    expr = a,
+                    dataType = a.dataType,
+                    origin = a.origin
+                  )
                 } else {
                   throw SparkException.internalError(s"Unable to decorrelate subquery: " +
                     s"join condition '${cond.sql}' cannot be resolved.")
diff --git a/sql/core/src/test/resources/sql-tests/analyzer-results/having-and-order-by-recursive-type-name-resolution.sql.out b/sql/core/src/test/resources/sql-tests/analyzer-results/having-and-order-by-recursive-type-name-resolution.sql.out
index e7c33c1ee6a0..cfcd9c5c42e2 100644
--- a/sql/core/src/test/resources/sql-tests/analyzer-results/having-and-order-by-recursive-type-name-resolution.sql.out
+++ b/sql/core/src/test/resources/sql-tests/analyzer-results/having-and-order-by-recursive-type-name-resolution.sql.out
@@ -371,3 +371,132 @@ Sort [col1#x.b ASC NULLS FIRST], true
    +- Aggregate [col1#x], [named_struct(b, 1) AS col1#x]
       +- SubqueryAlias t
          +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.name
+FROM VALUES (NAMED_STRUCT('name', 'test', 'id', 1)) t (col1)
+GROUP BY col1
+HAVING col1.id > 0
+ORDER BY col1.name
+-- !query analysis
+Project [name#x]
++- Sort [col1#x.name ASC NULLS FIRST], true
+   +- Project [name#x, col1#x]
+      +- Filter (col1#x.id > 0)
+         +- Aggregate [col1#x], [col1#x.name AS name#x, col1#x]
+            +- SubqueryAlias t
+               +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.items[0]
+FROM VALUES (NAMED_STRUCT('items', ARRAY(1, 2, 3))) t (col1)
+GROUP BY col1
+HAVING col1.items[0] > 0
+ORDER BY col1.items[0]
+-- !query analysis
+Sort [col1.items[0]#x ASC NULLS FIRST], true
++- Filter (col1.items[0]#x > 0)
+   +- Aggregate [col1#x], [col1#x.items[0] AS col1.items[0]#x]
+      +- SubqueryAlias t
+         +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.data['key']
+FROM VALUES (NAMED_STRUCT('data', MAP('key', 'value', 'num', '42'))) t (col1)
+GROUP BY col1
+HAVING col1.data['num'] IS NOT NULL
+ORDER BY col1.data['key']
+-- !query analysis
+Project [col1.data[key]#x]
++- Sort [col1#x.data[key] ASC NULLS FIRST], true
+   +- Project [col1.data[key]#x, col1#x]
+      +- Filter isnotnull(col1#x.data[num])
+         +- Aggregate [col1#x], [col1#x.data[key] AS col1.data[key]#x, col1#x]
+            +- SubqueryAlias t
+               +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.users[0].name
+FROM VALUES (
+             NAMED_STRUCT('users', ARRAY(NAMED_STRUCT('name', 'John', 'age', 30)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.users[0].age > 25
+ORDER BY col1.users[0].name
+-- !query analysis
+Project [col1.users[0].name#x]
++- Sort [col1#x.users[0].name ASC NULLS FIRST], true
+   +- Project [col1.users[0].name#x, col1#x]
+      +- Filter (col1#x.users[0].age > 25)
+         +- Aggregate [col1#x], [col1#x.users[0].name AS col1.users[0].name#x, col1#x]
+            +- SubqueryAlias t
+               +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.person.address.city
+FROM VALUES (
+             NAMED_STRUCT('person', NAMED_STRUCT('address', NAMED_STRUCT('city', 'NYC', 'zip', 10001)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.person.address.zip > 10000
+ORDER BY col1.person.address.city
+-- !query analysis
+Project [city#x]
++- Sort [col1#x.person.address.city ASC NULLS FIRST], true
+   +- Project [city#x, col1#x]
+      +- Filter (col1#x.person.address.zip > 10000)
+         +- Aggregate [col1#x], [col1#x.person.address.city AS city#x, col1#x]
+            +- SubqueryAlias t
+               +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.matrix[0][1]
+FROM VALUES (
+             NAMED_STRUCT('matrix', ARRAY(ARRAY(1, 2), ARRAY(3, 4)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.matrix[0][0] < 5
+ORDER BY col1.matrix[0][1]
+-- !query analysis
+Project [col1.matrix[0][1]#x]
++- Sort [col1#x.matrix[0][1] ASC NULLS FIRST], true
+   +- Project [col1.matrix[0][1]#x, col1#x]
+      +- Filter (col1#x.matrix[0][0] < 5)
+         +- Aggregate [col1#x], [col1#x.matrix[0][1] AS col1.matrix[0][1]#x, col1#x]
+            +- SubqueryAlias t
+               +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.data[0].props['status']
+FROM VALUES (
+             NAMED_STRUCT('data', ARRAY(NAMED_STRUCT('props', MAP('status', 'active'))))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.data[0].props['status'] = 'active'
+-- !query analysis
+Filter (col1.data[0].props[status]#x = active)
++- Aggregate [col1#x], [col1#x.data[0].props[status] AS col1.data[0].props[status]#x]
+   +- SubqueryAlias t
+      +- LocalRelation [col1#x]
+
+
+-- !query
+SELECT col1.nums[0] + col1.nums[1] AS sum_val
+FROM VALUES (NAMED_STRUCT('nums', ARRAY(10, 20))) t (col1)
+GROUP BY col1
+HAVING col1.nums[0] + col1.nums[1] > 25
+ORDER BY col1.nums[0]
+-- !query analysis
+Project [sum_val#x]
++- Sort [col1#x.nums[0] ASC NULLS FIRST], true
+   +- Filter (sum_val#x > 25)
+      +- Aggregate [col1#x], [(col1#x.nums[0] + col1#x.nums[1]) AS sum_val#x, col1#x]
+         +- SubqueryAlias t
+            +- LocalRelation [col1#x]
diff --git a/sql/core/src/test/resources/sql-tests/inputs/having-and-order-by-recursive-type-name-resolution.sql b/sql/core/src/test/resources/sql-tests/inputs/having-and-order-by-recursive-type-name-resolution.sql
index 36616e2cf1e1..1f53ca359fe1 100644
--- a/sql/core/src/test/resources/sql-tests/inputs/having-and-order-by-recursive-type-name-resolution.sql
+++ b/sql/core/src/test/resources/sql-tests/inputs/having-and-order-by-recursive-type-name-resolution.sql
@@ -86,3 +86,58 @@ SELECT NAMED_STRUCT('b', 1) AS col1 FROM VALUES (NAMED_STRUCT('a', 0)) t (col1)
 SELECT NAMED_STRUCT('b', 1) AS col1 FROM VALUES (NAMED_STRUCT('a', 0)) t (col1) GROUP BY col1 ORDER BY col1.b;
 SELECT NAMED_STRUCT('b', 1) AS col1 FROM VALUES (NAMED_STRUCT('a', 0)) t (col1) GROUP BY col1 HAVING col1.b > 0;
 SELECT NAMED_STRUCT('b', 1) AS col1 FROM VALUES (NAMED_STRUCT('a', 0)) t (col1) GROUP BY col1 HAVING col1.b > 0 ORDER BY col1.b;
+
+SELECT col1.name
+FROM VALUES (NAMED_STRUCT('name', 'test', 'id', 1)) t (col1)
+GROUP BY col1
+HAVING col1.id > 0
+ORDER BY col1.name;
+
+SELECT col1.items[0]
+FROM VALUES (NAMED_STRUCT('items', ARRAY(1, 2, 3))) t (col1)
+GROUP BY col1
+HAVING col1.items[0] > 0
+ORDER BY col1.items[0];
+
+SELECT col1.data['key']
+FROM VALUES (NAMED_STRUCT('data', MAP('key', 'value', 'num', '42'))) t (col1)
+GROUP BY col1
+HAVING col1.data['num'] IS NOT NULL
+ORDER BY col1.data['key'];
+
+SELECT col1.users[0].name
+FROM VALUES (
+             NAMED_STRUCT('users', ARRAY(NAMED_STRUCT('name', 'John', 'age', 30)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.users[0].age > 25
+ORDER BY col1.users[0].name;
+
+SELECT col1.person.address.city
+FROM VALUES (
+             NAMED_STRUCT('person', NAMED_STRUCT('address', NAMED_STRUCT('city', 'NYC', 'zip', 10001)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.person.address.zip > 10000
+ORDER BY col1.person.address.city;
+
+SELECT col1.matrix[0][1]
+FROM VALUES (
+             NAMED_STRUCT('matrix', ARRAY(ARRAY(1, 2), ARRAY(3, 4)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.matrix[0][0] < 5
+ORDER BY col1.matrix[0][1];
+
+SELECT col1.data[0].props['status']
+FROM VALUES (
+             NAMED_STRUCT('data', ARRAY(NAMED_STRUCT('props', MAP('status', 'active'))))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.data[0].props['status'] = 'active';
+
+SELECT col1.nums[0] + col1.nums[1] AS sum_val
+FROM VALUES (NAMED_STRUCT('nums', ARRAY(10, 20))) t (col1)
+GROUP BY col1
+HAVING col1.nums[0] + col1.nums[1] > 25
+ORDER BY col1.nums[0];
diff --git a/sql/core/src/test/resources/sql-tests/results/having-and-order-by-recursive-type-name-resolution.sql.out b/sql/core/src/test/resources/sql-tests/results/having-and-order-by-recursive-type-name-resolution.sql.out
index b52f96536e82..f685076f9f30 100644
--- a/sql/core/src/test/resources/sql-tests/results/having-and-order-by-recursive-type-name-resolution.sql.out
+++ b/sql/core/src/test/resources/sql-tests/results/having-and-order-by-recursive-type-name-resolution.sql.out
@@ -324,3 +324,106 @@ SELECT NAMED_STRUCT('b', 1) AS col1 FROM VALUES (NAMED_STRUCT('a', 0)) t (col1)
 struct<col1:struct<b:int>>
 -- !query output
 {"b":1}
+
+
+-- !query
+SELECT col1.name
+FROM VALUES (NAMED_STRUCT('name', 'test', 'id', 1)) t (col1)
+GROUP BY col1
+HAVING col1.id > 0
+ORDER BY col1.name
+-- !query schema
+struct<name:string>
+-- !query output
+test
+
+
+-- !query
+SELECT col1.items[0]
+FROM VALUES (NAMED_STRUCT('items', ARRAY(1, 2, 3))) t (col1)
+GROUP BY col1
+HAVING col1.items[0] > 0
+ORDER BY col1.items[0]
+-- !query schema
+struct<col1.items[0]:int>
+-- !query output
+1
+
+
+-- !query
+SELECT col1.data['key']
+FROM VALUES (NAMED_STRUCT('data', MAP('key', 'value', 'num', '42'))) t (col1)
+GROUP BY col1
+HAVING col1.data['num'] IS NOT NULL
+ORDER BY col1.data['key']
+-- !query schema
+struct<col1.data[key]:string>
+-- !query output
+value
+
+
+-- !query
+SELECT col1.users[0].name
+FROM VALUES (
+             NAMED_STRUCT('users', ARRAY(NAMED_STRUCT('name', 'John', 'age', 30)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.users[0].age > 25
+ORDER BY col1.users[0].name
+-- !query schema
+struct<col1.users[0].name:string>
+-- !query output
+John
+
+
+-- !query
+SELECT col1.person.address.city
+FROM VALUES (
+             NAMED_STRUCT('person', NAMED_STRUCT('address', NAMED_STRUCT('city', 'NYC', 'zip', 10001)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.person.address.zip > 10000
+ORDER BY col1.person.address.city
+-- !query schema
+struct<city:string>
+-- !query output
+NYC
+
+
+-- !query
+SELECT col1.matrix[0][1]
+FROM VALUES (
+             NAMED_STRUCT('matrix', ARRAY(ARRAY(1, 2), ARRAY(3, 4)))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.matrix[0][0] < 5
+ORDER BY col1.matrix[0][1]
+-- !query schema
+struct<col1.matrix[0][1]:int>
+-- !query output
+2
+
+
+-- !query
+SELECT col1.data[0].props['status']
+FROM VALUES (
+             NAMED_STRUCT('data', ARRAY(NAMED_STRUCT('props', MAP('status', 'active'))))
+     ) t (col1)
+GROUP BY col1
+HAVING col1.data[0].props['status'] = 'active'
+-- !query schema
+struct<col1.data[0].props[status]:string>
+-- !query output
+active
+
+
+-- !query
+SELECT col1.nums[0] + col1.nums[1] AS sum_val
+FROM VALUES (NAMED_STRUCT('nums', ARRAY(10, 20))) t (col1)
+GROUP BY col1
+HAVING col1.nums[0] + col1.nums[1] > 25
+ORDER BY col1.nums[0]
+-- !query schema
+struct<sum_val:int>
+-- !query output
+30
diff --git a/sql/core/src/test/resources/sql-tests/results/subquery/subquery-nested-data.sql.out b/sql/core/src/test/resources/sql-tests/results/subquery/subquery-nested-data.sql.out
index e0fd040ca4bc..90c59d3aa0d6 100644
--- a/sql/core/src/test/resources/sql-tests/results/subquery/subquery-nested-data.sql.out
+++ b/sql/core/src/test/resources/sql-tests/results/subquery/subquery-nested-data.sql.out
@@ -252,9 +252,9 @@ org.apache.spark.sql.AnalysisException
   "queryContext" : [ {
     "objectType" : "",
     "objectName" : "",
-    "startIndex" : 44,
-    "stopIndex" : 44,
-    "fragment" : "y"
+    "startIndex" : 23,
+    "stopIndex" : 66,
+    "fragment" : "(select sum(y2) from y where xm[y2] = ym[1])"
   } ]
 }
 
@@ -283,9 +283,9 @@ org.apache.spark.sql.AnalysisException
   "queryContext" : [ {
     "objectType" : "",
     "objectName" : "",
-    "startIndex" : 44,
-    "stopIndex" : 44,
-    "fragment" : "y"
+    "startIndex" : 23,
+    "stopIndex" : 65,
+    "fragment" : "(select sum(y2) from y where xm[1] = ym[1])"
   } ]
 }
 
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala
index 205f4f7eec80..3ba48da0e327 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/SubquerySuite.scala
@@ -2562,9 +2562,9 @@ class SubquerySuite extends QueryTest
             "UNSUPPORTED_CORRELATED_REFERENCE_DATA_TYPE",
           parameters = Map("expr" -> "v1.x", "dataType" -> "map"),
           context = ExpectedContext(
-            fragment = "select upper(x['a'] + rand()) as a",
-            start = 39,
-            stop = 72)
+            fragment = "(\n  select concat(a, a) from\n  (select upper(x['a'] + rand()) as a)\n)",
+            start = 7,
+            stop = 75)
         )
       }
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org