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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RowLevelAssignmentResolution.scala:
##########
@@ -64,24 +67,117 @@ 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.
+   * UPDATE and projection-based insert-only MERGE project shared assignment 
values in the rewrite.
+   * Explicitly supplied generated values pass through for validation against 
the final row.
+   */
+  def resolveGeneratedColumnAssignments(
+      table: LogicalPlan,
+      assignments: Seq[Assignment],
+      analyze: LogicalPlan => LogicalPlan,
+      shareAssignedValues: Boolean = true): Seq[Assignment] = {
+    if 
(!assignments.exists(_.value.isInstanceOf[GeneratedColumnAssignmentValue])) {
+      return assignments
+    }
+
+    val relation = table.collectFirst { case r: DataSourceV2Relation => r }.get
+    val generationExpressions = GeneratedColumn.expressionReaders(relation)
+    // For the example above, pair a with Alias(old.b + 1, "a") and b with 
Alias(100, "b").
+    // Each alias has a fresh attribute ID, distinct from the original table 
column.
+    val assigned = assignments.collect {
+      case Assignment(attr: Attribute, value)
+          if !value.isInstanceOf[GeneratedColumnAssignmentValue] =>
+        attr -> Alias(value, attr.name)()

Review Comment:
   **Non-blocking (P2):** For a column the action leaves unassigned, `value` is 
the raw target attribute, so this alias inherits its CHAR metadata and the 
post-hoc `ApplyCharTypePadding` pads comparisons on that column in the 
generation expression. INSERT resolves the same expression over its 
stored-value projection, whose aliases carry no CHAR metadata, so it compares 
without padding. Reading the code, for `c CHAR(4)` and a `BOOLEAN` column `g` 
with the SQL text `c = 'ab'`, inserting `c = 'ab'` stores `'ab  '` and `g = 
false`, while `UPDATE t SET v = 1` recomputes `g` as `c = rpad('ab', 4)`, which 
is true. The check is analyzed over the write's output, which has no CHAR 
metadata in a group-based or split UPDATE and in every MERGE, so those 
statements fail with CHECK_CONSTRAINT_VIOLATION on `g`, a column they never 
set; a delta UPDATE keeps the metadata in its output, so it stores `g = true`, 
and a later write that carries the row, such as `INSERT ... SELECT`, fails the 
check. This a
 ffects any generation expression that compares an unassigned CHAR column with 
a string literal or a CHAR column of another length, or tests it with IN, on 
rows where padding changes the result; assigning the CHAR column in the same 
statement avoids it.
   
   **Recommended change:** In resolveGeneratedColumnAssignments, give each 
alias attribute that a generation expression is resolved against its column's 
metadata with the CHAR and VARCHAR entries removed, as 
CharVarcharUtils.cleanMetadata does, so that an unassigned CHAR column reads 
like the stored value INSERT reads. In buildGeneratedColumnConstraints, analyze 
the checks of UPDATE and MERGE writes against the write query's output 
attributes with the same entries removed, and resolve the session-fallback form 
of such a check against those attributes before returning it, as 
ExpressionReader.resolve does for computed values. Add UPDATE and MERGE cases 
to the generated-column DML tests in which a generation expression compares an 
unassigned CHAR column.
   
   **Why this works:** ApplyCharTypePadding pads a comparison only for an 
attribute whose metadata records a CHAR type. Removing that metadata from both 
analysis inputs makes the computed value and its check read the stored CHAR 
value exactly as INSERT's stored-value projection does, so the computed value 
matches the one INSERT stores for the same row and passes the check in every 
write mode, also when a later write carries the row.
   
   **Compatibility:** INSERT keeps computing and checking generated values as 
on the base branch, and the rewrites keep the metadata of their output columns, 
which table CHECK constraints read.
   
   **Risks:** The check of a delta UPDATE that is not split into deletes and 
inserts stops applying CHAR comparison padding to unassigned CHAR columns, so a 
generated value that such an UPDATE supplies is compared as INSERT compares it; 
only these newly supported statements reach that check, and no flag gates the 
change.
   
   **Constraints:** Keep checking every computed generated value whose type the 
check can compare, as this pull request does; the fix for uncomparable 
generated column types removes only the checks that cannot be built. Leave 
INSERT's computation and checks, and the metadata of the rewrites' output 
attributes, unchanged. Apply the cleaning to modeled expressions, SQL text and 
the session fallback alike.
   
   **Exclusions:**
   - Whether INSERT should apply CHAR comparison semantics to a generation 
expression: INSERT keeps computing the value it computes on the base branch, 
and the row-level path is made to match it.
   
   **Verification:**
   - **Regression:** On a table with c CHAR(4) and a BOOLEAN generated column 
whose SQL text is c = 'ab', with a row inserted with c = 'ab', UPDATE t SET v = 
1 and a MERGE UPDATE action that sets only v succeed in group-based, delta and 
split-update modes and keep the generated value INSERT stored, and an INSERT 
... SELECT that carries the row with its generated value then passes the check.
   - **Regression:** The same holds when the generation expression is c IN 
('ab', 'cd'), when it compares c with a CHAR column of another length, and when 
it is a modeled expression.
   - **Compatibility:** Generated values that read an assigned CHAR column, 
CHAR and VARCHAR generated columns under spark.sql.preserveCharVarcharTypeInfo 
and spark.sql.charVarchar.standardSemantics.enabled, and INSERT auto-fill and 
validation keep their current results.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala:
##########
@@ -123,10 +125,9 @@ private[sql] class TableConstraintResolution(
 
     // Use V2 columns from the table to access both V2 expressions and SQL 
strings.
     r.table.columns().flatMap { col =>
-      GeneratedColumn.columnGenerationExpression(col)
+      generationExpressions.get(col.name)

Review Comment:
   **Non-blocking (P2):** For UPDATE and MERGE writes this selects every 
generated column for a check, including the values Spark computed, because only 
`WriteOutputResolution` marks auto-filled columns. The check is `<=>`, which 
needs an orderable type, so it can never resolve for a generated column whose 
type `OrderUtils.isOrderable` rejects, such as MAP, VARIANT, GEOMETRY or 
GEOGRAPHY, or a struct or array containing one. Reading the code, for `m 
MAP<STRING, INT> GENERATED ALWAYS AS (map('k', a))`, `INSERT INTO t (pk, a) 
VALUES (1, 1)` fills `m` without a check, but `UPDATE t SET a = 2` and every 
MERGE, including one whose only action is DELETE, fail at analysis in every 
write mode: with DATATYPE_MISMATCH on `<=>` for SQL text, or with 
INVALID_GENERATED_COLUMN_EXPRESSION for a modeled expression. Such tables still 
cannot run UPDATE or MERGE, now with an error about an internal comparison on a 
column the statement never set; tables whose generated columns are all 
orderable are unaf
 fected.
   
   **Recommended change:** When ResolveRowLevelCommandAssignments aligns an 
UPDATE or a MERGE on a table whose generated columns Spark computes, collect 
the generated columns whose type fails RowOrdering.isOrderable, the test that 
<=> applies, which rejects MAP, VARIANT, GEOMETRY and GEOGRAPHY and a struct or 
array containing one, and that no UPDATE or INSERT action of the statement 
assigns, whether directly, through a nested field or through a star action. 
Mark those columns as auto-filled with 
GeneratedColumn.markAutoFilledGeneratedColumns on the target relation the rule 
returns, copying the relation and mapping its metadata columns as 
cleanAttrMetadata already does when it removes CHAR metadata, so that the write 
relations RewriteUpdateTable and RewriteMergeIntoTable derive from it carry the 
mark and buildGeneratedColumnConstraints builds no check for those columns, as 
it does for INSERT. Update the buildGeneratedColumnConstraints scaladoc and the 
sentence of the SPARK-60757 migra
 tion note that says UPDATE and MERGE check every generated column of updated 
or inserted rows, and add UPDATE and MERGE cases with MAP, VARIANT and 
struct-of-MAP generated columns to the generated-column DML tests.
   
   **Why this works:** The auto-filled mark is the existing contract between 
write resolution and the check builder: a marked column holds a value Spark 
computed from its generation expression, so no check is built for it. Limiting 
the mark to columns whose type fails the orderability test of <=> and that 
every UPDATE and INSERT action leaves to Spark keeps the validation of computed 
values for every type the check can compare, and leaves a supplied value of 
such a type to the check, which fails the statement at analysis exactly as an 
INSERT that provides that value does. Selecting the columns with the same test 
that <=> applies covers every type the check rejects, not only the types named 
here.
   
   **Compatibility:** UPDATE and MERGE keep checking every generated column 
whose type <=> can compare, including the values Spark computes, and INSERT 
keeps marking only the columns it auto-fills.
   
   **Risks:** The auto-filled mark also lands on the attributes of the relation 
the rewrite reads, as internal metadata that removeInternalMetadata strips from 
exposed schemas and that only buildGeneratedColumnConstraints reads; no flag 
gates the change, which affects only tables with a generated column whose type 
<=> cannot compare.
   
   **Constraints:** Mark only generated columns whose type fails the 
orderability test that <=> applies and that no UPDATE or INSERT action of the 
statement assigns, whether directly, through a nested field, or through a star 
action. Keep the check for every other generated column, including the values 
Spark computes. Leave commands whose assignments are already aligned and tables 
that accept any schema unmarked, so their generated columns keep the checks 
they get today.
   
   **Exclusions:**
   - Validating a supplied value for a generated column whose type <=> cannot 
compare: an UPDATE or MERGE action that supplies one keeps failing at analysis, 
as an INSERT that provides one does.
   
   **Verification:**
   - **Regression:** On a table with a MAP generated column computed as 
map('k', a), a VARIANT generated column computed as parse_json(s) and a struct 
generated column that contains a MAP, an UPDATE that sets a and s and a MERGE 
whose actions omit all three generated columns succeed and store the generated 
values in group-based, delta and split-update modes, and a MERGE whose only 
action is DELETE succeeds too.
   - **Behavior:** An UPDATE or MERGE action that assigns the MAP generated 
column fails at analysis, as an INSERT that provides it does.
   - **Compatibility:** On a table whose generated columns all have comparable 
types, an UPDATE or MERGE that supplies a disagreeing generated value still 
fails with CHECK_CONSTRAINT_VIOLATION, and the analyzed write still carries a 
generated-column check for every such column, including the ones Spark computes.
   - **Inspection:** The generated columns that get no check are selected with 
RowOrdering.isOrderable, the test that <=> applies, rather than with a list of 
types.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -1818,6 +1818,14 @@ class Analyzer(
             def findAttrInTarget(name: String): Option[Attribute] = {
               targetTable.output.find(targetAttr => conf.resolver(name, 
targetAttr.name))
             }
+            val generatedColumns = targetTable.collectFirst {

Review Comment:
   **Nit (P3):** `generatedColumns` and `starTargetAttrs` are computed eagerly 
on every pass of this MERGE case, but only the `UPDATE SET *` and `INSERT *` 
expansions without schema evolution read them (lines 1856 and 1896). For a 
table that advertises `GENERATE_COLUMN_VALUES_ON_WRITE`, 
`GeneratedColumn.generationExpressions` calls `Table.columns()`, so, reading 
the code, a MERGE without a star action on such a table, even one with no 
generated column, now makes one more `Table.columns()` call per resolution 
pass: three for a typical statement, where the base branch made two. Nothing 
consumes that result. The cost is bounded and limited to analysis, and making 
both values `lazy` removes it without changing which columns star actions leave 
out.
   
   **Verification:**
   - **Inspection:** The MERGE case of ResolveReferences evaluates the 
generated-column lookup and the filtered target attributes only inside the 
UPDATE SET * and INSERT * expansions without schema evolution, and reads the 
source output once per expansion.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/AssignmentUtils.scala:
##########
@@ -107,13 +117,15 @@ 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 names of the target table's top-level generated 
columns

Review Comment:
   **Nit (P3):** This entry, like the one for `alignUpdateAssignments` at line 
66, says the set holds the target table's top-level generated columns, but both 
helpers need only the generated columns whose values Spark computes on write. 
Each name makes alignment emit a `GeneratedColumnAssignmentValue` for an 
omitted column, which `resolveGeneratedColumnAssignments` replaces through 
`GeneratedColumn.expressionReaders`, a map that is empty for a table without 
`GENERATE_COLUMN_VALUES_ON_WRITE`; in this method a non-empty set also stops 
omitted nullable ordinary columns from defaulting to NULL unless 
`spark.sql.generatedColumn.allowNullableIngest.enabled` is on. Reading the 
code, a caller that followed this doc for a connector that computes its own 
generated values, like the table in 'MERGE keeps nullable ingest for connectors 
that compute generated values', would get a `NoSuchElementException` for an 
omitted generated column, and that test's MERGE would fail with "No assignment 
for 'b'"
  instead of writing NULL. Both current callers pass 
`GeneratedColumn.generationExpressions(table).keySet`, so nothing misbehaves 
today. This wording follows the previous review's suggestion, which was broader 
than the contract.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/60560#discussion_r4594657918).
   
   **Verification:**
   - **Inspection:** The generatedColumns documentation of both alignment 
helpers names the generated columns whose values Spark computes on write rather 
than every generated column, and the alignInsertAssignments entry states that a 
non-empty set requires spark.sql.generatedColumn.allowNullableIngest.enabled 
for NULL filling.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnDMLSuite.scala:
##########
@@ -0,0 +1,790 @@
+/*
+ * 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}
+import org.apache.spark.tags.DataSourceV2Test
+
+@DataSourceV2Test
+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 shares fresh nondeterministic assignments with generated 
values") { props =>
+    createTable("id STRING, g STRING GENERATED ALWAYS AS (upper(id))", props)
+    sql(s"INSERT INTO $targetTableName (pk, part, id) VALUES (1, 'p', 'a'), 
(2, 'p', 'b')")
+    Seq("", "WHERE pk = 1", "WHERE pk IN (SELECT 1)").foreach { condition =>
+      sql(s"""UPDATE $targetTableName
+             |SET id = reflect('java.util.UUID', 'randomUUID') $condition
+             |""".stripMargin)
+      checkAnswer(sql(s"SELECT g <=> upper(id) FROM $targetTableName"), 
Seq(Row(true), Row(true)))
+    }
+  }
+
+  testDML("UPDATE shares random assignments with conditional generated 
values") { props =>
+    createTable("a DOUBLE, b INT, g DOUBLE GENERATED ALWAYS AS (IF(b > 0, a, 
0))", props)
+    sql(s"""INSERT INTO $targetTableName (pk, part, a, b)
+           |SELECT id, 'p', 0.5D, IF(id % 2 = 0, 1, -1) FROM range(0, 12, 1, 1)
+           |""".stripMargin)
+    sql(s"UPDATE $targetTableName SET a = rand(17)")
+    checkAnswer(sql(s"SELECT g <=> IF(b > 0, a, 0) FROM $targetTableName"),
+      Seq.fill(12)(Row(true)))
+  }
+
+  testDML("UPDATE evaluates a shared deterministic UDF once per updated row") 
{ 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)")
+    val calls = spark.sparkContext.longAccumulator
+    withUserDefinedFunction("count_assignment" -> true) {
+      spark.udf.register("count_assignment", (value: Int) => {
+        calls.add(1)
+        value + 1
+      })
+      Seq("pk = 1", "pk IN (SELECT 1)").foreach { condition =>
+        calls.reset()
+        sql(s"UPDATE $targetTableName SET a = count_assignment(a) WHERE 
$condition")
+        assert(calls.value == 1L)
+      }
+    }
+    checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 3, 6), Row(2, 
"p", 2, 4)))
+  }
+
+  Seq("pk = 1", "pk IN (SELECT 1)").foreach { condition =>
+    testDML(s"UPDATE guards shared assignments on copied rows ($condition)") { 
props =>
+      createTable("a INT, g INT GENERATED ALWAYS AS (a * 2)", props)
+      sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 2), (2, 
'p', 0)")
+      sql(s"UPDATE $targetTableName SET a = 10 DIV a WHERE $condition")
+      checkAnswer(spark.table(targetTableName), Seq(Row(1, "p", 5, 10), Row(2, 
"p", 0, 0)))
+    }
+  }
+
+  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 WHERE pk = 1")
+    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(s"insert-only MERGE rejects invalid generated values 
($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 lastAction = if (multipleActions) {
+        "WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p', s.a)"
+      } else {
+        ""
+      }
+      val error = intercept[Exception] {
+        sql(s"""MERGE INTO $targetTableName t
+               |USING (SELECT * FROM VALUES (2, 20) AS v(pk, a)) s ON t.pk = 
s.pk
+               |WHEN NOT MATCHED AND s.pk = 2
+               |  THEN INSERT (pk, part, a, g) VALUES (s.pk, 'p', s.a, 999)
+               |$lastAction
+               |""".stripMargin)
+      }
+      assert(error.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+      checkAnswer(spark.table(targetTableName), Row(1, "p", 1, 2))
+    }
+  }
+
+  testDML("insert-only MERGE shares nondeterministic assignments with 
generated values") { props =>
+    createTable("id STRING, a DOUBLE, b INT, " +
+      "g STRING GENERATED ALWAYS AS (upper(id)), " +
+      "h DOUBLE GENERATED ALWAYS AS (IF(b > 0, a, 0))", props)
+    sql(s"""MERGE INTO $targetTableName t
+           |USING (SELECT id AS pk FROM range(0, 12, 1, 1)) s ON t.pk = s.pk
+           |WHEN NOT MATCHED THEN INSERT (pk, part, id, a, b)
+           |  VALUES (s.pk, 'p', reflect('java.util.UUID', 'randomUUID'),
+           |    rand(17), IF(s.pk % 2 = 0, 1, -1))
+           |""".stripMargin)
+    checkAnswer(sql(s"""SELECT g <=> upper(id), h <=> IF(b > 0, a, 0)
+                       |FROM $targetTableName""".stripMargin), 
Seq.fill(12)(Row(true, true)))
+  }
+
+  testDML("UPDATE validates nested assignments to generated structs") { props 
=>
+    createTable("a INT, " +
+      "g STRUCT<x: INT, y: INT> GENERATED ALWAYS AS (named_struct('x', a, 'y', 
a + 1))", props)
+    sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 1)")
+    val error = intercept[Exception] {
+      sql(s"UPDATE $targetTableName SET g.x = 999")
+    }
+    assert(error.getMessage.contains("CHECK_CONSTRAINT_VIOLATION"))
+    checkAnswer(spark.table(targetTableName), Row(1, "p", 1, Row(1, 2)))
+    sql(s"UPDATE $targetTableName SET g.x = a")
+    checkAnswer(spark.table(targetTableName), Row(1, "p", 1, Row(1, 2)))
+  }
+
+  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)))
+  }
+
+  Seq(false, true).foreach { allowNullable =>
+    testDML(s"MERGE respects nullable ingest for missing ordinary columns 
($allowNullable)") {
+      props =>
+        createTable("a INT, b STRING, g INT GENERATED ALWAYS AS (a * 2)", 
props)
+        sql(s"INSERT INTO $targetTableName (pk, part, a, b) VALUES (1, 'p', 1, 
'present')")
+        withSQLConf(SQLConf.GENERATED_COLUMN_ALLOW_NULLABLE_INGEST.key -> 
allowNullable.toString) {
+          val insert = s"INSERT INTO $targetTableName (pk, part, a) VALUES (2, 
'p', 2)"
+          if (!allowNullable) {
+            intercept[AnalysisException] { sql(insert) }
+          }
+          Seq("single", "multiple", "full", "star").foreach { shape =>
+            val extraAction = shape match {
+              case "multiple" =>
+                "WHEN NOT MATCHED AND s.pk < 0 " +
+                  "THEN INSERT (pk, part, a) VALUES (s.pk, s.part, s.a)"
+              case "full" => "WHEN MATCHED THEN UPDATE SET a = s.a"
+              case _ => ""
+            }
+            val merge = if (shape == "star") "MERGE WITH SCHEMA EVOLUTION" 
else "MERGE"
+            val insertAction = if (shape == "star") {
+              "WHEN NOT MATCHED THEN INSERT *"
+            } else {
+              "WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 
s.part, s.a)"
+            }
+            val statement = s"""$merge INTO $targetTableName t
+                               |USING (SELECT 2 AS pk, 'q' AS part, 2 AS a) s 
ON t.pk = s.pk
+                               |$extraAction
+                               |$insertAction
+                               |""".stripMargin
+            if (allowNullable) {
+              sql(statement)
+              checkAnswer(spark.table(targetTableName),
+                Seq(Row(1, "p", 1, "present", 2), Row(2, "q", 2, null, 4)))
+              sql(s"DELETE FROM $targetTableName WHERE part = 'q'")
+            } else {
+              val error = intercept[AnalysisException] { sql(statement) }
+              assert(error.getCondition ==
+                "DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS")
+              assert(error.getMessage.contains("No assignment for 'b'"))
+            }
+          }
+        }
+    }
+
+    testDML(s"MERGE preserves declared defaults with nullable ingest 
$allowNullable") { props =>
+      createTable("a INT, b STRING DEFAULT 'default', g INT GENERATED ALWAYS 
AS (a * 2)", props)
+      withSQLConf(SQLConf.GENERATED_COLUMN_ALLOW_NULLABLE_INGEST.key -> 
allowNullable.toString) {
+        sql(s"""MERGE INTO $targetTableName t USING (SELECT 1 AS pk) s ON t.pk 
= s.pk
+               |WHEN NOT MATCHED THEN INSERT (pk, part, a) VALUES (s.pk, 'p', 
2)
+               |""".stripMargin)
+      }
+      checkAnswer(spark.table(targetTableName), Row(1, "p", 2, "default", 4))
+    }
+  }
+
+  testDML("MERGE keeps nullable ingest for connectors that compute generated 
values") { props =>
+    createTable("a INT, b STRING, g INT GENERATED ALWAYS AS (a * 2)",
+      props + ("generate-column-values-on-write" -> "false"))
+    withSQLConf(SQLConf.GENERATED_COLUMN_ALLOW_NULLABLE_INGEST.key -> "false") 
{
+      sql(s"""MERGE INTO $targetTableName t USING (SELECT 1 AS pk) s ON t.pk = 
s.pk
+             |WHEN NOT MATCHED THEN INSERT (pk, part, a, g) VALUES (s.pk, 'p', 
2, 999)
+             |""".stripMargin)
+    }
+    checkAnswer(spark.table(targetTableName), Row(1, "p", 2, null, 999))
+  }
+
+  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)
+    sql(s"INSERT INTO $targetTableName (pk, part, a) VALUES (1, 'p', 'ab')")
+    sql(s"UPDATE $targetTableName SET a = 'cd'")
+    checkAnswer(spark.table(targetTableName), Row(1, "p", "cd  ", "cd  "))
+    sql(s"""MERGE INTO $targetTableName t
+           |USING (SELECT * FROM VALUES (1, 'e'), (2, 'f')
+           |  AS v(pk, a)) AS 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)
+    checkAnswer(spark.table(targetTableName),
+      Seq(Row(1, "p", "e   ", "e   "), Row(2, "p", "f   ", "f   ")))
+  }
+
+  for {
+    config <- Seq(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key,
+      SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS.key)
+    dataType <- Seq("CHAR(5)", "VARCHAR(5)")
+  } {
+    testDML(s"DML validates generated $dataType values with $config") { props 
=>
+      withSQLConf(config -> "true") {
+        createTable(s"s $dataType, b $dataType GENERATED ALWAYS AS (s)", props)
+        def padded(value: String): String = if (dataType.startsWith("CHAR")) {
+          value.padTo(5, ' ')
+        } else {
+          value
+        }
+        sql(s"INSERT INTO $targetTableName (pk, part, s) VALUES (1, 'p', 'x')")
+        sql(s"UPDATE $targetTableName SET s = 'y'")
+        checkAnswer(spark.table(targetTableName), Row(1, "p", padded("y"), 
padded("y")))
+        sql(s"""MERGE INTO $targetTableName t
+               |USING (SELECT * FROM VALUES (1, 'z'), (2, 'w') AS v(pk, s)) s 
ON t.pk = s.pk
+               |WHEN MATCHED THEN UPDATE SET s = s.s
+               |WHEN NOT MATCHED THEN INSERT (pk, part, s) VALUES (s.pk, 'p', 
s.s)
+               |""".stripMargin)
+        checkAnswer(spark.table(targetTableName),
+          Seq(Row(1, "p", padded("z"), padded("z")), Row(2, "p", padded("w"), 
padded("w"))))
+        sql(s"""MERGE INTO $targetTableName t
+               |USING (SELECT * FROM VALUES (1, 'v'), (3, 'u') AS v(pk, s)) s 
ON t.pk = s.pk
+               |WHEN MATCHED THEN UPDATE SET s = s.s, b = s.s
+               |WHEN NOT MATCHED THEN INSERT (pk, part, s, b) VALUES (s.pk, 
'p', s.s, s.s)
+               |""".stripMargin)
+        checkAnswer(spark.table(targetTableName), Seq(
+          Row(1, "p", padded("v"), padded("v")), Row(2, "p", padded("w"), 
padded("w")),
+          Row(3, "p", padded("u"), padded("u"))))
+      }
+    }
+  }
+
+  testDML("DML preserves copied generated values after the session time zone 
changes") { props =>
+    createTable("a INT, ts TIMESTAMP, d DATE GENERATED ALWAYS AS (CAST(ts AS 
DATE))", props)
+    withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "America/Los_Angeles") {
+      sql(s"""INSERT INTO $targetTableName (pk, part, a, ts) VALUES
+             |(1, 'p', 0, TIMESTAMP'2024-01-01 20:00:00'),
+             |(2, 'p', 0, TIMESTAMP'2024-01-01 10:00:00')
+             |""".stripMargin)
+    }
+    withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+      sql(s"UPDATE $targetTableName SET a = 1 WHERE pk = 2")

Review Comment:
   **Nit (P3):** These statements update only pk = 2, whose 
`TIMESTAMP'2024-01-01 10:00:00'` written in America/Los_Angeles is still 
2024-01-01 in UTC, so the recomputed `d` equals the stored one. Every other 
UPDATE and MERGE UPDATE case in the suite assigns an input of each generated 
column it recomputes, or recomputes the constant `h GENERATED ALWAYS AS (1)`. A 
change that kept the stored value of an omitted generated column whenever an 
action assigns none of its inputs would therefore pass every assertion, 
although the new `TableCapability` Javadoc says Spark recomputes omitted values 
from the new row. Updating pk = 1 without assigning `ts` or `d` tells the two 
apart: reading the code, the implementation stores 2024-01-02 in a UTC session, 
while a keep-stored-value change would fail the check with 
CHECK_CONSTRAINT_VIOLATION.
   
   **Verification:**
   - **Behavior:** After rows are inserted in America/Los_Angeles with a DATE 
column generated from a TIMESTAMP column, an UPDATE in a UTC session that 
assigns neither the timestamp nor the date of the row whose timestamp falls on 
another UTC date stores the UTC date, and a MERGE UPDATE action that assigns 
neither does the same, in group-based, delta and split-update 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]

Reply via email to