anuragmantri commented on code in PR #55518:
URL: https://github.com/apache/spark/pull/55518#discussion_r4570711753


##########
sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryRowLevelOperationTable.scala:
##########
@@ -273,6 +335,426 @@ class InMemoryRowLevelOperationTable private (
     override def abort(messages: Array[WriterCommitMessage]): Unit = {}
   }
 
+  // The rows of `buf` in the table's current schema, matched to columns by 
name like a scan does.
+  private def currentRows(buf: BufferedRows): Seq[InternalRow] = {
+    val reader = new BufferedRowsReader(buf, Seq.empty, schema.fields.toSeq, 
schema)
+    try {
+      
Iterator.continually(reader).takeWhile(_.next()).map(_.get().copy()).toList
+    } finally {
+      reader.close()
+    }
+  }
+
+  // Spark resolves a row-ID reference such as `pk` against a column such as 
`PK`, so look a name
+  // up exactly first and then case-insensitively, in the same order.
+  private def findFieldIndex(s: StructType, name: String): Option[Int] =
+    s.getFieldIndex(name).orElse(s.getFieldIndexCaseInsensitive(name))
+
+  private def fieldIndexOf(s: StructType, name: String): Int =
+    findFieldIndex(s, name).getOrElse(s.fieldIndex(name))
+
+  // Finds the one current row with the given row-ID values, matching a data 
column by value and
+  // `_partition` by the partition key.
+  private def currentRowByRowId(values: Seq[(String, Any)]): InternalRow = {
+    val matches = dataMap.values.iterator.flatten.flatMap { buf =>
+      currentRows(buf).filter { row =>
+        values.forall {
+          case (name, value) if name.equalsIgnoreCase(PartitionKeyColumn.name) 
=>
+            buf.keyString() == value.toString
+          case (name, value) =>
+            val i = fieldIndexOf(schema, name)
+            row.get(i, schema.fields(i).dataType) == value
+        }
+      }
+    }.toSeq
+    matches match {
+      case Seq(row) => row
+      case _ => throw new IllegalStateException(
+        s"Expected one row with row ID $values, found ${matches.size}")
+    }
+  }
+
+  // Rebuilds a full table row for a narrow column-update row: the base row's 
values overlaid with
+  // the narrow row's columns. The base row is in the table's current schema.
+  private def overlayNarrowRow(
+      baseRow: Option[InternalRow],
+      narrowRow: InternalRow,
+      narrowSchema: StructType): InternalRow = {
+    val fullRow = new GenericInternalRow(schema.length)
+    baseRow.foreach { base =>
+      for (i <- schema.fields.indices) {
+        val field = schema.fields(i)
+        fullRow.update(i, base.get(i, field.dataType))
+      }
+    }
+    schema.fields.zipWithIndex.foreach { case (field, i) =>
+      narrowSchema.getFieldIndex(field.name).foreach { j =>
+        fullRow.update(i, narrowRow.get(j, field.dataType))
+      }
+    }
+    fullRow
+  }
+
+  private def requiredColumns(prop: String): Array[String] =
+    prop.split(",").map(_.trim).filter(_.nonEmpty)
+
+  // The base columns `pk` and `dep`, where the table has them, followed by 
the updated columns.
+  private def declaredColumns(updatedCols: Seq[NamedReference]): 
Seq[NamedReference] = {
+    val base = Seq("pk", "dep").flatMap(findFieldIndex(schema, _))
+      .map(i => FieldReference(schema.fields(i).name))
+    val baseNames = base.map(_.describe()).toSet
+    base ++ updatedCols.filterNot(r => baseNames.contains(r.describe()))
+  }
+
+  // A delta-based operation that supports column-level updates: Spark sends 
only the declared
+  // columns in the row projection instead of the full row schema.
+  class DeltaBasedColumnUpdateOperation(
+      command: Command,
+      declared: Seq[NamedReference],
+      options: CaseInsensitiveStringMap = CaseInsensitiveStringMap.empty())
+      extends DeltaBasedOperation(command, options)
+        with SupportsColumnUpdates {
+    override def representUpdateAsDeleteAndInsert(): Boolean = false
+    override def requiredDataAttributes(): Array[NamedReference] = 
declared.toArray
+
+    // The case-class equality of DeltaBasedOperation would make this 
operation equal to a wide
+    // one, or to another column-update operation, with the same command and 
options.
+    override def equals(other: Any): Boolean = other match {
+      case ref: AnyRef => this eq ref
+      case _ => false
+    }
+    override def hashCode(): Int = System.identityHashCode(this)
+    override def canEqual(other: Any): Boolean = false
+
+    private def writeRequirementRefs(key: String): Option[Seq[Expression]] =
+      
Option(properties.get(key)).map(requiredColumns(_).map(FieldReference(_)).toSeq)
+
+    private def withNestedTransforms(refs: Seq[Expression]): Seq[Expression] = 
{
+      if (properties.getOrDefault(COLUMN_UPDATE_CLUSTER_BY_NESTED_TRANSFORM, 
"false") == "true") {
+        refs.map(ref => LogicalExpressions.apply("f", 
LogicalExpressions.apply("g", ref)))
+      } else {
+        refs
+      }
+    }
+
+    private val clusterExprs: Seq[Expression] = withNestedTransforms(
+      
writeRequirementRefs(COLUMN_UPDATE_CLUSTER_BY).getOrElse(Seq(PARTITION_COLUMN_REF)))
+
+    private val orderExprs: Seq[Expression] =
+      
writeRequirementRefs(COLUMN_UPDATE_ORDER_BY).map(withNestedTransforms).getOrElse(clusterExprs)
+
+    override def newWriteBuilder(info: LogicalWriteInfo): DeltaWriteBuilder = {
+      lastWriteInfo = info
+      val writeSchema = info.columnUpdateSchema().orElse(info.schema())
+      val batchWrite = new TestBatchWrite with DeltaBatchWrite {
+        override def createBatchWriterFactory(
+            physicalInfo: PhysicalWriteInfo): DeltaWriterFactory = {
+          newWriterFactory(info, writeSchema)
+        }
+
+        override protected def doCommit(messages: Array[WriterCommitMessage]): 
Unit =
+          dataMap.synchronized {
+            val newData = messages.map(_.asInstanceOf[BufferedRows])
+            commitColumnUpdate(info, writeSchema, newData)
+          }
+
+        override def abort(messages: Array[WriterCommitMessage]): Unit = {}
+      }
+      new DeltaWriteBuilder {
+        override def build(): DeltaWrite =
+          if (noMetadata && !properties.containsKey(COLUMN_UPDATE_CLUSTER_BY)) 
{
+            new DeltaWrite {
+              override def toBatch: DeltaBatchWrite = batchWrite
+            }
+          } else {
+            new DeltaWrite with RequiresDistributionAndOrdering {
+
+              override def requiredDistribution(): Distribution = {
+                Distributions.clustered(clusterExprs.toArray)
+              }
+
+              override def requiredOrdering(): Array[SortOrder] = {
+                orderExprs.map { expr =>
+                  LogicalExpressions.sort(
+                    expr,
+                    SortDirection.ASCENDING,
+                    SortDirection.ASCENDING.defaultNullOrdering()): SortOrder
+                }.toArray
+              }
+
+              override def toBatch: DeltaBatchWrite = batchWrite
+            }
+          }
+      }
+    }
+
+    protected def newWriterFactory(
+        info: LogicalWriteInfo,
+        writeSchema: StructType): DeltaWriterFactory = {
+      new DeltaBufferedRowsWriterFactory(writeSchema)
+    }
+
+    // For column-update writes, updated rows contain only the declared columns
+    // (columnUpdateSchema from LogicalWriteInfo). We expand each row to the 
full
+    // table schema by overlaying them on the base row found by pk.
+    protected def commitColumnUpdate(
+        info: LogicalWriteInfo,
+        writeSchema: StructType,
+        newData: Array[BufferedRows]): Unit = {
+      val updateOpName = UTF8String.fromString(Update.toString)
+      val insertOpName = UTF8String.fromString(Insert.toString)
+
+      val mergedData = newData.map { buf =>
+        val merged = new BufferedRows(buf.key, schema)
+        buf.log.foreach { logRow =>
+          val opName = logRow.getUTF8String(0)
+          if (opName == updateOpName) {
+            val pk = logRow.getInt(1)
+            val narrowRow = logRow.get(3, 
writeSchema).asInstanceOf[InternalRow]
+            val baseRow = Some(currentRowByRowId(Seq("pk" -> pk)))
+            val fullRow = overlayNarrowRow(baseRow, narrowRow, writeSchema)
+            merged.rows.append(fullRow)
+          } else if (opName == insertOpName) {
+            // INSERT rows arrive with the full table schema via 
writer.insert()
+            val insertRow = logRow.get(3, schema).asInstanceOf[InternalRow]
+            merged.rows.append(insertRow.copy())
+          }
+        }
+        merged
+      }
+
+      withDeletes(newData)
+      withData(mergedData)
+      lastWriteLog = newData.flatMap(buffer => buffer.log).toIndexedSeq
+    }
+  }
+
+  class DeltaBasedColumnUpdateSplitOperation(
+      command: Command,
+      declared: Seq[NamedReference],
+      options: CaseInsensitiveStringMap)
+      extends DeltaBasedColumnUpdateOperation(command, declared, options) {
+    override def representUpdateAsDeleteAndInsert(): Boolean = true
+
+    override protected def newWriterFactory(
+        info: LogicalWriteInfo,
+        writeSchema: StructType): DeltaWriterFactory = {
+      val pkRowId = rowId().map(_.describe()).toSeq == Seq("pk") &&
+        info.rowIdSchema().get().fields.map(_.dataType).toSeq == 
Seq(IntegerType)
+      new DeltaBufferedRowsWriterFactory(writeSchema, pkRowId)
+    }
+
+    // For delete+reinsert with narrow writes, the REINSERT row has only the 
connector-declared
+    // columns (requiredDataAttributes order). The original row is located by 
the row ID, taking a
+    // data row-ID column from the narrow row and a metadata row-ID column 
from the preserved
+    // metadata, and the full row is rebuilt by overlaying the narrow row onto 
it. A DELETE logged
+    // without a `pk` row ID is resolved the same way from its metadata, so 
such a row ID must
+    // consist of metadata columns.
+    override protected def commitColumnUpdate(
+        info: LogicalWriteInfo,
+        writeSchema: StructType,
+        newData: Array[BufferedRows]): Unit = {
+      val metadataSchema = info.metadataSchema().orElse(new StructType())
+      val coversTable = 
schema.fieldNames.forall(writeSchema.getFieldIndex(_).isDefined)
+      val deleteOpName = UTF8String.fromString(Delete.toString)
+      val reinsertOpName = UTF8String.fromString(Reinsert.toString)
+      val insertOpName = UTF8String.fromString(Insert.toString)
+
+      def rowIdValues(narrowRow: Option[InternalRow], metadata: InternalRow): 
Seq[(String, Any)] = {
+        rowId().toSeq.map(_.describe()).map { name =>
+          (findFieldIndex(writeSchema, name), narrowRow) match {
+            case (Some(i), Some(row)) => name -> row.get(i, 
writeSchema(i).dataType)
+            case _ =>
+              val i = findFieldIndex(metadataSchema, name).filter(_ => 
metadata != null)
+                .getOrElse(throw new IllegalStateException(
+                  s"The split fixture can only locate a row by pk or by 
metadata row-ID " +
+                    s"columns, but row-ID column $name is in neither"))
+              name -> metadata.get(i, metadataSchema(i).dataType)
+          }
+        }
+      }
+
+      def metadataOf(logRow: InternalRow): InternalRow =
+        if (logRow.isNullAt(2)) null else logRow.getStruct(2, 
metadataSchema.length)
+
+      val expandedData = newData.map { buf =>
+        val expanded = new BufferedRows(buf.key, schema)
+        buf.log.foreach { logRow =>
+          val opName = logRow.getUTF8String(0)
+          if (opName == deleteOpName && logRow.isNullAt(1)) {
+            val values = rowIdValues(None, metadataOf(logRow))
+            buf.deletes += 
currentRowByRowId(values).getInt(fieldIndexOf(schema, "pk"))
+          } else if (opName == reinsertOpName) {
+            val narrowRow = logRow.get(3, 
writeSchema).asInstanceOf[InternalRow]
+            val baseRow = if (coversTable) {
+              None
+            } else {
+              Some(currentRowByRowId(rowIdValues(Some(narrowRow), 
metadataOf(logRow))))

Review Comment:
   Done. Both split fixtures fall back to a full-width delta write when the 
UPDATE assigns a declared `pk` and the declaration does not cover the table, 
and the shared reassignment test also runs on both.



##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/SupportsColumnUpdates.java:
##########
@@ -0,0 +1,114 @@
+/*
+ * 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.write;
+
+import org.apache.spark.annotation.Experimental;
+import org.apache.spark.sql.connector.expressions.NamedReference;
+
+/**
+ * A mix-in interface for {@link RowLevelOperation}. Data sources can 
implement this interface to
+ * receive a narrow row containing only the columns declared via {@link 
#requiredDataAttributes()}
+ * for updated, copied, and reinserted records, instead of the full table row.
+ * <p>
+ * When {@link LogicalWriteInfo#columnUpdateSchema()} is present, updated, 
copied, and reinserted
+ * rows follow it: group-based operations receive them through
+ * {@link DataWriter#writeColumnUpdate(Object, Object)} or
+ * {@link DataWriter#writeColumnUpdate(Object)}, and operations that mix in 
{@link SupportsDelta}
+ * through {@link DeltaWriter#update} and {@link DeltaWriter#reinsert}. Rows 
the command inserts
+ * always follow {@link LogicalWriteInfo#schema()} and arrive through
+ * {@link DataWriter#write(Object)} and {@link DeltaWriter#insert}. When
+ * {@link LogicalWriteInfo#columnUpdateSchema()} is absent, every row follows
+ * {@link LogicalWriteInfo#schema()}, as for any other operation. Connectors 
must decide which
+ * layout to expect by whether {@link LogicalWriteInfo#columnUpdateSchema()} 
is present, not by the
+ * command. A builder that wants full-width rows for some command can check
+ * {@link RowLevelOperationInfo#command()} and build an operation without this 
mix-in. An operation
+ * that wraps another must also mix this in, or Spark sends it full-width 
rows. Currently Spark
+ * narrows only UPDATE.
+ * <p>
+ * Scans built from {@link #newScanBuilder} should support schema pruning. 
Otherwise they read every
+ * column. For operations that do not mix in {@link SupportsDelta}, only 
top-level columns are
+ * pruned: a struct column the command references through a nested field is 
read in full.
+ *
+ * @since 4.4.0
+ */
+@Experimental
+public interface SupportsColumnUpdates extends RowLevelOperation {
+  /**
+   * Returns the data column references required to perform this row-level 
operation.
+   * <p>
+   * When Spark narrows the write, the returned columns become
+   * {@link LogicalWriteInfo#columnUpdateSchema()}, in declared order. Spark 
matches each declared
+   * name to the column with the same spelling, or else to the one column that 
the session's
+   * resolver matches, and {@link LogicalWriteInfo#columnUpdateSchema()} uses 
the table's spelling
+   * of each column, which can differ in case from the declared reference.
+   * Implementations must include every column they want to receive: every 
column reported by
+   * {@link RowLevelOperationInfo#updatedColumns()}, plus any columns needed 
for row lookup or
+   * routing. Columns that are not declared are absent from the rows the 
connector receives, so the
+   * connector must preserve their values itself. Spark may call this method 
more than once for the
+   * same operation, and every call must return the same columns.
+   * <p>
+   * If the returned array is empty, Spark does not narrow the write and the 
operation receives
+   * full-width rows. An UPDATE whose assignments are all identity assignments 
reports no
+   * {@link RowLevelOperationInfo#updatedColumns()}, so an operation that 
declares exactly those
+   * columns takes this path for such an UPDATE. An empty array is not an 
opt-out: an UPDATE that
+   * sets a column is still rejected, because the array misses that column.
+   * <p>
+   * An operation that does not mix in {@link SupportsDelta} should locate 
original rows through
+   * metadata columns returned by {@link #requiredMetadataAttributes()} that 
are preserved on
+   * update ({@link 
org.apache.spark.sql.connector.catalog.MetadataColumn#PRESERVE_ON_UPDATE}),
+   * such as a file and a row position. If it locates rows through a data 
column, its builder
+   * should build an operation without this mix-in when
+   * {@link RowLevelOperationInfo#updatedColumns()} contains that column.
+   * <p>
+   * Each entry must name a top-level data column of the table. For updates on 
nested fields such as
+   * {@code SET s.c1 = -1}, the connector must declare the root struct column 
{@code s}. For an
+   * UPDATE, Spark rejects with an analysis exception a name that no column 
has and that the
+   * resolver matches to no column or to several, a column declared more than 
once, a nested field,
+   * a metadata column (declare those through {@link 
#requiredMetadataAttributes()} instead), and an
+   * array that misses a column reported by {@link 
RowLevelOperationInfo#updatedColumns()}. When
+   * Spark narrows the write, it also rejects an UPDATE that assigns a new 
value to a metadata
+   * column, which only a table that accepts any schema allows, because a 
connector can locate
+   * original rows through metadata columns.
+   * <p>
+   * If the returned array is non-empty and this operation also mixes in 
{@link SupportsDelta} and
+   * represents updates as deletes and inserts
+   * ({@link SupportsDelta#representUpdateAsDeleteAndInsert()} returns {@code 
true}), the reinserted
+   * row carries only the columns declared here, and its metadata keeps only 
the values of the
+   * columns returned by {@link #requiredMetadataAttributes()} that are 
preserved on reinsert
+   * ({@link 
org.apache.spark.sql.connector.catalog.MetadataColumn#PRESERVE_ON_REINSERT}); 
the
+   * others are null. Spark does not relate a reinserted row to the deleted 
row.

Review Comment:
   Done, with your wording, and in the description.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala:
##########
@@ -358,6 +359,56 @@ trait RowLevelWrite extends V2WriteCommand with 
SupportsSubquery {
   def condition: Expression
   def originalTable: NamedRelation
 
+  /** The projections that read query columns by ordinal. */
+  protected def queryProjections: Seq[ProjectingInternalRow]
+
+  /**
+   * The write reads the operation column at ordinal 0 and other query columns 
only through
+   * projections, by ordinal. Any other query column can be pruned with 
[[withPrunedQuery]]. An
+   * ordinal the query does not have is skipped, so that the plan can still be 
printed;
+   * [[checkProjectionOrdinals]] rejects it.
+   */
+  override lazy val references: AttributeSet = {

Review Comment:
   Done.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedColumnUpdateTableSuite.scala:
##########
@@ -0,0 +1,727 @@
+/*
+ * 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 org.apache.spark.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{AnalysisException, Row}
+import org.apache.spark.sql.catalyst.analysis.RewriteRowLevelCommand
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.logical.WriteDelta
+import 
org.apache.spark.sql.catalyst.util.RowDeltaUtils.ORIGINAL_ROW_ID_VALUE_PREFIX
+import org.apache.spark.sql.connector.catalog.{Delete, 
InMemoryRowLevelOperationTable, Reinsert}
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.write.LogicalWriteInfo
+import org.apache.spark.sql.connector.write.RowLevelOperation.Command.UPDATE
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.execution.CommandExecutionMode
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * Tests for UPDATE statements targeting connectors that mix in
+ * [[org.apache.spark.sql.connector.write.SupportsColumnUpdates]].
+ *
+ * When a connector supports column updates, updated rows contain only the 
declared columns
+ * (LogicalWriteInfo.columnUpdateSchema()) rather than the full table row.
+ */
+class DeltaBasedColumnUpdateTableSuite extends DeltaBasedUpdateTableSuiteBase
+  with ColumnUpdateTableSharedTests {
+
+  override protected lazy val extraTableProps: java.util.Map[String, String] = 
{
+    val props = new java.util.HashMap[String, String]()
+    props.put("column-update", "true")
+    props
+  }
+
+  override protected def reqAttrsTableProps(reqAttrs: String): 
java.util.Map[String, String] = {
+    java.util.Map.of("column-update-req-attrs", reqAttrs)
+  }
+
+  override protected def fullWidthTableProps: java.util.Map[String, String] = {
+    java.util.Map.of("supports-deltas", "true")
+  }
+
+  override protected def scanMetadataColumns: String = ", _partition STRING"
+
+  private val splitOperationClass =
+    
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperation].getName
+
+  private def splitReqAttrsTableProps(reqAttrs: String): java.util.Map[String, 
String] = {
+    tablePropsWith(reqAttrsTableProps(reqAttrs), "split-updates" -> "true")
+  }
+
+  private val splitTableProps = tablePropsWith(extraTableProps, 
"split-updates" -> "true")
+
+  private val splitPartitionRowIdTableProps =
+    java.util.Map.of("column-update-split-row-id", "_partition")
+
+  test("column-update: column update schema contains a single assigned 
column") {
+    Seq(extraTableProps, splitTableProps).foreach { props =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+          """{ "pk": 1, "id": 1, "dep": "hr" }
+            |{ "pk": 2, "id": 2, "dep": "software" }
+            |{ "pk": 3, "id": 3, "dep": "hr" }
+            |""".stripMargin,
+          props)
+
+        sql(s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1")
+
+        checkLastWriteInfo(
+          expectedRowIdSchema = Some(StructType(Array(PK_FIELD))),
+          expectedMetadataSchema = Some(StructType(Array(PARTITION_FIELD, 
INDEX_FIELD_NULLABLE))),
+          expectedColumnUpdateSchema = Some(StructType(Seq(
+            PK_FIELD,
+            DEP_FIELD,
+            StructField("id", IntegerType, nullable = false)
+          ))))
+      }
+    }
+  }
+
+  test("column-update: update handles metadata columns correctly") {
+    Seq(
+      "id IN (1, 100)",
+      "id IN (1, 20) AND dep IN (SELECT * FROM updated_dep)"
+    ).foreach { condition =>
+      withTable(tableNameAsString) {
+        withTempView("updated_dep") {
+          createAndInitTable("pk INT NOT NULL, id INT, salary INT, dep STRING",
+            """{ "pk": 1, "id": 1, "salary": 100, "dep": "hr" }
+              |{ "pk": 2, "id": 2, "salary": 200, "dep": "software" }
+              |{ "pk": 3, "id": 3, "salary": 300, "dep": "hr" }
+              |""".stripMargin)
+          import testImplicits._
+          Seq(Some("hr"), 
Some("it")).toDF().createOrReplaceTempView("updated_dep")
+
+          sql(s"UPDATE $tableNameAsString SET id = -1 WHERE $condition")
+
+          checkLastColumnUpdateWriteLog(
+            updateWriteLogEntry(id = 1, metadata = Row("hr", null), data = 
Row(1, "hr", -1)))
+          checkAnswer(
+            sql(s"SELECT * FROM $tableNameAsString"),
+            Row(1, -1, 100, "hr") :: Row(2, 2, 200, "software") :: Row(3, 3, 
300, "hr") :: Nil)
+        }
+      }
+    }
+  }
+
+  test("column-update: CHAR and VARCHAR self-assignments are reported as 
updated") {
+    createTable("pk INT NOT NULL, id INT, c CHAR(3), v VARCHAR(10), " +
+      "a ARRAY<CHAR(3)>, m MAP<STRING, CHAR(3)>, s STRUCT<f: CHAR(3)>, dep 
STRING")
+    sql(s"INSERT INTO $tableNameAsString VALUES " +
+      "(1, 1, 'a', 'x', array('b'), map('k', 'c'), named_struct('f', 'd'), 
'hr')")
+
+    sql(s"UPDATE $tableNameAsString SET id = id, c = c, v = v, a = a, m = m, s 
= s WHERE pk = 1")
+
+    checkLastUpdatedColumns("c", "v", "a", "m", "s")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString"),
+      Row(1, 1, "a  ", "x", Seq("b  "), Map("k" -> "c  "), Row("d  "), "hr") 
:: Nil)
+  }
+
+  test("column-update: with preserved types, a CHAR self-assignment is 
reported only when its " +
+    "read is padded") {
+    Seq(
+      Seq(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true") -> Seq("id", 
"c", "a", "m", "s"),
+      Seq(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true",
+        SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") -> Seq("id")
+    ).foreach { case (confs, updated) =>
+      withTable(tableNameAsString) {
+        withSQLConf(confs: _*) {
+          createTable("pk INT NOT NULL, id INT, c CHAR(3), v VARCHAR(10), " +
+            "a ARRAY<CHAR(3)>, m MAP<STRING, CHAR(3)>, s STRUCT<f: CHAR(3)>, 
dep STRING")
+          sql(s"INSERT INTO $tableNameAsString VALUES " +
+            "(1, 1, 'a', 'x', array('b'), map('k', 'c'), named_struct('f', 
'd'), 'hr')")
+
+          sql(s"UPDATE $tableNameAsString SET id = -1, c = c, v = v, a = a, m 
= m, s = s " +
+            "WHERE pk = 1")
+
+          checkLastUpdatedColumns(updated: _*)
+          checkAnswer(
+            sql(s"SELECT * FROM $tableNameAsString"),
+            Row(1, -1, "a  ", "x", Seq("b  "), Map("k" -> "c  "), Row("d  "), 
"hr") :: Nil)
+        }
+      }
+    }
+  }
+
+  test("column-update: a LogicalWriteInfo that does not implement 
columnUpdateSchema throws") {
+    val info = new LogicalWriteInfo {
+      override def options(): CaseInsensitiveStringMap = 
CaseInsensitiveStringMap.empty()
+      override def queryId(): String = "query"
+      override def schema(): StructType = new StructType()
+    }
+
+    checkError(
+      exception = 
intercept[SparkUnsupportedOperationException](info.columnUpdateSchema()),
+      condition = "DATA_SOURCE_COLUMN_UPDATE_SCHEMA_NOT_IMPLEMENTED",
+      parameters = Map("class" -> info.getClass.getName))
+  }
+
+  test("column-update: updatedColumns and the column update schema follow the 
non-identity " +
+    "assignments") {
+    Seq(
+      ("id = -1", Seq("id"), Seq("pk", "dep", "id"), Row(1, -1, "hr")),
+      ("ID = -1", Seq("id"), Seq("pk", "dep", "id"), Row(1, -1, "hr")),
+      // assigns every column in table order, so the assignments are aligned 
as written
+      ("PK = PK, ID = -1, DEP = 'eng'", Seq("id", "dep"), Seq("pk", "dep", 
"id"),
+        Row(1, -1, "eng")),
+      ("id = -1, dep = 'eng'", Seq("id", "dep"), Seq("pk", "dep", "id"), 
Row(1, -1, "eng")),
+      ("id = -1, dep = dep", Seq("id"), Seq("pk", "dep", "id"), Row(1, -1, 
"hr")),
+      ("id = id, dep = 'eng'", Seq("dep"), Seq("pk", "dep"), Row(1, 10, 
"eng")),
+      ("id = id, dep = dep", Seq.empty, Seq("pk", "dep"), Row(1, 10, "hr")),
+      ("id = pk", Seq("id"), Seq("pk", "dep", "id"), Row(1, 1, "hr"))
+    ).foreach { case (assignments, updatedColumns, columnUpdateNames, 
updatedRow) =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+          """{ "pk": 1, "id": 10, "dep": "hr" }
+            |""".stripMargin)
+
+        sql(s"UPDATE $tableNameAsString SET $assignments WHERE pk = 1")
+
+        checkLastUpdatedColumns(updatedColumns: _*)
+        checkLastColumnUpdateSchema(columnUpdateNames: _*)
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), updatedRow :: 
Nil)
+      }
+    }
+  }
+
+  test("column-update split: row-level DELETE falls back to full-width rows") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "hr" }
+        |""".stripMargin,
+      splitTableProps)
+    checkDeleteFallsBackToFullWidthRows(Row(2, 200, "hr"))
+  }
+
+  test("column-update split: row-level DELETE by a metadata row ID falls back 
to full-width " +
+    "rows") {
+    // Each partition holds one row, so `_partition` identifies it.
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      splitPartitionRowIdTableProps)
+    checkDeleteFallsBackToFullWidthRows(Row(2, 200, "software"))
+  }
+
+  test("column-update split: MERGE falls back to full-width rows") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      splitTableProps)
+    checkMergeFallsBackToFullWidthRows()
+  }
+
+  test("column-update: undeclared write requirement columns are rejected") {
+    val excludeColumnPruning = SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> 
ColumnPruning.ruleName
+    Seq(
+      (reqAttrsTableProps("pk,salary"), "dep", columnUpdateOperationClass, 
"[`dep`]"),
+      (splitReqAttrsTableProps("pk,salary"), "dep", splitOperationClass, 
"[`dep`]"),
+      (tablePropsWith(reqAttrsTableProps("pk,salary"), 
"column-update-order-by" -> "pk"), "dep",
+        columnUpdateOperationClass, "[`dep`]"),
+      (tablePropsWith(reqAttrsTableProps("pk,salary"), 
"column-update-order-by" -> "dep"), "pk",
+        columnUpdateOperationClass, "[`dep`]"),
+      (tablePropsWith(reqAttrsTableProps("pk,salary"),
+        "column-update-cluster-by-nested-transform" -> "true"), "dep", 
columnUpdateOperationClass,
+        "[`dep`]"),
+      (reqAttrsTableProps("pk,salary"), "id,dep", columnUpdateOperationClass, 
"[`id`, `dep`]"),
+      (reqAttrsTableProps("pk,salary,s"), "s.missing", 
columnUpdateOperationClass,
+        "[`s`.`missing` (FIELD_NOT_FOUND)]")
+    ).foreach { case (props, clusterBy, operationClass, columns) =>
+      withTable(tableNameAsString) {
+        val tableProps = tablePropsWith(props, "column-update-cluster-by" -> 
clusterBy)
+        createAndInitTable("pk INT NOT NULL, salary INT, id INT, s STRUCT<c1: 
INT>, dep STRING",
+          """{ "pk": 1, "salary": 100, "id": 1, "s": { "c1": 1 }, "dep": "hr" }
+            |""".stripMargin,
+          tableProps)
+
+        Seq(Nil, Seq(excludeColumnPruning)).foreach { confs =>
+          withSQLConf(confs: _*) {
+            checkError(
+              exception = intercept[AnalysisException] {
+                sql(s"UPDATE $tableNameAsString SET salary = -1 WHERE pk = 1")
+              },
+              condition = "COLUMN_UPDATE_UNDECLARED_WRITE_REQUIREMENT_COLUMNS",
+              parameters = Map("connector" -> operationClass, "columns" -> 
columns))
+          }
+        }
+      }
+    }
+  }
+
+  test("column-update: an empty write requirement column name is reported as 
<empty>") {
+    checkError(
+      exception = 
QueryCompilationErrors.undeclaredWriteRequirementColumnsError(
+        columnUpdateOperationClass, Seq(Seq.empty[String] -> 
None)).asInstanceOf[AnalysisException],
+      condition = "COLUMN_UPDATE_UNDECLARED_WRITE_REQUIREMENT_COLUMNS",
+      parameters = Map("connector" -> columnUpdateOperationClass, "columns" -> 
"[<empty>]"))
+  }
+
+  test("column-update: distribution by an undeclared row ID column is 
allowed") {
+    Seq("salary = -1", "salary = -1, pk = pk").foreach { assignments =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }
+            |{ "pk": 2, "salary": 200, "dep": "hr" }
+            |""".stripMargin,
+          tablePropsWith(reqAttrsTableProps("salary,dep"), 
"column-update-cluster-by" -> "pk"))
+
+        sql(s"UPDATE $tableNameAsString SET $assignments WHERE pk = 1")
+
+        checkLastUpdatedColumns("salary")
+        checkAnswer(
+          sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+          Row(1, -1, "hr") :: Row(2, 200, "hr") :: Nil)
+      }
+    }
+  }
+
+  test("column-update: an undeclared, unreferenced partition column is not 
read") {
+    createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+      """{ "pk": 1, "id": 1, "dep": "hr" }
+        |{ "pk": 2, "id": 2, "dep": "software" }
+        |{ "pk": 3, "id": 3, "dep": "hr" }
+        |""".stripMargin,
+      reqAttrsTableProps("pk,id"))
+
+    executeAndCheckScan(
+      s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1", "pk INT, 
_partition STRING")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(1, -1, "hr") :: Row(2, 2, "software") :: Row(3, 3, "hr") :: Nil)
+  }
+
+  test("column-update: requiredDataAttributes resolves case-insensitively 
without adopting the " +
+    "declared spelling") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      reqAttrsTableProps("PK,SALARY,dep"))
+
+    sql(s"UPDATE $tableNameAsString SET salary = salary + 1 WHERE pk = 1")
+
+    checkLastColumnUpdateSchema("pk", "salary", "dep")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(1, 101, "hr") :: Row(2, 200, "software") :: Nil)
+  }
+
+  test("column-update: case-sensitive analysis accepts columns that differ 
only in case") {
+    withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+      createAndInitTable("pk INT NOT NULL, salary INT, SALARY INT, dep STRING",
+        """{ "pk": 1, "salary": 100, "SALARY": 200, "dep": "hr" }
+          |""".stripMargin,
+        reqAttrsTableProps("pk,salary,SALARY,dep"))
+
+      sql(s"UPDATE $tableNameAsString SET salary = -1 WHERE pk = 1")
+
+      checkLastColumnUpdateSchema("pk", "salary", "SALARY", "dep")
+      checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, -1, 200, 
"hr") :: Nil)
+    }
+  }
+
+  test("column-update: a declared name matches the same spelling, or else the 
one column that " +
+    "matches case-insensitively") {
+    Seq(
+      "pk,salary,SALARY,dep" -> Some(Seq("pk", "salary", "SALARY", "dep")),
+      "pk,SALARY,dep" -> Some(Seq("pk", "SALARY", "dep")),
+      "PK,SALARY,dep" -> Some(Seq("pk", "SALARY", "dep")),
+      "pk,Salary,dep" -> None
+    ).foreach { case (reqAttrs, writeColumns) =>
+      withTable(tableNameAsString) {
+        withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+          createAndInitTable("pk INT NOT NULL, salary INT, SALARY INT, dep 
STRING",
+            """{ "pk": 1, "salary": 100, "SALARY": 200, "dep": "hr" }
+              |""".stripMargin,
+            reqAttrsTableProps(reqAttrs))
+        }
+
+        val update = s"UPDATE $tableNameAsString SET pk = 3 WHERE pk = 1"
+        writeColumns match {
+          case Some(columns) =>
+            sql(update)
+            checkLastColumnUpdateSchema(columns: _*)
+            withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+              checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(3, 
100, 200, "hr") :: Nil)
+            }
+          case None =>
+            checkError(
+              exception = intercept[AnalysisException](sql(update)),
+              condition = "COLUMN_UPDATE_UNKNOWN_REQUIRED_DATA_ATTRIBUTE",
+              parameters = Map(
+                "connector" -> columnUpdateOperationClass, "unknownAttributes" 
-> "[`Salary`]"))
+        }
+      }
+    }
+  }
+
+  test("column-update: invalid requiredDataAttributes are rejected") {
+    Seq(
+      ("pk,s.c1,dep", "COLUMN_UPDATE_NESTED_REQUIRED_DATA_ATTRIBUTE",
+        "nestedAttributes" -> "[`s`.`c1`]"),
+      ("pk,pk,salary", "COLUMN_UPDATE_DUPLICATE_REQUIRED_DATA_ATTRIBUTE",
+        "duplicateAttributes" -> "[`pk`]"),
+      ("salary,PK,SALARY,pk", 
"COLUMN_UPDATE_DUPLICATE_REQUIRED_DATA_ATTRIBUTE",
+        "duplicateAttributes" -> "[`salary`, `PK`]"),
+      ("pk,_partition,salary", 
"COLUMN_UPDATE_METADATA_REQUIRED_DATA_ATTRIBUTE",
+        "metadataAttributes" -> "[`_partition`]"),
+      ("pk,nonexistent_col,salary", 
"COLUMN_UPDATE_UNKNOWN_REQUIRED_DATA_ATTRIBUTE",
+        "unknownAttributes" -> "[`nonexistent_col`]"),
+      ("pk,salary", 
"COLUMN_UPDATE_REQUIRED_DATA_ATTRIBUTES_MISSING_UPDATED_COLUMNS",
+        "missingColumns" -> "[`a.b`]")
+    ).foreach { case (reqAttrs, condition, columns) =>
+      withTable(tableNameAsString) {
+        createAndInitTable(
+          "pk INT NOT NULL, salary INT, s STRUCT<c1: INT, c2: INT>, `a.b` INT, 
dep STRING",
+          """{ "pk": 1, "salary": 100, "s": { "c1": 1, "c2": 2 }, "a.b": 1, 
"dep": "hr" }
+            |""".stripMargin,
+          reqAttrsTableProps(reqAttrs))
+
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"UPDATE $tableNameAsString SET salary = -1, `a.b` = -1 WHERE 
pk = 1")
+          },
+          condition = condition,
+          parameters = Map("connector" -> columnUpdateOperationClass, columns))
+      }
+    }
+  }
+
+  test("column-update: a declared metadata column in any case is rejected as a 
metadata column " +
+    "when the relation already has the metadata columns") {
+    // on a table that accepts any schema, an UPDATE that lists the metadata 
columns adds them to
+    // the relation's output
+    Seq("_partition", "_PARTITION").foreach { name =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }
+            |""".stripMargin,
+          tablePropsWith(reqAttrsTableProps(s"pk,salary,dep,$name"), 
"accept-any-schema" -> "true"))
+
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"UPDATE $tableNameAsString SET pk = pk, salary = -1, dep = 
dep, " +
+              "index = index, _partition = _partition")
+          },
+          condition = "COLUMN_UPDATE_METADATA_REQUIRED_DATA_ATTRIBUTE",
+          parameters = Map(
+            "connector" -> columnUpdateOperationClass, "metadataAttributes" -> 
s"[`$name`]"))
+      }
+    }
+  }
+
+  test("column-update: a declared column with no name parts is reported as 
<empty>") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |""".stripMargin)
+    val t = table
+    val nameless = FieldReference(Seq.empty[String])
+    val operation = new t.DeltaBasedColumnUpdateOperation(
+      UPDATE, Seq(nameless, FieldReference("pk"), nameless))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        RewriteRowLevelCommand.resolveRequiredDataAttrs(
+          spark.table(tableNameAsString).queryExecution.analyzed, operation)
+      },
+      condition = "COLUMN_UPDATE_UNKNOWN_REQUIRED_DATA_ATTRIBUTE",
+      parameters = Map(
+        "connector" -> operation.getClass.getName, "unknownAttributes" -> 
"[<empty>, <empty>]"))
+  }
+
+  test("column-update split: delete and reinsert carry the row ID and 
preserved metadata") {
+    createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+      """{ "pk": 1, "id": 1, "dep": "hr" }
+        |{ "pk": 2, "id": 2, "dep": "hr" }
+        |""".stripMargin,
+      splitTableProps)
+
+    sql(s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1")
+
+    checkLastColumnUpdateWriteLog(
+      deleteWriteLogEntry(id = 1, metadata = Row("hr", null)),
+      reinsertWriteLogEntry(metadata = Row("hr", null), data = Row(1, "hr", 
-1)))
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(1, -1, "hr") :: Row(2, 2, "hr") :: Nil)
+  }
+
+  test("column-update split: a reinserted row is found by a row-ID column 
declared in another " +
+    "case") {
+    createAndInitTable("PK INT NOT NULL, id INT, salary INT, dep STRING",
+      """{ "PK": 1, "id": 1, "salary": 100, "dep": "hr" }
+        |{ "PK": 2, "id": 2, "salary": 200, "dep": "hr" }
+        |""".stripMargin,
+      splitTableProps)
+
+    sql(s"UPDATE $tableNameAsString SET salary = -1 WHERE PK = 1")
+
+    checkLastColumnUpdateSchema("PK", "dep", "salary")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY PK"),
+      Row(1, 1, -1, "hr") :: Row(2, 2, 200, "hr") :: Nil)
+  }
+
+  test("column-update split: a row-ID reassignment is written when every 
column is declared") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      splitReqAttrsTableProps("pk,salary,dep"))
+
+    sql(s"UPDATE $tableNameAsString SET pk = pk + 10, salary = -1 WHERE dep = 
'hr'")
+
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(2, 200, "software") :: Row(11, -1, "hr") :: Nil)
+  }
+
+  test("column-update split: Spark does not check whether the row ID reaches 
the reinserted " +
+    "row") {
+    // the fixture cannot commit a reinserted row without its row ID, so this 
checks the plan

Review Comment:
   Done. The split reassignment test from item 95 replaces case 1. I left out 
case 2, since it fails in `ExpandExec` with a full-width split table too. The 
remaining two cases check the optimized plan.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryRowLevelOperationTable.scala:
##########
@@ -191,16 +246,23 @@ class InMemoryRowLevelOperationTable private (
     override def description(): String = "InMemoryPartitionReplaceOperation"
   }
 
+  // A group-based write replaces every partition its scan handed to Spark 
after runtime
+  // filtering. Drops those partitions and returns them.
+  private def replaceReadPartitions(scan: BatchScanBaseClass): 
Seq[BufferedRows] = {

Review Comment:
   Done.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedColumnUpdateTableSuite.scala:
##########
@@ -0,0 +1,727 @@
+/*
+ * 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 org.apache.spark.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{AnalysisException, Row}
+import org.apache.spark.sql.catalyst.analysis.RewriteRowLevelCommand
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.logical.WriteDelta
+import 
org.apache.spark.sql.catalyst.util.RowDeltaUtils.ORIGINAL_ROW_ID_VALUE_PREFIX
+import org.apache.spark.sql.connector.catalog.{Delete, 
InMemoryRowLevelOperationTable, Reinsert}
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.write.LogicalWriteInfo
+import org.apache.spark.sql.connector.write.RowLevelOperation.Command.UPDATE
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.execution.CommandExecutionMode
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * Tests for UPDATE statements targeting connectors that mix in
+ * [[org.apache.spark.sql.connector.write.SupportsColumnUpdates]].
+ *
+ * When a connector supports column updates, updated rows contain only the 
declared columns
+ * (LogicalWriteInfo.columnUpdateSchema()) rather than the full table row.
+ */
+class DeltaBasedColumnUpdateTableSuite extends DeltaBasedUpdateTableSuiteBase
+  with ColumnUpdateTableSharedTests {
+
+  override protected lazy val extraTableProps: java.util.Map[String, String] = 
{
+    val props = new java.util.HashMap[String, String]()
+    props.put("column-update", "true")
+    props
+  }
+
+  override protected def reqAttrsTableProps(reqAttrs: String): 
java.util.Map[String, String] = {
+    java.util.Map.of("column-update-req-attrs", reqAttrs)
+  }
+
+  override protected def fullWidthTableProps: java.util.Map[String, String] = {
+    java.util.Map.of("supports-deltas", "true")
+  }
+
+  override protected def scanMetadataColumns: String = ", _partition STRING"
+
+  private val splitOperationClass =
+    
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperation].getName
+
+  private def splitReqAttrsTableProps(reqAttrs: String): java.util.Map[String, 
String] = {
+    tablePropsWith(reqAttrsTableProps(reqAttrs), "split-updates" -> "true")
+  }
+
+  private val splitTableProps = tablePropsWith(extraTableProps, 
"split-updates" -> "true")
+
+  private val splitPartitionRowIdTableProps =
+    java.util.Map.of("column-update-split-row-id", "_partition")
+
+  test("column-update: column update schema contains a single assigned 
column") {
+    Seq(extraTableProps, splitTableProps).foreach { props =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+          """{ "pk": 1, "id": 1, "dep": "hr" }
+            |{ "pk": 2, "id": 2, "dep": "software" }
+            |{ "pk": 3, "id": 3, "dep": "hr" }
+            |""".stripMargin,
+          props)
+
+        sql(s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1")
+
+        checkLastWriteInfo(
+          expectedRowIdSchema = Some(StructType(Array(PK_FIELD))),
+          expectedMetadataSchema = Some(StructType(Array(PARTITION_FIELD, 
INDEX_FIELD_NULLABLE))),
+          expectedColumnUpdateSchema = Some(StructType(Seq(
+            PK_FIELD,
+            DEP_FIELD,
+            StructField("id", IntegerType, nullable = false)
+          ))))
+      }
+    }
+  }
+
+  test("column-update: update handles metadata columns correctly") {
+    Seq(
+      "id IN (1, 100)",
+      "id IN (1, 20) AND dep IN (SELECT * FROM updated_dep)"
+    ).foreach { condition =>
+      withTable(tableNameAsString) {
+        withTempView("updated_dep") {
+          createAndInitTable("pk INT NOT NULL, id INT, salary INT, dep STRING",
+            """{ "pk": 1, "id": 1, "salary": 100, "dep": "hr" }
+              |{ "pk": 2, "id": 2, "salary": 200, "dep": "software" }
+              |{ "pk": 3, "id": 3, "salary": 300, "dep": "hr" }
+              |""".stripMargin)
+          import testImplicits._
+          Seq(Some("hr"), 
Some("it")).toDF().createOrReplaceTempView("updated_dep")
+
+          sql(s"UPDATE $tableNameAsString SET id = -1 WHERE $condition")
+
+          checkLastColumnUpdateWriteLog(
+            updateWriteLogEntry(id = 1, metadata = Row("hr", null), data = 
Row(1, "hr", -1)))
+          checkAnswer(
+            sql(s"SELECT * FROM $tableNameAsString"),
+            Row(1, -1, 100, "hr") :: Row(2, 2, 200, "software") :: Row(3, 3, 
300, "hr") :: Nil)
+        }
+      }
+    }
+  }
+
+  test("column-update: CHAR and VARCHAR self-assignments are reported as 
updated") {

Review Comment:
   Done.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteUpdateTable.scala:
##########
@@ -43,15 +44,22 @@ object RewriteUpdateTable extends RewriteRowLevelCommand {
       EliminateSubqueryAliases(aliasedTable) match {
         case r @ ExtractV2Table(tbl: SupportsRowLevelOperations) =>
           checkNoGeneratedColumns(r, UPDATE)
-          val table = buildOperationTable(tbl, UPDATE, r.options)
+          val (metadataUpdates, dataUpdates) = nonIdentityAssignments(r, 
assignments).partition {
+            case (attr, _) => MetadataAttribute.isValid(attr.metadata)
+          }
+          val updatedAttrs = dataUpdates.map(_._1)
+          val table = buildOperationTable(tbl, UPDATE, r.options, updatedAttrs)
           val updateCond = cond.getOrElse(TrueLiteral)
+          val narrowAttrs = resolveNarrowWriteAttrs(

Review Comment:
   Done. It is `resolveWriteAttrs` again.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedColumnUpdateTableSuite.scala:
##########
@@ -0,0 +1,727 @@
+/*
+ * 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 org.apache.spark.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{AnalysisException, Row}
+import org.apache.spark.sql.catalyst.analysis.RewriteRowLevelCommand
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.logical.WriteDelta
+import 
org.apache.spark.sql.catalyst.util.RowDeltaUtils.ORIGINAL_ROW_ID_VALUE_PREFIX
+import org.apache.spark.sql.connector.catalog.{Delete, 
InMemoryRowLevelOperationTable, Reinsert}
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.write.LogicalWriteInfo
+import org.apache.spark.sql.connector.write.RowLevelOperation.Command.UPDATE
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.execution.CommandExecutionMode
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * Tests for UPDATE statements targeting connectors that mix in
+ * [[org.apache.spark.sql.connector.write.SupportsColumnUpdates]].
+ *
+ * When a connector supports column updates, updated rows contain only the 
declared columns
+ * (LogicalWriteInfo.columnUpdateSchema()) rather than the full table row.
+ */
+class DeltaBasedColumnUpdateTableSuite extends DeltaBasedUpdateTableSuiteBase
+  with ColumnUpdateTableSharedTests {
+
+  override protected lazy val extraTableProps: java.util.Map[String, String] = 
{
+    val props = new java.util.HashMap[String, String]()
+    props.put("column-update", "true")
+    props
+  }
+
+  override protected def reqAttrsTableProps(reqAttrs: String): 
java.util.Map[String, String] = {
+    java.util.Map.of("column-update-req-attrs", reqAttrs)
+  }
+
+  override protected def fullWidthTableProps: java.util.Map[String, String] = {
+    java.util.Map.of("supports-deltas", "true")
+  }
+
+  override protected def scanMetadataColumns: String = ", _partition STRING"
+
+  private val splitOperationClass =
+    
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperation].getName
+
+  private def splitReqAttrsTableProps(reqAttrs: String): java.util.Map[String, 
String] = {
+    tablePropsWith(reqAttrsTableProps(reqAttrs), "split-updates" -> "true")
+  }
+
+  private val splitTableProps = tablePropsWith(extraTableProps, 
"split-updates" -> "true")
+
+  private val splitPartitionRowIdTableProps =
+    java.util.Map.of("column-update-split-row-id", "_partition")
+
+  test("column-update: column update schema contains a single assigned 
column") {
+    Seq(extraTableProps, splitTableProps).foreach { props =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+          """{ "pk": 1, "id": 1, "dep": "hr" }
+            |{ "pk": 2, "id": 2, "dep": "software" }
+            |{ "pk": 3, "id": 3, "dep": "hr" }
+            |""".stripMargin,
+          props)
+
+        sql(s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1")
+
+        checkLastWriteInfo(
+          expectedRowIdSchema = Some(StructType(Array(PK_FIELD))),
+          expectedMetadataSchema = Some(StructType(Array(PARTITION_FIELD, 
INDEX_FIELD_NULLABLE))),
+          expectedColumnUpdateSchema = Some(StructType(Seq(
+            PK_FIELD,
+            DEP_FIELD,
+            StructField("id", IntegerType, nullable = false)
+          ))))
+      }
+    }
+  }
+
+  test("column-update: update handles metadata columns correctly") {
+    Seq(
+      "id IN (1, 100)",
+      "id IN (1, 20) AND dep IN (SELECT * FROM updated_dep)"
+    ).foreach { condition =>
+      withTable(tableNameAsString) {
+        withTempView("updated_dep") {
+          createAndInitTable("pk INT NOT NULL, id INT, salary INT, dep STRING",
+            """{ "pk": 1, "id": 1, "salary": 100, "dep": "hr" }
+              |{ "pk": 2, "id": 2, "salary": 200, "dep": "software" }
+              |{ "pk": 3, "id": 3, "salary": 300, "dep": "hr" }
+              |""".stripMargin)
+          import testImplicits._
+          Seq(Some("hr"), 
Some("it")).toDF().createOrReplaceTempView("updated_dep")
+
+          sql(s"UPDATE $tableNameAsString SET id = -1 WHERE $condition")
+
+          checkLastColumnUpdateWriteLog(
+            updateWriteLogEntry(id = 1, metadata = Row("hr", null), data = 
Row(1, "hr", -1)))
+          checkAnswer(
+            sql(s"SELECT * FROM $tableNameAsString"),
+            Row(1, -1, 100, "hr") :: Row(2, 2, 200, "software") :: Row(3, 3, 
300, "hr") :: Nil)
+        }
+      }
+    }
+  }
+
+  test("column-update: CHAR and VARCHAR self-assignments are reported as 
updated") {
+    createTable("pk INT NOT NULL, id INT, c CHAR(3), v VARCHAR(10), " +
+      "a ARRAY<CHAR(3)>, m MAP<STRING, CHAR(3)>, s STRUCT<f: CHAR(3)>, dep 
STRING")
+    sql(s"INSERT INTO $tableNameAsString VALUES " +
+      "(1, 1, 'a', 'x', array('b'), map('k', 'c'), named_struct('f', 'd'), 
'hr')")
+
+    sql(s"UPDATE $tableNameAsString SET id = id, c = c, v = v, a = a, m = m, s 
= s WHERE pk = 1")
+
+    checkLastUpdatedColumns("c", "v", "a", "m", "s")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString"),
+      Row(1, 1, "a  ", "x", Seq("b  "), Map("k" -> "c  "), Row("d  "), "hr") 
:: Nil)
+  }
+
+  test("column-update: with preserved types, a CHAR self-assignment is 
reported only when its " +
+    "read is padded") {
+    Seq(
+      Seq(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true") -> Seq("id", 
"c", "a", "m", "s"),
+      Seq(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true",
+        SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") -> Seq("id")
+    ).foreach { case (confs, updated) =>
+      withTable(tableNameAsString) {
+        withSQLConf(confs: _*) {
+          createTable("pk INT NOT NULL, id INT, c CHAR(3), v VARCHAR(10), " +
+            "a ARRAY<CHAR(3)>, m MAP<STRING, CHAR(3)>, s STRUCT<f: CHAR(3)>, 
dep STRING")
+          sql(s"INSERT INTO $tableNameAsString VALUES " +
+            "(1, 1, 'a', 'x', array('b'), map('k', 'c'), named_struct('f', 
'd'), 'hr')")
+
+          sql(s"UPDATE $tableNameAsString SET id = -1, c = c, v = v, a = a, m 
= m, s = s " +
+            "WHERE pk = 1")
+
+          checkLastUpdatedColumns(updated: _*)

Review Comment:
   Done. The new shared test stores `a` without padding under the legacy config 
and checks the column update schema and the stored `a  `.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteUpdateTable.scala:
##########
@@ -159,14 +169,15 @@ object RewriteUpdateTable extends RewriteRowLevelCommand {
       relation: DataSourceV2Relation,
       operationTable: RowLevelOperationTable,
       assignments: Seq[Assignment],
-      cond: Expression): WriteDelta = {
+      cond: Expression,
+      writeAttrs: Seq[AttributeReference]): WriteDelta = {
 
     val operation = operationTable.operation.asInstanceOf[SupportsDelta]
 
     // resolve all needed attrs (e.g. row ID and any required metadata attrs)
-    val rowAttrs = relation.output
     val rowIdAttrs = resolveRowIdAttrs(relation, operation)
     val metadataAttrs = resolveRequiredMetadataAttrs(relation, operation)
+    val splitUpdates = operation.representUpdateAsDeleteAndInsert

Review Comment:
   Done.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/RowLevelOperationSuiteBase.scala:
##########
@@ -246,18 +288,41 @@ abstract class RowLevelOperationSuiteBase
     assert(scans.isEmpty, "plan must not contain scan relations")
   }
 
+  // the schemas of the scans of the target table, directly or through a 
row-level operation, in
+  // the plan of the query
+  private def executeAndCollectScanSchemas(query: String): Seq[StructType] = {
+    val executedPlan = executeAndKeepPlan {
+      sql(query)
+    }
+    val targetName = table.name
+    val schemas = collect(executedPlan) {
+      case scan: BatchScanExec if scan.table.name == targetName => scan.schema
+    }
+    assert(schemas.nonEmpty, s"no scan of the target table for: $query")
+    schemas
+  }
+
+  /**

Review Comment:
   Done, here and in the description.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedColumnUpdateTableSuite.scala:
##########
@@ -0,0 +1,727 @@
+/*
+ * 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 org.apache.spark.{SparkRuntimeException, 
SparkUnsupportedOperationException}
+import org.apache.spark.sql.{AnalysisException, Row}
+import org.apache.spark.sql.catalyst.analysis.RewriteRowLevelCommand
+import org.apache.spark.sql.catalyst.optimizer.ColumnPruning
+import org.apache.spark.sql.catalyst.plans.logical.WriteDelta
+import 
org.apache.spark.sql.catalyst.util.RowDeltaUtils.ORIGINAL_ROW_ID_VALUE_PREFIX
+import org.apache.spark.sql.connector.catalog.{Delete, 
InMemoryRowLevelOperationTable, Reinsert}
+import org.apache.spark.sql.connector.expressions.FieldReference
+import org.apache.spark.sql.connector.write.LogicalWriteInfo
+import org.apache.spark.sql.connector.write.RowLevelOperation.Command.UPDATE
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.execution.CommandExecutionMode
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+import org.apache.spark.sql.util.CaseInsensitiveStringMap
+
+/**
+ * Tests for UPDATE statements targeting connectors that mix in
+ * [[org.apache.spark.sql.connector.write.SupportsColumnUpdates]].
+ *
+ * When a connector supports column updates, updated rows contain only the 
declared columns
+ * (LogicalWriteInfo.columnUpdateSchema()) rather than the full table row.
+ */
+class DeltaBasedColumnUpdateTableSuite extends DeltaBasedUpdateTableSuiteBase
+  with ColumnUpdateTableSharedTests {
+
+  override protected lazy val extraTableProps: java.util.Map[String, String] = 
{
+    val props = new java.util.HashMap[String, String]()
+    props.put("column-update", "true")
+    props
+  }
+
+  override protected def reqAttrsTableProps(reqAttrs: String): 
java.util.Map[String, String] = {
+    java.util.Map.of("column-update-req-attrs", reqAttrs)
+  }
+
+  override protected def fullWidthTableProps: java.util.Map[String, String] = {
+    java.util.Map.of("supports-deltas", "true")
+  }
+
+  override protected def scanMetadataColumns: String = ", _partition STRING"
+
+  private val splitOperationClass =
+    
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperation].getName
+
+  private def splitReqAttrsTableProps(reqAttrs: String): java.util.Map[String, 
String] = {
+    tablePropsWith(reqAttrsTableProps(reqAttrs), "split-updates" -> "true")
+  }
+
+  private val splitTableProps = tablePropsWith(extraTableProps, 
"split-updates" -> "true")
+
+  private val splitPartitionRowIdTableProps =
+    java.util.Map.of("column-update-split-row-id", "_partition")
+
+  test("column-update: column update schema contains a single assigned 
column") {
+    Seq(extraTableProps, splitTableProps).foreach { props =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+          """{ "pk": 1, "id": 1, "dep": "hr" }
+            |{ "pk": 2, "id": 2, "dep": "software" }
+            |{ "pk": 3, "id": 3, "dep": "hr" }
+            |""".stripMargin,
+          props)
+
+        sql(s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1")
+
+        checkLastWriteInfo(
+          expectedRowIdSchema = Some(StructType(Array(PK_FIELD))),
+          expectedMetadataSchema = Some(StructType(Array(PARTITION_FIELD, 
INDEX_FIELD_NULLABLE))),
+          expectedColumnUpdateSchema = Some(StructType(Seq(
+            PK_FIELD,
+            DEP_FIELD,
+            StructField("id", IntegerType, nullable = false)
+          ))))
+      }
+    }
+  }
+
+  test("column-update: update handles metadata columns correctly") {
+    Seq(
+      "id IN (1, 100)",
+      "id IN (1, 20) AND dep IN (SELECT * FROM updated_dep)"
+    ).foreach { condition =>
+      withTable(tableNameAsString) {
+        withTempView("updated_dep") {
+          createAndInitTable("pk INT NOT NULL, id INT, salary INT, dep STRING",
+            """{ "pk": 1, "id": 1, "salary": 100, "dep": "hr" }
+              |{ "pk": 2, "id": 2, "salary": 200, "dep": "software" }
+              |{ "pk": 3, "id": 3, "salary": 300, "dep": "hr" }
+              |""".stripMargin)
+          import testImplicits._
+          Seq(Some("hr"), 
Some("it")).toDF().createOrReplaceTempView("updated_dep")
+
+          sql(s"UPDATE $tableNameAsString SET id = -1 WHERE $condition")
+
+          checkLastColumnUpdateWriteLog(
+            updateWriteLogEntry(id = 1, metadata = Row("hr", null), data = 
Row(1, "hr", -1)))
+          checkAnswer(
+            sql(s"SELECT * FROM $tableNameAsString"),
+            Row(1, -1, 100, "hr") :: Row(2, 2, 200, "software") :: Row(3, 3, 
300, "hr") :: Nil)
+        }
+      }
+    }
+  }
+
+  test("column-update: CHAR and VARCHAR self-assignments are reported as 
updated") {
+    createTable("pk INT NOT NULL, id INT, c CHAR(3), v VARCHAR(10), " +
+      "a ARRAY<CHAR(3)>, m MAP<STRING, CHAR(3)>, s STRUCT<f: CHAR(3)>, dep 
STRING")
+    sql(s"INSERT INTO $tableNameAsString VALUES " +
+      "(1, 1, 'a', 'x', array('b'), map('k', 'c'), named_struct('f', 'd'), 
'hr')")
+
+    sql(s"UPDATE $tableNameAsString SET id = id, c = c, v = v, a = a, m = m, s 
= s WHERE pk = 1")
+
+    checkLastUpdatedColumns("c", "v", "a", "m", "s")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString"),
+      Row(1, 1, "a  ", "x", Seq("b  "), Map("k" -> "c  "), Row("d  "), "hr") 
:: Nil)
+  }
+
+  test("column-update: with preserved types, a CHAR self-assignment is 
reported only when its " +
+    "read is padded") {
+    Seq(
+      Seq(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true") -> Seq("id", 
"c", "a", "m", "s"),
+      Seq(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true",
+        SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") -> Seq("id")
+    ).foreach { case (confs, updated) =>
+      withTable(tableNameAsString) {
+        withSQLConf(confs: _*) {
+          createTable("pk INT NOT NULL, id INT, c CHAR(3), v VARCHAR(10), " +
+            "a ARRAY<CHAR(3)>, m MAP<STRING, CHAR(3)>, s STRUCT<f: CHAR(3)>, 
dep STRING")
+          sql(s"INSERT INTO $tableNameAsString VALUES " +
+            "(1, 1, 'a', 'x', array('b'), map('k', 'c'), named_struct('f', 
'd'), 'hr')")
+
+          sql(s"UPDATE $tableNameAsString SET id = -1, c = c, v = v, a = a, m 
= m, s = s " +
+            "WHERE pk = 1")
+
+          checkLastUpdatedColumns(updated: _*)
+          checkAnswer(
+            sql(s"SELECT * FROM $tableNameAsString"),
+            Row(1, -1, "a  ", "x", Seq("b  "), Map("k" -> "c  "), Row("d  "), 
"hr") :: Nil)
+        }
+      }
+    }
+  }
+
+  test("column-update: a LogicalWriteInfo that does not implement 
columnUpdateSchema throws") {
+    val info = new LogicalWriteInfo {
+      override def options(): CaseInsensitiveStringMap = 
CaseInsensitiveStringMap.empty()
+      override def queryId(): String = "query"
+      override def schema(): StructType = new StructType()
+    }
+
+    checkError(
+      exception = 
intercept[SparkUnsupportedOperationException](info.columnUpdateSchema()),
+      condition = "DATA_SOURCE_COLUMN_UPDATE_SCHEMA_NOT_IMPLEMENTED",
+      parameters = Map("class" -> info.getClass.getName))
+  }
+
+  test("column-update: updatedColumns and the column update schema follow the 
non-identity " +
+    "assignments") {
+    Seq(
+      ("id = -1", Seq("id"), Seq("pk", "dep", "id"), Row(1, -1, "hr")),
+      ("ID = -1", Seq("id"), Seq("pk", "dep", "id"), Row(1, -1, "hr")),
+      // assigns every column in table order, so the assignments are aligned 
as written
+      ("PK = PK, ID = -1, DEP = 'eng'", Seq("id", "dep"), Seq("pk", "dep", 
"id"),
+        Row(1, -1, "eng")),
+      ("id = -1, dep = 'eng'", Seq("id", "dep"), Seq("pk", "dep", "id"), 
Row(1, -1, "eng")),
+      ("id = -1, dep = dep", Seq("id"), Seq("pk", "dep", "id"), Row(1, -1, 
"hr")),
+      ("id = id, dep = 'eng'", Seq("dep"), Seq("pk", "dep"), Row(1, 10, 
"eng")),
+      ("id = id, dep = dep", Seq.empty, Seq("pk", "dep"), Row(1, 10, "hr")),
+      ("id = pk", Seq("id"), Seq("pk", "dep", "id"), Row(1, 1, "hr"))
+    ).foreach { case (assignments, updatedColumns, columnUpdateNames, 
updatedRow) =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+          """{ "pk": 1, "id": 10, "dep": "hr" }
+            |""".stripMargin)
+
+        sql(s"UPDATE $tableNameAsString SET $assignments WHERE pk = 1")
+
+        checkLastUpdatedColumns(updatedColumns: _*)
+        checkLastColumnUpdateSchema(columnUpdateNames: _*)
+        checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), updatedRow :: 
Nil)
+      }
+    }
+  }
+
+  test("column-update split: row-level DELETE falls back to full-width rows") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "hr" }
+        |""".stripMargin,
+      splitTableProps)
+    checkDeleteFallsBackToFullWidthRows(Row(2, 200, "hr"))
+  }
+
+  test("column-update split: row-level DELETE by a metadata row ID falls back 
to full-width " +
+    "rows") {
+    // Each partition holds one row, so `_partition` identifies it.
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      splitPartitionRowIdTableProps)
+    checkDeleteFallsBackToFullWidthRows(Row(2, 200, "software"))
+  }
+
+  test("column-update split: MERGE falls back to full-width rows") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      splitTableProps)
+    checkMergeFallsBackToFullWidthRows()
+  }
+
+  test("column-update: undeclared write requirement columns are rejected") {
+    val excludeColumnPruning = SQLConf.OPTIMIZER_EXCLUDED_RULES.key -> 
ColumnPruning.ruleName
+    Seq(
+      (reqAttrsTableProps("pk,salary"), "dep", columnUpdateOperationClass, 
"[`dep`]"),
+      (splitReqAttrsTableProps("pk,salary"), "dep", splitOperationClass, 
"[`dep`]"),
+      (tablePropsWith(reqAttrsTableProps("pk,salary"), 
"column-update-order-by" -> "pk"), "dep",
+        columnUpdateOperationClass, "[`dep`]"),
+      (tablePropsWith(reqAttrsTableProps("pk,salary"), 
"column-update-order-by" -> "dep"), "pk",
+        columnUpdateOperationClass, "[`dep`]"),
+      (tablePropsWith(reqAttrsTableProps("pk,salary"),
+        "column-update-cluster-by-nested-transform" -> "true"), "dep", 
columnUpdateOperationClass,
+        "[`dep`]"),
+      (reqAttrsTableProps("pk,salary"), "id,dep", columnUpdateOperationClass, 
"[`id`, `dep`]"),
+      (reqAttrsTableProps("pk,salary,s"), "s.missing", 
columnUpdateOperationClass,
+        "[`s`.`missing` (FIELD_NOT_FOUND)]")
+    ).foreach { case (props, clusterBy, operationClass, columns) =>
+      withTable(tableNameAsString) {
+        val tableProps = tablePropsWith(props, "column-update-cluster-by" -> 
clusterBy)
+        createAndInitTable("pk INT NOT NULL, salary INT, id INT, s STRUCT<c1: 
INT>, dep STRING",
+          """{ "pk": 1, "salary": 100, "id": 1, "s": { "c1": 1 }, "dep": "hr" }
+            |""".stripMargin,
+          tableProps)
+
+        Seq(Nil, Seq(excludeColumnPruning)).foreach { confs =>
+          withSQLConf(confs: _*) {
+            checkError(
+              exception = intercept[AnalysisException] {
+                sql(s"UPDATE $tableNameAsString SET salary = -1 WHERE pk = 1")
+              },
+              condition = "COLUMN_UPDATE_UNDECLARED_WRITE_REQUIREMENT_COLUMNS",
+              parameters = Map("connector" -> operationClass, "columns" -> 
columns))
+          }
+        }
+      }
+    }
+  }
+
+  test("column-update: an empty write requirement column name is reported as 
<empty>") {
+    checkError(
+      exception = 
QueryCompilationErrors.undeclaredWriteRequirementColumnsError(
+        columnUpdateOperationClass, Seq(Seq.empty[String] -> 
None)).asInstanceOf[AnalysisException],
+      condition = "COLUMN_UPDATE_UNDECLARED_WRITE_REQUIREMENT_COLUMNS",
+      parameters = Map("connector" -> columnUpdateOperationClass, "columns" -> 
"[<empty>]"))
+  }
+
+  test("column-update: distribution by an undeclared row ID column is 
allowed") {
+    Seq("salary = -1", "salary = -1, pk = pk").foreach { assignments =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }
+            |{ "pk": 2, "salary": 200, "dep": "hr" }
+            |""".stripMargin,
+          tablePropsWith(reqAttrsTableProps("salary,dep"), 
"column-update-cluster-by" -> "pk"))
+
+        sql(s"UPDATE $tableNameAsString SET $assignments WHERE pk = 1")
+
+        checkLastUpdatedColumns("salary")
+        checkAnswer(
+          sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+          Row(1, -1, "hr") :: Row(2, 200, "hr") :: Nil)
+      }
+    }
+  }
+
+  test("column-update: an undeclared, unreferenced partition column is not 
read") {
+    createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+      """{ "pk": 1, "id": 1, "dep": "hr" }
+        |{ "pk": 2, "id": 2, "dep": "software" }
+        |{ "pk": 3, "id": 3, "dep": "hr" }
+        |""".stripMargin,
+      reqAttrsTableProps("pk,id"))
+
+    executeAndCheckScan(
+      s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1", "pk INT, 
_partition STRING")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(1, -1, "hr") :: Row(2, 2, "software") :: Row(3, 3, "hr") :: Nil)
+  }
+
+  test("column-update: requiredDataAttributes resolves case-insensitively 
without adopting the " +
+    "declared spelling") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      reqAttrsTableProps("PK,SALARY,dep"))
+
+    sql(s"UPDATE $tableNameAsString SET salary = salary + 1 WHERE pk = 1")
+
+    checkLastColumnUpdateSchema("pk", "salary", "dep")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(1, 101, "hr") :: Row(2, 200, "software") :: Nil)
+  }
+
+  test("column-update: case-sensitive analysis accepts columns that differ 
only in case") {
+    withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+      createAndInitTable("pk INT NOT NULL, salary INT, SALARY INT, dep STRING",
+        """{ "pk": 1, "salary": 100, "SALARY": 200, "dep": "hr" }
+          |""".stripMargin,
+        reqAttrsTableProps("pk,salary,SALARY,dep"))
+
+      sql(s"UPDATE $tableNameAsString SET salary = -1 WHERE pk = 1")
+
+      checkLastColumnUpdateSchema("pk", "salary", "SALARY", "dep")
+      checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(1, -1, 200, 
"hr") :: Nil)
+    }
+  }
+
+  test("column-update: a declared name matches the same spelling, or else the 
one column that " +
+    "matches case-insensitively") {
+    Seq(
+      "pk,salary,SALARY,dep" -> Some(Seq("pk", "salary", "SALARY", "dep")),
+      "pk,SALARY,dep" -> Some(Seq("pk", "SALARY", "dep")),
+      "PK,SALARY,dep" -> Some(Seq("pk", "SALARY", "dep")),
+      "pk,Salary,dep" -> None
+    ).foreach { case (reqAttrs, writeColumns) =>
+      withTable(tableNameAsString) {
+        withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+          createAndInitTable("pk INT NOT NULL, salary INT, SALARY INT, dep 
STRING",
+            """{ "pk": 1, "salary": 100, "SALARY": 200, "dep": "hr" }
+              |""".stripMargin,
+            reqAttrsTableProps(reqAttrs))
+        }
+
+        val update = s"UPDATE $tableNameAsString SET pk = 3 WHERE pk = 1"
+        writeColumns match {
+          case Some(columns) =>
+            sql(update)
+            checkLastColumnUpdateSchema(columns: _*)
+            withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") {
+              checkAnswer(sql(s"SELECT * FROM $tableNameAsString"), Row(3, 
100, 200, "hr") :: Nil)
+            }
+          case None =>
+            checkError(
+              exception = intercept[AnalysisException](sql(update)),
+              condition = "COLUMN_UPDATE_UNKNOWN_REQUIRED_DATA_ATTRIBUTE",
+              parameters = Map(
+                "connector" -> columnUpdateOperationClass, "unknownAttributes" 
-> "[`Salary`]"))
+        }
+      }
+    }
+  }
+
+  test("column-update: invalid requiredDataAttributes are rejected") {
+    Seq(
+      ("pk,s.c1,dep", "COLUMN_UPDATE_NESTED_REQUIRED_DATA_ATTRIBUTE",
+        "nestedAttributes" -> "[`s`.`c1`]"),
+      ("pk,pk,salary", "COLUMN_UPDATE_DUPLICATE_REQUIRED_DATA_ATTRIBUTE",
+        "duplicateAttributes" -> "[`pk`]"),
+      ("salary,PK,SALARY,pk", 
"COLUMN_UPDATE_DUPLICATE_REQUIRED_DATA_ATTRIBUTE",
+        "duplicateAttributes" -> "[`salary`, `PK`]"),
+      ("pk,_partition,salary", 
"COLUMN_UPDATE_METADATA_REQUIRED_DATA_ATTRIBUTE",
+        "metadataAttributes" -> "[`_partition`]"),
+      ("pk,nonexistent_col,salary", 
"COLUMN_UPDATE_UNKNOWN_REQUIRED_DATA_ATTRIBUTE",
+        "unknownAttributes" -> "[`nonexistent_col`]"),
+      ("pk,salary", 
"COLUMN_UPDATE_REQUIRED_DATA_ATTRIBUTES_MISSING_UPDATED_COLUMNS",
+        "missingColumns" -> "[`a.b`]")
+    ).foreach { case (reqAttrs, condition, columns) =>
+      withTable(tableNameAsString) {
+        createAndInitTable(
+          "pk INT NOT NULL, salary INT, s STRUCT<c1: INT, c2: INT>, `a.b` INT, 
dep STRING",
+          """{ "pk": 1, "salary": 100, "s": { "c1": 1, "c2": 2 }, "a.b": 1, 
"dep": "hr" }
+            |""".stripMargin,
+          reqAttrsTableProps(reqAttrs))
+
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"UPDATE $tableNameAsString SET salary = -1, `a.b` = -1 WHERE 
pk = 1")
+          },
+          condition = condition,
+          parameters = Map("connector" -> columnUpdateOperationClass, columns))
+      }
+    }
+  }
+
+  test("column-update: a declared metadata column in any case is rejected as a 
metadata column " +
+    "when the relation already has the metadata columns") {
+    // on a table that accepts any schema, an UPDATE that lists the metadata 
columns adds them to
+    // the relation's output
+    Seq("_partition", "_PARTITION").foreach { name =>
+      withTable(tableNameAsString) {
+        createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+          """{ "pk": 1, "salary": 100, "dep": "hr" }
+            |""".stripMargin,
+          tablePropsWith(reqAttrsTableProps(s"pk,salary,dep,$name"), 
"accept-any-schema" -> "true"))
+
+        checkError(
+          exception = intercept[AnalysisException] {
+            sql(s"UPDATE $tableNameAsString SET pk = pk, salary = -1, dep = 
dep, " +
+              "index = index, _partition = _partition")
+          },
+          condition = "COLUMN_UPDATE_METADATA_REQUIRED_DATA_ATTRIBUTE",
+          parameters = Map(
+            "connector" -> columnUpdateOperationClass, "metadataAttributes" -> 
s"[`$name`]"))
+      }
+    }
+  }
+
+  test("column-update: a declared column with no name parts is reported as 
<empty>") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |""".stripMargin)
+    val t = table
+    val nameless = FieldReference(Seq.empty[String])
+    val operation = new t.DeltaBasedColumnUpdateOperation(
+      UPDATE, Seq(nameless, FieldReference("pk"), nameless))
+
+    checkError(
+      exception = intercept[AnalysisException] {
+        RewriteRowLevelCommand.resolveRequiredDataAttrs(
+          spark.table(tableNameAsString).queryExecution.analyzed, operation)
+      },
+      condition = "COLUMN_UPDATE_UNKNOWN_REQUIRED_DATA_ATTRIBUTE",
+      parameters = Map(
+        "connector" -> operation.getClass.getName, "unknownAttributes" -> 
"[<empty>, <empty>]"))
+  }
+
+  test("column-update split: delete and reinsert carry the row ID and 
preserved metadata") {
+    createAndInitTable("pk INT NOT NULL, id INT, dep STRING",
+      """{ "pk": 1, "id": 1, "dep": "hr" }
+        |{ "pk": 2, "id": 2, "dep": "hr" }
+        |""".stripMargin,
+      splitTableProps)
+
+    sql(s"UPDATE $tableNameAsString SET id = -1 WHERE pk = 1")
+
+    checkLastColumnUpdateWriteLog(
+      deleteWriteLogEntry(id = 1, metadata = Row("hr", null)),
+      reinsertWriteLogEntry(metadata = Row("hr", null), data = Row(1, "hr", 
-1)))
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(1, -1, "hr") :: Row(2, 2, "hr") :: Nil)
+  }
+
+  test("column-update split: a reinserted row is found by a row-ID column 
declared in another " +
+    "case") {
+    createAndInitTable("PK INT NOT NULL, id INT, salary INT, dep STRING",
+      """{ "PK": 1, "id": 1, "salary": 100, "dep": "hr" }
+        |{ "PK": 2, "id": 2, "salary": 200, "dep": "hr" }
+        |""".stripMargin,
+      splitTableProps)
+
+    sql(s"UPDATE $tableNameAsString SET salary = -1 WHERE PK = 1")
+
+    checkLastColumnUpdateSchema("PK", "dep", "salary")
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY PK"),
+      Row(1, 1, -1, "hr") :: Row(2, 2, 200, "hr") :: Nil)
+  }
+
+  test("column-update split: a row-ID reassignment is written when every 
column is declared") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin,
+      splitReqAttrsTableProps("pk,salary,dep"))
+
+    sql(s"UPDATE $tableNameAsString SET pk = pk + 10, salary = -1 WHERE dep = 
'hr'")
+
+    checkAnswer(
+      sql(s"SELECT * FROM $tableNameAsString ORDER BY pk"),
+      Row(2, 200, "software") :: Row(11, -1, "hr") :: Nil)
+  }
+
+  test("column-update split: Spark does not check whether the row ID reaches 
the reinserted " +
+    "row") {
+    // the fixture cannot commit a reinserted row without its row ID, so this 
checks the plan
+    Seq(
+      // reassigns the row ID, and the declared [pk, dep, salary] leaves out 
`extra`
+      ("pk INT NOT NULL, salary INT, dep STRING, extra STRING", 
splitTableProps,
+        "pk = pk + 10, salary = -1 WHERE dep = 'hr'", Seq("pk", "dep", 
"salary")),
+      // a table that accepts any schema lists the metadata columns in SET
+      ("pk INT NOT NULL, salary INT, dep STRING",
+        tablePropsWith(splitReqAttrsTableProps("pk,salary,dep"), 
"accept-any-schema" -> "true"),
+        "pk = 2, salary = salary, dep = dep, index = index, _partition = 
_partition",
+        Seq("pk", "salary", "dep")),
+      // the row ID is undeclared
+      ("pk INT NOT NULL, salary INT, dep STRING",
+        java.util.Map.of("column-update-split-row-id", "pk"), "salary = -1", 
Seq("salary")),
+      // without required metadata attributes, nothing projects `_partition` 
into the REINSERT row
+      ("pk INT NOT NULL, salary INT, dep STRING",
+        java.util.Map.of("column-update-split-row-id", "_partition", 
"no-metadata", "true"),
+        "salary = -1", Seq("salary"))
+    ).foreach { case (schema, props, assignments, writeColumns) =>
+      withTable(tableNameAsString) {
+        createAndInitTable(schema, """{ "pk": 1, "salary": 100, "dep": "hr" 
}""", props)
+
+        val analyzed = spark.sessionState.executePlan(
+          spark.sessionState.sqlParser.parsePlan(
+            s"UPDATE $tableNameAsString SET $assignments"),
+          CommandExecutionMode.SKIP).analyzed
+
+        val write = analyzed.collectFirst { case w: WriteDelta => w }
+          .getOrElse(fail("couldn't find WriteDelta in the analyzed plan"))
+        assert(write.table.output.map(_.name) == writeColumns)
+      }
+    }
+  }
+
+  test("column-update split: an empty declaration keeps the write full width") 
{
+    // `_partition` is the row ID, and with no metadata attributes it does not 
reach the REINSERT
+    // row. The fixture cannot commit such a row, so this checks the analyzed 
plan.
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |""".stripMargin,
+      tablePropsWith(splitPartitionRowIdTableProps, "no-metadata" -> "true"))

Review Comment:
   Done.



##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedNoMetadataColumnUpdateTableSuite.scala:
##########
@@ -0,0 +1,75 @@
+/*
+ * 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 org.apache.spark.sql.Row
+import org.apache.spark.sql.connector.catalog.Update
+
+class DeltaBasedNoMetadataColumnUpdateTableSuite extends UpdateTableSuiteBase
+  with ColumnUpdateTableSharedTests {
+
+  override protected def deltaUpdate: Boolean = true
+
+  override protected def extraTableProps: java.util.Map[String, String] = {
+    val props = new java.util.HashMap[String, String]()
+    props.put("column-update", "true")
+    props.put("no-metadata", "true")
+    props
+  }
+
+  override protected def reqAttrsTableProps(reqAttrs: String): 
java.util.Map[String, String] = {
+    java.util.Map.of("column-update-req-attrs", reqAttrs, "no-metadata", 
"true")
+  }
+
+  override protected def fullWidthTableProps: java.util.Map[String, String] = {
+    java.util.Map.of("supports-deltas", "true", "no-metadata", "true")
+  }
+
+  override protected def scanMetadataColumns: String = ""
+
+  test("column-update: narrow rows reach the delta writer without metadata") {
+    createAndInitTable("pk INT NOT NULL, salary INT, dep STRING",
+      """{ "pk": 1, "salary": 100, "dep": "hr" }
+        |{ "pk": 2, "salary": 200, "dep": "software" }
+        |""".stripMargin)
+
+    sql(s"UPDATE $tableNameAsString SET salary = -1 WHERE pk = 1")
+
+    assert(!table.lastWriteInfo.metadataSchema().isPresent)
+    checkLastColumnUpdateWriteLog(
+      WriteLogEntry(operation = Update, id = Some(1), data = Some(Row(1, "hr", 
-1))))

Review Comment:
   Done.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/RowLevelWriteColumnPruningSuite.scala:
##########
@@ -0,0 +1,291 @@
+/*
+ * 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.catalyst.optimizer
+
+import org.apache.spark.SparkException
+import org.apache.spark.sql.catalyst.ProjectingInternalRow
+import org.apache.spark.sql.catalyst.analysis.TestRelation
+import org.apache.spark.sql.catalyst.dsl.expressions._
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeReference, AttributeSet, EqualNullSafe, Expression, If, Literal, Not}
+import org.apache.spark.sql.catalyst.plans.PlanTest
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules.RuleExecutor
+import org.apache.spark.sql.catalyst.util.{ReplaceDataProjections, 
WriteDeltaProjections}
+import org.apache.spark.sql.catalyst.util.RowDeltaUtils._
+import org.apache.spark.sql.types.{IntegerType, StructField, StructType}
+
+/**
+ * Tests the [[ColumnPruning]] case that, for a [[RowLevelWrite]] whose write 
relation's column
+ * names differ from the table's, prunes the query columns its projections 
don't read and moves the
+ * projections to the ordinals of the pruned query.
+ */
+class RowLevelWriteColumnPruningSuite extends PlanTest {
+
+  object Optimize extends RuleExecutor[LogicalPlan] {
+    val batches = Batch("Column Pruning", FixedPoint(10),
+      ColumnPruning, CollapseProject, RemoveNoopOperators) :: Nil
+  }
+
+  // t(pk, id, dep, salary, bonus, extra) with the metadata column _partition
+  private val read = LocalRelation(
+    $"pk".int.notNull, $"id".int, $"dep".string, $"salary".int, $"bonus".int, 
$"extra".int,
+    $"_partition".string.notNull)
+
+  private val dataColumns = Seq("pk", "id", "dep", "salary", "bonus", "extra")
+
+  // the data columns of a write that receives pk and salary
+  private val writeColumns = Seq("pk", "salary")
+
+  // the original table, and the write relation that the rewrite narrows to 
`writeColumns`
+  private val tableRelation = TestRelation(relationColumns(dataColumns))
+  private val narrowRelation = TestRelation(relationColumns(writeColumns))
+  private val queryColumns = dataColumns :+ "_partition"
+
+  // the columns of `read` that `SET salary = salary + bonus WHERE dep = 'hr'` 
needs
+  private val updateScanColumns = Set("pk", "dep", "salary", "bonus", 
"_partition")
+
+  private def column(plan: LogicalPlan, name: String): Attribute = {
+    plan.output.find(_.name == name).getOrElse(fail(s"no column $name in 
${plan.output}"))
+  }
+
+  private def relationColumns(names: Seq[String]): Seq[AttributeReference] =
+    names.map(column(read, _).asInstanceOf[AttributeReference])
+
+  private def cond(plan: LogicalPlan): Expression = column(plan, "dep") === 
"hr"
+
+  // the value of every data column after `SET salary = salary + bonus`
+  private def updatedValue(plan: LogicalPlan, name: String): Expression = name 
match {
+    case "salary" => column(plan, "salary") + column(plan, "bonus")
+    case _ => column(plan, name)
+  }
+
+  private def projection(query: LogicalPlan, names: String*): 
ProjectingInternalRow = {
+    val ordinals = names.map(name => query.output.indexWhere(_.name == 
name)).toIndexedSeq
+    val fields = ordinals.map { i =>

Review Comment:
   Done.



##########
sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryRowLevelOperationTable.scala:
##########
@@ -273,6 +335,426 @@ class InMemoryRowLevelOperationTable private (
     override def abort(messages: Array[WriterCommitMessage]): Unit = {}
   }
 
+  // The rows of `buf` in the table's current schema, matched to columns by 
name like a scan does.
+  private def currentRows(buf: BufferedRows): Seq[InternalRow] = {
+    val reader = new BufferedRowsReader(buf, Seq.empty, schema.fields.toSeq, 
schema)
+    try {
+      
Iterator.continually(reader).takeWhile(_.next()).map(_.get().copy()).toList
+    } finally {
+      reader.close()
+    }
+  }
+
+  // Spark resolves a row-ID reference such as `pk` against a column such as 
`PK`, so look a name
+  // up exactly first and then case-insensitively, in the same order.
+  private def findFieldIndex(s: StructType, name: String): Option[Int] =
+    s.getFieldIndex(name).orElse(s.getFieldIndexCaseInsensitive(name))
+
+  private def fieldIndexOf(s: StructType, name: String): Int =
+    findFieldIndex(s, name).getOrElse(s.fieldIndex(name))
+
+  // Finds the one current row with the given row-ID values, matching a data 
column by value and
+  // `_partition` by the partition key.
+  private def currentRowByRowId(values: Seq[(String, Any)]): InternalRow = {
+    val matches = dataMap.values.iterator.flatten.flatMap { buf =>
+      currentRows(buf).filter { row =>
+        values.forall {
+          case (name, value) if name.equalsIgnoreCase(PartitionKeyColumn.name) 
=>
+            buf.keyString() == value.toString
+          case (name, value) =>
+            val i = fieldIndexOf(schema, name)
+            row.get(i, schema.fields(i).dataType) == value
+        }
+      }
+    }.toSeq
+    matches match {
+      case Seq(row) => row
+      case _ => throw new IllegalStateException(
+        s"Expected one row with row ID $values, found ${matches.size}")
+    }
+  }
+
+  // Rebuilds a full table row for a narrow column-update row: the base row's 
values overlaid with
+  // the narrow row's columns. The base row is in the table's current schema.
+  private def overlayNarrowRow(
+      baseRow: Option[InternalRow],
+      narrowRow: InternalRow,
+      narrowSchema: StructType): InternalRow = {
+    val fullRow = new GenericInternalRow(schema.length)
+    baseRow.foreach { base =>
+      for (i <- schema.fields.indices) {
+        val field = schema.fields(i)
+        fullRow.update(i, base.get(i, field.dataType))
+      }
+    }
+    schema.fields.zipWithIndex.foreach { case (field, i) =>
+      narrowSchema.getFieldIndex(field.name).foreach { j =>
+        fullRow.update(i, narrowRow.get(j, field.dataType))
+      }
+    }
+    fullRow
+  }
+
+  private def requiredColumns(prop: String): Array[String] =

Review Comment:
   Done.



-- 
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