dongjoon-hyun commented on code in PR #55518:
URL: https://github.com/apache/spark/pull/55518#discussion_r4516762973
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteRowLevelCommand.scala:
##########
@@ -354,3 +364,70 @@ trait RewriteRowLevelCommand extends Rule[LogicalPlan] {
}
}
}
+
+object RewriteRowLevelCommand extends SQLConfHelper {
+
+ /**
+ * Whether the operation asks for narrow rows: it mixes in
`SupportsColumnUpdates` and declares at
+ * least one column. Only UPDATE delivers them (see
`V2Writes.hasNarrowRows`). An operation that
+ * declares none receives full-width rows.
+ */
+ private[sql] def narrowsWrite(operation: RowLevelOperation): Boolean =
operation match {
+ case op: SupportsColumnUpdates => op.requiredDataAttributes.nonEmpty
+ case _ => false
+ }
+
+ /**
+ * Resolves the connector-declared required data attributes for
column-update writes against
+ * the given relation, in declared order and with the relation's spelling.
Nested fields,
+ * duplicate columns, columns that do not exist in the relation (including a
reference with no
+ * name parts) and metadata columns are rejected with an `AnalysisException`.
+ */
+ private[sql] def resolveRequiredDataAttrs(
+ relation: LogicalPlan,
+ operation: SupportsColumnUpdates): Seq[AttributeReference] = {
+ val refs = operation.requiredDataAttributes.toImmutableArraySeq
+ val names = refs.map(_.fieldNames.toImmutableArraySeq)
+ val nameless = names.filter(_.isEmpty)
+ if (nameless.nonEmpty) {
+ throw QueryCompilationErrors.unknownRequiredDataAttributeError(
+ operation.getClass.getName, nameless)
+ }
+ val nested = names.filter(_.length > 1)
+ if (nested.nonEmpty) {
+ throw QueryCompilationErrors.nestedRequiredDataAttributeError(
+ operation.getClass.getName, nested)
+ }
+ val normalizedNames = names.map(n => SchemaUtils.foldName(n.head,
conf.caseSensitiveAnalysis))
Review Comment:
**80.** Nit, new evidence on item 68: the premise of the reply there, that a
case-insensitive session can't use a table whose column names differ only by
case, no longer holds for UPDATE. f646a6ebf45 (SPARK-60978) makes UPDATE,
DELETE and MERGE on such a table correct in the default session, and the
inherited `UpdateTableSuiteBase` test "SPARK-60978: update keeps columns whose
names differ only by case" runs `UPDATE t SET pk = 3 WHERE pk = 1` on `pk INT
NOT NULL, salary INT, SALARY INT, dep STRING`. With the mix-in, that statement
can't pass when the declaration names either colliding column:
- `pk,salary,SALARY,dep` folds both names to `salary` here and fails with
`COLUMN_UPDATE_DUPLICATE_REQUIRED_DATA_ATTRIBUTE`, although each column is
declared once.
- `pk,salary,dep` or `pk,SALARY,dep` fails at L411 with
`AMBIGUOUS_REFERENCE`, which is not one of the dedicated errors.
Without the mix-in, master runs it. `rowId()` and
`requiredMetadataAttributes()` are also resolved with the resolver alone, so
this is consistent and fails loudly, and a connector that needs one of those
columns is rare. Still, could `resolveRequiredDataAttrs` prefer an exact name
before the resolver, as `findColOrdinal` now does, or could the Javadoc at
`SupportsColumnUpdates.java:55-57` say that a declared name matching two
columns is rejected?
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryRowLevelOperationTable.scala:
##########
@@ -273,6 +338,450 @@ 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()
+ }
+ }
+
+ // 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 == PartitionKeyColumn.name =>
buf.keyString() == value.toString
+ case (name, value) =>
+ val i = schema.fieldIndex(name)
Review Comment:
**79. After a rebase onto the latest master, an inherited test fails in
`DeltaBasedColumnUpdateTableSuite`, because this lookup is case-sensitive.**
[f646a6ebf45](https://github.com/apache/spark/commit/f646a6ebf454141f890d9add8e7a16b377a15c33)
(SPARK-60978) landed after this head's CI run. It adds ["SPARK-60978: update
with a row ID column whose name differs in
case"](https://github.com/apache/spark/blob/f646a6ebf454141f890d9add8e7a16b377a15c33/sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedUpdateTableSuiteBase.scala#L58-L70)
to `DeltaBasedUpdateTableSuiteBase`, which this suite extends with
`column-update=true`. The test creates `PK INT NOT NULL, id INT, dep STRING`
and runs `UPDATE t SET id = -1 WHERE PK = 1` in the default session:
- `declaredColumns` (L397) keeps `pk` only on an exact match, so the
operation declares `[dep, id]` and the write is narrow.
- Spark resolves the row ID `pk` to `PK` with the resolver, which is the
fallback that f646a6ebf45 keeps in `findColOrdinal` for this case.
- At commit, `commitColumnUpdate` calls `currentRowByRowId(Seq("pk" -> pk))`
(L509), and `schema.fieldIndex("pk")` here throws ``[FIELD_NOT_FOUND] No such
struct field `pk` in `PK`, `id`, `dep`.``, so the UPDATE fails.
Spark builds the right narrow write; only the fixture's lookup is off. Could
this match the exact name first and then ignore case, e.g.
`schema.getFieldIndex(name).orElse(schema.getFieldIndexCaseInsensitive(name))`?
L165, L397 and L761 compare `pk` exactly too, though no inherited test reaches
them with a `PK` table today.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/V2Writes.scala:
##########
@@ -109,22 +112,98 @@ object V2Writes extends Rule[LogicalPlan] with
PredicateHelper {
WriteToDataSourceV2(Some(r), microBatchWrite, newQuery, customMetrics)
case rd @ ReplaceData(r: DataSourceV2Relation, _, query, _, projections,
_, None) =>
- val rowSchema = projections.rowProjection.schema
+ val narrowRows = hasNarrowRows(rd)
+ validateWriteRelation(rd, narrowRows)
+ val (rowSchema, columnUpdateSchema) =
+ writeSchemas(projections.rowProjection.schema, narrowRows)
val metadataSchema = projections.metadataProjection.map(_.schema)
val writeOptions = mergeOptions(Map.empty,
r.options.asCaseSensitiveMap.asScala.toMap)
- val writeBuilder = newWriteBuilder(r.table, writeOptions, rowSchema,
metadataSchema)
+ val writeBuilder = newWriteBuilder(r.table, writeOptions, rowSchema,
metadataSchema,
+ columnUpdateSchema)
val write = writeBuilder.build()
+ validateColumnUpdateWrite(rd, write, narrowRows)
Review Comment:
**81.** Nit on the PR description, which becomes the commit message: it says
"For an UPDATE, Spark rejects an invalid declaration at analysis time with
dedicated error conditions", but a declaration that misses a column of the
required distribution or ordering is rejected here, in the optimizer, after
`build()` (L123, and L133 for `WriteDelta`) has already handed the connector
the narrow `LogicalWriteInfo`. For example, with
`column-update-req-attrs=pk,salary` and `column-update-cluster-by=dep`,
analyzing `UPDATE t SET salary = -1 WHERE pk = 1` succeeds, and
`COLUMN_UPDATE_UNDECLARED_WRITE_REQUIREMENT_COLUMNS` appears only when the plan
is optimized, on execution or `EXPLAIN`. The check can't run earlier, since the
requirements come from the `Write`, so maybe "...at analysis time, except for
the columns of the required distribution and ordering, which are checked when
the write is built".
##########
sql/catalyst/src/main/java/org/apache/spark/sql/connector/write/RowLevelOperationInfo.java:
##########
@@ -37,4 +38,22 @@ public interface RowLevelOperationInfo {
* Returns the row-level SQL command (e.g. DELETE, UPDATE, MERGE).
*/
Command command();
+
+ /**
+ * Returns the columns being updated by this operation. Currently only
UPDATE populates it;
+ * other commands report an empty array.
+ * <p>
+ * A column is reported unless its assigned value is the column itself, so
identity assignments
+ * such as {@code SET a = a} are excluded. With the default CHAR and VARCHAR
handling, a
+ * self-assignment on a CHAR or VARCHAR column is still reported, because
Spark pads or
Review Comment:
**82.** Nit on this Javadoc and the PR description, new evidence on item 70:
one more kind of self-assignment is reported. With the default CHAR and VARCHAR
handling, `SET tags = tags` on a column whose type has CHAR or VARCHAR inside
an array, map or struct, such as `tags ARRAY<CHAR(3)>`, is not an identity
either. Alignment targets the restored type (`AssignmentUtils.scala:77`), so
`TableOutputResolver` wraps the value in an `ArrayTransform` with a length
check (`MapFromArrays` or `CreateStruct` for maps and structs), and
`isIdentityAssignment` no longer sees the column itself. On `pk INT NOT NULL,
tags ARRAY<CHAR(3)>, dep STRING`, `UPDATE t SET tags = tags WHERE pk = 1`
reports `[tags]`, so an operation that declares `[pk, dep]` fails with
`COLUMN_UPDATE_REQUIRED_DATA_ATTRIBUTES_MISSING_UPDATED_COLUMNS`. The behavior
matches the top-level case; only the wording is narrower, and the description's
"with two exceptions" reads as a closed list. Maybe "a self-assignment on a
column
whose type contains CHAR or VARCHAR at any depth".
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1552,6 +1552,16 @@ object ColumnPruning extends Rule[LogicalPlan] {
case e @ MergeRows(_, _, _, _, _, _, _, child) if
!child.outputSet.subsetOf(e.references) =>
e.copy(child = prunedChild(child, e.references))
+ // prune unused columns from the query of ReplaceData/WriteDelta whose
write relation differs
+ // from the table, which a column update can cause; a column update that
declares every column
+ // in table order keeps its query, which then has nothing to prune
Review Comment:
**83.** Nit on this comment and the "Read side" bullet of the PR
description: a column update that declares every column in table order can
still have a column to prune, a metadata column that only the condition reads.
On a no-metadata delta table that declares `pk,salary,dep`, `UPDATE t SET
salary = -1 WHERE _partition = 'hr'` adds `_partition` to the read relation
(`RewriteRowLevelCommand.scala:121-122`), and the update projection passes it
through, so the query outputs `[__row_operation, pk, salary, dep, _partition]`
while no projection reads `_partition`. The guard on the next line is false for
this write, so the column stays in the write query. Results are not affected.
Maybe "...keeps its query, like a full-width write".
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala:
##########
@@ -356,6 +357,37 @@ 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 = {
+ val output = query.output.toIndexedSeq
+ AttributeSet(readOrdinals.filter(output.isDefinedAt).map(output))
+ }
+
+ private def readOrdinals: Seq[Int] = 0 +:
queryProjections.flatMap(_.colOrdinals)
+
+ /** Fails if a projection reads an ordinal that the query does not have. */
+ def checkProjectionOrdinals(): Unit = {
+ val numColumns = query.output.length
+ readOrdinals.find(ordinal => ordinal < 0 || ordinal >= numColumns).foreach
{ ordinal =>
+ throw SparkException.internalError(
+ s"A projection of $nodeName reads ordinal $ordinal of a query with
$numColumns columns.")
+ }
+ }
+
+ /**
+ * Replaces the query with a pruned one and moves the projections to the new
ordinals, given a
+ * map from each read ordinal of the current query to its ordinal in the new
one.
+ */
+ def withPrunedQuery(newQuery: LogicalPlan, ordinalMap: Int => Int):
RowLevelWrite
Review Comment:
**85.** Nit, related to [Finding
35](https://github.com/apache/spark/pull/55518#discussion_r4493745560):
`withPrunedQuery` takes the ordinal map from the caller, and
`checkProjectionOrdinals` (L377) only checks that the new ordinals are in
range, so a map that is total but built for another column order would bind
projections to other columns without an error. The only caller, the new
`ColumnPruning` case, builds the map and the pruned `Project` with the same
filter over `w.query.output`, so they agree today. A second caller, such as the
nested-field narrowing you plan, could prune with `Project(w.references.toSeq,
w.query)`, whose order is by name and exprId (`AttributeSet.scala:155`), while
building the map in query order, and every ordinal would still be in range.
Could `withPrunedQuery(newQuery)` derive the map itself from the exprIds of
`newQuery.output`, after checking the current ordinals as Finding 35 suggests
and that ordinal 0 is still the operation column? One trait met
hod could then replace the two overrides.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryRowLevelOperationTable.scala:
##########
@@ -273,6 +338,450 @@ 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()
+ }
+ }
+
+ // 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 == PartitionKeyColumn.name =>
buf.keyString() == value.toString
+ case (name, value) =>
+ val i = schema.fieldIndex(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]):
Array[NamedReference] = {
+ val base = Seq("pk",
"dep").filter(schema.fieldNames.contains).map(FieldReference(_))
+ val baseNames = base.map(_.describe()).toSet
+ (base ++ updatedCols.filterNot(r =>
baseNames.contains(r.describe()))).toArray
+ }
+
+ // 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. It declares
`pk` (the
+ // row-lookup key) and `dep`, where the table has them, plus whatever
columns Spark reports as
+ // being assigned via `RowLevelOperationInfo#updatedColumns()`.
+ class DeltaBasedColumnUpdateOperation(
+ command: Command,
+ updatedCols: Seq[NamedReference] = Nil,
+ options: CaseInsensitiveStringMap = CaseInsensitiveStringMap.empty())
+ extends DeltaBasedOperation(command, options)
+ with SupportsColumnUpdates {
+ override def representUpdateAsDeleteAndInsert(): Boolean = false
+ override def requiredDataAttributes(): Array[NamedReference] =
declaredColumns(updatedCols)
+
+ // 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]] =
Review Comment:
**89.** Nit: `writeRequirementRefs` splits the property itself, without the
empty-entry filter that `requiredColumns` (L392-393) got for item 62. With
`column-update-cluster-by` set to `""`, `",pk"` or `"pk,,dep"`,
`FieldReference("")` throws a `ParseException` in the eager `clusterExprs`
(L435-436), so building the operation fails for every command on that table,
DELETE and MERGE included, while the same text is accepted in
`column-update-req-attrs`.
`Option(properties.get(key)).map(requiredColumns(_).map(FieldReference(_)).toSeq)`
would reuse the existing parser.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteUpdateTable.scala:
##########
@@ -237,4 +253,140 @@ object RewriteUpdateTable extends RewriteRowLevelCommand {
val expandOutput = generateExpandOutput(attrs, outputs)
Expand(outputs, expandOutput, matchedRowsPlan)
}
+
+ /**
+ * Returns the data columns that these assignments set to a new value,
skipping identity
+ * assignments and metadata columns. The assignments must be aligned with
the relation output,
+ * one per column in order, so each assignment is paired with its column. A
column is reported as
+ * the relation's attribute, so it keeps the table's spelling when the SET
clause spells it
+ * differently.
+ */
+ private def collectUpdatedAttrs(
+ relation: DataSourceV2Relation,
+ assignments: Seq[Assignment]): Seq[AttributeReference] = {
+ nonIdentityAssignments(relation, assignments).collect {
+ case (attr, _) if !MetadataAttribute.isValid(attr.metadata) => attr
+ }
+ }
+
+ /**
+ * Pairs each column of the relation with its assignment and keeps the pairs
whose assignment
+ * sets a new value. The assignments must be aligned with the relation
output, one per column in
+ * order.
+ */
+ private def nonIdentityAssignments(
+ relation: DataSourceV2Relation,
+ assignments: Seq[Assignment]): Seq[(AttributeReference, Assignment)] = {
+ relation.output.zip(assignments).collect {
+ case (attr, a @ Assignment(key: Attribute, value)) if
!isIdentityAssignment(key, value) =>
+ attr -> a
+ }
+ }
+
+ /**
+ * Returns the output of a narrow write relation, which is the layout of the
data rows the
+ * connector receives: the connector's `requiredDataAttributes()` if the
operation opts into
+ * column updates and declares at least one column. Returns `None` for a
full-width write. A
+ * mixed-in operation's declaration must cover every updated column, even an
empty one, and a
+ * narrow write rejects a new value for a metadata column.
+ */
+ private def resolveNarrowWriteAttrs(
+ relation: DataSourceV2Relation,
+ operation: RowLevelOperation,
+ assignments: Seq[Assignment],
+ updatedAttrs: Seq[AttributeReference]): Option[Seq[AttributeReference]]
= operation match {
+ case op: SupportsColumnUpdates =>
+ val attrs = RewriteRowLevelCommand.resolveRequiredDataAttrs(relation, op)
+ validateUpdatedColumnsSubset(op, updatedAttrs, AttributeSet(attrs))
+ if (attrs.isEmpty) {
+ None
+ } else {
+ validateNoMetadataAssignments(relation, assignments)
+ Some(attrs)
+ }
+ case _ =>
+ None
+ }
+
+ /**
+ * A connector can locate the original rows of a narrow write through
metadata columns, so a new
+ * value assigned to one would point the connector at another row. Only a
table that accepts any
+ * schema lets an UPDATE assign them; on other tables
`ResolveRowLevelCommandAssignments` rejects
+ * such an assignment, or drops it under the legacy config.
+ */
+ private def validateNoMetadataAssignments(
+ relation: DataSourceV2Relation,
+ assignments: Seq[Assignment]): Unit = {
+ val metadataAssignments = nonIdentityAssignments(relation,
assignments).collect {
Review Comment:
**87.** Nit: `collectUpdatedAttrs` (L267) and this method each rebuild the
non-identity pairs from the raw assignments with complementary metadata
filters, and `resolveNarrowWriteAttrs` takes the raw assignments again only for
this second pass. Item 16 had removed that, and the fix for item 67 brought it
back. Splitting once in `apply`, e.g. `val (metadataUpdates, dataUpdates) =
nonIdentityAssignments(r, assignments).partition { case (attr, _) =>
MetadataAttribute.isValid(attr.metadata) }`, and passing
`metadataUpdates.map(_._2)` here would keep every check in the same order and
state the alignment precondition once instead of in two Scaladocs (L259-260 and
L274-275).
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1552,6 +1552,16 @@ object ColumnPruning extends Rule[LogicalPlan] {
case e @ MergeRows(_, _, _, _, _, _, _, child) if
!child.outputSet.subsetOf(e.references) =>
e.copy(child = prunedChild(child, e.references))
+ // prune unused columns from the query of ReplaceData/WriteDelta whose
write relation differs
+ // from the table, which a column update can cause; a column update that
declares every column
+ // in table order keeps its query, which then has nothing to prune
+ case w: RowLevelWrite if w.table.output != w.originalTable.output &&
Review Comment:
**86.** Nit: this guard and the check in `V2Writes` that makes early pruning
safe use different predicates. Pruning before `V2Writes` is safe only when the
write's distribution and ordering read columns that the projections keep, and
`validateColumnUpdateWrite` checks that only when `hasNarrowRows` holds, while
this case fires on attribute inequality. They agree for every plan Spark
builds, since the rewrite builds both relations from the same `r`. A rule that
rebuilds a full-width write relation with the same names and new exprIds or
nullability, for example through `DataSourceV2Relation.create` instead of
`copy`, would make this case prune a write that `V2Writes` doesn't check, and
`prepareQuery` would then fail to resolve a clustering column that only the
condition read, the failure b52b8d1 fixed. Comparing names here, as
`validateWriteRelation` does, or a `RowLevelWrite` member that both places use,
would rule that out.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteUpdateTable.scala:
##########
@@ -237,4 +253,140 @@ object RewriteUpdateTable extends RewriteRowLevelCommand {
val expandOutput = generateExpandOutput(attrs, outputs)
Expand(outputs, expandOutput, matchedRowsPlan)
}
+
+ /**
+ * Returns the data columns that these assignments set to a new value,
skipping identity
+ * assignments and metadata columns. The assignments must be aligned with
the relation output,
+ * one per column in order, so each assignment is paired with its column. A
column is reported as
+ * the relation's attribute, so it keeps the table's spelling when the SET
clause spells it
+ * differently.
+ */
+ private def collectUpdatedAttrs(
+ relation: DataSourceV2Relation,
+ assignments: Seq[Assignment]): Seq[AttributeReference] = {
+ nonIdentityAssignments(relation, assignments).collect {
+ case (attr, _) if !MetadataAttribute.isValid(attr.metadata) => attr
+ }
+ }
+
+ /**
+ * Pairs each column of the relation with its assignment and keeps the pairs
whose assignment
+ * sets a new value. The assignments must be aligned with the relation
output, one per column in
+ * order.
+ */
+ private def nonIdentityAssignments(
+ relation: DataSourceV2Relation,
+ assignments: Seq[Assignment]): Seq[(AttributeReference, Assignment)] = {
+ relation.output.zip(assignments).collect {
+ case (attr, a @ Assignment(key: Attribute, value)) if
!isIdentityAssignment(key, value) =>
+ attr -> a
+ }
+ }
+
+ /**
+ * Returns the output of a narrow write relation, which is the layout of the
data rows the
+ * connector receives: the connector's `requiredDataAttributes()` if the
operation opts into
+ * column updates and declares at least one column. Returns `None` for a
full-width write. A
+ * mixed-in operation's declaration must cover every updated column, even an
empty one, and a
+ * narrow write rejects a new value for a metadata column.
+ */
+ private def resolveNarrowWriteAttrs(
+ relation: DataSourceV2Relation,
+ operation: RowLevelOperation,
+ assignments: Seq[Assignment],
+ updatedAttrs: Seq[AttributeReference]): Option[Seq[AttributeReference]]
= operation match {
+ case op: SupportsColumnUpdates =>
+ val attrs = RewriteRowLevelCommand.resolveRequiredDataAttrs(relation, op)
+ validateUpdatedColumnsSubset(op, updatedAttrs, AttributeSet(attrs))
+ if (attrs.isEmpty) {
+ None
+ } else {
+ validateNoMetadataAssignments(relation, assignments)
+ Some(attrs)
+ }
+ case _ =>
+ None
+ }
+
+ /**
+ * A connector can locate the original rows of a narrow write through
metadata columns, so a new
+ * value assigned to one would point the connector at another row. Only a
table that accepts any
+ * schema lets an UPDATE assign them; on other tables
`ResolveRowLevelCommandAssignments` rejects
+ * such an assignment, or drops it under the legacy config.
+ */
+ private def validateNoMetadataAssignments(
+ relation: DataSourceV2Relation,
+ assignments: Seq[Assignment]): Unit = {
+ val metadataAssignments = nonIdentityAssignments(relation,
assignments).collect {
+ case (attr, a) if MetadataAttribute.isValid(attr.metadata) => a
+ }
+ if (metadataAssignments.nonEmpty) {
+ throw QueryCompilationErrors.invalidRowLevelOperationAssignments(
+ metadataAssignments,
+
ResolveRowLevelCommandAssignments.metadataColumnAssignmentErrors(metadataAssignments))
+ }
+ }
+
+ /**
+ * Enforces that every updated column is present in the connector-declared
+ * `requiredDataAttributes()`. Comparison is at root-column granularity.
+ */
+ private def validateUpdatedColumnsSubset(
+ operation: RowLevelOperation,
+ updatedAttrs: Seq[AttributeReference],
+ declared: AttributeSet): Unit = {
+ val missing = updatedAttrs.filterNot(declared.contains).map(a =>
Seq(a.name))
+ if (missing.nonEmpty) {
+ throw
QueryCompilationErrors.requiredDataAttributesMissingUpdatedColumnsError(
+ operation.getClass.getName, missing)
+ }
+ }
+
+ /**
+ * For connectors that opt into narrow column updates AND represent UPDATE
as delete + insert,
+ * reject reassignment of any row-ID column, unless
`requiredDataAttributes()` covers every
+ * column of the relation. In that case the REINSERT payload already is the
full row with
+ * the new row-ID value, and the DELETE half still carries the original
row-ID via
+ * `newLazyRowIdProjection`, so reassignment is safe. Otherwise the REINSERT
path has no row-ID
+ * channel to reconstruct columns outside `requiredDataAttributes()`.
+ */
+ private def validateNoRowIdReassignment(
+ operation: RowLevelOperation,
+ relation: DataSourceV2Relation,
+ declared: AttributeSet,
+ updatedAttrs: Seq[AttributeReference],
+ rowIdAttrs: Seq[Attribute]): Unit = {
+ if (!relation.outputSet.subsetOf(declared)) {
Review Comment:
**84.** Nit on the wording of this exemption: the Javadoc
(`SupportsColumnUpdates.java:93-96`), the PR description and
`COLUMN_UPDATE_SPLIT_ROW_ID_REASSIGNMENT` say that the UPDATE must not list a
metadata column, but this check also refuses the exemption when a metadata
column is only referenced. On a table that accepts any schema,
`AddMetadataColumns` does not skip the target (`Analyzer.scala:1198-1199`), so
a metadata column in WHERE adds every metadata column to the relation output,
and the connector's own alignment rule then has to give each one an identity
assignment. With a split operation that declares `pk,salary,dep`, `UPDATE t SET
pk = pk + 10, salary = -1 WHERE _partition = 'hr'` then fails here, and the
error asks not to list metadata columns in SET, which the statement doesn't do;
without the `_partition` predicate it passes. Spark itself doesn't align
UPDATEs on such tables, so this needs a connector rule to happen. If the
stricter check is intended, maybe "reference
s no metadata column" in those three places.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/connector/catalog/InMemoryRowLevelOperationTable.scala:
##########
@@ -273,6 +338,450 @@ 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()
+ }
+ }
+
+ // 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 == PartitionKeyColumn.name =>
buf.keyString() == value.toString
+ case (name, value) =>
+ val i = schema.fieldIndex(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]):
Array[NamedReference] = {
+ val base = Seq("pk",
"dep").filter(schema.fieldNames.contains).map(FieldReference(_))
+ val baseNames = base.map(_.describe()).toSet
+ (base ++ updatedCols.filterNot(r =>
baseNames.contains(r.describe()))).toArray
+ }
+
+ // 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. It declares
`pk` (the
+ // row-lookup key) and `dep`, where the table has them, plus whatever
columns Spark reports as
+ // being assigned via `RowLevelOperationInfo#updatedColumns()`.
+ class DeltaBasedColumnUpdateOperation(
+ command: Command,
+ updatedCols: Seq[NamedReference] = Nil,
+ options: CaseInsensitiveStringMap = CaseInsensitiveStringMap.empty())
+ extends DeltaBasedOperation(command, options)
+ with SupportsColumnUpdates {
+ override def representUpdateAsDeleteAndInsert(): Boolean = false
+ override def requiredDataAttributes(): Array[NamedReference] =
declaredColumns(updatedCols)
+
+ // 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(_.split(",").map(name =>
FieldReference(name.trim)).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 DeltaBasedColumnUpdateOperationWithReqAttrs(
Review Comment:
**90.** Nit: this class, `DeltaBasedColumnUpdateSplitOperationWithReqAttrs`
(L615) and `PartitionBasedColumnUpdateOperationWithReqAttrs` (L720) only
replace `requiredDataAttributes()` of a base class that derives it from
`updatedCols`, and the `updatedCols = Nil` defaults (L408, L537 and L638) are
there mostly for them. If the base classes took the declaration as a
constructor argument, the dispatcher could pass
`declaredColumns(info.updatedColumns().toSeq)`,
`requiredColumns(...).map(FieldReference(_))` or `info.updatedColumns()`, which
would drop about 20 lines and show where each declaration comes from in one
place. The class-name constants in the tests and the constructions at
`ColumnUpdateTableSharedTests.scala:192` and `:196`, which need `[pk, dep]`,
would change with it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteRowLevelCommand.scala:
##########
@@ -354,3 +364,70 @@ trait RewriteRowLevelCommand extends Rule[LogicalPlan] {
}
}
}
+
+object RewriteRowLevelCommand extends SQLConfHelper {
+
+ /**
+ * Whether the operation asks for narrow rows: it mixes in
`SupportsColumnUpdates` and declares at
+ * least one column. Only UPDATE delivers them (see
`V2Writes.hasNarrowRows`). An operation that
+ * declares none receives full-width rows.
+ */
+ private[sql] def narrowsWrite(operation: RowLevelOperation): Boolean =
operation match {
Review Comment:
**91.** Nit: since b52b8d1 replaced both uses in `RewriteUpdateTable`,
`V2Writes.hasNarrowRows` (`V2Writes.scala:145`) is the only caller, so
`hasNarrowRows` could match `case op: SupportsColumnUpdates => op.command ==
UPDATE && op.requiredDataAttributes.nonEmpty` itself. If you take the
shared-member option of item 86, this helper is the natural place for it
instead.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedColumnUpdateTableSuite.scala:
##########
@@ -0,0 +1,707 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.{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, InMemoryBaseTable,
InMemoryRowLevelOperationTable, Reinsert}
+import org.apache.spark.sql.connector.expressions.{FieldReference,
NamedReference}
+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 val splitWithRowIdOperationClass =
+
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperationWithRowId].getName
+
+ private val splitReqAttrsOperationClass =
+
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperationWithReqAttrs].getName
+
+ private def splitReqAttrsTableProps(reqAttrs: String): java.util.Map[String,
String] = {
+ tablePropsWith(reqAttrsTableProps(reqAttrs), "split-updates" -> "true")
+ }
+
+ private def createAndInitTableWithReqAttrs(
Review Comment:
**92.** Nit: `createAndInitTableWithReqAttrs` and `createAndInitTableSplit`
(L89) only reorder the arguments of `createAndInitTable(schema, data, props)`,
which L96, L446, L462, L478 and L541 of this suite, and
`GroupBasedColumnUpdateTableSuite.scala:447`, call directly with the same kind
of properties. Calling it directly at the eight call sites would leave one
spelling, and avoid a near-twin of the shared `createAndInitTableWithProps`,
which builds a fixed table.
##########
sql/core/src/test/scala/org/apache/spark/sql/connector/DeltaBasedColumnUpdateTableSuite.scala:
##########
@@ -0,0 +1,707 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connector
+
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.{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, InMemoryBaseTable,
InMemoryRowLevelOperationTable, Reinsert}
+import org.apache.spark.sql.connector.expressions.{FieldReference,
NamedReference}
+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 val splitWithRowIdOperationClass =
+
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperationWithRowId].getName
+
+ private val splitReqAttrsOperationClass =
+
classOf[InMemoryRowLevelOperationTable#DeltaBasedColumnUpdateSplitOperationWithReqAttrs].getName
+
+ private def splitReqAttrsTableProps(reqAttrs: String): java.util.Map[String,
String] = {
+ tablePropsWith(reqAttrsTableProps(reqAttrs), "split-updates" -> "true")
+ }
+
+ private def createAndInitTableWithReqAttrs(
+ reqAttrs: String,
+ schemaString: String,
+ jsonData: String): Unit = {
+ createAndInitTable(schemaString, jsonData, reqAttrsTableProps(reqAttrs))
+ }
+
+ private val splitTableProps = tablePropsWith(extraTableProps,
"split-updates" -> "true")
+
+ private val splitPartitionRowIdTableProps =
+ java.util.Map.of("column-update-split-row-id", "_partition")
+
+ private def createAndInitTableSplit(schemaString: String, jsonData: String):
Unit = {
+ createAndInitTable(schemaString, jsonData, splitTableProps)
+ }
+
+ 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), dep
STRING")
+ sql(s"INSERT INTO $tableNameAsString VALUES (1, 1, 'a', 'x', 'hr')")
+
+ sql(s"UPDATE $tableNameAsString SET id = id, c = c, v = v WHERE pk = 1")
+
+ checkLastUpdatedColumns("c", "v")
+ checkAnswer(
+ sql(s"SELECT * FROM $tableNameAsString"),
+ Row(1, 1, "a ", "x", "hr") :: Nil)
+ }
+
+ test("column-update: CHAR and VARCHAR self-assignments are not reported when
the types are " +
+ "preserved") {
+ withSQLConf(SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO.key -> "true") {
+ createTable("pk INT NOT NULL, id INT, c CHAR(3), v VARCHAR(10), dep
STRING")
+ sql(s"INSERT INTO $tableNameAsString VALUES (1, 1, 'a', 'x', 'hr')")
+
+ sql(s"UPDATE $tableNameAsString SET id = -1, c = c, v = v WHERE pk = 1")
+
+ checkLastUpdatedColumns("id")
+ checkAnswer(
+ sql(s"SELECT * FROM $tableNameAsString"),
+ Row(1, -1, "a ", "x", "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") {
+ createAndInitTableSplit("pk INT NOT NULL, salary INT, dep STRING",
+ """{ "pk": 1, "salary": 100, "dep": "hr" }
+ |{ "pk": 2, "salary": 200, "dep": "hr" }
+ |""".stripMargin)
+ 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") {
+ createAndInitTableSplit("pk INT NOT NULL, salary INT, dep STRING",
+ """{ "pk": 1, "salary": 100, "dep": "hr" }
+ |{ "pk": 2, "salary": 200, "dep": "software" }
+ |""".stripMargin)
+ checkMergeFallsBackToFullWidthRows()
+ }
+
+ test("column-update: undeclared write requirement columns are rejected") {
+ val excludeColumnPruning = SQLConf.OPTIMIZER_EXCLUDED_RULES.key ->
ColumnPruning.ruleName
+ Seq(
+ (reqAttrsTableProps("pk,salary"), "dep", reqAttrsOperationClass,
"[`dep`]"),
+ (splitReqAttrsTableProps("pk,salary"), "dep",
splitReqAttrsOperationClass, "[`dep`]"),
+ (tablePropsWith(reqAttrsTableProps("pk,salary"),
"column-update-order-by" -> "pk"), "dep",
+ reqAttrsOperationClass, "[`dep`]"),
+ (tablePropsWith(reqAttrsTableProps("pk,salary"),
"column-update-order-by" -> "dep"), "pk",
+ reqAttrsOperationClass, "[`dep`]"),
+ (tablePropsWith(reqAttrsTableProps("pk,salary"),
+ "column-update-cluster-by-nested-transform" -> "true"), "dep",
reqAttrsOperationClass,
+ "[`dep`]"),
+ (reqAttrsTableProps("pk,salary"), "id,dep", reqAttrsOperationClass,
"[`id`, `dep`]"),
+ (reqAttrsTableProps("pk,salary,s"), "s.missing", reqAttrsOperationClass,
+ "[`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(
+ reqAttrsOperationClass, Seq(Seq.empty[String] ->
None)).asInstanceOf[AnalysisException],
+ condition = "COLUMN_UPDATE_UNDECLARED_WRITE_REQUIREMENT_COLUMNS",
+ parameters = Map("connector" -> reqAttrsOperationClass, "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") {
+ createAndInitTableWithReqAttrs("pk,id", "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)
+
+ 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") {
+ createAndInitTableWithReqAttrs("PK,SALARY,dep", "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 = 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: DELETE on a scan that returns unrequested columns is
unaffected") {
Review Comment:
**88.** Nit: since b52b8d1 limited the new `ColumnPruning` case to writes
whose relation differs from the table, this test no longer reaches it. A DELETE
builds `relation.copy(table = operationTable)`
(`RewriteDeleteFromTable.scala:123`), so the guard is false, and the test runs
master's DELETE scan pushdown and the fixture's commit, the same PR paths as
the shared "row-level DELETE falls back to full-width rows"
(`ColumnUpdateTableSharedTests.scala:415`). The name suggests an interaction
with the new pruning that no longer exists, so maybe drop it or fold the
partial pruning into that shared test, as with the DELETE test in item 73.
--
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]