This is an automated email from the ASF dual-hosted git repository.
dongjoon-hyun 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 5bdd9574013d [SPARK-61479][SQL] Fix wrong results by DSv2 UPDATE and
MERGE when CHAR values are stored without padding
5bdd9574013d is described below
commit 5bdd9574013dae9cb2f05a5666d6ab06165e050d
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Wed Nov 11 20:30:31 2026 -0800
[SPARK-61479][SQL] Fix wrong results by DSv2 UPDATE and MERGE when CHAR
values are stored without padding
### What changes were proposed in this pull request?
This PR fixes a correctness issue of DSv2 `UPDATE` and `MERGE` with
`UPDATE` / `INSERT` actions when the target table has CHAR columns whose values
are stored without padding. The commands now read the target CHAR columns with
read-side padding in their conditions and assigned values, as `SELECT` does.
`ResolveRowLevelCommandAssignments` strips the CHAR metadata from the
target relation when it aligns the assignments, so `ApplyCharTypePadding` adds
no read-side padding to the target. The references in the command keep the
metadata, so their comparisons still get padded literals. This PR adds
`padTargetReferences`, which pads those references in place:
- It first pads the string comparisons of the command, as
`ApplyCharTypePadding` does, and then replaces each reference to a target CHAR
column in the conditions and assigned values with its read-side padding,
including outer references in subqueries.
- It runs before the alignment, so the values that the alignment adds for
the columns that are not assigned stay as stored. Carried-over rows and row IDs
also keep their stored values.
- It follows the configs of `ApplyCharTypePadding`. Nothing changes with
`spark.sql.readSideCharPadding=false` or
`spark.sql.legacy.charVarcharAsString=true`, and
`spark.sql.charVarchar.standardSemantics.enabled` applies its read-side checks.
Scope: this PR covers the target table. A CHAR column of the `MERGE` source
that is stored without padding is read without padding by the runtime group
filter, which is handled by #60345.
### Why are the changes needed?
This is a correctness issue. With `spark.sql.readSideCharPadding` enabled
(the default), `SELECT` reads a CHAR value stored without padding, for example
written by another engine or with `spark.sql.legacy.charVarcharAsString=true`,
as a padded value. `UPDATE` and `MERGE` compared and assigned the stored value
instead, so they silently:
- skipped the matching rows, for example with `c IN ('a', 'b')`, `c IN
(SELECT ...)`, a correlated `EXISTS`, `MERGE ... ON t.c = s.c`, `WHEN MATCHED
AND t.c = 'x'`, and a condition on a CHAR partition column, which was pushed
down with the padded literal.
- changed rows that do not match, for example with `c != 'a'`, `c NOT IN
(...)`, `c LIKE '%a'` or a comparison with a STRING column.
- assigned the stored value, for example `SET v = c` stored `a` instead of
`a `, and `SET id = length(c)` stored `1` instead of `3`.
- inserted duplicates in an insert-only `MERGE ... ON t.c = s.c WHEN NOT
MATCHED THEN INSERT`.
For example, with a catalog `cat` that supports row-level operations:
```sql
CREATE TABLE cat.ns.t (pk INT NOT NULL, c CHAR(3), id INT, dep STRING)
PARTITIONED BY (dep);
SET spark.sql.legacy.charVarcharAsString=true;
INSERT INTO cat.ns.t VALUES (1, 'a', 1, 'hr'), (2, 'b', 2, 'software');
SET spark.sql.legacy.charVarcharAsString=false;
-- Issue 1: It should update both rows, but it updates none of them.
UPDATE cat.ns.t SET id = -1 WHERE c IN ('a', 'b');
-- Issue 2: It should update only the row with pk 2, but it updates both
rows.
UPDATE cat.ns.t SET id = -2 WHERE c != 'a';
```
### Does this PR introduce _any_ user-facing change?
Yes. `UPDATE` and `MERGE` with `UPDATE` / `INSERT` actions on a DSv2 table
with CHAR columns stored without padding now match, update and insert the same
rows that a `SELECT` with the same conditions finds, and assign the padded
values.
- A CHAR predicate of these commands is no longer pushed down by name,
which compared the padded literal with the stored value. It is evaluated by
Spark, as for `SELECT`, and the runtime group filter still prunes the groups.
- The error message of a non-deterministic `MERGE` condition on a CHAR
column of the target shows the padding, for example
`static_invoke(CharVarcharCodegenUtils.readSidePadding(c, 3))`.
### How was this patch tested?
Pass the CIs with the newly added test cases: 4 in `UpdateTableSuiteBase`
and 2 in `MergeIntoTableSuiteBase`, run by the group-based and delta-based
suites. All of them fail without this fix.
I also ran the DELETE, UPDATE and MERGE suites (group-based and
delta-based), the runtime filtering suites,
`DataSourceV2EnhancedDeleteFilterSuite`, `DataSourceV2SQLSuite*`, the
`*CharVarchar*` suites, `AlignUpdateAssignmentsSuite`,
`AlignMergeAssignmentsSuite` and `PlanResolutionSuite`, and scalastyle on
`catalyst` and `sql`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
Closes #60359 from dongjoon-hyun/SPARK-61479.
Authored-by: Dongjoon Hyun <[email protected]>
Signed-off-by: Dongjoon Hyun <[email protected]>
skip-checks: true
---
.../ResolveRowLevelCommandAssignments.scala | 59 +++++++++--
.../sql/connector/MergeIntoTableSuiteBase.scala | 86 ++++++++++++++++
.../spark/sql/connector/UpdateTableSuiteBase.scala | 109 +++++++++++++++++++++
3 files changed, 246 insertions(+), 8 deletions(-)
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveRowLevelCommandAssignments.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveRowLevelCommandAssignments.scala
index 2eca2e1c4747..9db071e67e15 100644
---
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveRowLevelCommandAssignments.scala
+++
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ResolveRowLevelCommandAssignments.scala
@@ -19,7 +19,7 @@ package org.apache.spark.sql.catalyst.analysis
import scala.collection.mutable
-import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap}
+import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap,
AttributeReference, Expression, OuterReference, SubqueryExpression}
import org.apache.spark.sql.catalyst.plans.logical.{Assignment, InsertAction,
LogicalPlan, MergeIntoTable, UpdateAction, UpdateTable}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.catalyst.trees.TreePattern.COMMAND
@@ -49,10 +49,11 @@ object ResolveRowLevelCommandAssignments extends
Rule[LogicalPlan] {
case u: UpdateTable if !u.skipSchemaResolution && u.resolved &&
u.rewritable && !u.aligned =>
validateStoreAssignmentPolicy()
val (newTable, metadataAttrMap) = cleanAttrMetadata(u.table)
- val newAssignments =
AssignmentUtils.alignUpdateAssignments(u.table.output, u.assignments,
- fromStar = false, coerceNestedTypes = false,
+ val padded = padTargetReferences(u, u.table)
+ val newAssignments =
AssignmentUtils.alignUpdateAssignments(u.table.output,
+ padded.assignments, fromStar = false, coerceNestedTypes = false,
ansiStoreAssignmentCastCheck = ansiStoreAssignmentCastCheck(u.table))
- u.copy(table = newTable, assignments =
newAssignments).rewriteAttrs(metadataAttrMap)
+ padded.copy(table = newTable, assignments =
newAssignments).rewriteAttrs(metadataAttrMap)
case u: UpdateTable if !u.skipSchemaResolution && u.resolved && !u.aligned
=>
resolveAssignments(u)
@@ -62,21 +63,22 @@ object ResolveRowLevelCommandAssignments extends
Rule[LogicalPlan] {
val coerceNestedTypes = conf.coerceMergeNestedTypes &&
m.withSchemaEvolution
val castCheck = ansiStoreAssignmentCastCheck(m.targetTable)
val (newTargetTable, metadataAttrMap) = cleanAttrMetadata(m.targetTable)
- m.copy(
+ val padded = padTargetReferences(m, m.targetTable)
+ padded.copy(
targetTable = newTargetTable,
matchedActions = RowLevelAssignmentResolution.alignActions(
m.targetTable.output,
- m.matchedActions,
+ padded.matchedActions,
coerceNestedTypes,
castCheck),
notMatchedActions = RowLevelAssignmentResolution.alignActions(
m.targetTable.output,
- m.notMatchedActions,
+ padded.notMatchedActions,
coerceNestedTypes,
castCheck),
notMatchedBySourceActions = RowLevelAssignmentResolution.alignActions(
m.targetTable.output,
- m.notMatchedBySourceActions,
+ padded.notMatchedBySourceActions,
coerceNestedTypes,
castCheck)).rewriteAttrs(metadataAttrMap)
@@ -153,6 +155,47 @@ object ResolveRowLevelCommandAssignments extends
Rule[LogicalPlan] {
(newTable, AttributeMap(metadataAttrMapping.toSeq))
}
+ // A cleaned relation gets no read-side padding from ApplyCharTypePadding,
which keeps carried
+ // over rows and row IDs as they are stored. The conditions and assigned
values of a command must
+ // still see what any other read of the table sees, so the references in
them are padded in
+ // place. This is done before alignment, which adds references to the
columns that are not
+ // assigned, and after padding the comparisons, as ApplyCharTypePadding
cannot match them once
+ // their references are padded.
+ private def padTargetReferences[T <: LogicalPlan](command: T, target:
LogicalPlan): T = {
+ // standardSemantics takes precedence over legacy charVarcharAsString.
+ val readSidePadding = conf.charVarcharStandardSemantics ||
+ (conf.readSideCharPadding && !conf.charVarcharAsString)
+ val paddedAttrs = if (readSidePadding) {
+ AttributeMap(target.output.map(attr => attr ->
CharVarcharUtils.addPaddingForScan(attr))
+ .filter { case (attr, padded) => padded != attr })
+ } else {
+ AttributeMap.empty[Expression]
+ }
+
+ def padOuterReferences(plan: LogicalPlan): LogicalPlan =
plan.transformWithSubqueries {
+ case p => p.transformExpressionsUp {
+ case OuterReference(attr: AttributeReference) if
paddedAttrs.contains(attr) =>
+ paddedAttrs(attr).transform {
+ case a: AttributeReference if a.semanticEquals(attr) =>
OuterReference(a)
+ }
+ }
+ }
+
+ def padReferences(expr: Expression): Expression = expr match {
+ case assignment: Assignment => assignment.copy(value =
padReferences(assignment.value))
+ case attr: AttributeReference => paddedAttrs.getOrElse(attr, attr)
+ case subquery: SubqueryExpression =>
subquery.withNewPlan(padOuterReferences(subquery.plan))
+ case other => other.mapChildren(padReferences)
+ }
+
+ if (paddedAttrs.isEmpty) {
+ command
+ } else {
+ ApplyCharTypePaddingHelper.paddingForStringComparison(command,
padCharCol = false)
+ .mapExpressions(padReferences).asInstanceOf[T]
+ }
+ }
+
private def resolveAssignments(p: LogicalPlan): LogicalPlan = {
p.transformExpressions {
case assignment: Assignment =>
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala
b/sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala
index bbbb22b8aa75..540b315fd439 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/connector/MergeIntoTableSuiteBase.scala
@@ -2298,6 +2298,92 @@ abstract class MergeIntoTableSuiteBase extends
RowLevelOperationSuiteBase
}
}
+ test("SPARK-61479: merge with CHAR columns stored without padding") {
+ createTable("pk INT NOT NULL, c CHAR(3), id INT, v STRING, dep STRING")
+ sql(s"CREATE TABLE $sourceNameAsString (pk INT NOT NULL, c CHAR(3))")
+ sql(s"INSERT INTO $sourceNameAsString VALUES (1, 'a'), (2, 'q'), (3, 'x')")
+ // read-side padding also covers values that are not padded in the
storage, so the rows to
+ // update must be found by comparing the padded values of the target
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ append("pk INT NOT NULL, c STRING, id INT, v STRING, dep STRING",
+ """{ "pk": 1, "c": "a", "id": 1, "dep": "hr" }
+ |{ "pk": 2, "c": "b", "id": 2, "dep": "software" }
+ |{ "pk": 3, "c": "x", "id": 3, "dep": "hr" }
+ |{ "pk": 4, "c": "y", "id": 4, "dep": "finance" }
+ |""".stripMargin)
+ }
+
+ sql(
+ s"""MERGE INTO $tableNameAsString t
+ |USING $sourceNameAsString s
+ |ON t.pk = s.pk AND t.c IN ('a', 'b', 'c')
+ |WHEN MATCHED THEN
+ | UPDATE SET id = -1
+ |""".stripMargin)
+
+ checkAnswer(
+ sql(s"SELECT pk, id FROM $tableNameAsString"),
+ Row(1, -1) :: Row(2, -1) :: Row(3, 3) :: Row(4, 4) :: Nil)
+
+ sql(
+ s"""MERGE INTO $tableNameAsString t
+ |USING $sourceNameAsString s
+ |ON t.c = s.c
+ |WHEN MATCHED THEN
+ | UPDATE SET id = -2
+ |""".stripMargin)
+
+ checkAnswer(
+ sql(s"SELECT pk, id FROM $tableNameAsString"),
+ Row(1, -2) :: Row(2, -1) :: Row(3, -2) :: Row(4, 4) :: Nil)
+
+ sql(
+ s"""MERGE INTO $tableNameAsString t
+ |USING $sourceNameAsString s
+ |ON t.pk = s.pk
+ |WHEN MATCHED AND t.c = 'x' THEN
+ | UPDATE SET v = t.c
+ |WHEN NOT MATCHED BY SOURCE AND t.c = 'y' THEN
+ | UPDATE SET v = t.c
+ |""".stripMargin)
+
+ checkAnswer(
+ sql(s"SELECT pk, v FROM $tableNameAsString"),
+ Row(1, null) :: Row(2, null) :: Row(3, "x ") :: Row(4, "y ") :: Nil)
+
+ // only the conditions and the assigned values read the padded values
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ checkAnswer(
+ sql(s"SELECT c FROM $tableNameAsString"),
+ Row("a") :: Row("b") :: Row("x") :: Row("y") :: Nil)
+ }
+ }
+
+ test("SPARK-61479: insert-only merge with CHAR columns stored without
padding") {
+ withTempView("source") {
+ createTable("pk INT NOT NULL, c CHAR(3), dep STRING")
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ append("pk INT NOT NULL, c STRING, dep STRING",
+ """{ "pk": 1, "c": "a", "dep": "hr" }
+ |""".stripMargin)
+ }
+
+ Seq((1, "a "), (2, "b ")).toDF("pk",
"c").createOrReplaceTempView("source")
+
+ sql(
+ s"""MERGE INTO $tableNameAsString t
+ |USING source s
+ |ON t.c = s.c
+ |WHEN NOT MATCHED THEN
+ | INSERT (pk, c, dep) VALUES (s.pk, s.c, 'new')
+ |""".stripMargin)
+
+ checkAnswer(
+ sql(s"SELECT * FROM $tableNameAsString"),
+ Row(1, "a ", "hr") :: Row(2, "b ", "new") :: Nil)
+ }
+ }
+
test("SPARK-60667: insert-only merge with type coercion handles metadata
columns correctly") {
withTempView("source") {
createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/connector/UpdateTableSuiteBase.scala
b/sql/core/src/test/scala/org/apache/spark/sql/connector/UpdateTableSuiteBase.scala
index 4bbaa83aa6cc..19900a0cc667 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/connector/UpdateTableSuiteBase.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/connector/UpdateTableSuiteBase.scala
@@ -1052,6 +1052,115 @@ abstract class UpdateTableSuiteBase extends
RowLevelOperationSuiteBase {
Row(1, -1, "hr", "a") :: Row(2, 2, "software", "b") :: Row(3, 3, "hr",
"c") :: Nil)
}
+ test("SPARK-61479: update with conditions on CHAR columns stored without
padding") {
+ withTempView("updated") {
+ createTable("pk INT NOT NULL, c CHAR(3), id INT, dep STRING")
+ // read-side padding also covers values that are not padded in the
storage, so the rows to
+ // update must be found by comparing the padded values
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ append("pk INT NOT NULL, c STRING, id INT, dep STRING",
+ """{ "pk": 1, "c": "a", "id": 1, "dep": "hr" }
+ |{ "pk": 2, "c": "b", "id": 2, "dep": "software" }
+ |{ "pk": 3, "c": "x", "id": 3, "dep": "hr" }
+ |{ "pk": 4, "c": "y", "id": 4, "dep": "finance" }
+ |""".stripMargin)
+ }
+
+ sql(s"UPDATE $tableNameAsString SET id = -1 WHERE c IN ('a', 'b', 'c')")
+
+ checkAnswer(
+ sql(s"SELECT * FROM $tableNameAsString"),
+ Row(1, "a ", -1, "hr") :: Row(2, "b ", -1, "software") ::
+ Row(3, "x ", 3, "hr") :: Row(4, "y ", 4, "finance") :: Nil)
+
+ Seq("x ").toDF("v").createOrReplaceTempView("updated")
+
+ sql(s"UPDATE $tableNameAsString SET id = -2 WHERE c IN (SELECT v FROM
updated)")
+
+ checkAnswer(
+ sql(s"SELECT * FROM $tableNameAsString"),
+ Row(1, "a ", -1, "hr") :: Row(2, "b ", -1, "software") ::
+ Row(3, "x ", -2, "hr") :: Row(4, "y ", 4, "finance") :: Nil)
+
+ Seq("y ").toDF("v").createOrReplaceTempView("updated")
+
+ sql(
+ s"""UPDATE $tableNameAsString t
+ |SET id = -3
+ |WHERE EXISTS (SELECT 1 FROM updated WHERE updated.v = t.c)
+ |""".stripMargin)
+
+ checkAnswer(
+ sql(s"SELECT * FROM $tableNameAsString"),
+ Row(1, "a ", -1, "hr") :: Row(2, "b ", -1, "software") ::
+ Row(3, "x ", -2, "hr") :: Row(4, "y ", -3, "finance") :: Nil)
+
+ // only the conditions read the padded values, the rows keep what is
stored
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ checkAnswer(
+ sql(s"SELECT c FROM $tableNameAsString"),
+ Row("a") :: Row("b") :: Row("x") :: Row("y") :: Nil)
+ }
+ }
+ }
+
+ test("SPARK-61479: update with a condition on a CHAR partition column stored
without padding") {
+ createTable("pk INT NOT NULL, id INT, dep CHAR(8)")
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ append("pk INT NOT NULL, id INT, dep STRING",
+ """{ "pk": 1, "id": 1, "dep": "hr" }
+ |{ "pk": 2, "id": 2, "dep": "software" }
+ |""".stripMargin)
+ }
+
+ sql(s"UPDATE $tableNameAsString SET id = -1 WHERE dep = 'hr'")
+
+ checkAnswer(
+ sql(s"SELECT * FROM $tableNameAsString"),
+ Row(1, -1, "hr ") :: Row(2, 2, "software") :: Nil)
+ }
+
+ test("SPARK-61479: update with values from CHAR columns stored without
padding") {
+ createTable("pk INT NOT NULL, c CHAR(3), id INT, v STRING, dep STRING")
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ append("pk INT NOT NULL, c STRING, id INT, v STRING, dep STRING",
+ """{ "pk": 1, "c": "a", "id": 1, "dep": "hr" }
+ |{ "pk": 2, "c": "b", "id": 2, "dep": "software" }
+ |""".stripMargin)
+ }
+
+ sql(s"UPDATE $tableNameAsString SET v = c, id = IF(c = 'a', 10, 20)")
+
+ checkAnswer(
+ sql(s"SELECT pk, id, v FROM $tableNameAsString"),
+ Row(1, 10, "a ") :: Row(2, 20, "b ") :: Nil)
+ }
+
+ test("SPARK-61479: update reads CHAR columns as the read-side configs
define") {
+ createTable("pk INT NOT NULL, c CHAR(3), id INT, dep STRING")
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ append("pk INT NOT NULL, c STRING, id INT, dep STRING",
+ """{ "pk": 1, "c": "a", "id": 1, "dep": "hr" }
+ |""".stripMargin)
+ }
+
+ Seq(
+ Seq(SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") -> 1,
+ Seq(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") -> 1,
+ Seq(
+ SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true",
+ SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") -> 3,
+ Seq(
+ SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true",
+ SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") -> 3
+ ).foreach { case (confs, expectedLength) =>
+ withSQLConf(confs: _*) {
+ sql(s"UPDATE $tableNameAsString SET id = length(c)")
+ }
+ checkAnswer(sql(s"SELECT id FROM $tableNameAsString"),
Row(expectedLength))
+ }
+ }
+
test("update with NOT NULL checks") {
createAndInitTable("pk INT NOT NULL, s STRUCT<n_i: INT NOT NULL, n_l:
LONG>, dep STRING",
"""{ "pk": 1, "s": { "n_i": 1, "n_l": 11 }, "dep": "hr" }
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]