This is an automated email from the ASF dual-hosted git repository.
dongjoon-hyun 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 1cac6c19594a [SPARK-61512][SQL] Fix silent under-delete in DSv2
REPLACE WHERE and static partition overwrite when CHAR values are stored
without padding
1cac6c19594a is described below
commit 1cac6c19594af98111fb4ad299eab8d9bfdb1e00
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Thu Nov 12 16:09:35 2026 -0800
[SPARK-61512][SQL] Fix silent under-delete in DSv2 REPLACE WHERE and static
partition overwrite when CHAR values are stored without padding
### What changes were proposed in this pull request?
This PR fixes a correctness issue in `INSERT INTO ... REPLACE WHERE`,
static partition overwrite (`INSERT OVERWRITE ... PARTITION`) and
`DataFrameWriterV2.overwrite(condition)` on a DSv2 table whose CHAR values are
stored without padding. All of them build an `OverwriteByExpression`; since
SPARK-61504 (#60373), the condition of `DataFrameWriterV2.overwrite` also keeps
the CHAR types of the table.
`ApplyCharTypePadding` now pads the target CHAR columns in the `deleteExpr`
of `OverwriteByExpression`, as it already does for the condition of a
`DeleteFromTable` that is not rewritten as a row-level operation (SPARK-61461,
#60344):
- Each target attribute with a raw CHAR type in `deleteExpr` is replaced
with `readSidePadding(<stored attribute>)`. The predicate passed to
`canOverwrite` becomes `CHAR_READ_SIDE_PADDING(dep, 8, ' ') = 'hr '`
instead of `dep = 'hr '`.
- `DeleteFromTable` and `OverwriteByExpression` share the same transform,
`padRawTypedColumns`.
- A new internal legacy config,
`spark.sql.legacy.noCharPaddingInOverwriteCondition` (default `false`), leaves
`OverwriteByExpression` unchanged, so the condition compares the stored values
with the padded literals as before. The change is described in
`docs/sql-migration-guide.md`.
- With `spark.sql.charVarchar.standardSemantics.enabled=true`,
`OverwriteByExpression` is not changed either. There, the columns would get the
read-side check `charTypeReadSideCheck` / `varcharTypeReadSideCheck`, which
cannot be translated to a source filter, so even a static partition overwrite
on a `VARCHAR` column would fail on every connector.
The test-only `InMemoryTableWithV2Filter` gets an opt-in table property,
`accept-char-read-side-padding`. With it, an overwrite accepts and evaluates
`CHAR_READ_SIDE_PADDING(col, n, ' ') = | <=> literal`, as a connector that pads
the stored values would do.
Tradeoffs:
- An overwrite by expression has no row-level fallback. A connector that
does not accept `CHAR_READ_SIDE_PADDING` now rejects `REPLACE WHERE` and static
partition overwrite with a CHAR condition. It fails with
`_LEGACY_ERROR_TEMP_2245` (`Table does not support overwrite by expression`),
also for data stored with padding, which was replaced correctly before. This is
the same as `DELETE` (SPARK-61461) and as the existing behavior with
`spark.sql.readSideCharPadding=false`, where the con [...]
- `V2ExpressionBuilder` translates the padding only in `=`, `<=>`, `<>` and
`IN` against a literal of the CHAR length, and in `IS [NOT] NULL`. A condition
that uses a CHAR column in another way, such as `dep >= 'h'`, `dep LIKE 'h%'`
or `rtrim(dep) = 'hr'`, now fails with `_LEGACY_ERROR_TEMP_1109` (`cannot
translate expression to source filter`) on every connector.
- `IS [NOT] NULL` on a CHAR column still translates to `IS_NULL(col)` /
`IS_NOT_NULL(col)` and works as before.
- `SupportsOverwrite` (V1 filters) converts the predicates with
`PredicateUtils.toV1`. Since SPARK-61462 (#60345), `toV1` does not drop the
non-convertible side of an `OR`. So `REPLACE WHERE dep = 'hr' OR id = 2` is
rejected instead of replacing only the rows with `id = 2`.
### Why are the changes needed?
With `spark.sql.readSideCharPadding` enabled (the default), a DSv2 table
that stores CHAR values without padding is read with padding applied on top of
the scan. The table of `OverwriteByExpression` is not a child of the command,
so it gets no read-side padding, and only the literal in `deleteExpr` is
padded: `dep = 'hr'` becomes `dep = 'hr '`. The source compares it with
the stored `hr`, so the old rows are not deleted while the new rows are
appended, without any error.
This is a correctness issue.
Static partition overwrite builds the same `OverwriteByExpression` with
`dep <=> 'hr '`, so it has the same problem.
```sql
-- t is a DSv2 table whose source implements SupportsOverwriteV2 and stores
CHAR values as written
CREATE TABLE t (id BIGINT, dep CHAR(8)) USING ... PARTITIONED BY (dep);
SET spark.sql.legacy.charVarcharAsString=true;
INSERT INTO t VALUES (1, 'hr');
SET spark.sql.legacy.charVarcharAsString=false;
INSERT INTO t REPLACE WHERE dep = 'hr' VALUES (2, 'hr');
SELECT * FROM t;
-- Issue 1: It should return only [2, hr ], but it also returns [1, hr
].
```
### Does this PR introduce _any_ user-facing change?
Yes.
- On a connector that accepts `CHAR_READ_SIDE_PADDING`, `REPLACE WHERE`,
static partition overwrite and `DataFrameWriterV2.overwrite` with a condition
on a CHAR column now replace the rows stored without padding instead of
silently keeping them.
- On a connector that does not accept `CHAR_READ_SIDE_PADDING`, they now
fail with `_LEGACY_ERROR_TEMP_2245` instead of silently keeping such rows. This
also applies to data stored with padding, as described above.
- A condition that uses a CHAR column other than in `=`, `<=>`, `<>`, `IN`
or `IS [NOT] NULL` now fails with `_LEGACY_ERROR_TEMP_1109` on every connector.
- Setting `spark.sql.legacy.noCharPaddingInOverwriteCondition` to `true`
restores the previous behavior.
- None of this applies when
`spark.sql.charVarchar.standardSemantics.enabled` is `true`.
### How was this patch tested?
Added test cases to `DataSourceV2SQLSuite`:
- In the base suite, which runs on both the V1 filter and the V2 filter
catalogs:
- `REPLACE WHERE` on a CHAR partition column stored without padding fails
and leaves the table unchanged. This fails on master, where the old row is
silently kept.
- `REPLACE WHERE` on a CHAR partition column stored with padding fails
with `_LEGACY_ERROR_TEMP_2245`, and replaces the row as before with
`spark.sql.legacy.noCharPaddingInOverwriteCondition` set to `true`.
- With `spark.sql.charVarchar.standardSemantics.enabled=true`, a static
partition overwrite on a CHAR partition column replaces the row as before.
- In `DataSourceV2SQLSuiteV1Filter`: `REPLACE WHERE dep = 'hr' OR id = 2`
fails and leaves the table unchanged. This guards the `toV1` change of
SPARK-61462 for `SupportsOverwrite`.
- In `DataSourceV2SQLSuiteV2Filter`, with `accept-char-read-side-padding`:
`REPLACE WHERE` and static partition overwrite replace the rows stored with and
without padding. This fails on master, where the rows stored without padding
are kept.
Updated the SPARK-61504 test in `DataFrameWriterV2Suite` to use a table
with `accept-char-read-side-padding` and to add a row stored without padding.
`DataFrameWriterV2.overwrite($"dep" === "hr")` replaces the rows stored with
and without padding. On master, the row stored without padding is kept, and the
in-memory table that the test used before does not accept
`CHAR_READ_SIDE_PADDING`.
Also ran `DataSourceV2SQLSuiteV1Filter`, `DataSourceV2SQLSuiteV2Filter`,
`DataSourceV2DataFrameSuite`, `DataFrameWriterV2Suite`, `V1WriteFallbackSuite`,
the `*CharVarcharTestSuite` suites, and the DELETE, UPDATE and MERGE suites,
and scalastyle on `sql/core` and `catalyst`.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
Closes #60380 from dongjoon-hyun/SPARK-61512.
Authored-by: Dongjoon Hyun <[email protected]>
Signed-off-by: Dongjoon Hyun <[email protected]>
(cherry picked from commit 248f9caef5e5fff6d37a733cdfbc0a25865e2fd4)
Signed-off-by: Dongjoon Hyun <[email protected]>
skip-checks: true
---
docs/sql-migration-guide.md | 1 +
.../org/apache/spark/sql/internal/SQLConf.scala | 13 ++++
.../catalog/InMemoryTableWithV2Filter.scala | 49 ++++++++++--
.../datasources/ApplyCharTypePadding.scala | 39 ++++++----
.../apache/spark/sql/DataFrameWriterV2Suite.scala | 21 ++++--
.../spark/sql/connector/DataSourceV2SQLSuite.scala | 88 ++++++++++++++++++++++
6 files changed, 180 insertions(+), 31 deletions(-)
diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index 9748d3e1ed24..3729290d7ec5 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -58,6 +58,7 @@ license: |
- Since Spark 4.4, the Oracle JDBC datasource maps bare `NUMBER` columns
(declared without explicit precision or scale) to `DecimalType(38, 18)` instead
of `DecimalType(38, 10)`. This uses `DecimalType.DEFAULT_SCALE` and preserves
up to 18 fractional digits instead of 10, reducing silent precision loss.
However, the integer range shrinks from 28 to 20 digits; bare `NUMBER` values
with more than 20 integer digits that previously read correctly will raise
`NUMERIC_VALUE_OUT_OF_RANGE`. The [...]
- Since Spark 4.4, when `spark.sql.charVarchar.standardSemantics.enabled` is
false and `spark.sql.readSideCharPadding` is true (the default), JDBC Data
Source V2 catalog tables on H2, PostgreSQL, SQL Server, and Oracle push CHAR
equality, inequality, null-safe equality, and `IN`/`NOT IN`. In 4.3 the default
read-side padding wrap kept those filters in Spark. Pushed predicates use the
remote collation, so a case-insensitive SQL Server collation can match a stored
`'ABC'` with `flag = 'abc [...]
- Since Spark 4.4, when `spark.sql.charVarchar.standardSemantics.enabled` is
false and `spark.sql.readSideCharPadding` is true (the default), `IS [NOT]
NULL` over a CHAR scan column is unwrapped to the raw column for every Data
Source V2 source, including every JDBC dialect. Previously the padding wrap
kept that null check in Spark.
+- Since Spark 4.4, when `spark.sql.charVarchar.standardSemantics.enabled` is
false and `spark.sql.readSideCharPadding` is true (the default), an overwrite
of a Data Source V2 table by a condition on a CHAR column, such as `INSERT INTO
t REPLACE WHERE dep = 'hr'`, `INSERT OVERWRITE t PARTITION (dep = 'hr')` or
`DataFrameWriterV2.overwrite`, compares the column values padded as a read
returns them. For a `CHAR(8)` column `dep`, the data source receives
`CHAR_READ_SIDE_PADDING(dep, 8, ' ') [...]
- Since Spark 4.4, a CHAR/VARCHAR column of the outer query that a LATERAL or
correlated subquery returns keeps its CHAR/VARCHAR type, as an inner column
does. Previously it became `STRING`: comparisons against it were not padded and
could silently return no rows, and CTAS and views over it stored `STRING`.
Inside a LATERAL subquery this affected `t.c AS k`, `t.c` and `t.*` in all
earlier versions; in other correlated subqueries it affected `t.c AS k` in all
earlier versions, `t.*` since [...]
- Since Spark 4.4, the optimizer rule `SimplifyCaseConversionExpressions` no
longer simplifies mixed case conversions `LOWER(UPPER(str))` to `LOWER(str)` or
`UPPER(LOWER(str))` to `UPPER(str)`. This preserves standard Unicode case
mapping semantics for non-ASCII characters such as Latin small letter dotless i
(`ı` U+0131) and micro sign (`µ` U+00B5).
- Since Spark 4.4, the Oracle JDBC datasource maps Oracle DATE and TIMESTAMP
to TimestampNTZType by default, ignoring the JDBC read option
`preferTimestampNTZ` (DATE only when the driver default
`oracle.jdbc.mapDateToTimestamp=true` surfaces it as TIMESTAMP; otherwise DATE
stays DateType). In 4.3 and earlier these were read as TimestampType, or as
TimestampNTZType only when `preferTimestampNTZ=true`. This faithfully
represents these zoneless Oracle types. Unaffected: Oracle DATE read wit [...]
diff --git
a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index 3459c5290b66..20a22ed4b322 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -8208,6 +8208,19 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val LEGACY_NO_CHAR_PADDING_IN_OVERWRITE_CONDITION =
+ buildConf("spark.sql.legacy.noCharPaddingInOverwriteCondition")
+ .internal()
+ .doc("When true, an overwrite by a condition of a Data Source V2 table,
such as " +
+ "`INSERT INTO ... REPLACE WHERE`, compares the stored values of the
CHAR columns in the " +
+ "condition with the padded literals, as Spark 4.3 does. It then works
with data sources " +
+ "that do not support CHAR_READ_SIDE_PADDING, but keeps the rows whose
CHAR values are " +
+ "stored without padding.")
+ .version("4.4.0")
+ .withBindingPolicy(ConfigBindingPolicy.SESSION)
+ .booleanConf
+ .createWithDefault(false)
+
val CLI_PRINT_HEADER =
buildConf("spark.sql.cli.print.header")
.doc("When set to true, spark-sql CLI prints the names of the columns in
query output.")
diff --git
a/sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryTableWithV2Filter.scala
b/sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryTableWithV2Filter.scala
index 49346769c031..e353fe132c3e 100644
---
a/sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryTableWithV2Filter.scala
+++
b/sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryTableWithV2Filter.scala
@@ -21,14 +21,16 @@ import java.util
import org.scalatest.Assertions.assert
+import org.apache.spark.sql.catalyst.util.{CharVarcharCodegenUtils,
CharVarcharUtils}
import org.apache.spark.sql.connector.catalog.constraints.Constraint
import org.apache.spark.sql.connector.distributions.{Distribution,
Distributions}
-import org.apache.spark.sql.connector.expressions.{FieldReference,
LiteralValue, NamedReference, SortOrder, Transform}
+import org.apache.spark.sql.connector.expressions.{Expression => V2Expression,
FieldReference, GeneralScalarExpression, LiteralValue, NamedReference,
SortOrder, Transform}
import org.apache.spark.sql.connector.expressions.filter.{AlwaysFalse, And,
Predicate}
import org.apache.spark.sql.connector.read.{InputPartition, Scan, ScanBuilder,
SupportsRuntimeV2Filtering}
import org.apache.spark.sql.connector.write.{LogicalWriteInfo,
SupportsOverwriteV2, WriteBuilder, WriterCommitMessage}
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.util.CaseInsensitiveStringMap
+import org.apache.spark.unsafe.types.UTF8String
import org.apache.spark.util.ArrayImplicits._
class InMemoryTableWithV2Filter(
@@ -147,7 +149,9 @@ class InMemoryTableWithV2Filter(
}
override def canOverwrite(predicates: Array[Predicate]): Boolean = {
- InMemoryTableWithV2Filter.supportsPredicates(predicates)
+ val acceptCharReadSidePadding = properties.getOrDefault(
+ InMemoryTableWithV2Filter.AcceptCharReadSidePaddingKey,
"false").toBoolean
+ InMemoryTableWithV2Filter.supportsPredicates(predicates,
acceptCharReadSidePadding)
}
}
@@ -184,12 +188,19 @@ object InMemoryTableWithV2Filter {
pred: Predicate,
resolveValue: String => Any): Boolean = {
lazy val attr = pred.children()(0).toString
+ lazy val value = pred.children()(0) match {
+ case CharReadSidePadding(ref, length) =>
+ Option(resolveValue(ref.toString)).map { v =>
+ CharVarcharCodegenUtils.readSidePadding(v.asInstanceOf[UTF8String],
length)
+ }.orNull
+ case _ => resolveValue(attr)
+ }
pred.name() match {
case "=" =>
- resolveValue(attr) ==
+ value ==
pred.children()(1).asInstanceOf[LiteralValue[_]].value
case "<=>" =>
- val attrVal = resolveValue(attr)
+ val attrVal = value
val litVal =
pred.children()(1).asInstanceOf[LiteralValue[_]].value
(attrVal == null && litVal == null) ||
@@ -203,15 +214,39 @@ object InMemoryTableWithV2Filter {
}
}
+ /**
+ * Table property that lets an overwrite compare `CHAR_READ_SIDE_PADDING` of
a column with a
+ * literal, as a connector that pads the CHAR values stored without padding
would do.
+ */
+ val AcceptCharReadSidePaddingKey = "accept-char-read-side-padding"
+
+ private object CharReadSidePadding {
+ def unapply(expr: V2Expression): Option[(NamedReference, Int)] = expr
match {
+ case e: GeneralScalarExpression if e.name() ==
CharVarcharUtils.V2_CHAR_READ_SIDE_PADDING =>
+ e.children().toSeq match {
+ case Seq(ref: NamedReference, LiteralValue(length: Int, _), _) =>
Some((ref, length))
+ case _ => None
+ }
+ case _ => None
+ }
+ }
+
/**
* Whether every predicate has a shape [[evalPredicate]] can evaluate: a
plain column, or a
- * column and a literal. A predicate over an expression, e.g. a cast, is not
supported and
- * returned to Spark, as a real connector without expression support would
do.
+ * column and a literal. `CHAR_READ_SIDE_PADDING` of a column compared with
a literal is
+ * supported only if `acceptCharReadSidePadding` is true, which
`canOverwrite` takes from the
+ * [[AcceptCharReadSidePaddingKey]] table property. Any other predicate over
an expression,
+ * e.g. a cast, is not supported and returned to Spark, as a real connector
without expression
+ * support would do.
*/
- def supportsPredicates(predicates: Array[Predicate]): Boolean = {
+ def supportsPredicates(
+ predicates: Array[Predicate],
+ acceptCharReadSidePadding: Boolean = false): Boolean = {
predicates.flatMap(splitAnd).forall { p =>
(p.name(), p.children().toSeq) match {
case ("=" | "<=>", Seq(_: NamedReference, _: LiteralValue[_])) => true
+ case ("=" | "<=>", Seq(CharReadSidePadding(_, _), _: LiteralValue[_]))
=>
+ acceptCharReadSidePadding
case ("IS_NULL" | "IS_NOT_NULL", Seq(_: NamedReference)) => true
case ("ALWAYS_TRUE", _) => true
case _ => false
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala
index 453c6a9d1ffc..d896bc400d84 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala
@@ -23,9 +23,9 @@ import org.apache.spark.internal.LogKeys
import org.apache.spark.sql.catalyst.analysis.ApplyCharTypePaddingHelper
import org.apache.spark.sql.catalyst.catalog.HiveTableRelation
import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeMap,
AttributeReference, Expression, NamedExpression, OuterReference, SubExprUtils,
SubqueryExpression}
-import org.apache.spark.sql.catalyst.plans.logical.{DeleteFromTable,
LogicalPlan, Project, ReplaceData, WriteDelta}
+import org.apache.spark.sql.catalyst.plans.logical.{DeleteFromTable,
LogicalPlan, OverwriteByExpression, Project, ReplaceData, WriteDelta}
import org.apache.spark.sql.catalyst.rules.Rule
-import org.apache.spark.sql.catalyst.trees.TreePattern.{DELETE_FROM_TABLE,
REPLACE_DATA, WRITE_DELTA}
+import org.apache.spark.sql.catalyst.trees.TreePattern.{COMMAND, REPLACE_DATA,
WRITE_DELTA}
import org.apache.spark.sql.catalyst.util.CharVarcharUtils
import org.apache.spark.sql.connector.write.RowLevelOperationTable
import org.apache.spark.sql.errors.QueryCompilationErrors
@@ -102,25 +102,32 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
}
/**
- * A DELETE that is not rewritten as a row-level operation deletes with
filters translated from
- * its condition, which the data source compares with the stored values. To
match what a read of
- * the table returns, the condition evaluates the read-side padding of the
columns itself, after
- * its comparisons are padded. The data source can only delete with such a
filter if it supports
- * the padding, e.g. `CHAR_READ_SIDE_PADDING`.
+ * A DELETE that is not rewritten as a row-level operation, and an overwrite
by expression such
+ * as `INSERT INTO ... REPLACE WHERE`, delete with filters translated from
their condition, which
+ * the data source compares with the stored values. To match what a read of
the table returns,
+ * the condition evaluates the read-side padding of the columns itself,
after its comparisons are
+ * padded. The data source can only delete with such a filter if it supports
the padding, e.g.
+ * `CHAR_READ_SIDE_PADDING`.
*/
private def padDeleteConditions(plan: LogicalPlan): LogicalPlan = {
- plan.resolveOperatorsWithPruning(_.containsPattern(DELETE_FROM_TABLE)) {
- case d: DeleteFromTable =>
- d.copy(condition = d.condition.transform {
- // the padded value refers to the attribute without the raw type and
is not padded again
- case attr: AttributeReference if
CharVarcharUtils.getRawType(attr.metadata).isDefined =>
- CharVarcharUtils.addPaddingForScan(attr).transform {
- case a: AttributeReference =>
CharVarcharUtils.cleanAttrMetadata(a)
- }
- })
+ plan.resolveOperatorsWithPruning(_.containsPattern(COMMAND)) {
+ case d: DeleteFromTable => d.copy(condition =
padRawTypedColumns(d.condition))
+ // Under standard semantics, the read-side check of the columns cannot
be translated to a
+ // filter, so the overwrite keeps comparing the stored values.
+ case o: OverwriteByExpression if !conf.charVarcharStandardSemantics &&
+ !conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_OVERWRITE_CONDITION)
=>
+ o.copy(deleteExpr = padRawTypedColumns(o.deleteExpr))
}
}
+ private def padRawTypedColumns(condition: Expression): Expression =
condition.transform {
+ // the padded value refers to the attribute without the raw type and is
not padded again
+ case attr: AttributeReference if
CharVarcharUtils.getRawType(attr.metadata).isDefined =>
+ CharVarcharUtils.addPaddingForScan(attr).transform {
+ case a: AttributeReference => CharVarcharUtils.cleanAttrMetadata(a)
+ }
+ }
+
/**
* The conditions of a row-level write are not evaluated on top of the
padded read in its query:
* they are pushed down to the scan and to metadata-only deletes, and they
select the groups to
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameWriterV2Suite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameWriterV2Suite.scala
index 55c017dfbb27..9febf91e5a27 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/DataFrameWriterV2Suite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/DataFrameWriterV2Suite.scala
@@ -27,7 +27,7 @@ import org.apache.spark.sql.catalyst.TableIdentifier
import
org.apache.spark.sql.catalyst.analysis.{CannotReplaceMissingTableException,
TableAlreadyExistsException}
import org.apache.spark.sql.catalyst.plans.logical.{AppendData, LogicalPlan,
OverwriteByExpression, OverwritePartitionsDynamic}
import org.apache.spark.sql.connector.InMemoryV1Provider
-import org.apache.spark.sql.connector.catalog.{Column => ColumnV2, Identifier,
InMemoryTable, InMemoryTableCatalog, TableCatalog}
+import org.apache.spark.sql.connector.catalog.{Column => ColumnV2, Identifier,
InMemoryTable, InMemoryTableCatalog, InMemoryTableWithV2Filter,
InMemoryTableWithV2FilterCatalog, TableCatalog}
import
org.apache.spark.sql.connector.catalog.CatalogManager.SESSION_CATALOG_NAME
import org.apache.spark.sql.connector.expressions.{BucketTransform,
ClusterByTransform, DaysTransform, FieldReference, HoursTransform,
IdentityTransform, LiteralValue, MonthsTransform, YearsTransform}
import org.apache.spark.sql.execution.QueryExecution
@@ -280,16 +280,21 @@ class DataFrameWriterV2Suite extends SharedSparkSession
with BeforeAndAfter {
}
test("SPARK-61504: Overwrite: overwrite by expression on a CHAR column") {
- spark.sql(
- "CREATE TABLE testcat.table_name (id bigint, dep char(8)) USING foo
PARTITIONED BY (dep)")
- spark.sql("INSERT INTO testcat.table_name VALUES (1L, 'hr'), (2L,
'software')")
+ spark.conf.set(
+ "spark.sql.catalog.testv2filter",
classOf[InMemoryTableWithV2FilterCatalog].getName)
+ val t = "testv2filter.table_name"
+ // the table pads the stored values for the overwrite condition, as a read
does
+ spark.sql(s"CREATE TABLE $t (id bigint, dep char(8)) USING foo PARTITIONED
BY (dep) " +
+ s"TBLPROPERTIES
('${InMemoryTableWithV2Filter.AcceptCharReadSidePaddingKey}' = 'true')")
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ spark.sql(s"INSERT INTO $t VALUES (1L, 'hr')")
+ }
+ spark.sql(s"INSERT INTO $t VALUES (2L, 'hr'), (3L, 'software')")
// the query is not resolved when the command is created, unlike the query
of a SQL INSERT
- Seq((3L, "hr")).toDF("id",
"dep").writeTo("testcat.table_name").overwrite($"dep" === "hr")
+ Seq((4L, "hr")).toDF("id", "dep").writeTo(t).overwrite($"dep" === "hr")
- checkAnswer(
- spark.table("testcat.table_name"),
- Seq(Row(2L, "software"), Row(3L, "hr ")))
+ checkAnswer(spark.table(t), Seq(Row(3L, "software"), Row(4L, "hr ")))
}
test("Overwrite: write to a temp view of v2 relation") {
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2SQLSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2SQLSuite.scala
index 62411d717cd6..51abcd0ea2bc 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2SQLSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/connector/DataSourceV2SQLSuite.scala
@@ -232,6 +232,60 @@ abstract class DataSourceV2SQLSuite
}
}
+ test("SPARK-61512: REPLACE WHERE with a condition on a CHAR column") {
+ val t = s"${catalogAndNamespace}tbl"
+ withTable(t) {
+ sql(s"CREATE TABLE $t (id bigint, dep char(8)) USING foo PARTITIONED BY
(dep)")
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ sql(s"INSERT INTO $t VALUES (1L, 'hr')")
+ }
+ // a read pads the values stored without padding, so the source must not
delete them by
+ // comparing the stored values with the padded literal, which would not
match
+ checkError(
+ exception = intercept[SparkException] {
+ sql(s"INSERT INTO $t REPLACE WHERE dep = 'hr' VALUES (2L, 'hr')")
+ },
+ condition = "_LEGACY_ERROR_TEMP_2245",
+ parameters = Map("table" -> ".*"),
+ matchPVals = true)
+ checkAnswer(spark.table(t), Row(1L, "hr "))
+ }
+ }
+
+ test("SPARK-61512: REPLACE WHERE with a CHAR condition under the legacy
config") {
+ val t = s"${catalogAndNamespace}tbl"
+ withTable(t) {
+ sql(s"CREATE TABLE $t (id bigint, dep char(8)) USING foo PARTITIONED BY
(dep)")
+ sql(s"INSERT INTO $t VALUES (1L, 'hr')")
+ // the source does not support the padding, even if the values are
stored with padding
+ checkError(
+ exception = intercept[SparkException] {
+ sql(s"INSERT INTO $t REPLACE WHERE dep = 'hr' VALUES (2L, 'hr')")
+ },
+ condition = "_LEGACY_ERROR_TEMP_2245",
+ parameters = Map("table" -> ".*"),
+ matchPVals = true)
+ // the source compares the stored values with the padded literal, as
before
+ withSQLConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_OVERWRITE_CONDITION.key ->
"true") {
+ sql(s"INSERT INTO $t REPLACE WHERE dep = 'hr' VALUES (2L, 'hr')")
+ }
+ checkAnswer(spark.table(t), Row(2L, "hr "))
+ }
+ }
+
+ test("SPARK-61512: static partition overwrite on a CHAR column under
standard semantics") {
+ val t = s"${catalogAndNamespace}tbl"
+ withSQLConf(SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key -> "true") {
+ withTable(t) {
+ sql(s"CREATE TABLE $t (id bigint, dep char(8)) USING foo PARTITIONED
BY (dep)")
+ sql(s"INSERT INTO $t VALUES (1L, 'hr')")
+ // the read-side check of the column has no source filter, so it is
not applied
+ sql(s"INSERT OVERWRITE $t PARTITION (dep = 'hr') VALUES (2L)")
+ checkAnswer(spark.table(t), Row(2L, "hr "))
+ }
+ }
+ }
+
private def checkExplain(query: String, relationPattern: Regex): Unit = {
val explain = spark.sql(s"EXPLAIN EXTENDED $query").head().getString(0)
val relations = explain.split("\n").filter(_.contains("RelationV2"))
@@ -4646,6 +4700,23 @@ class DataSourceV2SQLSuiteV1Filter
}
}
+ test("SPARK-61512: REPLACE WHERE with a CHAR condition in an OR with a
partition condition") {
+ val t = "testcat.tbl"
+ withTable(t) {
+ sql(s"CREATE TABLE $t (id bigint, dep char(8)) USING foo PARTITIONED BY
(id, dep)")
+ sql(s"INSERT INTO $t VALUES (1L, 'hr'), (2L, 'it')")
+ // the padded comparison has no V1 filter, so it must not be dropped
from the OR
+ checkError(
+ exception = intercept[SparkException] {
+ sql(s"INSERT INTO $t REPLACE WHERE dep = 'hr' OR id = 2 VALUES (3L,
'hr')")
+ },
+ condition = "_LEGACY_ERROR_TEMP_2245",
+ parameters = Map("table" -> ".*"),
+ matchPVals = true)
+ checkAnswer(spark.table(t), Seq(Row(1L, "hr "), Row(2L, "it
")))
+ }
+ }
+
test("Session variable in INSERT REPLACE WHERE") {
val t = "testcat.tbl"
withTable(t) {
@@ -5568,6 +5639,23 @@ class DataSourceV2SQLSuiteV1Filter
class DataSourceV2SQLSuiteV2Filter extends DataSourceV2SQLSuite {
override protected val catalogAndNamespace = "testv2filter.ns1.ns2."
+ test("SPARK-61512: overwrite by a condition on a CHAR column stored without
padding") {
+ val t = s"${catalogAndNamespace}tbl"
+ withTable(t) {
+ sql(s"CREATE TABLE $t (id bigint, dep char(8)) USING foo PARTITIONED BY
(dep) " +
+ s"TBLPROPERTIES
('${InMemoryTableWithV2Filter.AcceptCharReadSidePaddingKey}' = 'true')")
+ withSQLConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING.key -> "true") {
+ sql(s"INSERT INTO $t VALUES (1L, 'hr'), (2L, 'it')")
+ }
+ sql(s"INSERT INTO $t VALUES (3L, 'hr'), (4L, 'it')")
+
+ // the source pads the stored values, so it deletes them whether stored
with padding or not
+ sql(s"INSERT INTO $t REPLACE WHERE dep = 'hr' VALUES (5L, 'hr')")
+ sql(s"INSERT OVERWRITE $t PARTITION (dep = 'it') VALUES (6L)")
+ checkAnswer(spark.table(t), Seq(Row(5L, "hr "), Row(6L, "it
")))
+ }
+ }
+
test("SPARK-56467: scalar subquery filters on partition columns are pushed
into runtimeFilters") {
val tbl = s"${catalogAndNamespace}tbl"
val dim = s"${catalogAndNamespace}dim"
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]