You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "DanielLeens (via GitHub)" <gi...@apache.org> on 2026/09/12 20:12:03 UTC

[PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

DanielLeens opened a new pull request, #12284:
URL: https://github.com/apache/seatunnel/pull/12284

   ### Purpose of this pull request
   
   Closes #8253.
   
   Today the `Sql` transform reacts to a `SchemaChangeEvent` by rebuilding its input schema and discarding its cached engine, but it forwards the **upstream** event downstream unchanged (`SQLTransform.mapSchemaChangeEvent`). Sinks re-derive their schema and the physical DDL from the column sub-events of that event, so as soon as the query is anything other than a bare `select *` the sink diverges from the rows the transform emits:
   
   - `select id, name` plus an upstream `ADD COLUMN age`: the sink table gains `age` and the sink writer expects 3 fields while the transform keeps emitting 2-field rows.
   - `select id, cast(price as decimal(10,2)) as price` plus `MODIFY price DOUBLE`: the sink column becomes `DOUBLE` while the rows still carry decimals.
   - `select id, name` plus `DROP COLUMN name`: nothing fails at the event; every following row fails in `ZetaSQLFunction` and is classified as a row error, so with row error skipping the data is silently lost.
   
   This PR makes the SQL transform translate every column-level change into a change of its **own output**:
   
   - **Identity-tracked lineage.** Sub-events are applied in order to an identity-annotated copy of the input (`SQLLineageSchema`); output columns are bound to input identities (`SQLOutputSlot`); the emitted events are the net effect per output column (`SQLSchemaChangeTranslator`). `CHANGE a -> b; ADD a` becomes a rename plus an add, `DROP a; ADD a` becomes a drop plus an add (never a modify), a rename reverted in the same statement is absorbed, and `select a` with `DROP a; ADD a BIGINT` becomes a drop plus an add of the output column.
   - **Replay contract.** Replaying the emitted events with `AlterTableSchemaEventHandler` onto the pre-event produced schema yields a `TableSchema` that is `equals` to the produced schema after the event (all column attributes, primary key, constraint keys). This is checked at runtime and in every unit test.
   - **Transactional evaluation.** The final input is evaluated on an isolated engine; live state (`inputCatalogTable`, engine, row type, produced table) is swapped only after every check passed, and the retired engine is closed exactly once, so UDF resources no longer leak on schema changes. A rejected event leaves the transform untouched at any chain position.
   - **Staged engine hand-off.** `setInputCatalogTable` only stages the pre-event state and the handed-over input; `mapSchemaChangeEvent` validates and commits. This also covers `rule_match_mode = ALL_MATCH` chains where the same transform is handed its input twice for one event.
   - **Provenance-aware metadata.** `sourceDialectName` is copied to an `ADD`/`MODIFY`/`CHANGE` sub-event only when the output column carries a `sourceType` inherited from an input column, so JDBC dialects never emit a `null` same-dialect type for derived expression columns and reconvert their SeaTunnel type instead.
   - **Fail fast, scoped.** A dropped or renamed column that the query references, a drop or rename of a primary key, constraint key or partition column, a rename cycle, a duplicate output name, an ordering comparison in `WHERE` whose operand families no longer match, or an upstream produced schema that does not match the event fail the job at the event with the new `TRANSFORM_COMMON-09` error code. Type changes that only surface inside functions, UDFs or lateral view arguments still surface at row time, as documented.
   - **Identity path of multi-table wrappers.** `IdentityMapTransform` and `IdentityFlatMapTransform` now derive their produced table from their live input and adopt the event's `changeAfter`, so a multi-table SQL job no longer stamps a stale table into the event for tables that no rule matches.
   
   `select *` jobs keep emitting the same DDL as today (same names, same positions, same metadata).
   
   ### Does this PR introduce _any_ user-facing change?
   
   - The `Sql` transform now supports schema evolution. Behaviour is documented in `docs/en/transforms/sql.md` and `docs/zh/transforms/sql.md` (rules, lineage, limits).
   - New error code `TRANSFORM_COMMON-09 SQL_SCHEMA_CHANGE_INCOMPATIBLE`.
   - Jobs with a non-`select *` SQL transform and `schema-changes.enabled = true` were broken at the sink before; they now either receive correct events or fail fast with an actionable message. Chains where a transform placed before the SQL transform forwards an event that does not describe its own produced schema (for example `Metadata` or `Copy` followed by `Sql`) now fail with `TRANSFORM_COMMON-09` instead of writing misaligned rows.
   - `docs/{en,zh}/introduction/configuration/schema-evolution.md` replace the "schema evolution does not support transforms" note with a per-transform support matrix derived from the transform class inventory.
   - No configuration option is added or changed. `seatunnel-api`, the engine and the sink side are untouched.
   
   ### How was this PR tested?
   
   Unit tests (`seatunnel-transforms-v2`):
   
   - `SQLTransformSchemaChangeTest`: star projections, projections, aliases, derived columns, absorbed changes, fail-fast cases with untouched state, composite rename-and-reuse / drop-and-re-add / rename-away-and-back, key column protection, duplicate output names, `WHERE` type compatibility, table-level events, resynchronisation from an event that carries the whole table, staged hand-offs at chain positions greater than zero (translation equal to position zero, rejected events, upstream mismatch, rows during a pending hand-off), `rule_match_mode = ALL_MATCH` at engine position greater than zero, a `FieldRename -> Sql` chain, and engine plus UDF lifecycle counts across successful, rejected and staged changes.
   - `SQLSchemaChangeTranslatorTest`: lineage, ordering, position derivation, key protection, replay verification, event shape and metadata rules.
   - `ZetaSQLEngineReferencedColumnsTest`: referenced column analysis, output slot description, `WHERE` type checks.
   - `SQLMultiCatalogSchemaChangeTest` and `MetadataMultiCatalogSchemaChangeTest`: unmatched-table identity path including a rename handed over before the event.
   - `TransformChainLiveAlterTest`: now asserts the outgoing SQL event (`ADD ... AFTER <last star column>`).
   
   E2E (`connector-cdc-mysql-e2e`, `MysqlCDCWithSchemaChangeIT`):
   
   - `mysqlcdc_to_mysql_with_schema_change_sql_star.conf`: the existing add/drop/change/modify/comment sequence through a `select *` transform, plus a new `rename_reuse_columns` template (rename with name reuse, then drop and re-create, each in one statement).
   - `mysqlcdc_to_mysql_with_schema_change_sql_projection.conf`: `select id, name, weight, weight * 2 as double_weight`; unrelated add/drop/rename absorbed, `modify name longtext` forwarded with the source type, a new `modify_weight_type` template changing `weight` to `DOUBLE` (direct column and derived expression column both become `DOUBLE` in the same-dialect MySQL sink), and a new `drop_readd_projected` template dropping and re-creating the referenced `name` column in one statement.
   
   Validation policy: only `./mvnw spotless:apply` was run locally on the touched modules; compilation, unit tests and E2E are validated by this PR's GitHub CI.
   
   ### Dependencies and follow-ups
   
   - Recovery after a failover depends on #11503: transforms are rebuilt from the planning-time schema on restore and the source's restore event is what resynchronises them. This PR handles any `AlterTableEvent` that carries the whole table in `changeAfter` as a resynchronisation (no DDL derived), which is exactly what `RestoreTableSchemaEvent` of #11503 is, so the two changes compose regardless of merge order. The "DDL, savepoint, restore, then rows with no further DDL" E2E is added once #11503 merges. Without #11503 a job restored after an output-affecting DDL now fails fast at the next DDL with `TRANSFORM_COMMON-09` instead of silently writing against a stale schema.
   - Follow-up: an explicit "input already handed over for this event" contract for `AbstractCatalogSupportMapTransform`, so map transforms placed after another transform no longer re-apply a column rename (pre-existing `IndexOutOfBoundsException` in `AlterTableSchemaEventHandler.applyChangeColumn`).
   - Follow-up: `Calcite`, `Python` and `TextChunk` can adopt the translator.
   
   ### Check list
   
   * [x] Code changed are covered with tests, or it does not need tests for reason: covered by unit tests and E2E listed above
   * [x] If any new Jar binary package adding in your PR, please add License Notice according [New License Guide](https://github.com/apache/seatunnel/blob/dev/docs/en/contribution/new-license.md): no new dependency
   * [x] If necessary, please update the documentation to describe the new feature. https://github.com/apache/seatunnel/tree/dev/docs
   * [x] If you are contributing the connector code, please check that the following files are updated: not a connector change
   * [ ] Update the [`release-note`](https://github.com/apache/seatunnel/blob/dev/release-note.md): the file does not exist on `dev`, so no entry was added.
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub) via commits" <co...@seatunnel.apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-7137302977

   Thanks @davidzollo for the independent approval! I checked the current head `c813dda99e931567c9a7cdde9d8146772e819520`: the reported Apache checks and exact-head fork Build are successful. Your approval is recorded separately from Daniel's earlier source assessment; I am the author here, so I am not adding a self-approval.
   
   No new source finding or CI retry is requested. The branch's behind/diverged fact remains recorded independently; GitHub currently reports `UNSTABLE` with reviewDecision `APPROVED`, so I am not treating the approval alone as a merge or production-acceptance result.
   
   This replies to the new approval on an already reviewed, unchanged head. No new full source review or local runtime validation is claimed.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-6139039196

   Conflict and review update:
   
   - Merge commit [`8894b7a22cf`](https://github.com/apache/seatunnel/commit/8894b7a22cf8914f771a33eb47df02954c4d6936) synchronizes the current `apache/dev` head (`b0f6feddf9e`) without rebasing. The only content conflicts were the English and Chinese SQL transform docs; both the schema-evolution section from this PR and the collection-expression section from `dev` were preserved.
   - The final GitHub PR diff remains the same 28 feature files (`+4683/-44`) and contains no `pom.xml` diff relative to current `dev`.
   - I rechecked the three review findings on the merged head: replay-safe add/rename ordering has the dedicated regression cases, the derived type test now exercises a real `INT` to `BIGINT` transition, and the single-event helper supplies the MySQL source dialect. The three addressed threads are now resolved.
   - Spotless completed successfully for `seatunnel-transforms-v2` and the MySQL CDC E2E module. The fresh Build is queued.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-5651443191

   Status update after the branch was merged with `dev` (`06daecd8822`):
   
   - #11503 is now merged and part of this branch, so the restore-after-failover dependency is resolved. Commit `e7bccdfb0b2` handles `RestoreTableSchemaEvent` explicitly in the SQL transform (re-evaluate on the restored table, derive no DDL, set `changeAfter` to the produced table, return the same instance) and fails fast with `TRANSFORM_COMMON-09` for any other table-level event without column sub-events. The merge kept this implementation over the four-line #11503 hunk in `SQLTransform`, which had the same effect; `SQLTransformTest.testRestoreSchemaEventRebuildsProducedSchema` from #11503 runs against it.
   - The E2E now covers savepoint and restore through the SQL transform: the `select *` job runs the same drop-while-stopped restore cycle as the no-transform test; the projection job adds a rows-only restore cycle, an operand type change while stopped (restore event, then the translated modify) and a DDL applied to the restored job. The PR description is updated accordingly, including the fixture changes from the first review round (FLOAT to DECIMAL(12,3), sink starting with the derived DOUBLE).
   - CI: the Build runs for the two earlier heads were cancelled by the following pushes; the run for this head is pending in the fork.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "davidzollo (via GitHub) via commits" <co...@seatunnel.apache.org>.
davidzollo commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-6703588191

   <!-- daniel-pr-followup-20261107 -->
   Yes, contributing to Apache SeaTunnel.
   
   Pushed `c813dda99e931567c9a7cdde9d8146772e819520` by normal fast-forward push. Pinned the legacy serialVersionUID values of IdentityMapTransform and IdentityFlatMapTransform so adding schema-change methods does not break prior serialized transforms. The map value is evidenced by the InvalidClassException; the original-signature UID calculation reproduces it before deriving the flat-map value. Existing legacy stream fixtures remain, and both identities are asserted.
   
   Validation: affected-module Spotless and diff whitespace checks passed; an independent maintainer source review of these deltas completed. No local compile, unit, integration, E2E, Docker or service execution was performed under the repository validation policy. No engine UI change or existing runtime artifact was used. The current-head [fork Build](https://github.com/DanielLeens/seatunnel/actions/runs/42346442140) was queued at the post-push inspection; this update does not claim runtime correctness or merge readiness. This supersedes earlier verification statements for the previous head.
   
   Existing connector registrations, configuration defaults, public contracts and prior test assertions were retained. Upstream-only POM changes in the approved conflict merges match dev exactly; no new dependency edits were made. Human review and any remaining explicit coverage/acceptance gaps are separate gates.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "davidzollo (via GitHub) via commits" <co...@seatunnel.apache.org>.
davidzollo merged PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on code in PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#discussion_r3998097068


##########
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/SQLSchemaChangeTranslator.java:
##########
@@ -0,0 +1,604 @@
+/*
+ * 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.seatunnel.transform.sql;
+
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.Column;
+import org.apache.seatunnel.api.table.catalog.ConstraintKey;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterColumnCommentEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableChangeColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnsEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableDropColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableModifyColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.handler.AlterTableSchemaEventHandler;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+/**
+ * Translates upstream column-level DDL into events that describe the change of the SQL transform's
+ * own output.
+ *
+ * <p>Sinks advance the produced schema they received at planning time by applying the events they
+ * receive, so the emitted events must satisfy one contract: replaying them onto the pre-event
+ * produced schema with {@link AlterTableSchemaEventHandler} yields a schema equal to the produced
+ * schema after the event, and every output column keeps its data lineage. Attribution therefore
+ * works on input column identities (see {@link SQLLineageSchema}) and on output slots (see {@link
+ * SQLOutputSlot}), never on names alone.
+ *
+ * <p>All methods are static and stateless. Validation problems that a user can act on are reported
+ * as {@link IllegalArgumentException}; violations of internal invariants as {@link
+ * IllegalStateException}.
+ */
+final class SQLSchemaChangeTranslator {
+
+    private SQLSchemaChangeTranslator() {}
+
+    /**
+     * Column-level sub-events of a single or composite event; empty for table-level events.
+     *
+     * @param event any schema change event
+     * @return the ordered column-level events
+     */
+    static List<AlterTableColumnEvent> flatten(SchemaChangeEvent event) {
+        if (event instanceof AlterTableColumnsEvent) {
+            return new ArrayList<>(((AlterTableColumnsEvent) event).getEvents());
+        }
+        if (event instanceof AlterTableColumnEvent) {
+            return Collections.singletonList((AlterTableColumnEvent) event);
+        }
+        return Collections.emptyList();
+    }
+
+    /**
+     * Identities of the input columns that back the produced primary key, the produced constraint
+     * keys and the input partition keys. The shared handler never renames or removes a key column,
+     * so dropping or renaming one of these columns cannot be represented by any event.
+     *
+     * @param preSlots output slots before the event
+     * @param preOutput produced schema before the event
+     * @param partitionKeys input partition keys, may be null
+     * @param initial initial lineage of the input
+     * @return protected identities
+     */
+    static Set<Integer> protectedIdentities(
+            List<SQLOutputSlot> preSlots,
+            TableSchema preOutput,
+            List<String> partitionKeys,
+            SQLLineageSchema initial) {
+        Set<String> protectedOutputNames = new HashSet<>();
+        if (preOutput.getPrimaryKey() != null) {
+            protectedOutputNames.addAll(preOutput.getPrimaryKey().getColumnNames());
+        }
+        if (preOutput.getConstraintKeys() != null) {
+            for (ConstraintKey constraintKey : preOutput.getConstraintKeys()) {
+                for (ConstraintKey.ConstraintKeyColumn keyColumn : constraintKey.getColumnNames()) {
+                    protectedOutputNames.add(keyColumn.getColumnName());
+                }
+            }
+        }
+        Set<Integer> identities = new HashSet<>();
+        for (SQLOutputSlot slot : preSlots) {
+            if (!protectedOutputNames.contains(slot.getName())) {
+                continue;
+            }
+            for (String referenced : slot.getReferencedInputColumns()) {
+                int identity = initial.identityOf(referenced);
+                if (identity >= 0) {
+                    identities.add(identity);
+                }
+            }
+        }
+        if (partitionKeys != null) {
+            for (String partitionKey : partitionKeys) {
+                int identity = initial.identityOf(partitionKey);
+                if (identity >= 0) {
+                    identities.add(identity);
+                }
+            }
+        }
+        return identities;
+    }
+
+    /**
+     * Rejects a drop or rename of a protected column.
+     *
+     * @param lineage lineage before the hint is applied
+     * @param hint the column-level event about to be applied
+     * @param protectedIdentities identities that must keep their name and existence
+     * @throws IllegalArgumentException when the hint drops or renames a protected column
+     */
+    static void rejectProtectedColumnChange(
+            SQLLineageSchema lineage,
+            AlterTableColumnEvent hint,
+            Set<Integer> protectedIdentities) {
+        String target = null;
+        if (hint instanceof AlterTableDropColumnEvent) {
+            target = ((AlterTableDropColumnEvent) hint).getColumn();
+        } else if (hint instanceof AlterTableChangeColumnEvent) {
+            AlterTableChangeColumnEvent change = (AlterTableChangeColumnEvent) hint;
+            if (!change.getOldColumn().equals(change.getColumn().getName())) {
+                target = change.getOldColumn();
+            }
+        }
+        if (target != null && protectedIdentities.contains(lineage.identityOf(target))) {
+            throw new IllegalArgumentException(
+                    String.format(
+                            "column [%s] is part of the primary key, a constraint key or the partition keys and cannot be dropped or renamed",
+                            target));
+        }
+    }
+
+    /**
+     * Computes the net effect of the change on every output slot and returns the events that
+     * reproduce it, ordered so that replaying them never collides on a column name.
+     *
+     * @param tableId produced table identifier used on the emitted events
+     * @param preSlots output slots before the event
+     * @param preOutput produced schema before the event
+     * @param preLineage initial lineage of the pre-event input
+     * @param finalSlots output slots after the event
+     * @param finalOutput produced schema after the event
+     * @param finalLineage lineage after all hints were applied
+     * @return ordered events, empty when the output did not change
+     * @throws IllegalArgumentException when renames form a cycle that no event order can replay
+     */
+    static List<AlterTableColumnEvent> translate(
+            TableIdentifier tableId,
+            List<SQLOutputSlot> preSlots,
+            TableSchema preOutput,
+            SQLLineageSchema preLineage,
+            List<SQLOutputSlot> finalSlots,
+            TableSchema finalOutput,
+            SQLLineageSchema finalLineage) {
+        List<BoundSlot> pre = bind(preSlots, preOutput, preLineage);
+        List<BoundSlot> fin = bind(finalSlots, finalOutput, finalLineage);
+
+        Map<Integer, BoundSlot> preStar = new LinkedHashMap<>();
+        Map<Integer, BoundSlot> finalStar = new LinkedHashMap<>();
+        Map<String, BoundSlot> preOther = new LinkedHashMap<>();
+        Map<String, BoundSlot> finalOther = new LinkedHashMap<>();
+        for (BoundSlot bound : pre) {
+            if (bound.isStar()) {
+                preStar.put(bound.identity(), bound);
+            } else {
+                preOther.put(bound.slot.pairingKey(), bound);
+            }
+        }
+        for (BoundSlot bound : fin) {
+            if (bound.isStar()) {
+                finalStar.put(bound.identity(), bound);
+            } else {
+                finalOther.put(bound.slot.pairingKey(), bound);
+            }
+        }
+
+        List<AlterTableDropColumnEvent> drops = new ArrayList<>();
+        List<AlterTableChangeColumnEvent> changes = new ArrayList<>();
+        // Adds and modifies are keyed by final output index so AFTER anchors always exist.
+        TreeMap<Integer, AlterTableColumnEvent> adds = new TreeMap<>();
+        TreeMap<Integer, AlterTableColumnEvent> modifies = new TreeMap<>();
+
+        for (BoundSlot preBound : preStar.values()) {
+            if (!finalStar.containsKey(preBound.identity())) {
+                drops.add(new AlterTableDropColumnEvent(tableId, preBound.column.getName()));
+            }
+        }
+        for (BoundSlot finalBound : finalStar.values()) {
+            BoundSlot preBound = preStar.get(finalBound.identity());
+            if (preBound == null) {
+                Position position =
+                        addPosition(
+                                finalBound,
+                                fin,
+                                finalLineage.creatingHint(finalBound.identity()),
+                                finalLineage);
+                adds.put(
+                        finalBound.index,
+                        new AlterTableAddColumnEvent(
+                                tableId, finalBound.column, position.first, position.afterColumn));
+                continue;
+            }
+            Position moved = movedPosition(preBound, finalBound, pre, fin, finalLineage);
+            if (!preBound.column.getName().equals(finalBound.column.getName())) {
+                changes.add(
+                        new AlterTableChangeColumnEvent(
+                                tableId,
+                                preBound.column.getName(),
+                                finalBound.column,
+                                moved.first,
+                                moved.afterColumn));
+            } else if (!preBound.column.equals(finalBound.column) || moved.isSet()) {
+                modifies.put(
+                        finalBound.index,
+                        modifyOrComment(tableId, preBound.column, finalBound.column, moved));
+            }
+        }
+
+        for (Map.Entry<String, BoundSlot> entry : preOther.entrySet()) {
+            BoundSlot preBound = entry.getValue();
+            BoundSlot finalBound = finalOther.get(entry.getKey());
+            if (finalBound == null) {
+                throw new IllegalStateException(
+                        String.format(
+                                "output column [%s] disappeared from the query output",
+                                preBound.column.getName()));
+            }
+            if (!preBound.signature.equals(finalBound.signature)) {
+                // The output column now carries data of a different physical input column.
+                drops.add(new AlterTableDropColumnEvent(tableId, preBound.column.getName()));
+                Position position = addPosition(finalBound, fin, null, finalLineage);
+                adds.put(
+                        finalBound.index,
+                        new AlterTableAddColumnEvent(
+                                tableId, finalBound.column, position.first, position.afterColumn));
+            } else if (!preBound.column.equals(finalBound.column)) {
+                modifies.put(
+                        finalBound.index,
+                        modifyOrComment(
+                                tableId, preBound.column, finalBound.column, Position.none()));
+            }
+        }
+        for (String key : finalOther.keySet()) {
+            if (!preOther.containsKey(key)) {
+                throw new IllegalStateException(
+                        String.format("output column [%s] appeared without a pre-event slot", key));
+            }
+        }
+
+        List<AlterTableColumnEvent> out = new ArrayList<>(drops);
+        out.addAll(orderChanges(changes, preOutput, drops));

Review Comment:
   Confirmed and fixed in 9bf19eb0efe. The translator no longer emits all renames before all adds. `translate` now drops first and then walks the final layout left to right on a simulated sink replay (`ReplayLayout`): the AFTER anchor of every positioned event is the final column to its left, which the walk has already placed under its final name, so `ADD c FIRST; CHANGE a TO x AFTER c` emits the add first and replays; a name that an add or a rename needs is freed just before by renaming its current holder in place (recursively for chains, a cycle still fails fast), so the inverse dependency `CHANGE a TO b; ADD a FIRST` replays as well. Regression tests: `testRenameAnchoredOnColumnAddedBySameEventReplays`, `testMoveAnchoredOnColumnAddedBySameEventReplays`, `testRenameFreesItsOldNameForAnAddAtALowerIndex` and `testBlockingRenameIsResolvedInPlaceFirst` in `SQLSchemaChangeTranslatorTest` (all go through `verifyReplay`), plus `testRenameAnchoredOnColumnAddedBySameCompositeReplays` throug
 h the transform in `SQLTransformSchemaChangeTest`.



##########
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLTransformSchemaChangeTest.java:
##########
@@ -0,0 +1,891 @@
+/*
+ * 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.seatunnel.transform.sql;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.event.EventType;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.PrimaryKey;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TablePath;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableChangeColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnsEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableCommentEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableDropColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableModifyColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableNameEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.handler.AlterTableSchemaEventHandler;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.transform.exception.TransformCommonErrorCode;
+import org.apache.seatunnel.transform.exception.TransformException;
+import org.apache.seatunnel.transform.rename.ConvertCase;
+import org.apache.seatunnel.transform.rename.FieldRenameConfig;
+import org.apache.seatunnel.transform.rename.FieldRenameTransform;
+import org.apache.seatunnel.transform.sql.zeta.ZetaSQLEngine;
+import org.apache.seatunnel.transform.sql.zeta.ZetaUDF;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Covers the SQL transform's schema change translation end to end: output-relative events for star
+ * projections, projections, aliases and derived columns, absorbed changes, fail-fast cases, lineage
+ * through composites, staged engine hand-offs at chain positions greater than zero, the multi-table
+ * wrapper with several rules per table, resynchronisation events and the engine and UDF lifecycle
+ * across changes.
+ */
+public class SQLTransformSchemaChangeTest {
+
+    private static final TablePath TBL = TablePath.of("db", "products");
+    private static final TableIdentifier TID = TableIdentifier.of("catalog", TBL);
+
+    @Test
+    public void testStarAddColumnKeepsUpstreamShape() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        AlterTableColumnsEvent event = composite(addAge());
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(event);
+
+        Assertions.assertTrue(out instanceof AlterTableColumnsEvent);
+        List<AlterTableColumnEvent> events = ((AlterTableColumnsEvent) out).getEvents();
+        Assertions.assertEquals(1, events.size());
+        AlterTableAddColumnEvent add = (AlterTableAddColumnEvent) events.get(0);
+        Assertions.assertEquals("age", add.getColumn().getName());
+        Assertions.assertFalse(add.isFirst());
+        Assertions.assertNull(add.getAfterColumn());
+        Assertions.assertEquals("MySQL", add.getSourceDialectName());
+        Assertions.assertEquals("job-1", add.getJobId());
+        Assertions.assertEquals(event.getStatement(), add.getStatement());
+        Assertions.assertSame(transform.getProducedCatalogTable(), add.getChangeAfter());
+        Assertions.assertSame(transform.getProducedCatalogTable(), out.getChangeAfter());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(4, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+    }
+
+    @Test
+    public void testStarAddAfterAndFirstKeepPositions() {
+        SQLTransform after = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addAfter =
+                (AlterTableAddColumnEvent)
+                        after.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addAfter(
+                                        TID, column("age", BasicType.INT_TYPE, "int"), "id"));
+        Assertions.assertEquals("id", addAfter.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "age", "name", "weight"},
+                after.getProducedCatalogTable().getTableSchema().getFieldNames());
+
+        SQLTransform first = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addFirst =
+                (AlterTableAddColumnEvent)
+                        first.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addFirst(
+                                        TID, column("age", BasicType.INT_TYPE, "int")));
+        Assertions.assertTrue(addFirst.isFirst());
+    }
+
+    @Test
+    public void testStarWithTrailingExpressionAddsAfterLastStarColumn() {
+        SQLTransform transform =
+                transform("select *, weight * 2 as double_weight from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(composite(addAge()));
+
+        AlterTableAddColumnEvent add =
+                (AlterTableAddColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("weight", add.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "name", "weight", "age", "double_weight"},
+                transform.getProducedCatalogTable().getTableSchema().getFieldNames());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.5d, 20}));
+        Assertions.assertEquals(5, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+        Assertions.assertEquals(3.0d, ((Number) rows.get(0).getField(4)).doubleValue(), 0.0001d);
+    }
+
+    @Test
+    public void testProjectionAbsorbsUnrelatedAddAndDrop() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        Assertions.assertNull(transform.mapSchemaChangeEvent(composite(addAge())));
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+        Assertions.assertEquals("a", rows.get(0).getField(1));
+
+        Assertions.assertNull(
+                transform.mapSchemaChangeEvent(
+                        composite(new AlterTableDropColumnEvent(TID, "age"))));
+        rows = transform.flatMap(new SeaTunnelRow(new Object[] {2L, "b", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testDropOrRenameOfReferencedColumnFailsFastAndLeavesStateUntouched() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        TransformException drop =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(new AlterTableDropColumnEvent(TID, "name"))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                drop.getSeaTunnelErrorCode());
+        Assertions.assertTrue(drop.getMessage().contains("[name]"), drop.getMessage());
+
+        TransformException rename =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(
+                                                AlterTableChangeColumnEvent.change(
+                                                        TID,
+                                                        "name",
+                                                        column(
+                                                                "full_name",
+                                                                BasicType.STRING_TYPE,
+                                                                "varchar(255)")))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                rename.getSeaTunnelErrorCode());
+
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows = transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testStarRenameEmitsChangeWithFinalColumn() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        PhysicalColumn fullName = column("full_name", BasicType.STRING_TYPE, "varchar(255)");
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        composite(AlterTableChangeColumnEvent.change(TID, "name", fullName)));
+
+        AlterTableChangeColumnEvent change =
+                (AlterTableChangeColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("name", change.getOldColumn());
+        Assertions.assertEquals("full_name", change.getColumn().getName());
+        Assertions.assertEquals("varchar(255)", change.getColumn().getSourceType());
+        Assertions.assertEquals("MySQL", change.getSourceDialectName());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+    }
+
+    @Test
+    public void testCompositeRenameReuseAndDropReaddKeepLineage() {
+        SQLTransform star = transform("select * from products", baseTable());
+        TableSchema starBefore = star.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent starOut =
+                star.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> starEvents = ((AlterTableColumnsEvent) starOut).getEvents();
+        Assertions.assertEquals(2, starEvents.size());
+        Assertions.assertTrue(starEvents.get(0) instanceof AlterTableChangeColumnEvent);
+        Assertions.assertTrue(starEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(starBefore, starOut, star.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform reference = transform("select id, name from products", baseTable());
+        TableSchema referenceBefore = reference.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent referenceOut =
+                reference.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> referenceEvents =
+                ((AlterTableColumnsEvent) referenceOut).getEvents();
+        Assertions.assertEquals(2, referenceEvents.size());
+        Assertions.assertTrue(referenceEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertEquals(
+                "name", ((AlterTableDropColumnEvent) referenceEvents.get(0)).getColumn());
+        AlterTableAddColumnEvent readd = (AlterTableAddColumnEvent) referenceEvents.get(1);
+        Assertions.assertEquals("name", readd.getColumn().getName());
+        Assertions.assertEquals("varchar(64)", readd.getColumn().getSourceType());
+        assertReplays(
+                referenceBefore,
+                referenceOut,
+                reference.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform dropReadd = transform("select id, name from products", baseTable());
+        TableSchema dropReaddBefore = dropReadd.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent dropReaddOut =
+                dropReadd.mapSchemaChangeEvent(
+                        composite(
+                                new AlterTableDropColumnEvent(TID, "name"),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> dropReaddEvents =
+                ((AlterTableColumnsEvent) dropReaddOut).getEvents();
+        Assertions.assertTrue(dropReaddEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertTrue(dropReaddEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(
+                dropReaddBefore,
+                dropReaddOut,
+                dropReadd.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform roundTrip = transform("select id, name from products", baseTable());
+        Assertions.assertNull(
+                roundTrip.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("tmp", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "tmp",
+                                        column("name", BasicType.STRING_TYPE, "varchar(255)")))));
+    }
+
+    @Test
+    public void testModifyDirectReferenceCarriesDialectAndSourceType() {
+        SQLTransform transform = transform("select id, name as n from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        AlterTableModifyColumnEvent.modify(
+                                TID, column("name", BasicType.STRING_TYPE, "longtext")));
+
+        Assertions.assertTrue(out instanceof AlterTableModifyColumnEvent);
+        AlterTableModifyColumnEvent modify = (AlterTableModifyColumnEvent) out;
+        Assertions.assertEquals("n", modify.getColumn().getName());
+        Assertions.assertEquals("longtext", modify.getColumn().getSourceType());
+        Assertions.assertEquals("MySQL", modify.getSourceDialectName());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+    }
+
+    @Test
+    public void testModifyDerivedColumnHasNoDialectAndNoSourceType() {
+        TableSchema schema =
+                TableSchema.builder()
+                        .column(column("id", BasicType.LONG_TYPE, "bigint"))
+                        .column(column("weight", BasicType.FLOAT_TYPE, "float"))
+                        .primaryKey(PrimaryKey.of("pk", Collections.singletonList("id")))
+                        .build();
+        SQLTransform transform =
+                transform(
+                        "select id, weight, weight * 2 as double_weight from products",
+                        table(schema));
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        Assertions.assertEquals(

Review Comment:
   Confirmed and fixed in 9bf19eb0efe. The unit test now uses `quantity INT` with `quantity * 2 as double_quantity` (derived INT) and a `MODIFY quantity BIGINT`, after which the expression is derived as BIGINT, so the derived-column modify is real; it also asserts the post-change row computes 42 for 21. The E2E fixture keeps the `weight * 2` projection but the sink now starts with `double_weight DOUBLE` (the type the transform derives for the FLOAT operand) and `modify_weight_type.sql` changes `weight` to `DECIMAL(12,3)`, which turns the derived type from DOUBLE into DECIMAL(12,3); the test asserts `decimal(12,3)` for both `weight` and `double_weight`. The docs example sentence was corrected the same way, and the fixture comment explains why a change to DOUBLE would not retype the expression.



##########
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLTransformSchemaChangeTest.java:
##########
@@ -0,0 +1,891 @@
+/*
+ * 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.seatunnel.transform.sql;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.event.EventType;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.PrimaryKey;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TablePath;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableChangeColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnsEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableCommentEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableDropColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableModifyColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableNameEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.handler.AlterTableSchemaEventHandler;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.transform.exception.TransformCommonErrorCode;
+import org.apache.seatunnel.transform.exception.TransformException;
+import org.apache.seatunnel.transform.rename.ConvertCase;
+import org.apache.seatunnel.transform.rename.FieldRenameConfig;
+import org.apache.seatunnel.transform.rename.FieldRenameTransform;
+import org.apache.seatunnel.transform.sql.zeta.ZetaSQLEngine;
+import org.apache.seatunnel.transform.sql.zeta.ZetaUDF;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Covers the SQL transform's schema change translation end to end: output-relative events for star
+ * projections, projections, aliases and derived columns, absorbed changes, fail-fast cases, lineage
+ * through composites, staged engine hand-offs at chain positions greater than zero, the multi-table
+ * wrapper with several rules per table, resynchronisation events and the engine and UDF lifecycle
+ * across changes.
+ */
+public class SQLTransformSchemaChangeTest {
+
+    private static final TablePath TBL = TablePath.of("db", "products");
+    private static final TableIdentifier TID = TableIdentifier.of("catalog", TBL);
+
+    @Test
+    public void testStarAddColumnKeepsUpstreamShape() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        AlterTableColumnsEvent event = composite(addAge());
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(event);
+
+        Assertions.assertTrue(out instanceof AlterTableColumnsEvent);
+        List<AlterTableColumnEvent> events = ((AlterTableColumnsEvent) out).getEvents();
+        Assertions.assertEquals(1, events.size());
+        AlterTableAddColumnEvent add = (AlterTableAddColumnEvent) events.get(0);
+        Assertions.assertEquals("age", add.getColumn().getName());
+        Assertions.assertFalse(add.isFirst());
+        Assertions.assertNull(add.getAfterColumn());
+        Assertions.assertEquals("MySQL", add.getSourceDialectName());
+        Assertions.assertEquals("job-1", add.getJobId());
+        Assertions.assertEquals(event.getStatement(), add.getStatement());
+        Assertions.assertSame(transform.getProducedCatalogTable(), add.getChangeAfter());
+        Assertions.assertSame(transform.getProducedCatalogTable(), out.getChangeAfter());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(4, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+    }
+
+    @Test
+    public void testStarAddAfterAndFirstKeepPositions() {
+        SQLTransform after = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addAfter =
+                (AlterTableAddColumnEvent)
+                        after.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addAfter(
+                                        TID, column("age", BasicType.INT_TYPE, "int"), "id"));
+        Assertions.assertEquals("id", addAfter.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "age", "name", "weight"},
+                after.getProducedCatalogTable().getTableSchema().getFieldNames());
+
+        SQLTransform first = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addFirst =
+                (AlterTableAddColumnEvent)
+                        first.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addFirst(
+                                        TID, column("age", BasicType.INT_TYPE, "int")));
+        Assertions.assertTrue(addFirst.isFirst());
+    }
+
+    @Test
+    public void testStarWithTrailingExpressionAddsAfterLastStarColumn() {
+        SQLTransform transform =
+                transform("select *, weight * 2 as double_weight from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(composite(addAge()));
+
+        AlterTableAddColumnEvent add =
+                (AlterTableAddColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("weight", add.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "name", "weight", "age", "double_weight"},
+                transform.getProducedCatalogTable().getTableSchema().getFieldNames());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.5d, 20}));
+        Assertions.assertEquals(5, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+        Assertions.assertEquals(3.0d, ((Number) rows.get(0).getField(4)).doubleValue(), 0.0001d);
+    }
+
+    @Test
+    public void testProjectionAbsorbsUnrelatedAddAndDrop() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        Assertions.assertNull(transform.mapSchemaChangeEvent(composite(addAge())));
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+        Assertions.assertEquals("a", rows.get(0).getField(1));
+
+        Assertions.assertNull(
+                transform.mapSchemaChangeEvent(
+                        composite(new AlterTableDropColumnEvent(TID, "age"))));
+        rows = transform.flatMap(new SeaTunnelRow(new Object[] {2L, "b", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testDropOrRenameOfReferencedColumnFailsFastAndLeavesStateUntouched() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        TransformException drop =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(new AlterTableDropColumnEvent(TID, "name"))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                drop.getSeaTunnelErrorCode());
+        Assertions.assertTrue(drop.getMessage().contains("[name]"), drop.getMessage());
+
+        TransformException rename =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(
+                                                AlterTableChangeColumnEvent.change(
+                                                        TID,
+                                                        "name",
+                                                        column(
+                                                                "full_name",
+                                                                BasicType.STRING_TYPE,
+                                                                "varchar(255)")))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                rename.getSeaTunnelErrorCode());
+
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows = transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testStarRenameEmitsChangeWithFinalColumn() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        PhysicalColumn fullName = column("full_name", BasicType.STRING_TYPE, "varchar(255)");
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        composite(AlterTableChangeColumnEvent.change(TID, "name", fullName)));
+
+        AlterTableChangeColumnEvent change =
+                (AlterTableChangeColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("name", change.getOldColumn());
+        Assertions.assertEquals("full_name", change.getColumn().getName());
+        Assertions.assertEquals("varchar(255)", change.getColumn().getSourceType());
+        Assertions.assertEquals("MySQL", change.getSourceDialectName());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+    }
+
+    @Test
+    public void testCompositeRenameReuseAndDropReaddKeepLineage() {
+        SQLTransform star = transform("select * from products", baseTable());
+        TableSchema starBefore = star.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent starOut =
+                star.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> starEvents = ((AlterTableColumnsEvent) starOut).getEvents();
+        Assertions.assertEquals(2, starEvents.size());
+        Assertions.assertTrue(starEvents.get(0) instanceof AlterTableChangeColumnEvent);
+        Assertions.assertTrue(starEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(starBefore, starOut, star.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform reference = transform("select id, name from products", baseTable());
+        TableSchema referenceBefore = reference.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent referenceOut =
+                reference.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> referenceEvents =
+                ((AlterTableColumnsEvent) referenceOut).getEvents();
+        Assertions.assertEquals(2, referenceEvents.size());
+        Assertions.assertTrue(referenceEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertEquals(
+                "name", ((AlterTableDropColumnEvent) referenceEvents.get(0)).getColumn());
+        AlterTableAddColumnEvent readd = (AlterTableAddColumnEvent) referenceEvents.get(1);
+        Assertions.assertEquals("name", readd.getColumn().getName());
+        Assertions.assertEquals("varchar(64)", readd.getColumn().getSourceType());
+        assertReplays(
+                referenceBefore,
+                referenceOut,
+                reference.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform dropReadd = transform("select id, name from products", baseTable());
+        TableSchema dropReaddBefore = dropReadd.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent dropReaddOut =
+                dropReadd.mapSchemaChangeEvent(
+                        composite(
+                                new AlterTableDropColumnEvent(TID, "name"),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> dropReaddEvents =
+                ((AlterTableColumnsEvent) dropReaddOut).getEvents();
+        Assertions.assertTrue(dropReaddEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertTrue(dropReaddEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(
+                dropReaddBefore,
+                dropReaddOut,
+                dropReadd.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform roundTrip = transform("select id, name from products", baseTable());
+        Assertions.assertNull(
+                roundTrip.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("tmp", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "tmp",
+                                        column("name", BasicType.STRING_TYPE, "varchar(255)")))));
+    }
+
+    @Test
+    public void testModifyDirectReferenceCarriesDialectAndSourceType() {
+        SQLTransform transform = transform("select id, name as n from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        AlterTableModifyColumnEvent.modify(

Review Comment:
   Confirmed and fixed in 9bf19eb0efe. Added a `single(event)` helper that sets the job id, statement and `MySQL` dialect the way CDC sources do, mirroring the composite helper, and applied it to every single incoming event in `SQLTransformSchemaChangeTest`, so the assertion validates propagation of real input metadata.



-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-5716973918

   CI result for the current head `672bd40ed8a` (fork run 35096464194, completed 2026-09-17): every leg that exercises this PR passed, and the merge with `dev` cleared the MinIO image failures (Iceberg S3, S3 file and Databend now pass).
   
   - `unit-test` passed on all four matrix entries.
   - `mysql-cdc-connector-it` passed on both JDKs, which covers both SQL transform E2E flows with their savepoint and restore cycles.
   - `transform-v2-it-part-2` passed on both JDKs and `transform-v2-it-part-1` passed on JDK 8.
   
   The six failed legs fail on `dev` as well (latest completed `dev` Build, `c7304ace6e1`, 2026-09-17, is red on the same legs), and each already has an owning PR:
   
   | Leg | Failing test | Owner |
   |---|---|---|
   | transform-v2-it-part-1 (JDK 11) | `TestFilterRowKindIT.testFilterRowKindMultiTable` on a Flink container, Assert row counts across restarts | #12216, #12350 |
   | all-connectors-it-2 (both) | `OpengaussCDCIT.testAddFieldWithRestore` | #12350 |
   | all-connectors-it-7 (JDK 11) | `PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes` | #12261 |
   | engine-v2-it (JDK 11) | `BackpressureSlowSinkIT` | #12313, #12350 |
   | engine-v2-it (JDK 11) | `SplitClusterFaultToleranceIT` cancel test, expected CANCELED but was FAILED | #12311 |
   | rocketmq-connector-it (JDK 11) | `RocketMqIT` | #12115, #12375, #12350 |
   
   `jdbc-connectors-it-part-1` (JDK 8), `paimon-connector-it` (both) and `kudu-connector-it` (JDK 11) were cancelled by the job time limit; the first two are cancelled on the `dev` Build too.
   
   No change to this PR follows from these results. Once the owning PRs land on `dev` I will merge `dev` again and let the Build rerun.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "goutamadwant (via GitHub)" <gi...@apache.org>.
goutamadwant commented on code in PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#discussion_r3997859744


##########
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/SQLSchemaChangeTranslator.java:
##########
@@ -0,0 +1,604 @@
+/*
+ * 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.seatunnel.transform.sql;
+
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.Column;
+import org.apache.seatunnel.api.table.catalog.ConstraintKey;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterColumnCommentEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableChangeColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnsEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableDropColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableModifyColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.handler.AlterTableSchemaEventHandler;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.stream.Collectors;
+
+/**
+ * Translates upstream column-level DDL into events that describe the change of the SQL transform's
+ * own output.
+ *
+ * <p>Sinks advance the produced schema they received at planning time by applying the events they
+ * receive, so the emitted events must satisfy one contract: replaying them onto the pre-event
+ * produced schema with {@link AlterTableSchemaEventHandler} yields a schema equal to the produced
+ * schema after the event, and every output column keeps its data lineage. Attribution therefore
+ * works on input column identities (see {@link SQLLineageSchema}) and on output slots (see {@link
+ * SQLOutputSlot}), never on names alone.
+ *
+ * <p>All methods are static and stateless. Validation problems that a user can act on are reported
+ * as {@link IllegalArgumentException}; violations of internal invariants as {@link
+ * IllegalStateException}.
+ */
+final class SQLSchemaChangeTranslator {
+
+    private SQLSchemaChangeTranslator() {}
+
+    /**
+     * Column-level sub-events of a single or composite event; empty for table-level events.
+     *
+     * @param event any schema change event
+     * @return the ordered column-level events
+     */
+    static List<AlterTableColumnEvent> flatten(SchemaChangeEvent event) {
+        if (event instanceof AlterTableColumnsEvent) {
+            return new ArrayList<>(((AlterTableColumnsEvent) event).getEvents());
+        }
+        if (event instanceof AlterTableColumnEvent) {
+            return Collections.singletonList((AlterTableColumnEvent) event);
+        }
+        return Collections.emptyList();
+    }
+
+    /**
+     * Identities of the input columns that back the produced primary key, the produced constraint
+     * keys and the input partition keys. The shared handler never renames or removes a key column,
+     * so dropping or renaming one of these columns cannot be represented by any event.
+     *
+     * @param preSlots output slots before the event
+     * @param preOutput produced schema before the event
+     * @param partitionKeys input partition keys, may be null
+     * @param initial initial lineage of the input
+     * @return protected identities
+     */
+    static Set<Integer> protectedIdentities(
+            List<SQLOutputSlot> preSlots,
+            TableSchema preOutput,
+            List<String> partitionKeys,
+            SQLLineageSchema initial) {
+        Set<String> protectedOutputNames = new HashSet<>();
+        if (preOutput.getPrimaryKey() != null) {
+            protectedOutputNames.addAll(preOutput.getPrimaryKey().getColumnNames());
+        }
+        if (preOutput.getConstraintKeys() != null) {
+            for (ConstraintKey constraintKey : preOutput.getConstraintKeys()) {
+                for (ConstraintKey.ConstraintKeyColumn keyColumn : constraintKey.getColumnNames()) {
+                    protectedOutputNames.add(keyColumn.getColumnName());
+                }
+            }
+        }
+        Set<Integer> identities = new HashSet<>();
+        for (SQLOutputSlot slot : preSlots) {
+            if (!protectedOutputNames.contains(slot.getName())) {
+                continue;
+            }
+            for (String referenced : slot.getReferencedInputColumns()) {
+                int identity = initial.identityOf(referenced);
+                if (identity >= 0) {
+                    identities.add(identity);
+                }
+            }
+        }
+        if (partitionKeys != null) {
+            for (String partitionKey : partitionKeys) {
+                int identity = initial.identityOf(partitionKey);
+                if (identity >= 0) {
+                    identities.add(identity);
+                }
+            }
+        }
+        return identities;
+    }
+
+    /**
+     * Rejects a drop or rename of a protected column.
+     *
+     * @param lineage lineage before the hint is applied
+     * @param hint the column-level event about to be applied
+     * @param protectedIdentities identities that must keep their name and existence
+     * @throws IllegalArgumentException when the hint drops or renames a protected column
+     */
+    static void rejectProtectedColumnChange(
+            SQLLineageSchema lineage,
+            AlterTableColumnEvent hint,
+            Set<Integer> protectedIdentities) {
+        String target = null;
+        if (hint instanceof AlterTableDropColumnEvent) {
+            target = ((AlterTableDropColumnEvent) hint).getColumn();
+        } else if (hint instanceof AlterTableChangeColumnEvent) {
+            AlterTableChangeColumnEvent change = (AlterTableChangeColumnEvent) hint;
+            if (!change.getOldColumn().equals(change.getColumn().getName())) {
+                target = change.getOldColumn();
+            }
+        }
+        if (target != null && protectedIdentities.contains(lineage.identityOf(target))) {
+            throw new IllegalArgumentException(
+                    String.format(
+                            "column [%s] is part of the primary key, a constraint key or the partition keys and cannot be dropped or renamed",
+                            target));
+        }
+    }
+
+    /**
+     * Computes the net effect of the change on every output slot and returns the events that
+     * reproduce it, ordered so that replaying them never collides on a column name.
+     *
+     * @param tableId produced table identifier used on the emitted events
+     * @param preSlots output slots before the event
+     * @param preOutput produced schema before the event
+     * @param preLineage initial lineage of the pre-event input
+     * @param finalSlots output slots after the event
+     * @param finalOutput produced schema after the event
+     * @param finalLineage lineage after all hints were applied
+     * @return ordered events, empty when the output did not change
+     * @throws IllegalArgumentException when renames form a cycle that no event order can replay
+     */
+    static List<AlterTableColumnEvent> translate(
+            TableIdentifier tableId,
+            List<SQLOutputSlot> preSlots,
+            TableSchema preOutput,
+            SQLLineageSchema preLineage,
+            List<SQLOutputSlot> finalSlots,
+            TableSchema finalOutput,
+            SQLLineageSchema finalLineage) {
+        List<BoundSlot> pre = bind(preSlots, preOutput, preLineage);
+        List<BoundSlot> fin = bind(finalSlots, finalOutput, finalLineage);
+
+        Map<Integer, BoundSlot> preStar = new LinkedHashMap<>();
+        Map<Integer, BoundSlot> finalStar = new LinkedHashMap<>();
+        Map<String, BoundSlot> preOther = new LinkedHashMap<>();
+        Map<String, BoundSlot> finalOther = new LinkedHashMap<>();
+        for (BoundSlot bound : pre) {
+            if (bound.isStar()) {
+                preStar.put(bound.identity(), bound);
+            } else {
+                preOther.put(bound.slot.pairingKey(), bound);
+            }
+        }
+        for (BoundSlot bound : fin) {
+            if (bound.isStar()) {
+                finalStar.put(bound.identity(), bound);
+            } else {
+                finalOther.put(bound.slot.pairingKey(), bound);
+            }
+        }
+
+        List<AlterTableDropColumnEvent> drops = new ArrayList<>();
+        List<AlterTableChangeColumnEvent> changes = new ArrayList<>();
+        // Adds and modifies are keyed by final output index so AFTER anchors always exist.
+        TreeMap<Integer, AlterTableColumnEvent> adds = new TreeMap<>();
+        TreeMap<Integer, AlterTableColumnEvent> modifies = new TreeMap<>();
+
+        for (BoundSlot preBound : preStar.values()) {
+            if (!finalStar.containsKey(preBound.identity())) {
+                drops.add(new AlterTableDropColumnEvent(tableId, preBound.column.getName()));
+            }
+        }
+        for (BoundSlot finalBound : finalStar.values()) {
+            BoundSlot preBound = preStar.get(finalBound.identity());
+            if (preBound == null) {
+                Position position =
+                        addPosition(
+                                finalBound,
+                                fin,
+                                finalLineage.creatingHint(finalBound.identity()),
+                                finalLineage);
+                adds.put(
+                        finalBound.index,
+                        new AlterTableAddColumnEvent(
+                                tableId, finalBound.column, position.first, position.afterColumn));
+                continue;
+            }
+            Position moved = movedPosition(preBound, finalBound, pre, fin, finalLineage);
+            if (!preBound.column.getName().equals(finalBound.column.getName())) {
+                changes.add(
+                        new AlterTableChangeColumnEvent(
+                                tableId,
+                                preBound.column.getName(),
+                                finalBound.column,
+                                moved.first,
+                                moved.afterColumn));
+            } else if (!preBound.column.equals(finalBound.column) || moved.isSet()) {
+                modifies.put(
+                        finalBound.index,
+                        modifyOrComment(tableId, preBound.column, finalBound.column, moved));
+            }
+        }
+
+        for (Map.Entry<String, BoundSlot> entry : preOther.entrySet()) {
+            BoundSlot preBound = entry.getValue();
+            BoundSlot finalBound = finalOther.get(entry.getKey());
+            if (finalBound == null) {
+                throw new IllegalStateException(
+                        String.format(
+                                "output column [%s] disappeared from the query output",
+                                preBound.column.getName()));
+            }
+            if (!preBound.signature.equals(finalBound.signature)) {
+                // The output column now carries data of a different physical input column.
+                drops.add(new AlterTableDropColumnEvent(tableId, preBound.column.getName()));
+                Position position = addPosition(finalBound, fin, null, finalLineage);
+                adds.put(
+                        finalBound.index,
+                        new AlterTableAddColumnEvent(
+                                tableId, finalBound.column, position.first, position.afterColumn));
+            } else if (!preBound.column.equals(finalBound.column)) {
+                modifies.put(
+                        finalBound.index,
+                        modifyOrComment(
+                                tableId, preBound.column, finalBound.column, Position.none()));
+            }
+        }
+        for (String key : finalOther.keySet()) {
+            if (!preOther.containsKey(key)) {
+                throw new IllegalStateException(
+                        String.format("output column [%s] appeared without a pre-event slot", key));
+            }
+        }
+
+        List<AlterTableColumnEvent> out = new ArrayList<>(drops);
+        out.addAll(orderChanges(changes, preOutput, drops));

Review Comment:
   This ordering is not replay-safe when a rename or move uses a column added by the same composite event as its AFTER anchor. I reproduced this with input schema [a, b] and the valid sequence ADD c FIRST; CHANGE a TO x AFTER c. The translator emits the CHANGE before ADD c, and verifyReplay throws NoSuchElementException because c does not exist yet. A blanket ADD-before-CHANGE ordering is also insufficient because the inverse dependency can occur, for example CHANGE a TO b followed by ADD a. Please dependency-order or interleave additions and changes using their source names and positional anchors, and add the add-anchor case as a regression test.



##########
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLTransformSchemaChangeTest.java:
##########
@@ -0,0 +1,891 @@
+/*
+ * 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.seatunnel.transform.sql;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.event.EventType;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.PrimaryKey;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TablePath;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableChangeColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnsEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableCommentEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableDropColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableModifyColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableNameEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.handler.AlterTableSchemaEventHandler;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.transform.exception.TransformCommonErrorCode;
+import org.apache.seatunnel.transform.exception.TransformException;
+import org.apache.seatunnel.transform.rename.ConvertCase;
+import org.apache.seatunnel.transform.rename.FieldRenameConfig;
+import org.apache.seatunnel.transform.rename.FieldRenameTransform;
+import org.apache.seatunnel.transform.sql.zeta.ZetaSQLEngine;
+import org.apache.seatunnel.transform.sql.zeta.ZetaUDF;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Covers the SQL transform's schema change translation end to end: output-relative events for star
+ * projections, projections, aliases and derived columns, absorbed changes, fail-fast cases, lineage
+ * through composites, staged engine hand-offs at chain positions greater than zero, the multi-table
+ * wrapper with several rules per table, resynchronisation events and the engine and UDF lifecycle
+ * across changes.
+ */
+public class SQLTransformSchemaChangeTest {
+
+    private static final TablePath TBL = TablePath.of("db", "products");
+    private static final TableIdentifier TID = TableIdentifier.of("catalog", TBL);
+
+    @Test
+    public void testStarAddColumnKeepsUpstreamShape() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        AlterTableColumnsEvent event = composite(addAge());
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(event);
+
+        Assertions.assertTrue(out instanceof AlterTableColumnsEvent);
+        List<AlterTableColumnEvent> events = ((AlterTableColumnsEvent) out).getEvents();
+        Assertions.assertEquals(1, events.size());
+        AlterTableAddColumnEvent add = (AlterTableAddColumnEvent) events.get(0);
+        Assertions.assertEquals("age", add.getColumn().getName());
+        Assertions.assertFalse(add.isFirst());
+        Assertions.assertNull(add.getAfterColumn());
+        Assertions.assertEquals("MySQL", add.getSourceDialectName());
+        Assertions.assertEquals("job-1", add.getJobId());
+        Assertions.assertEquals(event.getStatement(), add.getStatement());
+        Assertions.assertSame(transform.getProducedCatalogTable(), add.getChangeAfter());
+        Assertions.assertSame(transform.getProducedCatalogTable(), out.getChangeAfter());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(4, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+    }
+
+    @Test
+    public void testStarAddAfterAndFirstKeepPositions() {
+        SQLTransform after = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addAfter =
+                (AlterTableAddColumnEvent)
+                        after.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addAfter(
+                                        TID, column("age", BasicType.INT_TYPE, "int"), "id"));
+        Assertions.assertEquals("id", addAfter.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "age", "name", "weight"},
+                after.getProducedCatalogTable().getTableSchema().getFieldNames());
+
+        SQLTransform first = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addFirst =
+                (AlterTableAddColumnEvent)
+                        first.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addFirst(
+                                        TID, column("age", BasicType.INT_TYPE, "int")));
+        Assertions.assertTrue(addFirst.isFirst());
+    }
+
+    @Test
+    public void testStarWithTrailingExpressionAddsAfterLastStarColumn() {
+        SQLTransform transform =
+                transform("select *, weight * 2 as double_weight from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(composite(addAge()));
+
+        AlterTableAddColumnEvent add =
+                (AlterTableAddColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("weight", add.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "name", "weight", "age", "double_weight"},
+                transform.getProducedCatalogTable().getTableSchema().getFieldNames());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.5d, 20}));
+        Assertions.assertEquals(5, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+        Assertions.assertEquals(3.0d, ((Number) rows.get(0).getField(4)).doubleValue(), 0.0001d);
+    }
+
+    @Test
+    public void testProjectionAbsorbsUnrelatedAddAndDrop() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        Assertions.assertNull(transform.mapSchemaChangeEvent(composite(addAge())));
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+        Assertions.assertEquals("a", rows.get(0).getField(1));
+
+        Assertions.assertNull(
+                transform.mapSchemaChangeEvent(
+                        composite(new AlterTableDropColumnEvent(TID, "age"))));
+        rows = transform.flatMap(new SeaTunnelRow(new Object[] {2L, "b", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testDropOrRenameOfReferencedColumnFailsFastAndLeavesStateUntouched() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        TransformException drop =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(new AlterTableDropColumnEvent(TID, "name"))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                drop.getSeaTunnelErrorCode());
+        Assertions.assertTrue(drop.getMessage().contains("[name]"), drop.getMessage());
+
+        TransformException rename =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(
+                                                AlterTableChangeColumnEvent.change(
+                                                        TID,
+                                                        "name",
+                                                        column(
+                                                                "full_name",
+                                                                BasicType.STRING_TYPE,
+                                                                "varchar(255)")))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                rename.getSeaTunnelErrorCode());
+
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows = transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testStarRenameEmitsChangeWithFinalColumn() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        PhysicalColumn fullName = column("full_name", BasicType.STRING_TYPE, "varchar(255)");
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        composite(AlterTableChangeColumnEvent.change(TID, "name", fullName)));
+
+        AlterTableChangeColumnEvent change =
+                (AlterTableChangeColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("name", change.getOldColumn());
+        Assertions.assertEquals("full_name", change.getColumn().getName());
+        Assertions.assertEquals("varchar(255)", change.getColumn().getSourceType());
+        Assertions.assertEquals("MySQL", change.getSourceDialectName());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+    }
+
+    @Test
+    public void testCompositeRenameReuseAndDropReaddKeepLineage() {
+        SQLTransform star = transform("select * from products", baseTable());
+        TableSchema starBefore = star.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent starOut =
+                star.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> starEvents = ((AlterTableColumnsEvent) starOut).getEvents();
+        Assertions.assertEquals(2, starEvents.size());
+        Assertions.assertTrue(starEvents.get(0) instanceof AlterTableChangeColumnEvent);
+        Assertions.assertTrue(starEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(starBefore, starOut, star.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform reference = transform("select id, name from products", baseTable());
+        TableSchema referenceBefore = reference.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent referenceOut =
+                reference.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> referenceEvents =
+                ((AlterTableColumnsEvent) referenceOut).getEvents();
+        Assertions.assertEquals(2, referenceEvents.size());
+        Assertions.assertTrue(referenceEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertEquals(
+                "name", ((AlterTableDropColumnEvent) referenceEvents.get(0)).getColumn());
+        AlterTableAddColumnEvent readd = (AlterTableAddColumnEvent) referenceEvents.get(1);
+        Assertions.assertEquals("name", readd.getColumn().getName());
+        Assertions.assertEquals("varchar(64)", readd.getColumn().getSourceType());
+        assertReplays(
+                referenceBefore,
+                referenceOut,
+                reference.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform dropReadd = transform("select id, name from products", baseTable());
+        TableSchema dropReaddBefore = dropReadd.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent dropReaddOut =
+                dropReadd.mapSchemaChangeEvent(
+                        composite(
+                                new AlterTableDropColumnEvent(TID, "name"),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> dropReaddEvents =
+                ((AlterTableColumnsEvent) dropReaddOut).getEvents();
+        Assertions.assertTrue(dropReaddEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertTrue(dropReaddEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(
+                dropReaddBefore,
+                dropReaddOut,
+                dropReadd.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform roundTrip = transform("select id, name from products", baseTable());
+        Assertions.assertNull(
+                roundTrip.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("tmp", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "tmp",
+                                        column("name", BasicType.STRING_TYPE, "varchar(255)")))));
+    }
+
+    @Test
+    public void testModifyDirectReferenceCarriesDialectAndSourceType() {
+        SQLTransform transform = transform("select id, name as n from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        AlterTableModifyColumnEvent.modify(
+                                TID, column("name", BasicType.STRING_TYPE, "longtext")));
+
+        Assertions.assertTrue(out instanceof AlterTableModifyColumnEvent);
+        AlterTableModifyColumnEvent modify = (AlterTableModifyColumnEvent) out;
+        Assertions.assertEquals("n", modify.getColumn().getName());
+        Assertions.assertEquals("longtext", modify.getColumn().getSourceType());
+        Assertions.assertEquals("MySQL", modify.getSourceDialectName());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+    }
+
+    @Test
+    public void testModifyDerivedColumnHasNoDialectAndNoSourceType() {
+        TableSchema schema =
+                TableSchema.builder()
+                        .column(column("id", BasicType.LONG_TYPE, "bigint"))
+                        .column(column("weight", BasicType.FLOAT_TYPE, "float"))
+                        .primaryKey(PrimaryKey.of("pk", Collections.singletonList("id")))
+                        .build();
+        SQLTransform transform =
+                transform(
+                        "select id, weight, weight * 2 as double_weight from products",
+                        table(schema));
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        Assertions.assertEquals(

Review Comment:
   This fixture cannot exercise a FLOAT-to-DOUBLE change for the derived column. Existing ZetaSQLType numeric promotion produces DOUBLE for weight * 2 even when weight is FLOAT, so this assertion fails before the schema-change event is processed and double_weight remains DOUBLE after weight changes to DOUBLE. The corresponding E2E fixture has the same problem: it initially declares double_weight as FLOAT even though the transform produces DOUBLE, and the later source change cannot emit the expected derived-column type modification. Please use an expression and operand transition whose output type genuinely changes, such as an INT-to-BIGINT case, and align the initial sink schema with the transform pre-event output.



##########
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/sql/SQLTransformSchemaChangeTest.java:
##########
@@ -0,0 +1,891 @@
+/*
+ * 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.seatunnel.transform.sql;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.event.EventType;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.PrimaryKey;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+import org.apache.seatunnel.api.table.catalog.TablePath;
+import org.apache.seatunnel.api.table.catalog.TableSchema;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableChangeColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableColumnsEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableCommentEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableDropColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableModifyColumnEvent;
+import org.apache.seatunnel.api.table.schema.event.AlterTableNameEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.handler.AlterTableSchemaEventHandler;
+import org.apache.seatunnel.api.table.type.BasicType;
+import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
+import org.apache.seatunnel.api.table.type.SeaTunnelRow;
+import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
+import org.apache.seatunnel.transform.exception.TransformCommonErrorCode;
+import org.apache.seatunnel.transform.exception.TransformException;
+import org.apache.seatunnel.transform.rename.ConvertCase;
+import org.apache.seatunnel.transform.rename.FieldRenameConfig;
+import org.apache.seatunnel.transform.rename.FieldRenameTransform;
+import org.apache.seatunnel.transform.sql.zeta.ZetaSQLEngine;
+import org.apache.seatunnel.transform.sql.zeta.ZetaUDF;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Covers the SQL transform's schema change translation end to end: output-relative events for star
+ * projections, projections, aliases and derived columns, absorbed changes, fail-fast cases, lineage
+ * through composites, staged engine hand-offs at chain positions greater than zero, the multi-table
+ * wrapper with several rules per table, resynchronisation events and the engine and UDF lifecycle
+ * across changes.
+ */
+public class SQLTransformSchemaChangeTest {
+
+    private static final TablePath TBL = TablePath.of("db", "products");
+    private static final TableIdentifier TID = TableIdentifier.of("catalog", TBL);
+
+    @Test
+    public void testStarAddColumnKeepsUpstreamShape() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        AlterTableColumnsEvent event = composite(addAge());
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(event);
+
+        Assertions.assertTrue(out instanceof AlterTableColumnsEvent);
+        List<AlterTableColumnEvent> events = ((AlterTableColumnsEvent) out).getEvents();
+        Assertions.assertEquals(1, events.size());
+        AlterTableAddColumnEvent add = (AlterTableAddColumnEvent) events.get(0);
+        Assertions.assertEquals("age", add.getColumn().getName());
+        Assertions.assertFalse(add.isFirst());
+        Assertions.assertNull(add.getAfterColumn());
+        Assertions.assertEquals("MySQL", add.getSourceDialectName());
+        Assertions.assertEquals("job-1", add.getJobId());
+        Assertions.assertEquals(event.getStatement(), add.getStatement());
+        Assertions.assertSame(transform.getProducedCatalogTable(), add.getChangeAfter());
+        Assertions.assertSame(transform.getProducedCatalogTable(), out.getChangeAfter());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(4, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+    }
+
+    @Test
+    public void testStarAddAfterAndFirstKeepPositions() {
+        SQLTransform after = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addAfter =
+                (AlterTableAddColumnEvent)
+                        after.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addAfter(
+                                        TID, column("age", BasicType.INT_TYPE, "int"), "id"));
+        Assertions.assertEquals("id", addAfter.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "age", "name", "weight"},
+                after.getProducedCatalogTable().getTableSchema().getFieldNames());
+
+        SQLTransform first = transform("select * from products", baseTable());
+        AlterTableAddColumnEvent addFirst =
+                (AlterTableAddColumnEvent)
+                        first.mapSchemaChangeEvent(
+                                AlterTableAddColumnEvent.addFirst(
+                                        TID, column("age", BasicType.INT_TYPE, "int")));
+        Assertions.assertTrue(addFirst.isFirst());
+    }
+
+    @Test
+    public void testStarWithTrailingExpressionAddsAfterLastStarColumn() {
+        SQLTransform transform =
+                transform("select *, weight * 2 as double_weight from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out = transform.mapSchemaChangeEvent(composite(addAge()));
+
+        AlterTableAddColumnEvent add =
+                (AlterTableAddColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("weight", add.getAfterColumn());
+        Assertions.assertArrayEquals(
+                new String[] {"id", "name", "weight", "age", "double_weight"},
+                transform.getProducedCatalogTable().getTableSchema().getFieldNames());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.5d, 20}));
+        Assertions.assertEquals(5, rows.get(0).getArity());
+        Assertions.assertEquals(20, rows.get(0).getField(3));
+        Assertions.assertEquals(3.0d, ((Number) rows.get(0).getField(4)).doubleValue(), 0.0001d);
+    }
+
+    @Test
+    public void testProjectionAbsorbsUnrelatedAddAndDrop() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        Assertions.assertNull(transform.mapSchemaChangeEvent(composite(addAge())));
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows =
+                transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d, 20}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+        Assertions.assertEquals("a", rows.get(0).getField(1));
+
+        Assertions.assertNull(
+                transform.mapSchemaChangeEvent(
+                        composite(new AlterTableDropColumnEvent(TID, "age"))));
+        rows = transform.flatMap(new SeaTunnelRow(new Object[] {2L, "b", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testDropOrRenameOfReferencedColumnFailsFastAndLeavesStateUntouched() {
+        SQLTransform transform = transform("select id, name from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        TransformException drop =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(new AlterTableDropColumnEvent(TID, "name"))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                drop.getSeaTunnelErrorCode());
+        Assertions.assertTrue(drop.getMessage().contains("[name]"), drop.getMessage());
+
+        TransformException rename =
+                Assertions.assertThrows(
+                        TransformException.class,
+                        () ->
+                                transform.mapSchemaChangeEvent(
+                                        composite(
+                                                AlterTableChangeColumnEvent.change(
+                                                        TID,
+                                                        "name",
+                                                        column(
+                                                                "full_name",
+                                                                BasicType.STRING_TYPE,
+                                                                "varchar(255)")))));
+        Assertions.assertEquals(
+                TransformCommonErrorCode.SQL_SCHEMA_CHANGE_INCOMPATIBLE,
+                rename.getSeaTunnelErrorCode());
+
+        Assertions.assertEquals(before, transform.getProducedCatalogTable().getTableSchema());
+        List<SeaTunnelRow> rows = transform.flatMap(new SeaTunnelRow(new Object[] {1L, "a", 1.0d}));
+        Assertions.assertEquals(2, rows.get(0).getArity());
+    }
+
+    @Test
+    public void testStarRenameEmitsChangeWithFinalColumn() {
+        SQLTransform transform = transform("select * from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+        PhysicalColumn fullName = column("full_name", BasicType.STRING_TYPE, "varchar(255)");
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        composite(AlterTableChangeColumnEvent.change(TID, "name", fullName)));
+
+        AlterTableChangeColumnEvent change =
+                (AlterTableChangeColumnEvent) ((AlterTableColumnsEvent) out).getEvents().get(0);
+        Assertions.assertEquals("name", change.getOldColumn());
+        Assertions.assertEquals("full_name", change.getColumn().getName());
+        Assertions.assertEquals("varchar(255)", change.getColumn().getSourceType());
+        Assertions.assertEquals("MySQL", change.getSourceDialectName());
+        assertReplays(before, out, transform.getProducedCatalogTable().getTableSchema());
+    }
+
+    @Test
+    public void testCompositeRenameReuseAndDropReaddKeepLineage() {
+        SQLTransform star = transform("select * from products", baseTable());
+        TableSchema starBefore = star.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent starOut =
+                star.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> starEvents = ((AlterTableColumnsEvent) starOut).getEvents();
+        Assertions.assertEquals(2, starEvents.size());
+        Assertions.assertTrue(starEvents.get(0) instanceof AlterTableChangeColumnEvent);
+        Assertions.assertTrue(starEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(starBefore, starOut, star.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform reference = transform("select id, name from products", baseTable());
+        TableSchema referenceBefore = reference.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent referenceOut =
+                reference.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("name_old", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> referenceEvents =
+                ((AlterTableColumnsEvent) referenceOut).getEvents();
+        Assertions.assertEquals(2, referenceEvents.size());
+        Assertions.assertTrue(referenceEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertEquals(
+                "name", ((AlterTableDropColumnEvent) referenceEvents.get(0)).getColumn());
+        AlterTableAddColumnEvent readd = (AlterTableAddColumnEvent) referenceEvents.get(1);
+        Assertions.assertEquals("name", readd.getColumn().getName());
+        Assertions.assertEquals("varchar(64)", readd.getColumn().getSourceType());
+        assertReplays(
+                referenceBefore,
+                referenceOut,
+                reference.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform dropReadd = transform("select id, name from products", baseTable());
+        TableSchema dropReaddBefore = dropReadd.getProducedCatalogTable().getTableSchema();
+        SchemaChangeEvent dropReaddOut =
+                dropReadd.mapSchemaChangeEvent(
+                        composite(
+                                new AlterTableDropColumnEvent(TID, "name"),
+                                AlterTableAddColumnEvent.add(
+                                        TID,
+                                        column("name", BasicType.STRING_TYPE, "varchar(64)"))));
+        List<AlterTableColumnEvent> dropReaddEvents =
+                ((AlterTableColumnsEvent) dropReaddOut).getEvents();
+        Assertions.assertTrue(dropReaddEvents.get(0) instanceof AlterTableDropColumnEvent);
+        Assertions.assertTrue(dropReaddEvents.get(1) instanceof AlterTableAddColumnEvent);
+        assertReplays(
+                dropReaddBefore,
+                dropReaddOut,
+                dropReadd.getProducedCatalogTable().getTableSchema());
+
+        SQLTransform roundTrip = transform("select id, name from products", baseTable());
+        Assertions.assertNull(
+                roundTrip.mapSchemaChangeEvent(
+                        composite(
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "name",
+                                        column("tmp", BasicType.STRING_TYPE, "varchar(255)")),
+                                AlterTableChangeColumnEvent.change(
+                                        TID,
+                                        "tmp",
+                                        column("name", BasicType.STRING_TYPE, "varchar(255)")))));
+    }
+
+    @Test
+    public void testModifyDirectReferenceCarriesDialectAndSourceType() {
+        SQLTransform transform = transform("select id, name as n from products", baseTable());
+        TableSchema before = transform.getProducedCatalogTable().getTableSchema();
+
+        SchemaChangeEvent out =
+                transform.mapSchemaChangeEvent(
+                        AlterTableModifyColumnEvent.modify(

Review Comment:
   This input event never sets sourceDialectName, so the translated event correctly carries null and the MySQL assertion at line 315 fails. I reproduced this test independently. Please set MySQL on the incoming modify event before passing it to the transform, as the composite-event helper does, so the test validates propagation of actual input metadata.



-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-5662049411

   Follow-up to the second review round and to the fork's Build run for `e7bccdfb0b2` (run 34740882765). Commit `ea03511df99` addresses everything that is this PR's to fix.
   
   **Blocker 1, staged hand-off behind a column-appending wrapper: fixed.** The hand-off no longer requires positional equality between the hint-derived schema and the upstream produced table. `SQLLineageSchema.inOrderOf` adopts the upstream layout when it holds exactly the columns the hints produce (same names and definitions), keeping identities, creating hints and repositioning flags; anything else still fails fast with `TRANSFORM_COMMON-09`. For `Metadata -> Sql (select *)` the translator now emits `ADD age AFTER weight` (the last base column), which replays onto the pre-event output, so `ProductionPipelineSchemaChangeTest` passes by construction. `TransformChainLiveAlterTest` drives the transforms without the engine hand-off and keeps its tail positions. New unit tests: `testStagedHandOffAdoptsLayoutOfColumnAppendingWrapper` (Metadata upstream, rows through) and `testStagedHandOffRejectsLayoutWithOtherColumns`. The error message names the event class and type when the event carr
 ies no statement instead of printing `'null'`. Docs describe the adopted layout.
   
   **Blocker 2, `TestFilterRowKindIT.testFilterRowKindMultiTable`: not caused by this PR, but checked rather than dismissed.** Unmatched tables of that job do go through `IdentityMapTransform`, which this PR touches. In the same run the job passed on Zeta, Spark 2.4.6, Spark 3.3.0, Flink 1.13.6 and Flink 1.18.0 and failed only on the Flink 1.15.3 container, where the log shows the Assert sink failing `MIN_ROW 100` with 25 and then 91 rows, the Flink job restarting twice, and then `MAX_ROW 100` failing with 150 rows: counts accumulated across restarts, the `AssertSinkWriter` static-counter problem that has its own fix in flight. An identity regression would fail on every engine.
   
   **This PR's own E2E failures: root cause in `MultiTableSinkWriter`, worked around and documented.** With `multi_table_sink_replica = 2` the writer dispatches every schema change to both sub-writers of the same physical table. The second sub-writer replays `CHANGE reuse_col reuse_col_old, ADD reuse_col` after the first one already re-added `reuse_col`, so MySQL answers `Duplicate column name 'reuse_col_old'` and the job restarts forever; `DROP name, ADD name` is executed twice, and the projection test's query happened to run between the two statements, which aborted the test instead of retrying. The same events reach the sink without any transform, so this is independent of the translator; the physical DDL should be applied once per physical table and siblings refreshed at runtime only, the way `RestoreTableSchemaEvent` already is. Recorded as a follow-up in the description. The two SQL jobs now run with one sub-writer per table (the pre-existing jobs keep replica 2), and polls tha
 t hit the moment between the two statements of one composite are retried.
   
   **Remaining failures in that run, none in this PR's scope:** Iceberg S3, S3 file, Paimon S3 and Databend cannot pull `minio/minio` from Docker Hub any more; `SplitClusterFaultToleranceIT.testStreamJobCancelResolvesWhenWorkerCrashesBeforeCancelAck` and `RocketMqIT` also fail on the latest completed `dev` build; `kafka-connector-it` was cancelled by the job time limit.
   
   CI for `ea03511df99` is queued in the fork.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-5697479964

   CI result for `ea03511df99` (fork run 34829400025, completed 2026-09-15): the legs that exercise this PR passed.
   
   - `unit-test` passed on all four matrix entries, so `ProductionPipelineSchemaChangeTest` and the new hand-off tests pass with the layout adoption fix.
   - `mysql-cdc-connector-it` passed on both JDKs, so both SQL transform E2E flows pass end to end, including the savepoint and restore cycles.
   - `transform-v2-it-part-1` passed on JDK 8 and failed on JDK 11 only on the Flink 1.18.0 container of `TestFilterRowKindIT.testFilterRowKindMultiTable`, with the same Assert `MIN_ROW`/`MAX_ROW` counts across restarts. The latest completed `dev` build (`b37af3a9bf6`, 2026-09-16) fails the same test on a Flink container without this PR, which closes the question left open in the last review: it is a `dev`-wide flake, not this PR's identity-path change.
   
   Remaining failures in that run are outside this PR: `IcebergSourceIT`, `S3FileWithFilterIT`, `PaimonWithS3IT` and the Databend tests could not pull `minio/minio` (fixed on `dev` by #12287 and #12302); `jdbc-connectors-it-part-2` lost the Maven download of `protobuf-java` (`Connection reset`); `SplitClusterFaultToleranceIT` cancel test and `RocketMqIT` fail on `dev` as well; `kudu-connector-it` was cancelled by the time limit.
   
   To pick up the MinIO mirror fixes the branch is now merged with current `dev` (`672bd40ed8a`, clean merge, PR scope unchanged at 28 files). CI for that head is queued in the fork.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub) via commits" <co...@seatunnel.apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-6538591410

   Merged `dev` (`3ac2d1cec6a`) into this branch with a plain merge commit (no rebase, no force push). New head: `bc0703539ed` (previous head `8894b7a22c`). Only formatting was run locally (module-scoped `spotless:apply`); `git diff origin/dev --name-status` lists only this PR's own 28 files and no deletions.
   
   Conflicts and resolution:
   - `docs/zh/transforms/sql.md`: kept both changelog lines (DDL event support from this PR, then struct query from `dev`), same order as the English doc.
   - `SQLTransform.java`: import-only conflict, kept both `java.util.Locale` (from `dev`) and `java.util.Set` (this PR).
   - `ZetaSQLEngine.java`: kept both fields side by side, this PR's `referencedInputColumns` and `dev`'s `directProjectionIndexes` (fast path for plain column projections). `init()` re-runs `parseSQL()` and then collects referenced columns, so each isolated engine used for schema-change translation recomputes the fast-path indexes for its own input row type.
   - `docs/en/transforms/sql.md` merged without conflict.
   
   Compile and tests are left to the fork CI run per the validation policy (queued at the time of writing, no result claimed): https://github.com/DanielLeens/seatunnel/actions/runs/41164781897
   


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Feature][Transform-V2] Support schema change events in SQL transform [seatunnel]

Posted by "DanielLeens (via GitHub) via commits" <co...@seatunnel.apache.org>.
DanielLeens commented on PR #12284:
URL: https://github.com/apache/seatunnel/pull/12284#issuecomment-6646489443

   The previously queued Build has failed in all four unit-test matrices. AbstractMultiCatalogTransformTest's legacy-state tests report InvalidClassException for IdentityMapTransform: stream serialVersionUID=-4681742342014343446, local serialVersionUID=-6984890629531373588 (legacy reader at line 387, cases at 172/183/193). Please reconcile the class's serialization identity with the historical checkpoint fixture and demonstrate that actual old state can still be read; regenerating the legacy bytes from the new class would hide the compatibility failure. The corresponding fixture is unchanged in latest dev, so a simple sync is not an established fix. This observed compatibility-test failure supersedes the earlier unexecuted-CI status and must clear before merge; it is not a new full review of this head.
   
   CI reference: [Build 41568270953](https://github.com/DanielLeens/seatunnel/actions/runs/41568270953).
   
   This updates CI/merge facts on the already-reviewed head; it is not another full source review. No local runtime testing was performed. Daniel has READ permission; effective maintainer approval/dismissal remains separate.


-- 
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: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org