spark-test commented on code in PR #60486:
URL: https://github.com/apache/spark/pull/60486#discussion_r4573595937
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/RewriteUpdateTable.scala:
##########
@@ -43,22 +45,48 @@ object RewriteUpdateTable extends RewriteRowLevelCommand {
EliminateSubqueryAliases(aliasedTable) match {
case r @ ExtractV2Table(tbl: SupportsRowLevelOperations) =>
checkNoGeneratedColumns(r, UPDATE)
+ val dataAssignments = removeMetadataAssignments(assignments)
val table = buildOperationTable(tbl, UPDATE, r.options)
val updateCond = cond.getOrElse(TrueLiteral)
table.operation match {
case _: SupportsDelta =>
- buildWriteDeltaPlan(r, table, assignments, updateCond)
+ buildWriteDeltaPlan(r, table, dataAssignments, updateCond)
case _ if SubqueryExpression.hasSubquery(updateCond) =>
- buildReplaceDataWithUnionPlan(r, table, assignments, updateCond)
+ buildReplaceDataWithUnionPlan(r, table, dataAssignments,
updateCond)
case _ =>
- buildReplaceDataPlan(r, table, assignments, updateCond)
+ buildReplaceDataPlan(r, table, dataAssignments, updateCond)
}
case _ =>
u
}
}
+ // AddMetadataColumns may add the metadata columns to the target table of an
UPDATE on a table
+ // that accepts any schema, so its aligned assignments may include one for
each metadata column.
+ // However, only data columns are written, and the metadata values passed to
the writer are
+ // defined by MetadataColumn (e.g. PRESERVE_ON_UPDATE). So an assignment of
a metadata column to
+ // itself is removed, and any other assignment to a metadata column is
rejected unless the legacy
+ // behavior is enabled, as ResolveRowLevelCommandAssignments does for other
tables.
+ private def removeMetadataAssignments(assignments: Seq[Assignment]):
Seq[Assignment] = {
Review Comment:
**Non-blocking (P2):** This handling stays private to `RewriteUpdateTable`,
but `RewriteMergeIntoTable` consumes the same target output and is unchanged.
For a MERGE on a table that accepts any schema, `AddMetadataColumns` still
appends every metadata column to the target once the resolved MERGE references
one (`isRowLevelCommandTarget` is false there, Analyzer.scala:1259-1260), and
`MetadataColumnAssignments` skips the command
(ResolveRowLevelCommandAssignments.scala:100). Spark leaves resolving such a
MERGE to rules the table injects (Analyzer.scala:1805-1809), but it still
rewrites the MERGE once its actions are aligned.
Reading the code with this PR's in-memory test table and an injected rule
that resolves and aligns MERGE the way `ResolveRowLevelCommandAssignments` does
for other tables:
- `MERGE INTO t USING s ON t.pk = s.pk WHEN MATCHED AND t._partition = 'hr'
THEN DELETE` builds a group-based `ReplaceData` whose row attributes are
`relation.output` (RewriteMergeIntoTable.scala:197). The carried-over rows and
`LogicalWriteInfo.schema()` therefore include `index` and `_partition` as data
columns. The delta-based plan (:308) and the insert-only plans (:73, :118) take
the same output.
- With `THEN UPDATE SET id = -1` instead, the aligned action gains `index =
index` and `_partition = _partition`, and the group-based instruction emits
those values ahead of the nullified metadata (:486-490). The metadata
projection looks `index` up by name and finds the aligned value, so the
connector gets the old `index` instead of `null`, although its
`PRESERVE_ON_UPDATE` is false.
- `index = 5` in that action passes analysis and reaches the connector as
the `index` metadata, although the Spark 4.4 migration note and the doc of
`spark.sql.legacy.ignoreMetadataColumnAssignments` say that MERGE fails on it.
So after this PR, UPDATE and MERGE handle the same table differently, and no
MERGE test covers such a target. If MERGE is meant to stay out of this PR, a
TODO here naming it would show readers of this code that the fix is partial.
**Recommended change:** Move the PR's data-column filter (dataAttrs) and its
metadata-assignment check out of RewriteUpdateTable into
RewriteRowLevelCommand, and apply them in RewriteMergeIntoTable. When
AddMetadataColumns has widened the target of a MERGE, the rewrite then uses
only the target's data columns as the row attributes of the ReplaceData and
WriteDelta plans and as the output of both insert-only append plans. Each
UPDATE and INSERT action keeps only its data-column assignments. An UPDATE
assignment of a metadata column to itself, or an INSERT assignment of a
nullable metadata column to a null literal, including the Alias around a null
literal that Spark's INSERT aligner produces, is what alignment over the
widened target adds, so it is dropped. Any other metadata-column assignment
fails with DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS, unless
spark.sql.legacy.ignoreMetadataColumnAssignments is true, in which case it is
dropped. In the group-based MERGE pl
an, every instruction emits its metadata values in the order of the metadata
columns of the relation it reads, as the carry-over output already does,
instead of the order of the operation's required metadata columns.
RewriteUpdateTable switches to the shared helpers without changing its
behavior. Add DSv2 MERGE row-level tests on tables marked accept-any-schema.
They run through a test-only session extension that injects a rule to resolve
and align MERGE on such tables, because Spark itself never resolves those MERGE
statements. The INSERT cases need a test table whose metadata columns are
nullable, because the in-memory table's index and _partition are NOT NULL, so
an INSERT action aligned over its widened output must give them non-null
values, which the repair rejects.
**Why this works:** A widened target output is the data columns followed by
every metadata column, and aligned assignments follow it position by position.
Dropping the metadata-column assignments therefore lines each action's row
values up with the data columns, which become the row projection and the write
schema. After the row values, each instruction emits metadata values from the
MetadataColumn preservation flags for updated, deleted and reinserted rows, and
nulls for inserted rows. Because those values follow the read relation's
metadata order, the metadata projection, which looks each column up by name,
reads the value meant for that column. The connector then receives the same
rows, write schema and metadata as for the same MERGE on a table that does not
accept any schema, and assignments to metadata columns fail as the 4.4
migration note and the legacy config's documentation describe.
**Scope:** Make the UPDATE and MERGE rewrites share one rule for targets
widened with metadata columns, and test MERGE on tables that accept any schema
through an injected resolution rule.
**Compatibility:** UPDATE on tables that accept any schema keeps the
behavior this PR adds. UPDATE, MERGE and DELETE on tables that do not accept
any schema keep their current plans, write schemas, metadata values and errors.
**Risks:** Group-based MERGE instructions must emit their metadata values in
the order of the metadata columns of the relation they read. In the in-memory
test table that order (index, _partition) is the reverse of the required order
(_partition, index), so keeping the required order on a widened target would
hand one column's value to another. Dropping an INSERT assignment of a metadata
column to a null literal also accepts an explicit NULL written by the user,
which tables that do not accept any schema reject. It changes nothing the
connector receives, because inserted rows reach the connector without metadata.
MERGE statements that assign a metadata column on these tables and ran on the
base branch now fail, unless spark.sql.legacy.ignoreMetadataColumnAssignments
is set. This includes a MERGE whose INSERT action an injected rule completes
with a non-null value or a default for a metadata column, because only a null
fill counts as an alignment artifact. With that config they run
again, with the assignment ignored.
**Constraints:** AddMetadataColumns keeps widening the targets of UPDATE and
MERGE on tables that accept any schema, so the plan that injected rules see
does not change. For targets without appended metadata columns, the shared
helpers must return their input unchanged, so plans for tables that do not
accept any schema stay identical, including the metadata order of group-based
instructions. The rejection must use the same error condition, error helper and
message format as on tables that do not accept any schema.
**Exclusions:**
- Resolving or aligning MERGE on tables that accept any schema inside Spark;
those tables keep resolving MERGE through the rules they inject.
- DELETE, whose target is never widened with metadata columns.
**Success:** A MERGE on a table that supports row-level operations, accepts
any schema and exposes metadata columns hands the connector rows and a
LogicalWriteInfo.schema() with only the table's data columns, in group-based,
delta-based and insert-only plans. Updated, deleted and reinserted rows carry
the metadata values that the MetadataColumn preservation flags define,
carried-over rows keep their metadata, and inserted rows reach the connector
without metadata, exactly as for the same MERGE on a table that does not accept
any schema. In a MERGE action, any metadata-column assignment other than a
self-assignment in UPDATE or a null in INSERT fails with
DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS. With
spark.sql.legacy.ignoreMetadataColumnAssignments set to true it is ignored
instead. UPDATE keeps the behavior this PR gives it, and plans on tables that
do not accept any schema are unchanged.
**Verification:**
- **Behavior:** On a table marked accept-any-schema, in a session whose
injected rule resolves MERGE on such tables and aligns its actions over the
target output, run MERGE statements whose conditions reference a target
metadata column, with DELETE, UPDATE and INSERT actions. Run the INSERT
actions, including the insert-only forms, on a table whose metadata columns are
nullable, because the in-memory table's index and _partition are NOT NULL, so
an INSERT action aligned over its widened output must give them non-null
values, which the repair rejects. Check that the connector's row schema and
rows hold only the data columns, in group-based, delta-based and
delete-and-insert operations and in the insert-only forms.
- **Regression:** In that setup, check that a matched UPDATE passes null for
a metadata column whose PRESERVE_ON_UPDATE is false and keeps the preserved
ones for the updated row. Check that carried-over rows keep their metadata,
that inserted rows reach the writer without metadata, and that every value
matches what the same MERGE passes on a table that does not accept any schema.
- **Regression:** In that setup, check that a MERGE UPDATE action assigning
index = 5, and an INSERT action assigning a non-null value to a metadata
column, fail with DATATYPE_MISMATCH.INVALID_ROW_LEVEL_OPERATION_ASSIGNMENTS and
the 'Cannot assign to metadata column' message. Then check that, with
spark.sql.legacy.ignoreMetadataColumnAssignments set to true, the same
statements run, the updated row carries the metadata values MetadataColumn
defines rather than the assigned ones, and the inserted row carries only its
data columns.
- **Compatibility:** Check that a group-based MERGE on a table that does not
accept any schema, whose target gets no appended metadata columns, still emits
instruction metadata values in the same order and produces the same write
schema and metadata values as before the change. Check also that UPDATE on a
table that accepts any schema keeps the write schema, metadata values and
errors it has with this PR.
--
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]