This is an automated email from the ASF dual-hosted git repository.
uros-b 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 9e81552e2079 [SPARK-60871][SQL] Respect collated result types in
variant_get and JSON RETURNING
9e81552e2079 is described below
commit 9e81552e2079bf627b37c7578249ec2d10cbbfec
Author: Stevo Mitric <[email protected]>
AuthorDate: Thu Nov 12 10:47:57 2026 +0000
[SPARK-60871][SQL] Respect collated result types in variant_get and JSON
RETURNING
### What changes were proposed in this pull request?
1. **Goal:** `variant_get` / `try_variant_get` with a collated target type,
and `JSON_VALUE` / `JSON_QUERY` / `JSON_ARRAY` / `JSON_OBJECT` with a collated
`RETURNING` type, compare using that collation.
2. **Problem:** The result takes the collation of the arguments, so it gets
cast back to UTF8_BINARY before the comparison.
```sql
-- status values: 'Open', 'open', 'OPEN', 'closed'
SELECT id FROM t WHERE variant_get(v, '$.status', 'STRING COLLATE
UTF8_LCASE') = 'open';
-- Before: 2. Target: 1, 2, 3
```
3. **Solution:** These expressions now take the collation of an explicitly
collated result type with implicit strength, like a column of that type. Plain
`STRING` is unchanged. Runtime Bloom filters are also skipped for join keys
that aren't binary stable, since the filter hashes raw bytes and can drop rows
that match under the collation.
### Why are the changes needed?
Wrong results.
### Does this PR introduce _any_ user-facing change?
Yes. These results now use the declared collation. Mixing one with a string
of a different implicit collation, e.g. a plain `STRING` column, fails with
`INDETERMINATE_COLLATION_IN_EXPRESSION`, same as two columns with different
collations. See the migration guide note.
### How was this patch tested?
New tests.
### Was this patch authored or co-authored using generative AI tooling?
Co-authored-by: Claude Opus 5.5
Closes #60060 from stevomitric/stevomitric/variant-get-collated-target.
Authored-by: Stevo Mitric <[email protected]>
Signed-off-by: Uros Bojanic <[email protected]>
skip-checks: true
---
docs/sql-migration-guide.md | 1 +
.../catalyst/analysis/CollationTypeCoercion.scala | 8 ++
.../catalyst/optimizer/InjectRuntimeFilter.scala | 54 ++++----
.../spark/sql/InjectRuntimeFilterSuite.scala | 94 ++++++++++++-
.../collation/CollationTypePrecedenceSuite.scala | 149 +++++++++++++++++++++
5 files changed, 275 insertions(+), 31 deletions(-)
diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index 593517d4768e..0e74722273f4 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -41,6 +41,7 @@ license: |
- Since Spark 4.4, Data Source V2 file scans correctly evaluate deterministic
Python UDF filter predicates that reference only partition columns. Previously,
these predicates could be dropped, returning rows that did not satisfy the
filter (SPARK-60486). Data derived from affected query results may need to be
recomputed.
- Since Spark 4.4, when a file source reads a partition column with a
user-specified datetime type such as `DATE` or `TIMESTAMP` from directory
names, a value that cannot be cast to that type fails with
`INVALID_PARTITION_VALUE` regardless of `spark.sql.ansi.enabled`. Previously,
such a value became `NULL` when `spark.sql.ansi.enabled` was `false`. When it
was `true`, a `TIMESTAMP_NTZ` value with a valid date and an invalid time, such
as `2020-01-01 25:00:00`, became the start of that da [...]
- Since Spark 4.4, quoted Variant path keys decode `\\`, `\/`, `\b`, `\f`,
`\n`, `\r`, `\t`, `\uXXXX` (including valid surrogate pairs), and escapes of
the enclosing quote (`\'` or `\"`). Previously, backslashes were literal, so
existing paths can match different keys or become invalid. For example, use
`$['a\\']` instead of `$['a\']`. Unknown escapes and unpaired surrogate escapes
stay literal. Dot-notation keys are unchanged. To keep the old behavior, set
`spark.sql.legacy.variantPathB [...]
+- Since Spark 4.4, `variant_get` and `try_variant_get` with an explicitly
collated target type, such as `'STRING COLLATE UTF8_LCASE'`, compare and
combine their result using that collation, as a column of that type does.
Previously the target collation was ignored, so `variant_get(v, '$.a', 'STRING
COLLATE UTF8_LCASE') = 'abc'` was case-sensitive. Combining such a result with
a string of a different implicit collation, such as a `STRING` column, now
fails with `INDETERMINATE_COLLATION_IN [...]
- Since Spark 4.4, a write to a Data Source V2 table that parses the SQL text
of a generation expression binds an unqualified built-in function name to
`system.builtin`, regardless of the SQL path and
`spark.sql.functionResolution.sessionOrder`. Previously, a temporary function
or a function in the SQL path with the same name could shadow the built-in
function, so that the write could silently store a value of an auto-filled
generated column that does not match the generation expression, [...]
- Since Spark 4.4, `CREATE TABLE` and `REPLACE TABLE` on a Data Source V2
table fail with `UNSUPPORTED_EXPRESSION_GENERATED_COLUMN` when a generation
expression calls a Data Source V2 scalar function that has a magic `invoke`
method. Previously, they accepted such a call, and a write could resolve the
function name in its own session, so that it stored another value or failed
(SPARK-60866). To run these statements, change the expression to call only
built-in functions. Existing generated [...]
- Since Spark 4.4, an auto-filled generated column of a Data Source V2 table
reads a column referenced in a lambda function, such as `i` in `transform(a, x
-> x + i)`, or with `IDENTIFIER`, such as `IDENTIFIER('i')`, from the value
stored in that column. Previously, it read the value of the query before the
store assignment cast, so it could silently store a value that does not match
the stored column, and a later write of that row failed with
`CHECK_CONSTRAINT_VIOLATION` (SPARK-60817). [...]
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CollationTypeCoercion.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CollationTypeCoercion.scala
index 907cdfc7d16b..578b5b6824ae 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CollationTypeCoercion.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/CollationTypeCoercion.scala
@@ -21,8 +21,10 @@ import org.apache.spark.sql.catalyst.SQLConfHelper
import org.apache.spark.sql.catalyst.analysis.CollationStrength.{Default,
Explicit, Implicit, Indeterminate}
import org.apache.spark.sql.catalyst.analysis.TypeCoercion.haveSameType
import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.variant.VariantGet
import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan,
Project}
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
import org.apache.spark.sql.catalyst.util.TypeUtils.toSQLExpr
import org.apache.spark.sql.errors.QueryCompilationErrors
import org.apache.spark.sql.types.{
@@ -399,6 +401,12 @@ object CollationTypeCoercion extends SQLConfHelper {
Some(addContextToStringType(cast.dataType, castStrength))
+ // An explicitly collated target or RETURNING type (even UTF8_BINARY), not
the arguments,
+ // decides the collation, like a column of that type.
+ case e @ (_: VariantGet | _: JsonValue | _: JsonQuery | _: JsonArray | _:
JsonObjectExpr)
+ if DataTypeUtils.hasNonDefaultStringCharOrVarcharType(e.dataType) =>
+ Some(addContextToStringType(e.dataType, Implicit))
+
case expr @ (_: NamedExpression | _: SubqueryExpression | _:
VariableReference) =>
Some(addContextToStringType(expr.dataType, Implicit))
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala
index 95dd6bdcdd8a..2fc882fcd04f 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InjectRuntimeFilter.scala
@@ -302,6 +302,8 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
/**
* Extracts the beneficial filter creation plan with check show below:
+ * - Both keys are binary stable. The Bloom filter hashes the bytes of the
key, so it could drop
+ * a row whose key is equal under a non-binary collation but has different
bytes
* - The filterApplicationSideKey can be pushed down through joins,
aggregates and windows
* (ie the expression references originate from a single leaf node)
* - The filter creation side has a selective predicate, or its exact
materialized row count
@@ -313,11 +315,11 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
filterCreationSide: LogicalPlan,
filterApplicationSideKey: Expression,
filterCreationSideKey: Expression): Option[FilterCreationSide] = {
- if (findExpressionAndTrackLineageDown(
+ if (UnsafeRowUtils.isBinaryStable(filterCreationSideKey.dataType) &&
+ UnsafeRowUtils.isBinaryStable(filterApplicationSideKey.dataType) &&
+ findExpressionAndTrackLineageDown(
filterApplicationSideKey, filterApplicationSide).isDefined &&
satisfyByteSizeRequirement(filterApplicationSide)) {
- val allowMaterializedCache =
UnsafeRowUtils.isBinaryStable(filterCreationSideKey.dataType) &&
- UnsafeRowUtils.isBinaryStable(filterApplicationSideKey.dataType)
def distinctCount(key: Expression, plan: LogicalPlan): Option[BigInt] =
key match {
case attribute: Attribute =>
plan.stats.attributeStats.get(attribute).flatMap(_.distinctCount)
@@ -351,34 +353,26 @@ object InjectRuntimeFilter extends Rule[LogicalPlan] with
PredicateHelper with J
currentDistinctCount
}
}
- if (allowMaterializedCache) {
- var sawMaterializedLeaf = false
- val selectiveCreationSide = extractSelectiveFilterOverScan(
- filterCreationSide,
- filterCreationSideKey,
- allowMaterializedCache = false,
- applicationDistinctCount = None,
- onMaterializedLeaf = { sawMaterializedLeaf = true })
- selectiveCreationSide
- .filter(_.plan.stats.sizeInBytes <=
conf.runtimeFilterCreationSideThreshold)
- .orElse {
- if (sawMaterializedLeaf) {
- extractSelectiveFilterOverScan(
- filterCreationSide,
- filterCreationSideKey,
- allowMaterializedCache = true,
- applicationDistinctCount = applicationDistinctCount)
- } else {
- selectiveCreationSide
- }
+ var sawMaterializedLeaf = false
+ val selectiveCreationSide = extractSelectiveFilterOverScan(
+ filterCreationSide,
+ filterCreationSideKey,
+ allowMaterializedCache = false,
+ applicationDistinctCount = None,
+ onMaterializedLeaf = { sawMaterializedLeaf = true })
+ selectiveCreationSide
+ .filter(_.plan.stats.sizeInBytes <=
conf.runtimeFilterCreationSideThreshold)
+ .orElse {
+ if (sawMaterializedLeaf) {
+ extractSelectiveFilterOverScan(
+ filterCreationSide,
+ filterCreationSideKey,
+ allowMaterializedCache = true,
+ applicationDistinctCount = applicationDistinctCount)
+ } else {
+ selectiveCreationSide
}
- } else {
- extractSelectiveFilterOverScan(
- filterCreationSide,
- filterCreationSideKey,
- allowMaterializedCache = false,
- applicationDistinctCount = None)
- }
+ }
} else {
None
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala
index 53c5d5ba0863..6f10c5e6c33b 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/InjectRuntimeFilterSuite.scala
@@ -616,6 +616,93 @@ class InjectRuntimeFilterSuite extends SharedSparkSession
}
}
+ test("SPARK-60871: no runtime filters for nonbinary collated join keys") {
+ withSQLConf(
+ SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key
-> "0",
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.RUNTIME_BLOOM_FILTER_CREATION_SIDE_THRESHOLD.key -> "1MB") {
+ withTable("bf_variant_fact", "bf_variant_dim") {
+ sql("CREATE TABLE bf_variant_fact (id INT, v VARIANT) USING parquet")
+ sql("""INSERT INTO bf_variant_fact SELECT id, parse_json(j) FROM VALUES
+ | (1, '{"k": "Open"}'), (2, '{"k": "x"}') AS t(id,
j)""".stripMargin)
+ sql("CREATE TABLE bf_variant_dim (id INT, v VARIANT) USING parquet")
+ sql("""INSERT INTO bf_variant_dim SELECT id, parse_json(j) FROM VALUES
+ | (10, '{"k": "open"}'), (20, '{"k": "y"}') AS t(id,
j)""".stripMargin)
+
+ val dim = "(SELECT * FROM bf_variant_dim WHERE id = 10) d"
+ def queries(targetType: String): Seq[String] = {
+ val on = s"ON variant_get(f.v, '$$.k', '$targetType') = " +
+ s"variant_get(d.v, '$$.k', '$targetType')"
+ Seq(
+ s"SELECT f.id FROM bf_variant_fact f JOIN $dim $on",
+ s"SELECT f.id FROM bf_variant_fact f LEFT SEMI JOIN $dim $on",
+ s"SELECT f.id FROM bf_variant_fact f RIGHT OUTER JOIN $dim $on",
+ s"SELECT f.id FROM $dim LEFT OUTER JOIN bf_variant_fact f $on")
+ }
+
+ // Binary keys get a Bloom filter on the fact side.
+ queries("STRING").foreach(assertRewroteWithBloomFilter(_))
+ // A Bloom filter over UTF8_LCASE keys would drop the fact row 'Open',
which the join
+ // matches with 'open'.
+ queries("STRING COLLATE UTF8_LCASE").foreach { query =>
+ assertDidNotRewriteWithBloomFilter(query)
+ checkAnswer(sql(query), Row(1))
+ }
+ }
+ }
+ }
+
+ test("SPARK-60871: runtime filters for casts of collated join key columns") {
+ withSQLConf(
+ SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key
-> "0",
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
+ SQLConf.RUNTIME_BLOOM_FILTER_CREATION_SIDE_THRESHOLD.key -> "1MB") {
+ withTable("bf_cast_fact", "bf_cast_dim") {
+ Seq("bf_cast_fact", "bf_cast_dim").foreach { t =>
+ sql(s"CREATE TABLE $t (id INT, k STRING COLLATE UTF8_LCASE, p
STRING) USING parquet")
+ }
+ sql("INSERT INTO bf_cast_fact VALUES (1, 'Open', 'Open'), (2, 'x',
'x')")
+ sql("INSERT INTO bf_cast_dim VALUES (10, 'open', 'open'), (20, 'y',
'y')")
+
+ val dim = "(SELECT * FROM bf_cast_dim WHERE id = 10) d"
+ // Inner, left semi, right outer and left outer joins with the fact
table as the
+ // application side.
+ def queries(key: String => String): Seq[String] = {
+ val on = s"ON ${key("f")} = ${key("d")}"
+ Seq(
+ s"SELECT f.id FROM bf_cast_fact f JOIN $dim $on",
+ s"SELECT f.id FROM bf_cast_fact f LEFT SEMI JOIN $dim $on",
+ s"SELECT f.id FROM bf_cast_fact f RIGHT OUTER JOIN $dim $on",
+ s"SELECT f.id FROM $dim LEFT OUTER JOIN bf_cast_fact f $on")
+ }
+ val matched = Seq.fill(4)(Seq(Row(1)))
+ val unmatched = Seq(Seq.empty, Seq.empty, Seq(Row(null)),
Seq(Row(null)))
+
+ // Column keys get a Bloom filter on their collation keys.
+ queries(t => s"$t.k").zip(matched).foreach { case (query, answer) =>
+ assertRewroteWithBloomFilter(query)
+ checkAnswer(sql(query), answer)
+ }
+ // Casts of the UTF8_LCASE column to STRING are binary keys, so 'Open'
and 'open' differ.
+ Seq[String => String](t => s"CAST($t.k AS STRING)", t =>
s"$t.k::STRING").foreach { key =>
+ queries(key).zip(unmatched).foreach { case (query, answer) =>
+ assertRewroteWithBloomFilter(query)
+ checkAnswer(sql(query), answer)
+ }
+ }
+ // Casts to UTF8_LCASE are non-binary expression keys, so they get no
Bloom filter.
+ Seq[String => String](
+ t => s"CAST($t.p AS STRING COLLATE UTF8_LCASE)",
+ t => s"$t.p::STRING COLLATE UTF8_LCASE").foreach { key =>
+ queries(key).zip(matched).foreach { case (query, answer) =>
+ assertDidNotRewriteWithBloomFilter(query)
+ checkAnswer(sql(query), answer)
+ }
+ }
+ }
+ }
+ }
+
test("SPARK-58272: use materialized caches without predicates only with
pruning statistics") {
withSQLConf(
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key
-> "0",
@@ -1654,7 +1741,12 @@ class InjectRuntimeFilterSuite extends SharedSparkSession
val query = "select v from testcat.cf where k in (select k from
testcat.cd where flag = 1)"
withDppTestConf(SQLConf.AUTO_BROADCASTJOIN_THRESHOLD.key -> "-1",
SQLConf.RUNTIME_BLOOM_FILTER_APPLICATION_SIDE_SCAN_SIZE_THRESHOLD.key -> "0") {
- assertBloomFilterWithoutDpp(query)
+ // Nothing wraps the semi join's keys in CollationKey, so they get
no bloom filter
+ // without DPP either (SPARK-60871).
+ assertBloomFilterWithoutDpp(query, numBloomFilters = 0)
+ withSQLConf(SQLConf.DYNAMIC_PARTITION_PRUNING_ENABLED.key ->
"false") {
+ checkAnswer(sql(query), Row(1))
+ }
assert(bloomFilterKeys(query).isEmpty)
checkAnswer(sql(query), Row(1))
}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/collation/CollationTypePrecedenceSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/collation/CollationTypePrecedenceSuite.scala
index 605e838b8c5a..901f509e3f0b 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/collation/CollationTypePrecedenceSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/collation/CollationTypePrecedenceSuite.scala
@@ -490,6 +490,155 @@ 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 keep default strength, through the recolored path or the
rewritten cast type.
+ withView(viewName) {
+ sql(
+ s"""
+ |CREATE VIEW $viewName DEFAULT COLLATION UTF8_LCASE AS SELECT
+ | $fn(v, '$$.s', 'STRING') = 'OPEN' AS plain,
+ | $fn(v, '$$.s', 'STRING COLLATE UTF8_BINARY') = 'OPEN' AS
binary,
+ | v:s::STRING = 'OPEN' AS plain_cast,
+ | $fn(v, '$$.s', 'STRING') = c AS plain_col,
+ | v:s::STRING = c AS plain_cast_col
+ |FROM $tableName WHERE id = 1
+ |""".stripMargin)
+ checkAnswer(sql(s"SELECT * FROM $viewName"), Row(true, false, true,
true, true))
+ }
+ }
+ }
+ }
+
+ testFixedPointAndSinglePass("collated JSON RETURNING types have implicit
strength") {
+ val tableName = "json_returning_tbl"
+ val viewName = "json_returning_view"
+ def jsonFns(json: String, value: String, returning: String): Seq[String] =
Seq(
+ s"JSON_VALUE($json, '$$.s' RETURNING $returning)",
+ s"JSON_QUERY($json, '$$.o' RETURNING $returning)",
+ s"JSON_ARRAY($value RETURNING $returning)",
+ s"JSON_OBJECT('k' VALUE $value RETURNING $returning)")
+ val jsonLit = """'{"s": "Open", "o": {"k": "Open"}}'"""
+ val lcase = "STRING COLLATE UTF8_LCASE"
+ withTable(tableName) {
+ sql(s"CREATE TABLE $tableName (id INT, c STRING COLLATE UNICODE_CI, p
STRING, j STRING) " +
+ s"USING $dataSource")
+ sql(
+ s"""
+ |INSERT INTO $tableName SELECT id, 'OPEN', 'OPEN', j FROM VALUES
+ | (1, '{"s": "Open", "o": {"k": "Open"}}'),
+ | (2, '{"s": "open", "o": {"k": "open"}}'),
+ | (3, '{"s": "closed", "o": {"k": "closed"}}') AS t(id, j)
+ |""".stripMargin)
+
+ jsonFns("j", "get_json_object(j, '$.s')", lcase).foreach { fn =>
+ checkAnswer(
+ sql(s"SELECT DISTINCT COLLATION($fn || 'a') FROM $tableName"),
+ Row(UTF8_LCASE_COLLATION_NAME))
+ checkAnswer(
+ sql(s"SELECT id FROM $tableName WHERE contains($fn, 'OPEN')"),
Seq(Row(1), Row(2)))
+ Seq(s"$fn = c", s"$fn = p").foreach { cond =>
+ assertIndeterminateCollation(sql(s"SELECT id FROM $tableName WHERE
$cond"))
+ }
+ }
+ jsonFns(jsonLit, "'Open'", lcase).foreach { fn =>
+ checkAnswer(sql(s"SELECT contains($fn, 'OPEN')"), Row(true))
+ }
+ jsonFns("j", "get_json_object(j, '$.s')", "STRING COLLATE
UTF8_BINARY").foreach { fn =>
+ assertIndeterminateCollation(sql(s"SELECT id FROM $tableName WHERE $fn
= c"))
+ }
+
+ // A plain RETURNING type keeps default strength, so the column
collation wins.
+ jsonFns(jsonLit, "'Open'", "STRING").foreach { fn =>
+ checkAnswer(sql(s"SELECT DISTINCT contains($fn, c) FROM $tableName"),
Row(true))
+ }
+
+ // Under a default collation, an explicit UTF8_BINARY RETURNING type
keeps UTF8_BINARY.
+ withView(viewName) {
+ val columns = Seq("STRING", "STRING COLLATE UTF8_BINARY")
+ .flatMap(jsonFns(jsonLit, "'Open'", _))
+ .zipWithIndex
+ .map { case (fn, i) => s"contains($fn, 'OPEN') AS c$i" }
+ sql(s"CREATE VIEW $viewName DEFAULT COLLATION UTF8_LCASE AS SELECT " +
+ columns.mkString(", "))
+ checkAnswer(
+ sql(s"SELECT * FROM $viewName"),
+ Row(Seq.fill(4)(true) ++ Seq.fill(4)(false): _*))
+ }
+ }
+ }
+
test("str fns without params have default strength") {
val tableName = "str_fns_tbl"
val columnCollation = "UNICODE"
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]