spark-test commented on code in PR #60560:
URL: https://github.com/apache/spark/pull/60560#discussion_r4594657918
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AssignmentUtils.scala:
##########
@@ -61,27 +61,34 @@ object AssignmentUtils extends SQLConfHelper with
CastSupport {
* @param ansiStoreAssignmentCastCheck when the ANSI store-assignment cast
check runs:
* ANALYSIS (default) rejects an unsafe
cast at analysis
* time; RUNTIME rejects invalid values
at execution time.
+ * @param generatedColumns top-level column names whose omitted values must
be generated
Review Comment:
**Nit (P3):** With `generatedColumns`, this method returns an Unevaluable
`GeneratedColumnAssignmentValue` for each unassigned generated column, yet the
scaladoc above still says an unassigned column "will be set to its current
value" and that the result allows Spark to "construct an updated version of a
row". A caller that trusts it and skips
`RowLevelAssignmentResolution.resolveGeneratedColumnAssignments` builds a plan
that `AssignmentUtils.aligned` still accepts for columns other than CHAR and
VARCHAR, because the placeholder carries the column's type and nullability, and
that fails only at execution. The `@param` of `alignInsertAssignments` also
calls the argument "omitted columns", although callers pass every generated
column name of the target and the method decides which are omitted. Documenting
the placeholder output and the step that replaces it, qualifying the
current-value sentence, and describing `generatedColumns` in both methods as
the target's generated column names
would fix this; the placeholder's own scaladoc could again say which step
replaces it, as it did before the commit that shortened these comments.
**Verification:**
- **Inspection:** The scaladoc of both alignment methods and of
GeneratedColumnAssignmentValue describes the placeholder output, the resolution
step that replaces it and the generatedColumns parameter as the code uses them.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RowLevelAssignmentResolution.scala:
##########
@@ -64,20 +66,68 @@ private[sql] object RowLevelAssignmentResolution {
Assignment(cleanedKey, finalValue)
}
+ /**
+ * Fills omitted generated-column assignments for UPDATE and MERGE actions,
including INSERT
+ * actions within MERGE. Regular INSERT uses WriteOutputResolution instead.
+ *
+ * For g GENERATED ALWAYS AS (a * 2), UPDATE t SET a = b + 1, b = 100 must
assign
+ * g = (old.b + 1) * 2. Resolve the generation expression against attributes
for the new values,
+ * then substitute the aligned assignments while preserving their references
to the original row.
+ * Explicitly supplied generated values pass through for validation against
the final row.
+ */
+ def resolveGeneratedColumnAssignments(
+ table: LogicalPlan,
+ assignments: Seq[Assignment],
+ analyze: LogicalPlan => LogicalPlan): Seq[Assignment] = {
+ if
(!assignments.exists(_.value.isInstanceOf[GeneratedColumnAssignmentValue])) {
+ return assignments
+ }
+
+ val relation = table.collectFirst { case r: DataSourceV2Relation => r }.get
+ val generationExpressions = GeneratedColumn.expressionReaders(relation)
+ // assigned aliases old.b + 1 as a and 100 as b, each with a fresh
attribute ID.
+ val assigned = assignments.collect {
+ case Assignment(attr: Attribute, value)
+ if !value.isInstanceOf[GeneratedColumnAssignmentValue] =>
+ Alias(value, attr.name)()
+ }
+ // input exposes the new a and b; valuesByAttribute maps them back to
old.b + 1 and 100.
+ val input = assigned.map(_.toAttribute)
+ val valuesByAttribute = AttributeMap(assigned.map(a => a.toAttribute ->
a.child))
+
+ assignments.map {
+ case Assignment(attr: Attribute, _: GeneratedColumnAssignmentValue) =>
+ // resolved binds a * 2 to input's new a, before substituting assigned
values.
+ val resolved = generationExpressions(attr.name).resolve(input,
analyze) { expr =>
+ Cast(expr, attr.dataType, Some(conf.sessionLocalTimeZone),
ansiEnabled = true)
+ }
+ // generated uses valuesByAttribute once: (old.b + 1) * 2, keeping the
original b.
+ val generated = resolved.transform {
+ case a: AttributeReference if valuesByAttribute.contains(a) =>
valuesByAttribute(a)
Review Comment:
**Non-blocking (P2):** This `transform` replaces each new-value attribute
with the assigned expression itself, so the written column and each generated
column that reads it get their own copy, unlike INSERT, which computes
generated values from the projected values it stores. Reading the code, `UPDATE
t SET id = reflect('java.util.UUID', 'randomUUID')` with `g STRING GENERATED
ALWAYS AS (upper(id))` writes `id` from one call and computes `g` from another,
so the check `g <=> upper(id)` fails every row with CHECK_CONSTRAINT_VIOLATION
on `g`. A seeded `rand()` diverges when a copy sits in a lazily evaluated
position: with `g DOUBLE GENERATED ALWAYS AS (IF(b > 0, a, 0))`, the copy in
the IF branch advances only on rows with `b > 0` and falls behind the copy
written to `a`. A MERGE with a single NOT MATCHED clause, which is planned as a
plain projection, is affected the same way; MERGE plans built on MergeRows
reject nondeterministic action values in CheckAnalysis. The test 'UPDATE ev
aluates a nondeterministic assignment once' passes only because its three
identically seeded `rand()` copies advance in step, so it cannot catch this,
and the failure stays loud only because every generated column of a rewritten
write is checked. The substitution also evaluates an expensive deterministic
assignment, such as a UDF, once per reference where subexpression elimination
does not apply: in the `If(cond, ...)` projection of a group-based UPDATE with
a WHERE clause and in MergeRows code generation.
**Recommended change:** Keep the link between each omitted generated value
and the assigned values it reads instead of inlining anonymous copies, and in
the UPDATE rewrites (the group-based projection, its Union branch for subquery
conditions, the delta projection and the split-update Expand) and in the
rewrite of a MERGE with one NOT MATCHED clause, evaluate each such assigned
value once per row in a projection below the node that produces the written
row, guarded so that it runs only on the rows where the assignment itself runs,
and have both the column and the generated value read that projected value.
MERGE plans built on MergeRows keep evaluating the substituted expression.
Replace the test 'UPDATE evaluates a nondeterministic assignment once', which
passes even with three evaluations, with generated-column cases that fail when
an assigned value is evaluated more than once.
**Why this works:** The shared value is still computed from the row before
the update, so every SET clause keeps reading the original row; because the
column and every generated value that reads it take the same evaluated value, a
function that returns a new value on each call, a seeded generator read in a
lazily evaluated branch, or an expensive expression is evaluated once per
written row, and the generated-column check compares two values derived from
that single evaluation.
**Scope:** UPDATE and single-clause insert-only MERGE compute generated
values from one evaluation of each assigned value they read; MERGE plans built
on MergeRows are unchanged.
**Compatibility:** Every SET clause still reads the row before the update:
for g GENERATED ALWAYS AS (a * 2) and a row (a=1, b=3, g=2), UPDATE t SET a = b
+ 1, b = 100 still writes (a=4, b=100, g=8).
**Risks:** Plans of UPDATE and single-clause insert-only MERGE on tables
whose generated columns Spark computes gain a projection below the
row-producing node; statements on other tables, INSERT and DELETE keep their
plans, and there is no flag, so rolling back means reverting the change. A
group-based UPDATE with a WHERE clause must guard the shared value by the
update condition: evaluating it on every row would also run it on copied rows,
where an expression that fails could fail a statement that the current If(cond,
...) projection never evaluates there.
**Constraints:** Evaluate each shared value on exactly the rows on which the
current form evaluates it, so error and laziness behavior stay the same. Shared
values read the original row, never another assignment's new value. The rows
these statements insert or update keep their generated-column check.
**Exclusions:**
- MERGE plans built on MergeRows keep evaluating a deterministic assigned
value once per reference in whole-stage code generation; results are unaffected
because their actions cannot hold nondeterministic values, and sharing it would
need subexpression elimination in MergeRowsExec for every MERGE.
**Success:** An UPDATE in group, delta and split modes, or a MERGE with one
NOT MATCHED clause, that assigns a nondeterministic value to a column read by
an omitted generated column succeeds and writes a generated value computed from
the value written to that column on every row. On those paths each assigned
value that a generated value reads is evaluated once per written row, apart
from cheap deterministic expressions the optimizer may repeat, and only on the
rows the assignment applies to. Generated values, simultaneous SET semantics,
explicit-value validation and the results of every other UPDATE and MERGE case
stay as they are.
**Verification:**
- **Regression:** UPDATE t SET id = reflect('java.util.UUID', 'randomUUID')
on a table with g GENERATED ALWAYS AS (upper(id)) succeeds and writes g =
upper(id) on every row, in group, delta and split modes.
- **Regression:** UPDATE t SET a = rand() on a table with g GENERATED ALWAYS
AS (IF(b > 0, a, 0)), over several rows of one partition whose b alternates
sign, succeeds and every written row satisfies its generation expression in
each mode, and a MERGE with a single NOT MATCHED clause that inserts rand()
into a column such an expression reads does the same.
- **Behavior:** A deterministic user-defined function assigned to a column
that a generated column reads is invoked once per updated row, in a group-based
UPDATE with a WHERE clause and in a delta UPDATE.
- **Behavior:** A group-based UPDATE with a WHERE clause whose assigned
value would fail on the rows the clause excludes, such as 10 DIV x where only
excluded rows have x = 0, still succeeds and writes the generated value of the
updated rows.
- **Compatibility:** Existing generated-column UPDATE and MERGE cases keep
their results in all three write modes, including simultaneous assignments,
changed row IDs, generated partitions, nested values and star actions.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnDMLSuite.scala:
##########
@@ -0,0 +1,547 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.sql.{AnalysisException, QueryTest, Row}
+import org.apache.spark.sql.connector.catalog.{Column, GenerationExpression,
Identifier, InMemoryRowLevelOperationTableCatalog, TableInfo}
+import org.apache.spark.sql.connector.expressions.{Cast => V2Cast, Expression
=> V2Expression, Expressions, FieldReference, GeneralScalarExpression,
LiteralValue}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StringType}
+
+class GeneratedColumnDMLSuite extends QueryTest with SharedSparkSession {
Review Comment:
**Nit (P3):** The other 69 suites in this package, including
`GeneratedColumnWriteSuite`, carry `@DataSourceV2Test`, which
`build_and_test.yml` uses to run them in the DSv2 job and to keep them out of
the job for the remaining SQL suites. Without it, these 99 cases run in that
other job, and a run with
`included-tags=org.apache.spark.tags.DataSourceV2Test`, such as one reproducing
the DSv2 job, skips them. Adding the annotation and its import,
`org.apache.spark.tags.DataSourceV2Test`, fixes it.
**Verification:**
- **Inspection:** GeneratedColumnDMLSuite carries the @DataSourceV2Test
annotation like the other suites in its package.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnDMLSuite.scala:
##########
@@ -0,0 +1,547 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.sql.{AnalysisException, QueryTest, Row}
+import org.apache.spark.sql.connector.catalog.{Column, GenerationExpression,
Identifier, InMemoryRowLevelOperationTableCatalog, TableInfo}
+import org.apache.spark.sql.connector.expressions.{Cast => V2Cast, Expression
=> V2Expression, Expressions, FieldReference, GeneralScalarExpression,
LiteralValue}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StringType}
+
+class GeneratedColumnDMLSuite extends QueryTest with SharedSparkSession {
+
+ private val targetTableName = "rowlevelcat.t"
+
+ private def testDML(name: String)(f: Map[String, String] => Unit): Unit = {
+ Seq("group", "delta", "split").foreach { mode =>
+ test(s"$name ($mode)") {
+ withSQLConf("spark.sql.catalog.rowlevelcat" ->
+ classOf[InMemoryRowLevelOperationTableCatalog].getName) {
+ withTable(targetTableName) {
+ f(Map("supports-deltas" -> (mode != "group").toString,
+ "split-updates" -> (mode == "split").toString))
+ }
+ }
+ }
+ }
+ }
+
+ private def createTable(columns: String, properties: Map[String, String]):
Unit = {
+ val props = properties.map { case (key, value) => s"'$key' = '$value'"
}.mkString(", ")
+ sql(s"""CREATE TABLE $targetTableName (
+ | pk INT NOT NULL,
+ | part STRING,
+ | $columns
+ |) USING foo PARTITIONED BY (part) TBLPROPERTIES
($props)""".stripMargin)
+ }
+
+ private def createTable(columns: Array[Column], properties: Map[String,
String]): Unit = {
+ val catalog = spark.sessionState.catalogManager.catalog("rowlevelcat")
+ .asInstanceOf[InMemoryRowLevelOperationTableCatalog]
+ val info = new TableInfo.Builder()
+ .withColumns(Array(Column.create("pk", IntegerType, false),
+ Column.create("part", StringType)) ++ columns)
+ .withPartitions(Array(Expressions.identity("part")))
+ .withProperties(properties.asJava)
+ .build()
+ catalog.createTable(Identifier.of(Array.empty[String], "t"), info)
+ }
+
+ testDML("UPDATE generates values from stored assignments and preserves other
rows") { props =>
+ createTable("a INT, g BIGINT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2), (3, 'q', 3)")
+ sql(s"UPDATE $targetTableName SET a = 5.9 WHERE pk = 1")
+ checkAnswer(spark.table(targetTableName),
+ Seq(Row(1, "p", 5, 10L), Row(2, "p", 2, 4L), Row(3, "q", 3, 6L)))
+ }
+
+ testDML("UPDATE evaluates a nondeterministic assignment once") { props =>
+ createTable("a DOUBLE, g DOUBLE GENERATED ALWAYS AS (a + a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2)")
+ sql(s"UPDATE $targetTableName SET a = rand()")
+ val rows = spark.table(targetTableName).collect()
+ assert(rows.length == 2)
+ rows.foreach { row =>
+ assert(row.getDouble(2) >= 0 && row.getDouble(2) < 1)
+ assert(row.getDouble(3) == row.getDouble(2) * 2)
+ }
+ }
+
+ testDML("UPDATE generates values from nested assignments and lambda inputs")
{ props =>
+ createTable(
+ "s STRUCT<f: INT>, a ARRAY<INT>, " +
+ "g INT GENERATED ALWAYS AS (s.f * 2), " +
+ "h ARRAY<INT> GENERATED ALWAYS AS (transform(a, x -> x + s.f))", props)
+ sql(s"""INSERT INTO $targetTableName (pk, part, s, a)
+ |VALUES (1, 'p', named_struct('f', 1), array(1, 2))""".stripMargin)
+ sql(s"UPDATE $targetTableName SET s.f = 5.9, a = array(3.9, 4.9)")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", Row(5), Seq(3, 4),
10, Seq(8, 9)))
+ }
+
+ testDML("UPDATE generates values from simultaneous assignments and changed
row IDs") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (pk + a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 10)")
+ sql(s"UPDATE $targetTableName SET pk = pk + 1, a = pk + a")
+ checkAnswer(spark.table(targetTableName), Row(2, "p", 11, 13))
+ }
+
+ testDML("DML assignments use original values regardless of SET order") {
props =>
+ createTable("a INT, b INT, g INT GENERATED ALWAYS AS (a * 10 + b)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a, b) VALUES (1, 'p', 1, 2)")
+ Seq("a = b, b = a", "b = a, a = b").foreach { assignments =>
+ sql(s"UPDATE $targetTableName SET $assignments")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 2, 1, 21))
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET $assignments
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 1, 2, 12))
+ }
+ }
+
+ testDML("DML preserves original row IDs when their new values are
generated") { props =>
+ val properties = props.map { case (key, value) => s"'$key' = '$value'"
}.mkString(", ")
+ sql(s"""CREATE TABLE $targetTableName (
+ | pk INT GENERATED ALWAYS AS (a) NOT NULL, part STRING, a INT NOT
NULL
+ |) USING foo PARTITIONED BY (part) TBLPROPERTIES ($properties)
+ |""".stripMargin)
+ sql(s"INSERT INTO $targetTableName (part, a) VALUES ('p', 1)")
+ sql(s"UPDATE $targetTableName SET a = 2")
+ checkAnswer(spark.table(targetTableName), Row(2, "p", 2))
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 2 AS pk, 3 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Row(3, "p", 3))
+ }
+
+ testDML("DML moves rows to their generated partitions") { props =>
+ val properties = props.map { case (key, value) => s"'$key' = '$value'"
}.mkString(", ")
+ sql(s"""CREATE TABLE $targetTableName (
+ | pk INT NOT NULL, a INT, part INT GENERATED ALWAYS AS (a % 2)
+ |) USING foo PARTITIONED BY (part) TBLPROPERTIES ($properties)
+ |""".stripMargin)
+ sql(s"INSERT INTO $targetTableName (pk, a) VALUES (1, 1), (2, 2)")
+ sql(s"UPDATE $targetTableName SET a = 4 WHERE pk = 1")
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, 4, 0), Row(2, 2, 0)))
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 2 AS pk, 5 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, 4, 0), Row(2, 5, 1)))
+ }
+
+ testDML("MERGE validates supplied generated values regardless of SET order")
{ props =>
+ createTable(
+ "a INT, g INT GENERATED ALWAYS AS (a * 2), h INT GENERATED ALWAYS AS (a
+ 1)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ Seq("a = s.a, g = s.g", "g = s.g, a = s.a").foreach { assignments =>
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, 10 AS a, 20 AS g) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET $assignments
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ val e = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, 20 AS a, 999 AS g) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET $assignments
+ |""".stripMargin)
+ }
+ assert(e.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ }
+ }
+
+ testDML("MERGE generates values only for the selected action") { props =>
+ createTable("a INT, g BIGINT GENERATED ALWAYS AS (100 DIV a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2)")
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, 10 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED AND s.a < 0 THEN UPDATE SET a = 0
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p', 0)
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 10, 10L), Row(2,
"p", 2, 50L)))
+ val e = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, -1 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED AND s.a < 0 THEN UPDATE SET a = 0
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |""".stripMargin)
+ }
+ assert(e.getMessage.contains("DIVIDE_BY_ZERO"))
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 10, 10L), Row(2,
"p", 2, 50L)))
+ }
+
+ testDML("UPDATE validates explicit generated values") { props =>
+ createTable(
+ "a INT, g INT GENERATED ALWAYS AS (a * 2), h INT GENERATED ALWAYS AS (a
+ 1)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ sql(s"UPDATE $targetTableName SET a = 10, g = 20")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ val e = intercept[Exception] {
+ sql(s"UPDATE $targetTableName SET a = 20, g = 999")
+ }
+ assert(e.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ }
+
+ testDML("UPDATE with a subquery generates only matching rows") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2)")
+ sql(s"UPDATE $targetTableName SET a = 10 WHERE pk IN (SELECT * FROM VALUES
(1) AS s(pk))")
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 10, 20), Row(2,
"p", 2, 4)))
+ }
+
+ testDML("MERGE generates values for each action and skips deletes") { props
=>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2), h INT GENERATED
ALWAYS AS (1)",
+ props)
+ sql(s"""INSERT INTO $targetTableName (pk, part, a)
+ |VALUES (1, 'p', 1), (2, 'p', 2), (3, 'p', 3), (4, 'p', 4), (5,
'p', 5)
+ |""".stripMargin)
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 10), (2, -1), (6, 60), (7, 70)
+ | AS v(pk, a)) AS s
+ |ON t.pk = s.pk
+ |WHEN MATCHED AND s.a < 0 THEN DELETE
+ |WHEN MATCHED THEN UPDATE SET a = s.a + 0.9
+ |WHEN NOT MATCHED AND s.pk = 6
+ | THEN INSERT (pk, part, a) VALUES (s.pk, 'p', s.a)
+ |WHEN NOT MATCHED
+ | THEN INSERT (pk, part, a, g) VALUES (s.pk, 'p', s.a, s.a * 2)
+ |WHEN NOT MATCHED BY SOURCE AND t.pk = 3 THEN UPDATE SET a = t.a +
10
+ |WHEN NOT MATCHED BY SOURCE AND t.pk = 4 THEN DELETE
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(
+ Row(1, "p", 10, 20, 1), Row(3, "p", 13, 26, 1), Row(5, "p", 5, 10, 1),
+ Row(6, "p", 60, 120, 1), Row(7, "p", 70, 140, 1)))
+ }
+
+ testDML("MERGE uses the stored nondeterministic source values") { props =>
+ createTable("a DOUBLE, g DOUBLE GENERATED ALWAYS AS (a + a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ withSQLConf(SQLConf.RUNTIME_ROW_LEVEL_OPERATION_GROUP_FILTER_ENABLED.key
-> "false") {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT pk, rand() AS a FROM VALUES (1), (2) AS v(pk)) s
+ |ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p',
s.a)
+ |""".stripMargin)
+ }
+ val rows = spark.table(targetTableName).collect()
+ assert(rows.length == 2)
+ rows.foreach { row =>
+ assert(row.getDouble(2) >= 0 && row.getDouble(2) < 1)
+ assert(row.getDouble(3) == row.getDouble(2) * 2)
+ }
+ }
+
+ testDML("DML enforces NOT NULL on generated values") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a + 1) NOT NULL", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ sql(s"UPDATE $targetTableName SET a = 10")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 11))
+ val updateError = intercept[Exception] {
+ sql(s"UPDATE $targetTableName SET a = NULL")
+ }
+ assert(updateError.getMessage.contains("NOT_NULL_ASSERT_VIOLATION"))
+ val mergeError = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (2)
+ | AS v(pk)) AS s ON t.pk = s.pk
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p',
NULL)
+ |""".stripMargin)
+ }
+ assert(mergeError.getMessage.contains("NOT_NULL_ASSERT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 11))
+ }
+
+ testDML("DML resolves dotted column names and case-insensitive assignments")
{ props =>
+ createTable("`A.b` INT, `G.c` INT GENERATED ALWAYS AS (`A.b` * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, `a.B`) VALUES (1, 'p', 1)")
+ sql(s"UPDATE $targetTableName SET `a.B` = 10")
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 20), (2, 30)
+ | AS v(pk, a)) AS s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET `a.B` = s.a
+ |WHEN NOT MATCHED THEN INSERT (pk, part, `a.B`) VALUES (s.pk, 'p',
s.a)
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 20, 40), Row(2,
"p", 30, 60)))
+ }
+
+ Seq(false, true).foreach { multipleActions =>
+ testDML(s"insert-only MERGE generates values (multiple actions:
$multipleActions)") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ val firstAction = if (multipleActions) {
+ "WHEN NOT MATCHED AND s.pk = 2 " +
+ "THEN INSERT (pk, part, a, g) VALUES (s.pk, 'p', s.a, s.a * 2)"
Review Comment:
**Nit (P3):** This insert-only case supplies `g = s.a * 2`, which agrees
with the expression, and every CHECK_CONSTRAINT_VIOLATION case in the suite is
an UPDATE or a MERGE with a MATCHED clause, which goes through ReplaceData or
WriteDelta. Insert-only MERGE writes through the separate `InsertOnlyMerge`
command, over a projection for one clause or MergeRows for several, so a change
that stopped checking that command, or that matched keys exactly in
`alignUpdateAssignments` so that `SET g.x = 999` on a generated struct column
regenerated the column instead of validating it, would leave every test passing
in all three write modes. Cases that supply a disagreeing value through both
insert-only shapes, and that assign a nested field of a generated struct
column, would give these paths a failure signal.
**Verification:**
- **Regression:** An insert-only MERGE with one NOT MATCHED clause, and one
with several, that supply g = 999 for g GENERATED ALWAYS AS (a * 2) fail with
CHECK_CONSTRAINT_VIOLATION and leave the table unchanged, in group, delta and
split modes.
- **Regression:** For a column g STRUCT<x: INT, y: INT> GENERATED ALWAYS AS
(named_struct('x', a, 'y', a + 1)), UPDATE t SET g.x = 999 fails with
CHECK_CONSTRAINT_VIOLATION, while UPDATE t SET g.x = a succeeds and stores the
assigned struct, in each mode.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -111,11 +112,19 @@ private[sql] class TableConstraintResolution(
s"${col.name} <=> $genExprSql")
// Analyze the check under the settings an auto-filled value is
analyzed under, so that a
// row Spark auto-filled passes it when a later write carries it.
- reader.analyze(
+ val invariant = reader.analyze(
check(catalystExpr),
check(reader.toCatalyst(StoredExpressionText.parseWithSessionAnsi)),
v2Write.query.output,
analyze)
+ v2Write match {
Review Comment:
**Nit (P3):** The scaladoc of `buildGeneratedColumnConstraints` still
describes only INSERT: a check for each generated column "whose value was
provided by the write", with auto-filled columns excluded because
`ResolveOutputRelation` marks them and "their values are correct by
construction". Only `WriteOutputResolution` marks columns, so for the UPDATE
and MERGE writes that now reach this method every generated column of every
written row is checked, including values Spark computed in
`resolveGeneratedColumnAssignments` and, in group-based writes, rows copied
unchanged, while this new branch lets delta delete records pass. That check is
what currently turns diverging copies of a nondeterministic assignment into
CHECK_CONSTRAINT_VIOLATION, so a cleanup that follows the documented reasoning
and marks computed columns auto-filled would let those values be stored.
Stating which writes and rows are checked, including the delete-record
exemption and how copied rows are treated, would fi
x it.
**Verification:**
- **Inspection:** The buildGeneratedColumnConstraints scaladoc matches how
the code treats INSERT auto-filled columns, UPDATE and MERGE writes, DELETE,
delta delete records and rows copied by group-based writes.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala:
##########
@@ -205,6 +223,24 @@ object GeneratedColumn {
}
}
}
+
+ /**
+ * Reads and analyzes a value, applying the caller's wrappers to both
expression forms.
+ * Resolve the lazy SQL session fallback before returning, so callers can
substitute the
+ * resolved input attributes without waiting for another analyzer pass.
+ */
+ def resolve(
+ input: Seq[Attribute],
+ analyzer: LogicalPlan => LogicalPlan)(
+ prepare: Expression => Expression): Expression = {
+ def inSession: Expression = {
+ val value =
prepare(toCatalyst(StoredExpressionText.parseWithSessionAnsi))
+ val Project(Seq(Alias(resolved, _)), _) =
Review Comment:
**Non-blocking (P2):** `StoredExpressionText.analyze` hands this fallback
exactly the texts that the fixed settings could not read as a resolved scalar,
and its scaladoc names one: a text that "analyzes to another plan, such as an
aggregate that a catalog stores". Reading the code, for a stored `sum(i)` the
analyzer's `GlobalAggregates` turns this `Project` into `Aggregate(Nil, ...)`,
so this pattern throws `scala.MatchError`, which Spark reports as
INTERNAL_ERROR ("You hit a bug in Spark"). A text the session cannot resolve
comes back unresolved, and for a NOT NULL generated column `resolveAssignment`
reads its `nullable`, which throws `UnresolvedException`, also INTERNAL_ERROR.
For INSERT, GeneratedColumnWriteSuite's 'a stored text that is not a scalar
expression fails the analysis of the write' fixes the error for this text as
MISSING_GROUP_BY. Accepting only a resolved single-alias `Project` over the
`LocalRelation`, the shape `StoredExpressionText.expressionFromPlan` already
checks, and otherwise running CheckAnalysis and failing with an
AnalysisException that names the table, the column and its expression would
keep these statements on a user-facing error.
**Verification:**
- **Regression:** With a catalog that stores sum(i) as a generated column's
SQL text, as the existing INSERT test's catalog does, an UPDATE and a MERGE
action that omit that column fail with an AnalysisException that names it, in
group, delta and split modes.
- **Regression:** A stored text that references a missing column fails
UPDATE with the unresolved-column error for a nullable and for a NOT NULL
generated column.
- **Compatibility:** A SQL-only generation text that resolves only under the
session, such as a = 1 on a BOOLEAN column, still generates its values for
UPDATE and MERGE.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/expressions.scala:
##########
@@ -92,6 +92,9 @@ object ConstantFolding extends Rule[LogicalPlan] {
case c: ConditionalExpression if !c.foldable =>
c.mapChildren(constantFolding(_, isConditionalBranch = true))
+ case i: MergeRows.Instruction =>
Review Comment:
**Non-blocking (P2):** This case covers `MergeRows.Instruction` only, but
`RewriteMergeIntoTable` plans a MERGE with exactly one NOT MATCHED clause as
`InsertOnlyMerge(Project(values, Join(Filter(cond, source), target,
LeftAnti)))`, whose expressions ConstantFolding folds outside any conditional
branch, where `tryFold` rethrows. Reading the code, under ANSI and with every
source row matching, `MERGE INTO t USING s ON t.pk = s.pk WHEN NOT MATCHED THEN
INSERT (pk, salary, dep) VALUES (s.pk, 1 DIV 0, s.dep)` still fails with
DIVIDE_BY_ZERO during optimization, while the new test statement, which adds
MATCHED and NOT MATCHED BY SOURCE clauses, succeeds. Generated values reach the
same path: for `g INT GENERATED ALWAYS AS (100 DIV a)`, a lone `WHEN NOT
MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p', 0)` folds `100 DIV 0` at
planning, and a lone `WHEN NOT MATCHED AND 1 DIV 0 = 1` fails in the source
filter. The description of #60559 states the problem as an expression in "a
clause
that is never evaluated", including "expressions in unmatched clause types",
which describes this form too. Only statements in which no row reaches the
clause are affected, since a row that reaches it raises the same error during
execution.
**Recommended change:** Record the boundary instead of extending the
deferral: add a TODO at the single-clause insert-only MERGE rewrite, and a
sentence next to the MergeRows instruction case in ConstantFolding, saying that
this rewrite plans the clause as a plain projection over a left anti join with
its condition filtering the source, so a constant in its insert values, in the
generated values computed from them, or in its condition that fails to fold
still fails planning even when no row reaches the clause, unlike a MERGE with
more clauses.
**Why this works:** The comments make the uncovered plan shape explicit
where it is chosen and where the deferral is defined, so the deferral no longer
reads as covering every MERGE action and a later change can extend it
deliberately.
**Scope:** Comments that limit the MERGE folding deferral to plans built on
MergeRows and name the single-clause insert-only rewrite as not covered.
**Compatibility:** A MERGE with one NOT MATCHED clause keeps its plain
projection plan and keeps accepting nondeterministic insert values.
**Risks:** None for results or plans, since the change adds comments only;
the single-clause form keeps failing during planning on a constant that fails
to fold, as on the base branch.
**Constraints:** Keep the single-clause rewrite's plain projection and its
source-side condition filter, which accept nondeterministic insert values and
let the condition reach the source.
**Exclusions:**
- Extending the deferral to the single-clause insert-only MERGE, which needs
either a different plan shape or a ConstantFolding case that depends on the
plan shape.
**Success:** The single-clause insert-only MERGE rewrite carries a TODO, and
the MERGE instruction case in ConstantFolding a note, saying that this form is
outside the deferral and why its folding failures still fail planning. Plans
and results of every MERGE stay as they are.
**Verification:**
- **Inspection:** The comments at the single-clause insert-only MERGE
rewrite and at the MERGE instruction case in ConstantFolding state that the
deferral covers MergeRows instructions only and that the single-clause form
folds its insert values, the generated values computed from them and its
condition eagerly.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AssignmentUtils.scala:
##########
@@ -130,7 +139,9 @@ object AssignmentUtils extends SQLConfHelper with
CastSupport {
val matchingAssignments = topLevelAssignments.collect {
case assignment if assignment.key.semanticEquals(attr) => assignment
}
- val resolvedValue = if (matchingAssignments.isEmpty) {
+ val resolvedValue = if (matchingAssignments.isEmpty &&
generatedColumns.contains(attr.name)) {
+ GeneratedColumnAssignmentValue(attr.dataType, attr.nullable)
+ } else if (matchingAssignments.isEmpty) {
Review Comment:
**Blocking (P1):** This branch fills an omitted non-generated column with
its DEFAULT or NULL based only on
`spark.sql.defaultColumn.useNullsForMissingDefaultValues`. INSERT into the same
tables also requires `spark.sql.generatedColumn.allowNullableIngest.enabled`
when the target has generation expressions Spark evaluates
(`TableOutputResolver.useNullAsDefaultForMissingColumn`), and that config
documents that when it is false "all non-generated columns must be provided".
Reading the code, with the config set to false and `t(pk INT NOT NULL, part
STRING, a INT, b STRING, g INT GENERATED ALWAYS AS (a * 2))`, `INSERT INTO t
(pk, part, a) VALUES (1, 'p', 1)` fails because `b` is missing, while `MERGE
INTO t USING s ON t.pk = s.pk WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES
(s.pk, 'p', s.a)` writes `b = NULL`: the generated-column check covers only
generated columns, so nothing rejects the row. The same holds for insert-only
MERGE with one or several clauses, for a full MERGE, an
d for `INSERT *` with schema evolution when the source lacks the column. The
`generatedColumns` set this method already receives says the table has such
expressions, so the INSERT rule can be applied here: fill NULL only when the
config is true or the set is empty, and otherwise report the column through the
existing "No assignment" error, keeping the DEFAULT of a column that has one.
**Verification:**
- **Regression:** With
spark.sql.generatedColumn.allowNullableIngest.enabled=false, a MERGE INSERT
that omits a nullable non-generated column of a table with a generated column
is rejected with one NOT MATCHED clause, with several, and in a MERGE that also
has a MATCHED clause, and so is INSERT * WITH SCHEMA EVOLUTION from a source
that lacks that column, while INSERT INTO with the same omission keeps failing.
- **Compatibility:** With the config at its default the same MERGE
statements still write NULL for the omitted column, an omitted column with a
DEFAULT still gets its default with the config on or off, and MERGE INSERT into
a table without the generated-column write capability still fills NULL with the
config off.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnDMLSuite.scala:
##########
@@ -0,0 +1,547 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.sql.{AnalysisException, QueryTest, Row}
+import org.apache.spark.sql.connector.catalog.{Column, GenerationExpression,
Identifier, InMemoryRowLevelOperationTableCatalog, TableInfo}
+import org.apache.spark.sql.connector.expressions.{Cast => V2Cast, Expression
=> V2Expression, Expressions, FieldReference, GeneralScalarExpression,
LiteralValue}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{BooleanType, IntegerType, StringType}
+
+class GeneratedColumnDMLSuite extends QueryTest with SharedSparkSession {
+
+ private val targetTableName = "rowlevelcat.t"
+
+ private def testDML(name: String)(f: Map[String, String] => Unit): Unit = {
+ Seq("group", "delta", "split").foreach { mode =>
+ test(s"$name ($mode)") {
+ withSQLConf("spark.sql.catalog.rowlevelcat" ->
+ classOf[InMemoryRowLevelOperationTableCatalog].getName) {
+ withTable(targetTableName) {
+ f(Map("supports-deltas" -> (mode != "group").toString,
+ "split-updates" -> (mode == "split").toString))
+ }
+ }
+ }
+ }
+ }
+
+ private def createTable(columns: String, properties: Map[String, String]):
Unit = {
+ val props = properties.map { case (key, value) => s"'$key' = '$value'"
}.mkString(", ")
+ sql(s"""CREATE TABLE $targetTableName (
+ | pk INT NOT NULL,
+ | part STRING,
+ | $columns
+ |) USING foo PARTITIONED BY (part) TBLPROPERTIES
($props)""".stripMargin)
+ }
+
+ private def createTable(columns: Array[Column], properties: Map[String,
String]): Unit = {
+ val catalog = spark.sessionState.catalogManager.catalog("rowlevelcat")
+ .asInstanceOf[InMemoryRowLevelOperationTableCatalog]
+ val info = new TableInfo.Builder()
+ .withColumns(Array(Column.create("pk", IntegerType, false),
+ Column.create("part", StringType)) ++ columns)
+ .withPartitions(Array(Expressions.identity("part")))
+ .withProperties(properties.asJava)
+ .build()
+ catalog.createTable(Identifier.of(Array.empty[String], "t"), info)
+ }
+
+ testDML("UPDATE generates values from stored assignments and preserves other
rows") { props =>
+ createTable("a INT, g BIGINT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2), (3, 'q', 3)")
+ sql(s"UPDATE $targetTableName SET a = 5.9 WHERE pk = 1")
+ checkAnswer(spark.table(targetTableName),
+ Seq(Row(1, "p", 5, 10L), Row(2, "p", 2, 4L), Row(3, "q", 3, 6L)))
+ }
+
+ testDML("UPDATE evaluates a nondeterministic assignment once") { props =>
+ createTable("a DOUBLE, g DOUBLE GENERATED ALWAYS AS (a + a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2)")
+ sql(s"UPDATE $targetTableName SET a = rand()")
+ val rows = spark.table(targetTableName).collect()
+ assert(rows.length == 2)
+ rows.foreach { row =>
+ assert(row.getDouble(2) >= 0 && row.getDouble(2) < 1)
+ assert(row.getDouble(3) == row.getDouble(2) * 2)
+ }
+ }
+
+ testDML("UPDATE generates values from nested assignments and lambda inputs")
{ props =>
+ createTable(
+ "s STRUCT<f: INT>, a ARRAY<INT>, " +
+ "g INT GENERATED ALWAYS AS (s.f * 2), " +
+ "h ARRAY<INT> GENERATED ALWAYS AS (transform(a, x -> x + s.f))", props)
+ sql(s"""INSERT INTO $targetTableName (pk, part, s, a)
+ |VALUES (1, 'p', named_struct('f', 1), array(1, 2))""".stripMargin)
+ sql(s"UPDATE $targetTableName SET s.f = 5.9, a = array(3.9, 4.9)")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", Row(5), Seq(3, 4),
10, Seq(8, 9)))
+ }
+
+ testDML("UPDATE generates values from simultaneous assignments and changed
row IDs") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (pk + a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 10)")
+ sql(s"UPDATE $targetTableName SET pk = pk + 1, a = pk + a")
+ checkAnswer(spark.table(targetTableName), Row(2, "p", 11, 13))
+ }
+
+ testDML("DML assignments use original values regardless of SET order") {
props =>
+ createTable("a INT, b INT, g INT GENERATED ALWAYS AS (a * 10 + b)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a, b) VALUES (1, 'p', 1, 2)")
+ Seq("a = b, b = a", "b = a, a = b").foreach { assignments =>
+ sql(s"UPDATE $targetTableName SET $assignments")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 2, 1, 21))
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET $assignments
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 1, 2, 12))
+ }
+ }
+
+ testDML("DML preserves original row IDs when their new values are
generated") { props =>
+ val properties = props.map { case (key, value) => s"'$key' = '$value'"
}.mkString(", ")
+ sql(s"""CREATE TABLE $targetTableName (
+ | pk INT GENERATED ALWAYS AS (a) NOT NULL, part STRING, a INT NOT
NULL
+ |) USING foo PARTITIONED BY (part) TBLPROPERTIES ($properties)
+ |""".stripMargin)
+ sql(s"INSERT INTO $targetTableName (part, a) VALUES ('p', 1)")
+ sql(s"UPDATE $targetTableName SET a = 2")
+ checkAnswer(spark.table(targetTableName), Row(2, "p", 2))
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 2 AS pk, 3 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Row(3, "p", 3))
+ }
+
+ testDML("DML moves rows to their generated partitions") { props =>
+ val properties = props.map { case (key, value) => s"'$key' = '$value'"
}.mkString(", ")
+ sql(s"""CREATE TABLE $targetTableName (
+ | pk INT NOT NULL, a INT, part INT GENERATED ALWAYS AS (a % 2)
+ |) USING foo PARTITIONED BY (part) TBLPROPERTIES ($properties)
+ |""".stripMargin)
+ sql(s"INSERT INTO $targetTableName (pk, a) VALUES (1, 1), (2, 2)")
+ sql(s"UPDATE $targetTableName SET a = 4 WHERE pk = 1")
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, 4, 0), Row(2, 2, 0)))
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 2 AS pk, 5 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, 4, 0), Row(2, 5, 1)))
+ }
+
+ testDML("MERGE validates supplied generated values regardless of SET order")
{ props =>
+ createTable(
+ "a INT, g INT GENERATED ALWAYS AS (a * 2), h INT GENERATED ALWAYS AS (a
+ 1)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ Seq("a = s.a, g = s.g", "g = s.g, a = s.a").foreach { assignments =>
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, 10 AS a, 20 AS g) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET $assignments
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ val e = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, 20 AS a, 999 AS g) s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET $assignments
+ |""".stripMargin)
+ }
+ assert(e.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ }
+ }
+
+ testDML("MERGE generates values only for the selected action") { props =>
+ createTable("a INT, g BIGINT GENERATED ALWAYS AS (100 DIV a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2)")
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, 10 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED AND s.a < 0 THEN UPDATE SET a = 0
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p', 0)
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 10, 10L), Row(2,
"p", 2, 50L)))
+ val e = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT 1 AS pk, -1 AS a) s ON t.pk = s.pk
+ |WHEN MATCHED AND s.a < 0 THEN UPDATE SET a = 0
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |""".stripMargin)
+ }
+ assert(e.getMessage.contains("DIVIDE_BY_ZERO"))
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 10, 10L), Row(2,
"p", 2, 50L)))
+ }
+
+ testDML("UPDATE validates explicit generated values") { props =>
+ createTable(
+ "a INT, g INT GENERATED ALWAYS AS (a * 2), h INT GENERATED ALWAYS AS (a
+ 1)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ sql(s"UPDATE $targetTableName SET a = 10, g = 20")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ val e = intercept[Exception] {
+ sql(s"UPDATE $targetTableName SET a = 20, g = 999")
+ }
+ assert(e.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 20, 11))
+ }
+
+ testDML("UPDATE with a subquery generates only matching rows") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1), (2,
'p', 2)")
+ sql(s"UPDATE $targetTableName SET a = 10 WHERE pk IN (SELECT * FROM VALUES
(1) AS s(pk))")
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 10, 20), Row(2,
"p", 2, 4)))
+ }
+
+ testDML("MERGE generates values for each action and skips deletes") { props
=>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2), h INT GENERATED
ALWAYS AS (1)",
+ props)
+ sql(s"""INSERT INTO $targetTableName (pk, part, a)
+ |VALUES (1, 'p', 1), (2, 'p', 2), (3, 'p', 3), (4, 'p', 4), (5,
'p', 5)
+ |""".stripMargin)
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 10), (2, -1), (6, 60), (7, 70)
+ | AS v(pk, a)) AS s
+ |ON t.pk = s.pk
+ |WHEN MATCHED AND s.a < 0 THEN DELETE
+ |WHEN MATCHED THEN UPDATE SET a = s.a + 0.9
+ |WHEN NOT MATCHED AND s.pk = 6
+ | THEN INSERT (pk, part, a) VALUES (s.pk, 'p', s.a)
+ |WHEN NOT MATCHED
+ | THEN INSERT (pk, part, a, g) VALUES (s.pk, 'p', s.a, s.a * 2)
+ |WHEN NOT MATCHED BY SOURCE AND t.pk = 3 THEN UPDATE SET a = t.a +
10
+ |WHEN NOT MATCHED BY SOURCE AND t.pk = 4 THEN DELETE
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(
+ Row(1, "p", 10, 20, 1), Row(3, "p", 13, 26, 1), Row(5, "p", 5, 10, 1),
+ Row(6, "p", 60, 120, 1), Row(7, "p", 70, 140, 1)))
+ }
+
+ testDML("MERGE uses the stored nondeterministic source values") { props =>
+ createTable("a DOUBLE, g DOUBLE GENERATED ALWAYS AS (a + a)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ withSQLConf(SQLConf.RUNTIME_ROW_LEVEL_OPERATION_GROUP_FILTER_ENABLED.key
-> "false") {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT pk, rand() AS a FROM VALUES (1), (2) AS v(pk)) s
+ |ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p',
s.a)
+ |""".stripMargin)
+ }
+ val rows = spark.table(targetTableName).collect()
+ assert(rows.length == 2)
+ rows.foreach { row =>
+ assert(row.getDouble(2) >= 0 && row.getDouble(2) < 1)
+ assert(row.getDouble(3) == row.getDouble(2) * 2)
+ }
+ }
+
+ testDML("DML enforces NOT NULL on generated values") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a + 1) NOT NULL", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ sql(s"UPDATE $targetTableName SET a = 10")
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 11))
+ val updateError = intercept[Exception] {
+ sql(s"UPDATE $targetTableName SET a = NULL")
+ }
+ assert(updateError.getMessage.contains("NOT_NULL_ASSERT_VIOLATION"))
+ val mergeError = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (2)
+ | AS v(pk)) AS s ON t.pk = s.pk
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p',
NULL)
+ |""".stripMargin)
+ }
+ assert(mergeError.getMessage.contains("NOT_NULL_ASSERT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 10, 11))
+ }
+
+ testDML("DML resolves dotted column names and case-insensitive assignments")
{ props =>
+ createTable("`A.b` INT, `G.c` INT GENERATED ALWAYS AS (`A.b` * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, `a.B`) VALUES (1, 'p', 1)")
+ sql(s"UPDATE $targetTableName SET `a.B` = 10")
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 20), (2, 30)
+ | AS v(pk, a)) AS s ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET `a.B` = s.a
+ |WHEN NOT MATCHED THEN INSERT (pk, part, `a.B`) VALUES (s.pk, 'p',
s.a)
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 20, 40), Row(2,
"p", 30, 60)))
+ }
+
+ Seq(false, true).foreach { multipleActions =>
+ testDML(s"insert-only MERGE generates values (multiple actions:
$multipleActions)") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ val firstAction = if (multipleActions) {
+ "WHEN NOT MATCHED AND s.pk = 2 " +
+ "THEN INSERT (pk, part, a, g) VALUES (s.pk, 'p', s.a, s.a * 2)"
+ } else {
+ ""
+ }
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 10), (2, 20), (3, 30)
+ | AS v(pk, a)) AS s
+ |ON t.pk = s.pk
+ |$firstAction
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p',
s.a)
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName),
+ Seq(Row(1, "p", 1, 2), Row(2, "p", 20, 40), Row(3, "p", 30, 60)))
+ }
+ }
+
+ testDML("MERGE star actions generate columns omitted from the source") {
props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 'p', 10), (2, 'p', 20)
+ | AS v(pk, part, a)) AS s
+ |ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET *
+ |WHEN NOT MATCHED THEN INSERT *
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 10, 20), Row(2,
"p", 20, 40)))
+ }
+
+ testDML("MERGE star actions validate generated columns supplied by the
source") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ val e = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 'p', 10, 999)
+ | AS v(pk, part, a, g)) AS s
+ |ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET *
+ |WHEN NOT MATCHED THEN INSERT *
+ |""".stripMargin)
+ }
+ assert(e.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 1, 2))
+ }
+
+ testDML("MERGE validates explicit values when another action generates the
column") { props =>
+ createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+ val e = intercept[Exception] {
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1, 10), (2, 20) AS v(pk, a)) s
+ |ON t.pk = s.pk
+ |WHEN MATCHED THEN UPDATE SET a = s.a
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a, g) VALUES (s.pk, 'p',
s.a, 999)
+ |""".stripMargin)
+ }
+ assert(e.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+ checkAnswer(spark.table(targetTableName), Row(1, "p", 1, 2))
+ }
+
+ testDML("MERGE generates values from defaults and handles nulls") { props =>
+ createTable(
+ "a INT DEFAULT 5, g INT GENERATED ALWAYS AS (a * 2), " +
+ "h INT GENERATED ALWAYS AS (coalesce(a, 0) + 1)", props)
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (1), (2)
+ | AS v(pk)) AS s
+ |ON t.pk = s.pk
+ |WHEN NOT MATCHED AND s.pk = 1 THEN INSERT (pk, part) VALUES (s.pk,
'p')
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p', NULL)
+ |""".stripMargin)
+ checkAnswer(spark.table(targetTableName),
+ Seq(Row(1, "p", 5, 10, 6), Row(2, "p", null, null, 1)))
+ }
+
+ testDML("DML generation uses stored expression settings and hides internal
metadata") { props =>
+ createTable("a STRING, g STRING GENERATED ALWAYS AS (concat(a,
'x\\\\y'))", props)
+ sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 'a')")
+ withSQLConf(SQLConf.ESCAPED_STRING_LITERALS.key -> "true") {
+ sql(s"UPDATE $targetTableName SET a = 'b'")
+ sql(s"""MERGE INTO $targetTableName t
+ |USING (SELECT * FROM VALUES (2, 'c')
+ | AS v(pk, a)) AS s ON t.pk = s.pk
+ |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p',
s.a)
+ |""".stripMargin)
+ }
+ checkAnswer(spark.table(targetTableName),
+ Seq(Row(1, "p", "b", "bx\\y"), Row(2, "p", "c", "cx\\y")))
+ assert(spark.table(targetTableName).schema.fields.forall(_.metadata.json
== "{}"))
+ }
+
+ testDML("DML generates values from stored CHAR values after padding") {
props =>
+ createTable("a CHAR(4), g STRING GENERATED ALWAYS AS (a)", props)
Review Comment:
**Nit (P3):** This is the suite's only CHAR case, and its generated column
is STRING. For a CHAR or VARCHAR generated column, UPDATE and MERGE cast the
computed value to the column type and add `resolveAssignment`'s write-side
length check, and the generated-column check then compares it with the
expression cast to STRING. INSERT reaches the same check through
`TableOutputResolver` and needed the 'SPARK-61495: generated CHAR/VARCHAR
values survive explicit validation' grid under
`spark.sql.preserveCharVarcharTypeInfo` and
`spark.sql.charVarchar.standardSemantics.enabled`. Running those cases through
UPDATE and MERGE here, for example `s CHAR(5)` with `b CHAR(5) GENERATED ALWAYS
AS (s)`, would give the row-level path a failure signal.
**Verification:**
- **Behavior:** Under each of spark.sql.preserveCharVarcharTypeInfo and
spark.sql.charVarchar.standardSemantics.enabled, for CHAR(5) and VARCHAR(5),
UPDATE t SET s = 'y' and a MERGE that updates one row and inserts another store
b equal to s with the type's padding, 'y ' for CHAR, and a MERGE that
supplies an agreeing b succeeds, in group, delta and split modes.
--
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]