dongjoon-hyun commented on code in PR #55518:
URL: https://github.com/apache/spark/pull/55518#discussion_r4570000394
##########
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:
**95. Since 1bfb0f5b43c, this lookup can pick the wrong row, and no test
runs it.** The split commit rebuilds a REINSERT row from the current row whose
row ID equals the value in the narrow row (L563-567, L589-593), and
`currentRowByRowId` searches the stored rows before `withDeletes` runs (L605).
When the UPDATE assigns a declared `pk`, that value is the new one, and Spark
no longer rejects such an UPDATE. With `splitReqAttrsTableProps("pk,salary")`
and the rows of `createAndInitTableWithProps`:
- `UPDATE t SET pk = 2, salary = 0 WHERE pk = 1` overlays `[2, 0]` on the
stored `pk = 2` row and commits `(2, 2, hr, 0, 20, 1)` instead of `(2, 1, hr,
0, 10, 1)`, with no error.
- `SET pk = 3 - pk, salary = 0 WHERE dep = 'hr'` commits `(1, 1, hr, 0, 10,
1)` and `(2, 2, hr, 0, 20, 1)` instead of `(1, 2, hr, 0, 20, 1)` and `(2, 1,
hr, 0, 10, 1)`.
- `SET pk = pk + 10, salary = 0 WHERE pk = 1` throws `IllegalStateException:
Expected one row with row ID ..., found 0`.
The copy-on-write arm of the dispatcher falls back to full width for this
case (L172-173, L182-184), but the split arms (L178-179, and L187-190 with a
`pk` row ID) don't. The shared test "reassigning a declared row-ID column keeps
the row's other columns" (`ColumnUpdateTableSharedTests.scala:246-271`) never
runs on a split table, and the only executed split reassignment
(`DeltaBasedColumnUpdateTableSuite.scala:486-498`) declares every column, so
`coversTable` skips the lookup. L547-552 and L611-612 also still describe the
guarantee that 1bfb0f5b43c removed. Could the split arms get the same fallback
when `updatedColumns()` contains `pk` and the declaration does not cover the
table, and could the shared reassignment test also run on a split table?
##########
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:
**98. These tests can't tell whether `c` is written.** Both CHAR
self-assignment tests check `updatedColumns()` and then read back values that
`INSERT ... VALUES` already padded on write, so `checkAnswer` passes whether or
not the narrow write includes `c`. 4e7c51d8f4b shows it: it changed the
expected list here from `id` to `id, c, a, m, s` without touching the expected
row, and CI stayed green. Reporting `c` matters for a CHAR value stored without
padding, for example by another engine or with
`spark.sql.legacy.charVarcharAsString=true`: a full-width `SET c = c` stores
the padded value, and a narrow write must store it too. None of the inherited
SPARK-61479 tests self-assigns a CHAR column, and
`ColumnUpdateTableSharedTests` has no CHAR test. Could a shared test append `c
= 'a'` under `spark.sql.legacy.charVarcharAsString=true`, run `UPDATE t SET id
= -1, c = c WHERE pk = 1`, and check both `checkLastColumnUpdateSchema(...)`,
so that a fallback to full width cannot pass it, and
the stored value read under the legacy config?
##########
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:
**94. Since 1bfb0f5b43c, a declared row-ID column in the reinserted row can
carry a new value, and this paragraph doesn't say so.** A narrow split UPDATE
that assigns a declared data row-ID column is now accepted. Its REINSERT row
carries the assigned value, because `deltaReinsertOutput` reads
`assignments.map(_.value)` (`RewriteRowLevelCommand.scala:221`), and only the
DELETE carries the original row ID. L59-62 tell a connector to declare "any
columns needed for row lookup or routing" and to preserve undeclared values
itself, while L71-76 give the way out ("its builder should build an operation
without this mix-in when ... `updatedColumns()` contains that column") only to
an operation that does not mix in `SupportsDelta`. So a split connector that
completes a reinserted row by looking up its declared row ID, as this PR's own
fixture does (item 95), stitches it onto the wrong row:
- `rowId()` is `[pk]`, `representUpdateAsDeleteAndInsert()` is true, the
declaration is `[pk, salary]`, and the table has rows with `pk` 1 and 2.
- `UPDATE t SET pk = 2, salary = 0 WHERE pk = 1` sends `delete(id = [1])`
and `reinsert(row = [2, 0])`. A lookup by `pk = 2` finds the other row and
silently copies its undeclared columns. With `pk = pk + 10`, it finds no row.
- A CHAR row-ID column stored without padding does the same with `SET pk =
pk`, which `updatedColumns()` reports.
Before 1bfb0f5b43c, Spark rejected this UPDATE with
`COLUMN_UPDATE_SPLIT_ROW_ID_REASSIGNMENT`; now only this Javadoc can warn.
Keeping the agreed outcome, with no Spark check, could this paragraph add
something like the following? The PR description's "A group-based connector
should locate original rows ..." bullet has the same gap.
```java
* others are null. Spark does not relate a reinserted row to the deleted
row. A declared
* column that {@link RowLevelOperationInfo#updatedColumns()} reports,
such as an assigned
* row-ID column, carries its assigned value in the reinserted row, which
can differ from the
* row ID passed to {@link DeltaWriter#delete}. A connector that relates
the two rows through a
* data column can build an operation without this mix-in when
* {@link RowLevelOperationInfo#updatedColumns()} contains that column.
```
##########
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:
**96. This reason holds only for the last two cases, and case 2 builds a
plan that cannot run.** Cases 1 and 2 are the two removed
`COLUMN_UPDATE_SPLIT_ROW_ID_REASSIGNMENT` tests: `pk` is declared and reaches
the reinserted row, with its new value.
- Case 1 cannot commit because the fixture looks up the reassigned `pk = 11`
(item 95), not because the row ID is missing.
- Case 2 declares every data column, so `coversTable` skips the lookup, and
the fixture could commit it. But the table accepts any schema, so the target
also outputs `index` and `_partition`, and `buildDeletesAndInserts` builds an
`Expand` whose REINSERT projection has 8 expressions over 6 output columns:
`assignments.map(_.value)` already includes the two metadata values, and
`nullifyMetadataOnReinsert` adds them again. As far as I can tell from the
code, running it with `sql(...)` fails in `ExpandExec` codegen with
`ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6`. The same
statement fails the same way on master with a full-width split table, so that
bug is not this PR's, but this test now asserts that Spark accepts a plan that
cannot run.
Could cases 1 and 2 move to a test named for the reassignment, with case 2
left out or noted until that `Expand` bug is fixed, and the comment say why
each remaining case only checks the plan? Using `.optimizedPlan` under
`CommandExecutionMode.SKIP` would also run `V2Writes` without running the write.
##########
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:
**100.** Nit: "every scan of the target table" leaves out the scan of the
runtime group filter. The PR description says `executeAndCheckScan` "checks
every scan of the target table", and this Scaladoc says "its scans of the
target table", but `executeAndCollectScanSchemas` uses `collect` (L298-300),
which does not descend into subqueries. So the group filter's scan of the same
table, under the primary scan's `runtimeFilters`, is never checked, and some
tests depend on that. "column-update ReplaceData: the subquery plan narrows the
write relation and the scan" (`GroupBasedColumnUpdateTableSuite.scala:171-181`)
expects `pk, dep, salary, bonus, extra, _partition, index`, while the group
filter's scan of the target reads only `dep`. Maybe "every scan of the target
table in the main plan, not the one of the runtime group filter" in both places.
##########
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:
**105.** Nit: `DataTypeUtils.fromAttributes` builds this schema.
`ProjectingInternalRow(DataTypeUtils.fromAttributes(ordinals.map(query.output)),
ordinals)` gives the same `StructType` here, since these attributes carry no
metadata.
##########
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:
**104.** Nit: this test could be the first row of the next one. After
4e7c51d8f4b turned the next test into a table over SQL confs, the two tests
share the DDL, the INSERT and the expected row except `id`. Adding `Nil ->
Seq("id", "c", "v", "a", "m", "s")` to that table, which assigns `id = -1`, and
removing this test loses only the `id = id` check, which L188-189 already make.
##########
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:
**103.** Nit, placement as in item 19: `replaceReadPartitions` now sits
between `PartitionBasedOperation` and its batch write
`PartitionBasedReplaceData`, which were adjacent before. The PR's other shared
commit helpers (`currentRows`, `currentRowByRowId`, `overlayNarrowRow`,
`requiredColumns`, `declaredColumns`) are grouped at L338-407, near its second
caller (L724). AGENTS.md asks to "put the new member with the code it belongs
with". Could it move into that group?
##########
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:
**106.** Nit: `requiredColumns` is `Utils.stringToSeq`.
`SparkStringUtils.stringToSeq`, which `org.apache.spark.util.Utils` mixes in,
also does `split(",").map(_.trim()).filter(_.nonEmpty)`, and catalyst already
calls it (`Optimizer.scala:566`). Both callers (L169, L430) could use it and
drop `.toSeq`.
##########
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:
**107.** Nit: `updateWriteLogEntry(id = 1, metadata = null, data = ...)`
builds these entries, as in the sibling no-metadata suites
(`DeltaBasedNoMetadataUpdateTableSuite.scala:53`).
`checkLastColumnUpdateWriteLog` compares `metadata.orNull`, so the check is the
same here and at L70, and the `Update` import goes away.
##########
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:
**102.** Nit: `narrowAttrs` is now only unwrapped. `resolveNarrowWriteAttrs`
returns an `Option` so that `buildWriteDeltaPlan` could test
`narrowAttrs.isDefined`, and since 1bfb0f5b43c the only use is
`narrowAttrs.getOrElse(r.output)` (L55). Returning the write attributes
directly, `relation.output` for a full-width write, as `resolveWriteAttrs` did
before b52b8d1, would drop the local, the `None` and `Some` branches and the
"Returns `None` for a full-width write" sentence (L271).
##########
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:
**101.** Nit: `splitUpdates` is left over from the removed validation. It
was added to share the flag with `if (splitUpdates && narrowAttrs.isDefined)`,
which 1bfb0f5b43c removed, and now only L190 reads it. Inlining it restores
master's `val rowDeltaPlan = if (operation.representUpdateAsDeleteAndInsert) {`
and drops two changed lines of existing code.
##########
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:
**97.** Nit: this setup existed only for the removed
`COLUMN_UPDATE_SPLIT_ROW_ID_NOT_DECLARED`. Item 72 asked for a `_partition` row
ID with `no-metadata` because, without the empty-declaration guard, this UPDATE
failed with that error. With the error gone, the setup only stops the fixture
from committing, which is why the test checks the analyzed plan (L536-537) and
repeats the analysis block of the previous test. The empty-declaration branch
(`RewriteUpdateTable.scala:283-284`) does not depend on split mode, and
`splitReqAttrsTableProps("")` with `SET salary = salary WHERE pk = 1` commits
end to end, because the row ID is `pk` and the write is full width. A
regression of that guard would still fail it, and the test would also run
`V2Writes` and check the answer. Could this test use that form, with
`checkLastUpdatedColumns()`, `checkLastWriteIsFullWidth()` and `checkAnswer`?
##########
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:
**99.** Nit: since the merge of master, a comment in `ApplyCharTypePadding`
explains its behavior with the `references` that this PR replaces.
[aa77cd990b7](https://github.com/apache/spark/commit/aa77cd990b7a42753d01e12ef24d1b94381fa4f2)
(SPARK-61462), merged here in 12a461d2248, says a group-based DELETE refers to
the padded alias because "`ReplaceData.references` is `query.outputSet`"
(`ApplyCharTypePadding.scala:147`). This PR removed that override, so
`references` is now the operation column plus the columns the projections read
(L371-374). Nothing changes today, because the row projection of a group-based
DELETE reads every data column, but the stated reason no longer holds, and that
file is outside this diff, so it is easy to miss. Maybe: "a `ReplaceData`
references every column its projections read, and the row projection of a
group-based DELETE reads every data column, so a group-based DELETE refers to
the padded alias".
--
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]