This is an automated email from the ASF dual-hosted git repository.

dongjoon-hyun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new f3c88ce66394 [SPARK-61550][SQL] Fix writes leaving stale or mismatched 
values in legacy SQL-only generated columns
f3c88ce66394 is described below

commit f3c88ce66394a090c388a872509be81510e24d98
Author: Dongjoon Hyun <[email protected]>
AuthorDate: Thu Nov 12 16:33:45 2026 -0800

    [SPARK-61550][SQL] Fix writes leaving stale or mismatched values in legacy 
SQL-only generated columns
    
    ### What changes were proposed in this pull request?
    
    This PR adds `GeneratedColumn.columnGenerationExpression(col)`. It returns 
`Column.columnGenerationExpression()`, or a `GenerationExpression` of the 
legacy SQL getter `Column.generationExpression()` when a connector implements 
only that getter.
    
    ```scala
    def columnGenerationExpression(col: Column): Option[GenerationExpression] = 
{
      Option(col.columnGenerationExpression())
        .orElse(Option(col.generationExpression()).map(new 
GenerationExpression(_)))
    }
    ```
    
    Spark now uses it in the two places that read only 
`columnGenerationExpression()`:
    - `GeneratedColumn.supportsGeneratedColumnsOnWrite(table, columns)`. For 
tables with `GENERATE_COLUMN_VALUES_ON_WRITE`, it gates:
      - `RewriteRowLevelCommand.checkNoGeneratedColumns`, which rejects UPDATE 
and MERGE.
      - `ResolveWriteToStream`, which rejects streaming writes.
      - `TableConstraintResolution.buildGeneratedColumnConstraints`.
    - `TableConstraintResolution.buildGeneratedColumnConstraints`, which builds 
the checks of the values a write provides for generated columns.
    
    ### Why are the changes needed?
    
    A connector can define a generated column by overriding only 
`Column.generationExpression()`, the SQL getter that Spark 4.0.0 already has. 
`Column.columnGenerationExpression()`, added in 4.3.0, then returns `null` by 
default. For such a table with `GENERATE_COLUMN_VALUES_ON_WRITE`, Spark 
auto-fills the column on INSERT, because 
`GeneratedColumn.attachGenerationExpressions` reads the SQL getter. But the 
write checks read only `columnGenerationExpression()`, so a generated column 
could  [...]
    
    - UPDATE and MERGE were not rejected. Spark cannot recompute generated 
values for rewritten rows, which is why `checkNoGeneratedColumns` rejects these 
commands, so `UPDATE t SET a = 5` kept the old value of a column generated from 
`a`.
    - Streaming writes were not rejected.
    - INSERT accepted a provided value that does not match the generation 
expression, such as `INSERT INTO t(id, doubled) VALUES (1, 3)` when `doubled` 
is generated as `id * 2`.
    
    Apache Spark 4.3.0 
([v4.3.0](https://github.com/apache/spark/releases/tag/v4.3.0), 2026-10-27) has 
this behavior.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for connectors that report `GENERATE_COLUMN_VALUES_ON_WRITE` and 
implement only the legacy SQL getter of a generated column. These writes now 
fail, as they already do for columns defined with 
`columnGenerationExpression()`:
    - UPDATE, MERGE and streaming writes fail with 
`UNSUPPORTED_FEATURE.TABLE_OPERATION`.
    - INSERT with a value that does not match the generation expression fails 
with `CHECK_CONSTRAINT_VIOLATION`.
    
    In Spark 4.3.0, they ran and could leave generated values that do not match 
the generation expression.
    
    ### How was this patch tested?
    
    Pass the CIs with the newly added test cases in 
`GeneratedColumnWriteSuite`. All three fail without the fix, because no 
exception is thrown.
    - `SPARK-61550: INSERT validates a provided value of a legacy SQL-only 
generated column`
    - `SPARK-61550: streaming write with a legacy SQL-only generated column is 
blocked`
    - `SPARK-61550: UPDATE and MERGE with a legacy SQL-only generated column 
are blocked`. It also checks that INSERT auto-fills the column from the legacy 
getter.
    
    ```
    $ build/sbt 'sql/testOnly *GeneratedColumnWriteSuite'
    ...
    [info] Tests: succeeded 112, failed 0, canceled 0, ignored 0, pending 0
    ```
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60393 from dongjoon-hyun/SPARK-61550.
    
    Authored-by: Dongjoon Hyun <[email protected]>
    Signed-off-by: Dongjoon Hyun <[email protected]>
---
 .../analysis/TableConstraintResolution.scala       |  2 +-
 .../spark/sql/catalyst/util/GeneratedColumn.scala  | 16 +++-
 .../sql/connector/GeneratedColumnWriteSuite.scala  | 95 ++++++++++++++++++++++
 3 files changed, 109 insertions(+), 4 deletions(-)

diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala
index 56b43d3fdea1..e668217b89b1 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TableConstraintResolution.scala
@@ -94,7 +94,7 @@ private[sql] class TableConstraintResolution(
 
     // Use V2 columns from the table to access both V2 expressions and SQL 
strings.
     r.table.columns().flatMap { col =>
-      Option(col.columnGenerationExpression())
+      GeneratedColumn.columnGenerationExpression(col)
         .filter(_ => !autoFilledGenCols.exists(n => resolver(n, col.name)))
         .map { genExpr =>
           val catalystExpr = buildGenerationCatalystExpression(r, col.name, 
genExpr)
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala
index 574d4edb21bb..2866f8644993 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/GeneratedColumn.scala
@@ -19,8 +19,8 @@ package org.apache.spark.sql.catalyst.util
 
 import org.apache.spark.sql.catalyst.expressions.{Attribute, 
AttributeReference}
 import org.apache.spark.sql.catalyst.plans.logical.ColumnDefinition
-import org.apache.spark.sql.connector.catalog.{Column, Identifier, Table, 
TableCapability,
-  TableCatalog, TableCatalogCapability}
+import org.apache.spark.sql.connector.catalog.{Column, GenerationExpression, 
Identifier, Table,
+  TableCapability, TableCatalog, TableCatalogCapability}
 import org.apache.spark.sql.errors.QueryCompilationErrors
 import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
 import org.apache.spark.sql.types.{Metadata, MetadataBuilder, StructField, 
StructType}
@@ -109,6 +109,16 @@ object GeneratedColumn {
     
table.capabilities().contains(TableCapability.GENERATE_COLUMN_VALUES_ON_WRITE)
   }
 
+  /**
+   * Returns the generation expression of the V2 column `col`, if it is a 
generated column. A
+   * connector can implement only the legacy SQL getter 
[[Column.generationExpression]], which
+   * auto-fill reads as well, so fall back to it.
+   */
+  def columnGenerationExpression(col: Column): Option[GenerationExpression] = {
+    Option(col.columnGenerationExpression())
+      .orElse(Option(col.generationExpression()).map(new 
GenerationExpression(_)))
+  }
+
   /**
    * Whether the table supports generated columns on write (see
    * [[supportsGeneratedColumnsOnWrite]]) and the given columns include at 
least one generated
@@ -118,7 +128,7 @@ object GeneratedColumn {
       table: Table,
       columns: Array[Column]): Boolean = {
     supportsGeneratedColumnsOnWrite(table) &&
-      columns.exists(_.columnGenerationExpression() != null)
+      columns.exists(columnGenerationExpression(_).isDefined)
   }
 
   /**
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnWriteSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnWriteSuite.scala
index 7ea26d96eb39..0dab782046ef 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnWriteSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/connector/GeneratedColumnWriteSuite.scala
@@ -32,6 +32,7 @@ import 
org.apache.spark.sql.connector.catalog.functions.{ScalarFunction, Unbound
 import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, 
GeneralScalarExpression, Transform}
 import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
 import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.internal.connector.ColumnImpl
 import org.apache.spark.sql.types.{DataType, IntegerType, MetadataBuilder, 
StringType, StructType}
 import org.apache.spark.unsafe.types.UTF8String
 
@@ -62,6 +63,21 @@ class GeneratedColumnWriteSuite extends QueryTest with 
DatasourceV2SQLBase {
   // generated columns for it.
   private val noWriteCapProp = "generate-column-values-on-write"
 
+  // A generated column of a connector that implements only the legacy SQL 
getter.
+  private def legacyGeneratedColumn(name: String, dataType: DataType, sql: 
String): Column = {
+    new ColumnImpl(
+        name = name,
+        dataType = dataType,
+        nullable = true,
+        comment = null,
+        defaultValue = null,
+        columnGenerationExpression = null,
+        identityColumnSpec = null,
+        metadataInJSON = null) {
+      override def generationExpression(): String = sql
+    }
+  }
+
   private def hasCheckInvariant(sqlText: String): Boolean = {
     val parsed = spark.sessionState.sqlParser.parsePlan(sqlText)
     val analyzed = spark.sessionState.analyzer.executeAndCheck(parsed, new 
QueryPlanningTracker)
@@ -448,6 +464,23 @@ class GeneratedColumnWriteSuite extends QueryTest with 
DatasourceV2SQLBase {
     }
   }
 
+  test("SPARK-61550: INSERT validates a provided value of a legacy SQL-only 
generated column") {
+    val tblName = "my_tab"
+    withTable(s"testcat.$tblName") {
+      catalog("testcat").asTableCatalog.createTable(
+        Identifier.of(Array(), tblName),
+        Array(
+          Column.create("id", IntegerType),
+          legacyGeneratedColumn("doubled", IntegerType, "id * 2")),
+        Array.empty[Transform],
+        Collections.emptyMap[String, String])
+      val ex = intercept[SparkRuntimeException] {
+        sql(s"INSERT INTO testcat.$tblName(id, doubled) VALUES (1, 3)")
+      }
+      assert(ex.getCondition == "CHECK_CONSTRAINT_VIOLATION")
+    }
+  }
+
   test("SPARK-60764: INSERT by name with a double quote in the generation 
expression") {
     val tblName = "my_tab"
     withTable(s"testcat.$tblName") {
@@ -1349,6 +1382,30 @@ class GeneratedColumnWriteSuite extends QueryTest with 
DatasourceV2SQLBase {
     }
   }
 
+  test("SPARK-61550: streaming write with a legacy SQL-only generated column 
is blocked") {
+    import testImplicits._
+    val tblName = "my_tab"
+    withTable(s"testcat.$tblName") {
+      withTempDir { checkpointDir =>
+        catalog("testcat").asTableCatalog.createTable(
+          Identifier.of(Array(), tblName),
+          Array(
+            Column.create("id", IntegerType),
+            legacyGeneratedColumn("doubled", IntegerType, "id * 2")),
+          Array.empty[Transform],
+          Collections.emptyMap[String, String])
+        val df = MemoryStream[Int].toDF().toDF("id")
+        val ex = intercept[AnalysisException] {
+          df.writeStream
+            .option("checkpointLocation", checkpointDir.getAbsolutePath)
+            .toTable(s"testcat.$tblName")
+        }
+        assert(ex.getCondition == "UNSUPPORTED_FEATURE.TABLE_OPERATION")
+        assert(ex.getMessage.contains("streaming write with generated 
columns"))
+      }
+    }
+  }
+
   test("INSERT by position validates generated column with type cast on source 
column") {
     val tblName = "my_tab"
     withTable(s"testcat.$tblName") {
@@ -1476,6 +1533,44 @@ class GeneratedColumnWriteSuite extends QueryTest with 
DatasourceV2SQLBase {
     }
   }
 
+  test("SPARK-61550: UPDATE and MERGE with a legacy SQL-only generated column 
are blocked") {
+    val legacyCat = "legacycat"
+    // This catalog keeps the given columns, so the legacy getter reaches the 
analyzer.
+    withSQLConf(s"spark.sql.catalog.$legacyCat" ->
+        classOf[NonTransactionalRowLevelOperationCatalog].getName) {
+      val tblName = "my_tab"
+      withTable(s"$legacyCat.$tblName") {
+        catalog(legacyCat).asTableCatalog.createTable(
+          Identifier.of(Array(), tblName),
+          Array(
+            Column.create("id", IntegerType),
+            Column.create("data", StringType),
+            legacyGeneratedColumn("doubled", IntegerType, "id * 2")),
+          Array.empty[Transform],
+          Collections.emptyMap[String, String])
+        Seq(
+          "UPDATE" -> s"UPDATE $legacyCat.$tblName SET data = 'x' WHERE id = 
1",
+          "MERGE" ->
+            s"""MERGE INTO $legacyCat.$tblName AS t
+               |USING source AS s
+               |ON t.id = s.id
+               |WHEN MATCHED THEN UPDATE SET t.data = s.data
+               |""".stripMargin
+        ).foreach { case (command, sqlText) =>
+          val ex = intercept[AnalysisException] {
+            sql(sqlText)
+          }
+          assert(ex.getCondition == "UNSUPPORTED_FEATURE.TABLE_OPERATION")
+          assert(ex.getMessage.contains(s"$command with generated columns"))
+        }
+        // INSERT auto-fills the column from the legacy getter. Write last, 
because a write to
+        // this in-memory table rebuilds its columns with 
`columnGenerationExpression()`.
+        sql(s"INSERT INTO $legacyCat.$tblName(id, data) VALUES (1, 'a')")
+        checkAnswer(spark.table(s"$legacyCat.$tblName"), Row(1, "a", 2))
+      }
+    }
+  }
+
   test("DELETE with generated columns is allowed") {
     withRowLevelCatalog {
       val tblName = "my_tab"


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to