spark-test commented on code in PR #60060:
URL: https://github.com/apache/spark/pull/60060#discussion_r4509857101


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CollationTypeCoercion.scala:
##########
@@ -399,6 +401,11 @@ object CollationTypeCoercion extends SQLConfHelper {
 
       Some(addContextToStringType(cast.dataType, castStrength))
 
+    // An explicitly collated target type (even UTF8_BINARY), not the path, 
decides the
+    // collation, like a column of that type.
+    case v: VariantGet if 
DataTypeUtils.hasNonDefaultStringCharOrVarcharType(v.dataType) =>

Review Comment:
   **Non-blocking (P2):** This arm covers only `VariantGet`. `JsonValue`, 
`JsonQuery`, `JsonArray` and `JsonObjectExpr` also take their result type from 
a user-declared `RETURNING` clause, but no base case matches them, so 
`findCollationContext` falls through to its generic fallback and adopts the 
collation of their string arguments. The analyzer then casts an explicitly 
collated result to that collation before comparing it, which is the mechanism 
this PR removes for `variant_get`.
   
   For example, with `j` a `STRING` column holding `{"s": "Open"}`, 
`variant_get(parse_json(j), '$.s', 'STRING COLLATE UTF8_LCASE') = 'open'` is 
now true, but `JSON_VALUE(j, '$.s' RETURNING STRING COLLATE UTF8_LCASE) = 
'open'` is still false, with no error. You confirmed this for `JSON_VALUE` and 
`JSON_QUERY` in the PR conversation, and `JSON_ARRAY` and `JSON_OBJECT` with a 
collated `RETURNING` type take the same fallback. These four are the only 
expressions with a `RETURNING` type; `JSON_TABLE` columns are not affected, 
because they reach comparisons as attributes. None of these functions is in 
Spark 4.3.0, so covering them before 4.4 ships gives one rule for declared 
result collations and needs no migration note of its own.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60060#issuecomment-6664340600), 
[2](https://github.com/apache/spark/pull/60060#pullrequestreview-5779474253).
   
   **Recommended change:** Extend the explicit-target collation rule from 
variant_get to JSON_VALUE, JSON_QUERY, JSON_ARRAY and JSON_OBJECT. When their 
RETURNING type contains an explicitly collated string, the result takes that 
type's collation with Implicit strength. Add collation precedence tests for 
these functions under both analyzers.
   
   **Why this works:** Generalize the variant_get case in 
collationStrengthBaseCases to also match JsonValue, JsonQuery, JsonArray and 
JsonObjectExpr. When the RETURNING type contains an explicitly collated string, 
return it with Implicit strength, ahead of the generic children fallback. Plain 
RETURNING types, which the parser keeps as the StringType companion, keep the 
current derivation.
   
   **Scope:** Collation strength for the JSON SQL functions with a collated 
RETURNING type, plus collation precedence tests.
   
   **Compatibility:** Results with a plain RETURNING STRING keep following 
their inputs or the object's default collation, as they do today.
   
   **Risks:** JSON functions with an explicitly collated RETURNING type will 
then conflict with other implicit collations and fail with 
INDETERMINATE_COLLATION_IN_EXPRESSION, as variant_get now does; the change is 
analysis-only and can be rolled back.
   
   **Constraints:** Plain RETURNING types, including RETURNING STRING inside a 
view or table with a DEFAULT COLLATION, keep their current resolution. Both 
analyzers produce the same results and the same errors for these functions. 
Land the change before Spark 4.4 ships. None of these functions is in Spark 
4.3.0, so the migration note then needs no entry for them.
   
   **Exclusions:**
   - Casts from VARIANT keep the existing Cast rule, as the PR description 
states.
   
   **Success:** JSON_VALUE(j, '$.s' RETURNING STRING COLLATE UTF8_LCASE) = 
'open' matches the value 'Open', like the equivalent variant_get call. 
JSON_QUERY, JSON_ARRAY and JSON_OBJECT with an explicitly collated RETURNING 
type compare their result in that collation. JSON functions with a plain 
RETURNING type resolve as before. Inside a view with DEFAULT COLLATION 
UTF8_LCASE, a result with an explicit RETURNING STRING COLLATE UTF8_BINARY 
compares in UTF8_BINARY, as the variant_get rule does.
   
   **Verification:**
   - **Regression:** Under both analyzers, JSON_VALUE, JSON_QUERY, JSON_ARRAY 
and JSON_OBJECT with RETURNING STRING COLLATE UTF8_LCASE compare their result 
case-insensitively with a UTF8_BINARY literal, whether their string input is a 
column or a literal, and inside a view with DEFAULT COLLATION UTF8_LCASE a 
result with RETURNING STRING COLLATE UTF8_BINARY compares case-sensitively.
   - **Behavior:** Comparing such a JSON result with a plain STRING column 
fails with INDETERMINATE_COLLATION_IN_EXPRESSION, as it does for variant_get.
   - **Compatibility:** JSON functions with a plain RETURNING type, including 
inside a view with DEFAULT COLLATION UTF8_LCASE, keep their current comparison 
collation under both analyzers.



##########
sql/core/src/test/scala/org/apache/spark/sql/collation/CollationTypePrecedenceSuite.scala:
##########
@@ -490,6 +490,97 @@ class CollationTypePrecedenceSuite extends 
SharedSparkSession {
     }
   }
 
+  testFixedPointAndSinglePass("variant_get with a collated target type has 
implicit strength") {
+    val tableName = "variant_get_tbl"
+    val viewName = "variant_get_view"
+    withTable(tableName) {
+      sql(s"CREATE TABLE $tableName (id INT, c STRING COLLATE UNICODE_CI, p 
STRING, v VARIANT) " +
+        s"USING $dataSource")
+      sql(
+        s"""
+           |INSERT INTO $tableName SELECT id, 'OPEN', 'OPEN', parse_json(j) 
FROM VALUES
+           |  (1, '{"s": "Open", "a": ["Open"]}'),
+           |  (2, '{"s": "open", "a": ["open"]}'),
+           |  (3, '{"s": "closed", "a": ["closed"]}') AS t(id, j)
+           |""".stripMargin)
+
+      Seq("variant_get", "try_variant_get").foreach { fn =>
+        val lcase = s"$fn(v, '$$.s', 'STRING COLLATE UTF8_LCASE')"
+        val lcaseMap = s"$fn(v, '$$', 'MAP<STRING, STRING COLLATE 
UTF8_LCASE>')"
+        val mixedStruct = s"$fn(v, '$$', 'STRUCT<s: STRING, t: STRING COLLATE 
UTF8_LCASE>')"
+        checkAnswer(
+          sql(s"SELECT DISTINCT COLLATION($lcase || 'a') FROM $tableName"),
+          Row(UTF8_LCASE_COLLATION_NAME))
+
+        Seq(
+          s"$lcase = 'OPEN'",
+          s"$lcase IN ('OPEN', 'x')",
+          s"startswith($lcase, 'OP')",
+          s"array_contains($fn(v, '$$.a', 'ARRAY<STRING COLLATE UTF8_LCASE>'), 
'OPEN')",
+          s"$fn(v, '$$', 'STRUCT<s: STRING COLLATE UTF8_LCASE>').s = 'OPEN'",
+          s"$lcaseMap['s'] = 'OPEN'",
+          s"element_at($lcaseMap, 's') = 'OPEN'",
+          // The collation of the path does not take part.
+          s"$fn(v, '$$.s' COLLATE UNICODE, 'STRING COLLATE UTF8_LCASE') = 
'OPEN'").foreach { cond =>
+          checkAnswer(sql(s"SELECT id FROM $tableName WHERE $cond"), 
Seq(Row(1), Row(2)))
+        }
+
+        // The UTF8_BINARY field of a partly collated struct stays UTF8_BINARY.
+        checkAnswer(sql(s"SELECT id FROM $tableName WHERE $mixedStruct.s = 
'OPEN'"), Seq.empty)
+
+        checkAnswer(
+          sql(s"SELECT id FROM $tableName WHERE $lcase = 'Open' COLLATE 
UTF8_BINARY"),
+          Seq(Row(1)))
+
+        // Like a column of the target type, it conflicts with other implicit 
collations.
+        Seq(
+          s"$lcase = c",
+          s"$lcase = p",
+          s"$lcase IN (p, 'x')",
+          s"$fn(v, '$$.s', 'STRING COLLATE UTF8_BINARY') = c",
+          s"$mixedStruct.s = c",
+          s"$lcase || p = 'OPEN'",
+          s"(CASE WHEN id = 1 THEN $lcase ELSE p END) = 'OPEN'",
+          // A cast from VARIANT keeps the Cast rule: default strength, so it 
conflicts with a
+          // literal of another collation.
+          s"CAST($fn(v, '$$.s') AS STRING COLLATE UTF8_LCASE) = 'OPEN'",
+          s"v:s::STRING COLLATE UTF8_LCASE = 'OPEN'").foreach { cond =>
+          assertIndeterminateCollation(sql(s"SELECT id FROM $tableName WHERE 
$cond"))
+        }
+        // Combining them gives an indeterminate collation that fails when the 
result is stored.
+        withTable("variant_get_ctas") {
+          assertIndeterminateCollation(sql(s"CREATE TABLE variant_get_ctas 
USING $dataSource " +
+            s"AS SELECT coalesce($lcase, p) AS s FROM $tableName"))
+        }
+
+        // A target without an explicit collation keeps default strength.
+        Seq(
+          s"$fn(v, '$$.s', 'STRING') = c",
+          s"array_contains($fn(v, '$$.a', 'ARRAY<STRING>'), c)",
+          s"CAST($fn(v, '$$.s') AS STRING) = c",
+          s"v:s::STRING = c").foreach { cond =>
+          checkAnswer(sql(s"SELECT id FROM $tableName WHERE $cond"), 
Seq(Row(1), Row(2)))
+        }
+
+        // Under a default collation, an explicit UTF8_BINARY target keeps 
UTF8_BINARY, and plain
+        // targets, whose type the default collation rewrites, keep default 
strength.

Review Comment:
   **Nit (P3):** For `variant_get`, nothing rewrites the target type. The 
default-collation rules recolor literals, user casts and column definitions, 
and wrap default-string-producing expressions in a cast, so a plain `'STRING'` 
target stays the `StringType` companion, and its UTF8_LCASE context comes from 
the recolored `'$.s'` path literal. With a path such as `'$.s' COLLATE 
UTF8_BINARY`, `plain` would be false, which this explanation does not predict. 
Only the `v:s::STRING` casts have their target type rewritten.
   
   ```suggestion
           // targets keep default strength, through the recolored path or the 
rewritten cast type.
   ```
   
   **Verification:**
   - **Inspection:** The comment above the DEFAULT COLLATION view says that 
plain variant_get targets follow the recolored path literal and that plain 
casts from VARIANT have their target type rewritten, which matches what the 
assertions check.



-- 
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