You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/07 17:03:24 UTC
(seatunnel) branch dev updated: [Feature][Connector-V2] Support PostgreSQL CDC ADD COLUMN schema evolution (#11922)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new 8bea8c681c [Feature][Connector-V2] Support PostgreSQL CDC ADD COLUMN schema evolution (#11922)
8bea8c681c is described below
commit 8bea8c681cacccbd99fa642ca0853718980b9234
Author: Doyeon Kim <13...@users.noreply.github.com>
AuthorDate: Mon Sep 7 16:06:15 2026 +0000
[Feature][Connector-V2] Support PostgreSQL CDC ADD COLUMN schema evolution (#11922)
---
docs/en/connectors/source/PostgreSQL-CDC.md | 26 +++
docs/zh/connectors/source/PostgreSQL-CDC.md | 24 +++
.../cdc/base/schema/SchemaChangeResolver.java | 10 +
.../cdc/base/utils/SourceRecordUtils.java | 5 +-
.../row/SeaTunnelRowDebeziumDeserializeSchema.java | 6 +
.../connector/postgresql/PostgresObjectUtils.java | 6 +-
.../postgresql/RelationAwarePostgresSchema.java | 96 +++++++++
.../config/PostgresSourceConfigFactory.java | 6 +-
.../cdc/postgres/source/PostgresDialect.java | 9 +-
.../postgres/source/PostgresIncrementalSource.java | 28 ++-
.../source/PostgresIncrementalSourceFactory.java | 23 ++-
.../PostgresRelationSchemaChangeResolver.java | 206 +++++++++++++++++++
.../source/PostgresRelationSchemaRecord.java | 74 +++++++
.../reader/PostgresSourceFetchTaskContext.java | 76 ++++++-
.../cdc/postgres/utils/PostgresTypeUtils.java | 20 +-
.../PostgresRelationSchemaChangeResolverTest.java | 226 +++++++++++++++++++++
.../seatunnel/cdc/postgres/PostgresCDCIT.java | 39 +++-
.../postgrescdc_to_postgres_test_add_Filed.conf | 4 +-
18 files changed, 857 insertions(+), 27 deletions(-)
diff --git a/docs/en/connectors/source/PostgreSQL-CDC.md b/docs/en/connectors/source/PostgreSQL-CDC.md
index 248a710b9e..b5e7facc77 100644
--- a/docs/en/connectors/source/PostgreSQL-CDC.md
+++ b/docs/en/connectors/source/PostgreSQL-CDC.md
@@ -116,6 +116,9 @@ ALTER TABLE your_table_name REPLICA IDENTITY FULL;
| exactly_once | Boolean | No | false | Enable exactly-once semantics during the snapshot phase. This option is only available when `startup.mode` is `initial` or `snapshot-only`. [...]
| format | Enum | No | DEFAULT | Optional output format for PostgreSQL CDC, valid enumerations are `DEFAULT`, `COMPATIBLE_DEBEZIUM_JSON`. [...]
| require-replica-identity-full | Boolean | No | true | Require the table to have REPLICA IDENTITY FULL. When set to false, allows tables with other replica identity settings, but UPDATE/DELETE events may not contain the previous state. This should only be used for append-only tables (e.g., outbox pattern). Default is true for backward compatibility. [...]
+| schema-changes.enabled | Boolean | No | false | Enable schema evolution events. PostgreSQL CDC currently supports only `ADD COLUMN`, and this option requires `decoding.plugin.name = "pgoutput"`. The change is observed when PostgreSQL sends the next RELATION message, normally immediately before the first subsequent row change for that table. |
+| schema-changes.include | List | No | - | Only the listed schema change event types are sent downstream when schema evolution is enabled. For the currently supported operation, use `add.column` (or the `update.columns` group alias). Empty means all supported types are eligible. |
+| schema-changes.exclude | List | No | - | Schema change event types listed here are not sent downstream. Exclude is applied after include and wins when the same type appears in both lists. |
| debezium | Config | No | - | Pass-through [Debezium's properties](https://github.com/debezium/debezium/blob/v1.9.8.Final/documentation/modules/ROOT/pages/connectors/postgresql.adoc#connector-configuration-properties) to Debezium Embedded Engine which is used to capture data changes from PostgreSQL server. [...]
| common-options | | no | - | Source plugin common parameters, please refer to [Source Common Options](../common-options/source-common-options.md) for details [...]
@@ -172,6 +175,29 @@ sink {
}
```
+### Schema evolution for ADD COLUMN
+
+PostgreSQL does not put the original `ALTER TABLE` SQL text in the logical replication stream.
+With `pgoutput`, SeaTunnel detects the changed table definition from the RELATION message, emits an
+`ADD COLUMN` event before the following row event, and updates the downstream table schema. A table
+must therefore receive a row change after the DDL before the schema change can be observed.
+
+If a RELATION message contains a row-schema change other than `ADD COLUMN`, the job fails before
+processing rows with that schema. Restoring the same checkpoint will encounter the change again;
+resume only after upgrading to a connector that supports the change or performing a controlled
+schema migration and restart.
+
+```hocon
+source {
+ Postgres-CDC {
+ # ...
+ decoding.plugin.name = "pgoutput"
+ schema-changes.enabled = true
+ schema-changes.include = ["add.column"]
+ }
+}
+```
+
### Support custom primary key for table
```
diff --git a/docs/zh/connectors/source/PostgreSQL-CDC.md b/docs/zh/connectors/source/PostgreSQL-CDC.md
index cbcbffaca6..1f7c2855bc 100644
--- a/docs/zh/connectors/source/PostgreSQL-CDC.md
+++ b/docs/zh/connectors/source/PostgreSQL-CDC.md
@@ -114,6 +114,9 @@ ALTER TABLE your_table_name REPLICA IDENTITY FULL;
| exactly_once | Boolean | 否 | false | 在快照阶段启用精确一次语义。仅当 `startup.mode` 为 `initial` 或 `snapshot-only` 时可用。 [...]
| format | Enum | 否 | DEFAULT | PostgreSQL CDC 的可选输出格式,有效枚举为 `DEFAULT`、`COMPATIBLE_DEBEZIUM_JSON`。 [...]
| require-replica-identity-full | Boolean | 否 | true | 要求表具有 REPLICA IDENTITY FULL。设置为 false 时,允许表使用其他副本标识设置,但 UPDATE/DELETE 事件可能不包含之前的状态。此选项仅应用于仅追加的表(例如 outbox 模式)。默认为 true 以保持向后兼容性。 [...]
+| schema-changes.enabled | Boolean | 否 | false | 启用 Schema 演进事件。PostgreSQL CDC 当前仅支持 `ADD COLUMN`,并且要求 `decoding.plugin.name = "pgoutput"`。PostgreSQL 发送下一条 RELATION 消息时才能感知该变更,通常发生在该表 DDL 后的第一条行变更之前。 |
+| schema-changes.include | List | 否 | - | Schema 演进启用后,仅向下游发送列出的事件类型。当前支持的操作请使用 `add.column`(或分组别名 `update.columns`)。为空表示允许全部受支持的类型。 |
+| schema-changes.exclude | List | 否 | - | 不向下游发送列出的 Schema change 事件类型。先应用 include,再应用 exclude;同一类型同时出现时 exclude 优先。 |
| debezium | Config | 否 | - | 将 [Debezium 的属性](https://github.com/debezium/debezium/blob/v1.9.8.Final/documentation/modules/ROOT/pages/connectors/postgresql.adoc#connector-configuration-properties) 传递给用于捕获 PostgreSQL 服务器数据更改的 Debezium 嵌入式引擎。 [...]
| common-options | | 否 | - | 源插件的公共参数,请参阅 [源公共选项](../common-options/source-common-options.md) 获取详细信息。 [...]
@@ -170,6 +173,27 @@ sink {
}
```
+### ADD COLUMN Schema 演进
+
+PostgreSQL 不会把原始 `ALTER TABLE` SQL 文本写入逻辑复制流。使用 `pgoutput` 时,SeaTunnel 会从
+RELATION 消息中检测变化后的表结构,在后续行事件之前发出 `ADD COLUMN` 事件,并更新下游表结构。
+因此,执行 DDL 后该表必须再发生一条行变更,连接器才能感知 Schema 变化。
+
+如果 RELATION 消息包含 `ADD COLUMN` 之外的行 Schema 变更,作业会在处理新 Schema 的数据行之前
+失败。恢复同一 Checkpoint 时仍会再次遇到该变更;只有升级到支持该变更的连接器,或完成受控的
+Schema 迁移并重新启动作业后,才能继续处理。
+
+```hocon
+source {
+ Postgres-CDC {
+ # ...
+ decoding.plugin.name = "pgoutput"
+ schema-changes.enabled = true
+ schema-changes.include = ["add.column"]
+ }
+}
+```
+
### 支持自定义表的主键
```
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/schema/SchemaChangeResolver.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/schema/SchemaChangeResolver.java
index a391358fd9..4e6d8b46a4 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/schema/SchemaChangeResolver.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/schema/SchemaChangeResolver.java
@@ -19,15 +19,25 @@ package org.apache.seatunnel.connectors.cdc.base.schema;
import org.apache.seatunnel.api.table.catalog.CatalogTable;
import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionException;
import org.apache.kafka.connect.source.SourceRecord;
import java.io.Serializable;
import java.util.List;
+/** Converts a Debezium schema-change record into a SeaTunnel schema-change event. */
public interface SchemaChangeResolver extends Serializable {
boolean support(SourceRecord record);
+ /**
+ * Resolve one schema-change record against SeaTunnel's currently tracked tables.
+ *
+ * <p>Implementations must throw {@link SchemaEvolutionException} when continuing after a
+ * resolution failure could make the produced row schema diverge from the source schema. The
+ * shared deserializer treats other exceptions as recoverable parser failures for backward
+ * compatibility and may log and skip them.
+ */
SchemaChangeEvent resolve(SourceRecord record, List<CatalogTable> catalogTables);
}
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/utils/SourceRecordUtils.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/utils/SourceRecordUtils.java
index 3d9f2a25f0..f10c15db02 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/utils/SourceRecordUtils.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/base/utils/SourceRecordUtils.java
@@ -46,12 +46,13 @@ public class SourceRecordUtils {
private SourceRecordUtils() {}
- /** Todo: Support more schema change event key name, currently only support MySQL and Oracle. */
+ /** Debezium schema-change key names supported by SeaTunnel CDC sources. */
public static final List<String> SUPPORT_SCHEMA_CHANGE_EVENT_KEY_NAME =
Arrays.asList(
"io.debezium.connector.mysql.SchemaChangeKey",
"io.debezium.connector.oracle.SchemaChangeKey",
- "io.debezium.connector.sqlserver.SchemaChangeKey");
+ "io.debezium.connector.sqlserver.SchemaChangeKey",
+ "io.debezium.connector.postgresql.SchemaChangeKey");
public static final String HEARTBEAT_VALUE_SCHEMA_KEY_NAME =
"io.debezium.connector.common.Heartbeat";
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/debezium/row/SeaTunnelRowDebeziumDeserializeSchema.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/debezium/row/SeaTunnelRowDebeziumDeserializeSchema.java
index 0732a121a9..d03946eef8 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/debezium/row/SeaTunnelRowDebeziumDeserializeSchema.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-base/src/main/java/org/apache/seatunnel/connectors/cdc/debezium/row/SeaTunnelRowDebeziumDeserializeSchema.java
@@ -26,6 +26,7 @@ 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.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionException;
import org.apache.seatunnel.api.table.schema.handler.TableSchemaChangeEventDispatcher;
import org.apache.seatunnel.api.table.schema.handler.TableSchemaChangeEventHandler;
import org.apache.seatunnel.api.table.type.MetadataUtil;
@@ -133,6 +134,11 @@ public final class SeaTunnelRowDebeziumDeserializeSchema
if (schemaChangeResolver != null) {
schemaChangeEvent = schemaChangeResolver.resolve(record, tables);
}
+ } catch (SchemaEvolutionException e) {
+ // A resolver uses SchemaEvolutionException only when continuing would make the
+ // produced row schema diverge from the source relation. Keep generic parser failures
+ // backward-compatible, but fail fast for an explicitly classified schema error.
+ throw e;
} catch (Exception e) {
log.warn("Failed to resolve schemaChangeEvent, just skip.", e);
return;
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/io/debezium/connector/postgresql/PostgresObjectUtils.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/io/debezium/connector/postgresql/PostgresObjectUtils.java
index 4244421b9f..a7b8675624 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/io/debezium/connector/postgresql/PostgresObjectUtils.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/io/debezium/connector/postgresql/PostgresObjectUtils.java
@@ -43,15 +43,15 @@ import static org.apache.seatunnel.connectors.seatunnel.cdc.postgres.exception.P
public class PostgresObjectUtils {
/** Create a new PostgresSchema and initialize the content of the schema. */
- public static PostgresSchema newSchema(
+ public static RelationAwarePostgresSchema newSchema(
PostgresConnection connection,
PostgresConnectorConfig config,
TypeRegistry typeRegistry,
TopicSelector<TableId> topicSelector,
PostgresValueConverter valueConverter)
throws SQLException {
- PostgresSchema schema =
- new PostgresSchema(
+ RelationAwarePostgresSchema schema =
+ new RelationAwarePostgresSchema(
config,
typeRegistry,
connection.getDefaultValueConverter(),
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/io/debezium/connector/postgresql/RelationAwarePostgresSchema.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/io/debezium/connector/postgresql/RelationAwarePostgresSchema.java
new file mode 100644
index 0000000000..6300dd8d6b
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/io/debezium/connector/postgresql/RelationAwarePostgresSchema.java
@@ -0,0 +1,96 @@
+/*
+ * 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 io.debezium.connector.postgresql;
+
+import io.debezium.connector.postgresql.connection.PostgresDefaultValueConverter;
+import io.debezium.relational.Column;
+import io.debezium.relational.Table;
+import io.debezium.relational.TableId;
+import io.debezium.schema.TopicSelector;
+
+import java.util.List;
+import java.util.Objects;
+import java.util.function.Consumer;
+
+/** A PostgreSQL schema that exposes pgoutput RELATION changes to SeaTunnel. */
+public class RelationAwarePostgresSchema extends PostgresSchema {
+
+ private Consumer<Table> relationChangeListener;
+
+ public RelationAwarePostgresSchema(
+ PostgresConnectorConfig config,
+ TypeRegistry typeRegistry,
+ PostgresDefaultValueConverter defaultValueConverter,
+ TopicSelector<TableId> topicSelector,
+ PostgresValueConverter valueConverter) {
+ super(config, typeRegistry, defaultValueConverter, topicSelector, valueConverter);
+ }
+
+ public void setRelationChangeListener(Consumer<Table> relationChangeListener) {
+ this.relationChangeListener = relationChangeListener;
+ }
+
+ /**
+ * Updates Debezium's schema first and then publishes a synthetic schema record before the DML
+ * record that caused PostgreSQL to send the RELATION message.
+ */
+ @Override
+ public void applySchemaChangesForTable(int relationId, Table table) {
+ Table previousTable = tableFor(table.id());
+ super.applySchemaChangesForTable(relationId, table);
+
+ // Always forward streaming RELATION messages for known tables. After recovery Debezium may
+ // have refreshed its in-memory schema from the live database already, while SeaTunnel's
+ // restored CatalogTable still contains the schema from the checkpoint. Comparing only with
+ // Debezium's current table would then hide the change from SeaTunnel.
+ if (relationChangeListener != null && previousTable != null) {
+ relationChangeListener.accept(table);
+ }
+ }
+
+ /** Compare two raw pgoutput RELATION schemas, including their primary-key definitions. */
+ public static boolean hasSameRelationSchema(Table before, Table after) {
+ if (!Objects.equals(before.primaryKeyColumnNames(), after.primaryKeyColumnNames())) {
+ return false;
+ }
+
+ List<Column> beforeColumns = before.columns();
+ List<Column> afterColumns = after.columns();
+ if (beforeColumns.size() != afterColumns.size()) {
+ return false;
+ }
+
+ for (int i = 0; i < beforeColumns.size(); i++) {
+ if (!hasSameColumnDefinition(beforeColumns.get(i), afterColumns.get(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static boolean hasSameColumnDefinition(Column before, Column after) {
+ return Objects.equals(before.name(), after.name())
+ && before.jdbcType() == after.jdbcType()
+ && before.nativeType() == after.nativeType()
+ && Objects.equals(before.typeName(), after.typeName())
+ && Objects.equals(before.typeExpression(), after.typeExpression())
+ && before.length() == after.length()
+ && Objects.equals(before.scale(), after.scale())
+ && before.isOptional() == after.isOptional();
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/config/PostgresSourceConfigFactory.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/config/PostgresSourceConfigFactory.java
index 83e7089128..1aec7df2d5 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/config/PostgresSourceConfigFactory.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/config/PostgresSourceConfigFactory.java
@@ -80,8 +80,6 @@ public class PostgresSourceConfigFactory extends JdbcSourceConfigFactory {
props.setProperty("database.history.refer.ddl", String.valueOf(true));
props.setProperty("database.tcpKeepAlive", String.valueOf(true));
- props.setProperty("include.schema.changes", String.valueOf(false));
-
if (schemaList != null) {
props.setProperty("schema.include.list", String.join(",", schemaList));
}
@@ -111,6 +109,10 @@ public class PostgresSourceConfigFactory extends JdbcSourceConfigFactory {
if (dbzProperties != null) {
props.putAll(dbzProperties);
}
+ // Debezium PostgreSQL does not emit DDL records, but SeaTunnel uses this flag to enable
+ // synthetic schema records produced from pgoutput RELATION messages. Apply it after the
+ // Debezium pass-through properties so the SeaTunnel option remains authoritative.
+ props.setProperty("include.schema.changes", String.valueOf(schemaChangeEnabled));
if (startupConfig != null && startupConfig.getStartupMode() == StartupMode.SNAPSHOT_ONLY) {
props.setProperty("snapshot.mode", "initial_only");
} else if (startupConfig != null
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresDialect.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresDialect.java
index 0af26e71df..650b6068d1 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresDialect.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresDialect.java
@@ -176,8 +176,15 @@ public class PostgresDialect implements JdbcDataSourceDialect {
}
}
+ List<CatalogTable> relationSchemaBaseline = new ArrayList<>(tableMap.values());
+ if (sourceSplitBase.isIncrementalSplit()
+ && sourceSplitBase.asIncrementalSplit().getCheckpointTables() != null
+ && !sourceSplitBase.asIncrementalSplit().getCheckpointTables().isEmpty()) {
+ relationSchemaBaseline = sourceSplitBase.asIncrementalSplit().getCheckpointTables();
+ }
+
return new PostgresSourceFetchTaskContext(
- taskSourceConfig, this, jdbcConnection, tableChangeList);
+ taskSourceConfig, this, jdbcConnection, tableChangeList, relationSchemaBaseline);
}
@Override
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSource.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSource.java
index 69469cf1e9..a38bf49478 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSource.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSource.java
@@ -20,7 +20,9 @@ package org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source;
import org.apache.seatunnel.api.configuration.Option;
import org.apache.seatunnel.api.configuration.ReadonlyConfig;
import org.apache.seatunnel.api.source.SupportParallelism;
+import org.apache.seatunnel.api.source.SupportSchemaEvolution;
import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.schema.SchemaChangeType;
import org.apache.seatunnel.common.utils.JdbcUrlUtil;
import org.apache.seatunnel.common.utils.SeaTunnelException;
import org.apache.seatunnel.connectors.cdc.base.config.JdbcSourceConfig;
@@ -28,8 +30,10 @@ import org.apache.seatunnel.connectors.cdc.base.config.SourceConfig;
import org.apache.seatunnel.connectors.cdc.base.config.StartupConfig;
import org.apache.seatunnel.connectors.cdc.base.dialect.DataSourceDialect;
import org.apache.seatunnel.connectors.cdc.base.option.JdbcSourceOptions;
+import org.apache.seatunnel.connectors.cdc.base.option.SourceOptions;
import org.apache.seatunnel.connectors.cdc.base.option.StartupMode;
import org.apache.seatunnel.connectors.cdc.base.option.StopMode;
+import org.apache.seatunnel.connectors.cdc.base.schema.SchemaChangeEventFilter;
import org.apache.seatunnel.connectors.cdc.base.source.IncrementalSource;
import org.apache.seatunnel.connectors.cdc.base.source.offset.OffsetFactory;
import org.apache.seatunnel.connectors.cdc.debezium.DebeziumDeserializationSchema;
@@ -50,6 +54,7 @@ import io.debezium.relational.history.TableChanges;
import io.debezium.util.SchemaNameAdjuster;
import java.time.ZoneId;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -57,7 +62,7 @@ import java.util.function.Function;
import java.util.stream.Collectors;
public class PostgresIncrementalSource<T> extends IncrementalSource<T, JdbcSourceConfig>
- implements SupportParallelism {
+ implements SupportParallelism, SupportSchemaEvolution {
static final String IDENTIFIER = "Postgres-CDC";
@@ -67,6 +72,7 @@ public class PostgresIncrementalSource<T> extends IncrementalSource<T, JdbcSourc
super(options, catalogTables);
this.requireReplicaIdentityFull =
options.get(PostgresIncrementalSourceOptions.REQUIRE_REPLICA_IDENTITY_FULL);
+ validateSchemaEvolutionOptions(options);
}
@Override
@@ -123,6 +129,8 @@ public class PostgresIncrementalSource<T> extends IncrementalSource<T, JdbcSourc
.setTables(catalogTables)
.setServerTimeZone(ZoneId.of(zoneId))
.setTableIdTableChangeMap(tableIdTableChangeMap)
+ .setSchemaChangeResolver(new PostgresRelationSchemaChangeResolver())
+ .setSchemaChangeEventFilter(SchemaChangeEventFilter.fromConfig(config))
.build();
}
@@ -145,6 +153,11 @@ public class PostgresIncrementalSource<T> extends IncrementalSource<T, JdbcSourc
return Optional.of("org.postgresql.Driver");
}
+ @Override
+ public List<SchemaChangeType> supports() {
+ return Collections.singletonList(SchemaChangeType.ADD_COLUMN);
+ }
+
private void validateStartupOptions(ReadonlyConfig options, StartupConfig startupConfig) {
if (startupConfig.getStartupMode() != StartupMode.COMMITTED_OFFSET) {
return;
@@ -162,6 +175,19 @@ public class PostgresIncrementalSource<T> extends IncrementalSource<T, JdbcSourc
}
}
+ private void validateSchemaEvolutionOptions(ReadonlyConfig options) {
+ if (options.get(SourceOptions.SCHEMA_CHANGES_ENABLED)
+ && !"pgoutput"
+ .equalsIgnoreCase(
+ options.get(
+ PostgresIncrementalSourceOptions.DECODING_PLUGIN_NAME))) {
+ throw new SeaTunnelException(
+ String.format(
+ "PostgreSQL-CDC schema evolution requires '%s = pgoutput' because PostgreSQL RELATION messages provide the changed schema.",
+ PostgresIncrementalSourceOptions.DECODING_PLUGIN_NAME.key()));
+ }
+ }
+
private Map<TableId, Struct> tableChanges() {
JdbcSourceConfig jdbcSourceConfig = configFactory.create(0);
PostgresDialect dialect =
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSourceFactory.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSourceFactory.java
index 39e36c36ad..5d73d3518f 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSourceFactory.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresIncrementalSourceFactory.java
@@ -17,6 +17,7 @@
package org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source;
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
import org.apache.seatunnel.api.configuration.util.OptionRule;
import org.apache.seatunnel.api.options.ConnectorCommonOptions;
import org.apache.seatunnel.api.source.SeaTunnelSource;
@@ -26,11 +27,12 @@ import org.apache.seatunnel.api.table.catalog.CatalogTableUtil;
import org.apache.seatunnel.api.table.catalog.TablePath;
import org.apache.seatunnel.api.table.connector.TableSource;
import org.apache.seatunnel.api.table.factory.Factory;
-import org.apache.seatunnel.api.table.factory.TableSourceFactory;
import org.apache.seatunnel.api.table.factory.TableSourceFactoryContext;
import org.apache.seatunnel.connectors.cdc.base.config.JdbcSourceTableConfig;
import org.apache.seatunnel.connectors.cdc.base.option.JdbcSourceOptions;
+import org.apache.seatunnel.connectors.cdc.base.option.SourceOptions;
import org.apache.seatunnel.connectors.cdc.base.option.StartupMode;
+import org.apache.seatunnel.connectors.cdc.base.source.BaseChangeStreamTableSourceFactory;
import org.apache.seatunnel.connectors.cdc.base.utils.CatalogTableUtils;
import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.config.PostgresIncrementalSourceOptions;
import org.apache.seatunnel.connectors.seatunnel.jdbc.config.JdbcCommonOptions;
@@ -44,7 +46,7 @@ import java.util.Optional;
@AutoService(Factory.class)
@Slf4j
-public class PostgresIncrementalSourceFactory implements TableSourceFactory {
+public class PostgresIncrementalSourceFactory extends BaseChangeStreamTableSourceFactory {
@Override
public String factoryIdentifier() {
return org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source
@@ -73,7 +75,10 @@ public class PostgresIncrementalSourceFactory implements TableSourceFactory {
JdbcSourceOptions.SAMPLE_SHARDING_THRESHOLD,
JdbcSourceOptions.INVERSE_SAMPLING_RATE,
JdbcSourceOptions.SPLIT_ALLOW_SAMPLING,
- JdbcSourceOptions.TABLE_NAMES_CONFIG)
+ JdbcSourceOptions.TABLE_NAMES_CONFIG,
+ SourceOptions.SCHEMA_CHANGES_ENABLED,
+ SourceOptions.SCHEMA_CHANGES_INCLUDE,
+ SourceOptions.SCHEMA_CHANGES_EXCLUDE)
.optional(PostgresSourceOptions.STARTUP_MODE, PostgresSourceOptions.STOP_MODE)
.conditional(
PostgresSourceOptions.STARTUP_MODE,
@@ -94,7 +99,8 @@ public class PostgresIncrementalSourceFactory implements TableSourceFactory {
@Override
public <T, SplitT extends SourceSplit, StateT extends Serializable>
- TableSource<T, SplitT, StateT> createSource(TableSourceFactoryContext context) {
+ TableSource<T, SplitT, StateT> restoreSource(
+ TableSourceFactoryContext context, List<CatalogTable> restoreTables) {
return () -> {
// Load the JDBC driver in to DriverManager
try {
@@ -102,9 +108,12 @@ public class PostgresIncrementalSourceFactory implements TableSourceFactory {
} catch (Exception e) {
log.warn("Failed to load JDBC driver {}", "org.postgresql.Driver", e);
}
+ ReadonlyConfig config = context.getOptions();
List<CatalogTable> catalogTables =
- CatalogTableUtil.getCatalogTables(
- context.getOptions(), context.getClassLoader());
+ CatalogTableUtil.getCatalogTables(config, context.getClassLoader());
+ if (!restoreTables.isEmpty() && config.get(SourceOptions.SCHEMA_CHANGES_ENABLED)) {
+ catalogTables = mergeTableStruct(catalogTables, restoreTables);
+ }
Optional<List<JdbcSourceTableConfig>> tableConfigs =
context.getOptions().getOptional(JdbcSourceOptions.TABLE_NAMES_CONFIG);
if (tableConfigs.isPresent()) {
@@ -114,7 +123,7 @@ public class PostgresIncrementalSourceFactory implements TableSourceFactory {
}
return (SeaTunnelSource<T, SplitT, StateT>)
new org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source
- .PostgresIncrementalSource<>(context.getOptions(), catalogTables);
+ .PostgresIncrementalSource<>(config, catalogTables);
};
}
}
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaChangeResolver.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaChangeResolver.java
new file mode 100644
index 0000000000..8471cb7aa7
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaChangeResolver.java
@@ -0,0 +1,206 @@
+/*
+ * 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.connectors.seatunnel.cdc.postgres.source;
+
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.Column;
+import org.apache.seatunnel.api.table.schema.event.AlterTableAddColumnEvent;
+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.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionErrorCode;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionException;
+import org.apache.seatunnel.api.table.schema.exception.SchemaValidationException;
+import org.apache.seatunnel.connectors.cdc.base.schema.SchemaChangeResolver;
+import org.apache.seatunnel.connectors.cdc.debezium.ConnectTableChangeSerializer;
+import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.utils.PostgresTypeUtils;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.DatabaseIdentifier;
+import org.apache.seatunnel.connectors.seatunnel.jdbc.internal.dialect.psql.PostgresTypeConverter;
+
+import org.apache.kafka.connect.data.Struct;
+import org.apache.kafka.connect.source.SourceRecord;
+
+import io.debezium.relational.Table;
+import io.debezium.relational.history.HistoryRecord;
+import io.debezium.relational.history.TableChanges;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.StreamSupport;
+
+/** Resolves PostgreSQL ADD COLUMN events by diffing the cached schema and a pgoutput RELATION. */
+public class PostgresRelationSchemaChangeResolver implements SchemaChangeResolver {
+
+ @Override
+ public boolean support(SourceRecord record) {
+ return record.keySchema() != null
+ && PostgresRelationSchemaRecord.KEY_SCHEMA_NAME.equals(record.keySchema().name());
+ }
+
+ @Override
+ public SchemaChangeEvent resolve(SourceRecord record, List<CatalogTable> catalogTables) {
+ Table after = null;
+ CatalogTable before = null;
+ try {
+ after = extractTable(record);
+ before = findCatalogTable(after, catalogTables);
+ List<AlterTableColumnEvent> events = resolveAddedColumns(before, after);
+ if (events.isEmpty()) {
+ return null;
+ }
+
+ events.forEach(event -> event.setSourceDialectName(DatabaseIdentifier.POSTGRESQL));
+ AlterTableColumnsEvent result = new AlterTableColumnsEvent(before.getTableId(), events);
+ result.setSourceDialectName(DatabaseIdentifier.POSTGRESQL);
+ return result;
+ } catch (SchemaEvolutionException e) {
+ throw e;
+ } catch (Exception e) {
+ String relationId = after == null ? "unknown" : after.id().toString();
+ throw new SchemaEvolutionException(
+ SchemaEvolutionErrorCode.INVALID_SCHEMA_STRUCTURE,
+ "Failed to resolve PostgreSQL RELATION schema change for "
+ + relationId
+ + ". Continuing could make the produced row schema diverge from the source relation.",
+ before == null ? null : before.getTableId(),
+ null,
+ e);
+ }
+ }
+
+ private Table extractTable(SourceRecord record) {
+ Struct value = (Struct) record.value();
+ List<Struct> changes = value.getArray(HistoryRecord.Fields.TABLE_CHANGES);
+ if (changes == null || changes.isEmpty()) {
+ throw invalidRelationRecord("PostgreSQL relation record has no table change payload");
+ }
+ TableChanges tableChanges = new ConnectTableChangeSerializer().deserialize(changes, true);
+ return StreamSupport.stream(tableChanges.spliterator(), false)
+ .map(TableChanges.TableChange::getTable)
+ .findFirst()
+ .orElseThrow(
+ () -> invalidRelationRecord("PostgreSQL relation record has no table"));
+ }
+
+ private CatalogTable findCatalogTable(Table after, List<CatalogTable> catalogTables) {
+ if (catalogTables == null) {
+ throw invalidRelationRecord(
+ "Cached schemas are unavailable for PostgreSQL relation " + after.id());
+ }
+ return catalogTables.stream()
+ .filter(
+ table ->
+ Objects.equals(
+ table.getTablePath().getSchemaName(),
+ relationSchemaName(after))
+ && Objects.equals(
+ table.getTablePath().getTableName(),
+ after.id().table()))
+ .findFirst()
+ .orElseThrow(
+ () ->
+ invalidRelationRecord(
+ "Cannot find cached schema for PostgreSQL table "
+ + after.id()));
+ }
+
+ public static String relationSchemaName(Table relation) {
+ // SeaTunnel's ConnectTableChangeSerializer parses a two-part quoted PostgreSQL identifier
+ // into TableId.catalog + TableId.table. Prefer the real schema field when present and fall
+ // back to catalog for synthetic relation records after deserialization.
+ return relation.id().schema() != null ? relation.id().schema() : relation.id().catalog();
+ }
+
+ private List<AlterTableColumnEvent> resolveAddedColumns(CatalogTable before, Table after) {
+ List<Column> beforeColumns = before.getTableSchema().getColumns();
+
+ if (after.columns().size() < beforeColumns.size()) {
+ throw unsupportedChange(before, after);
+ }
+
+ for (int i = 0; i < beforeColumns.size(); i++) {
+ Column beforeColumn = beforeColumns.get(i);
+ Column afterColumn = convertToSeaTunnelColumn(after, i);
+ if (!Objects.equals(beforeColumn.getName(), afterColumn.getName())
+ || !Objects.equals(beforeColumn.getDataType(), afterColumn.getDataType())
+ || beforeColumn.isNullable() != afterColumn.isNullable()) {
+ throw unsupportedChange(before, after);
+ }
+ }
+
+ List<AlterTableColumnEvent> events = new ArrayList<>();
+ for (int i = beforeColumns.size(); i < after.columns().size(); i++) {
+ Column addedColumn = convertToSeaTunnelColumn(after, i);
+ AlterTableAddColumnEvent event;
+ if (i == 0) {
+ event = AlterTableAddColumnEvent.addFirst(before.getTableId(), addedColumn);
+ } else {
+ event =
+ AlterTableAddColumnEvent.addAfter(
+ before.getTableId(),
+ addedColumn,
+ after.columns().get(i - 1).name());
+ }
+ events.add(event);
+ }
+ return events;
+ }
+
+ /** Compare SeaTunnel's tracked catalog schema with a pgoutput RELATION schema. */
+ public static boolean hasSameCatalogSchema(CatalogTable before, Table after) {
+ List<Column> beforeColumns = before.getTableSchema().getColumns();
+ if (beforeColumns.size() != after.columns().size()) {
+ return false;
+ }
+ for (int i = 0; i < beforeColumns.size(); i++) {
+ Column beforeColumn = beforeColumns.get(i);
+ Column afterColumn = convertToSeaTunnelColumn(after, i);
+ if (!Objects.equals(beforeColumn.getName(), afterColumn.getName())
+ || !Objects.equals(beforeColumn.getDataType(), afterColumn.getDataType())
+ || beforeColumn.isNullable() != afterColumn.isNullable()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static Column convertToSeaTunnelColumn(Table table, int columnIndex) {
+ return PostgresTypeConverter.INSTANCE.convert(
+ PostgresTypeUtils.convertRelationColumnToTypeDefine(
+ table.columns().get(columnIndex)));
+ }
+
+ private SchemaValidationException invalidRelationRecord(String message) {
+ return new SchemaValidationException(
+ SchemaEvolutionErrorCode.INVALID_SCHEMA_STRUCTURE, message, null, null);
+ }
+
+ private SchemaValidationException unsupportedChange(CatalogTable before, Table after) {
+ return new SchemaValidationException(
+ SchemaEvolutionErrorCode.UNSUPPORTED_SCHEMA_CHANGE_TYPE,
+ String.format(
+ "PostgreSQL CDC currently supports only ADD COLUMN relation changes. "
+ + "The job stopped before processing rows with the new schema. "
+ + "Restoring the same checkpoint will encounter this relation again until the change is supported or the job is restarted through a controlled schema migration. "
+ + "Cached columns: %s, relation columns: %s",
+ before.getTableSchema().getColumns(), after.columns()),
+ before.getTableId(),
+ null);
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaRecord.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaRecord.java
new file mode 100644
index 0000000000..d5b22d9b06
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaRecord.java
@@ -0,0 +1,74 @@
+/*
+ * 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.connectors.seatunnel.cdc.postgres.source;
+
+import org.apache.seatunnel.connectors.cdc.debezium.ConnectTableChangeSerializer;
+
+import org.apache.kafka.connect.data.Schema;
+import org.apache.kafka.connect.data.SchemaBuilder;
+import org.apache.kafka.connect.data.Struct;
+import org.apache.kafka.connect.source.SourceRecord;
+
+import io.debezium.relational.Table;
+import io.debezium.relational.history.HistoryRecord;
+import io.debezium.relational.history.TableChanges;
+
+import java.util.List;
+import java.util.Map;
+
+/** Creates an in-memory schema record from a PostgreSQL pgoutput RELATION message. */
+public final class PostgresRelationSchemaRecord {
+
+ public static final String KEY_SCHEMA_NAME = "io.debezium.connector.postgresql.SchemaChangeKey";
+
+ private static final String TABLE_ID = "table";
+
+ private static final Schema KEY_SCHEMA =
+ SchemaBuilder.struct()
+ .name(KEY_SCHEMA_NAME)
+ .field(TABLE_ID, Schema.STRING_SCHEMA)
+ .build();
+
+ private static final Schema VALUE_SCHEMA =
+ SchemaBuilder.struct()
+ .name("io.debezium.connector.postgresql.SchemaChangeValue")
+ .field(
+ HistoryRecord.Fields.TABLE_CHANGES,
+ SchemaBuilder.array(ConnectTableChangeSerializer.CHANGE_SCHEMA).build())
+ .build();
+
+ private PostgresRelationSchemaRecord() {}
+
+ /** Serialize a pgoutput RELATION table as a Debezium-compatible in-memory schema record. */
+ public static SourceRecord create(
+ Table table,
+ Map<String, ?> sourcePartition,
+ Map<String, ?> sourceOffset,
+ String topic) {
+ TableChanges tableChanges = new TableChanges();
+ tableChanges.alter(table);
+ List<Struct> serializedChanges = new ConnectTableChangeSerializer().serialize(tableChanges);
+
+ Struct key = new Struct(KEY_SCHEMA).put(TABLE_ID, table.id().toDoubleQuotedString());
+ Struct value =
+ new Struct(VALUE_SCHEMA).put(HistoryRecord.Fields.TABLE_CHANGES, serializedChanges);
+
+ return new SourceRecord(
+ sourcePartition, sourceOffset, topic, KEY_SCHEMA, key, VALUE_SCHEMA, value);
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/reader/PostgresSourceFetchTaskContext.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/reader/PostgresSourceFetchTaskContext.java
index d3328f1718..71b707d4db 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/reader/PostgresSourceFetchTaskContext.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/reader/PostgresSourceFetchTaskContext.java
@@ -17,6 +17,7 @@
package org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source.reader;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
import org.apache.seatunnel.common.exception.SeaTunnelRuntimeException;
import org.apache.seatunnel.connectors.cdc.base.config.JdbcSourceConfig;
@@ -27,6 +28,8 @@ import org.apache.seatunnel.connectors.cdc.base.source.reader.external.JdbcSourc
import org.apache.seatunnel.connectors.cdc.base.source.split.SourceSplitBase;
import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.config.PostgresSourceConfig;
import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.exception.PostgresConnectorErrorCode;
+import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source.PostgresRelationSchemaChangeResolver;
+import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source.PostgresRelationSchemaRecord;
import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.source.offset.LsnOffset;
import org.apache.seatunnel.connectors.seatunnel.cdc.postgres.utils.PostgresUtils;
@@ -44,6 +47,7 @@ import io.debezium.connector.postgresql.PostgresPartition;
import io.debezium.connector.postgresql.PostgresSchema;
import io.debezium.connector.postgresql.PostgresTaskContext;
import io.debezium.connector.postgresql.PostgresTopicSelector;
+import io.debezium.connector.postgresql.RelationAwarePostgresSchema;
import io.debezium.connector.postgresql.TypeRegistry;
import io.debezium.connector.postgresql.connection.PostgresConnection;
import io.debezium.connector.postgresql.connection.ReplicationConnection;
@@ -69,6 +73,7 @@ import lombok.extern.slf4j.Slf4j;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -91,7 +96,7 @@ public class PostgresSourceFetchTaskContext extends JdbcSourceFetchTaskContext {
private final EventMetadataProvider metadataProvider;
@Getter private Snapshotter snapshotter;
- private PostgresSchema databaseSchema;
+ private RelationAwarePostgresSchema databaseSchema;
private PostgresOffsetContext offsetContext;
private PostgresPartition partition;
private TopicSelector<TableId> topicSelector;
@@ -108,15 +113,26 @@ public class PostgresSourceFetchTaskContext extends JdbcSourceFetchTaskContext {
private Collection<TableChanges.TableChange> engineHistory;
+ // Suppresses duplicate RELATION messages within one task lifetime. Accessed only by the
+ // single Debezium reader thread and cleared whenever the context is configured for a split.
+ private final Map<TableId, Table> lastRelationSchemas = new HashMap<>();
+
+ // The schema SeaTunnel had already propagated downstream before this task started. On restore,
+ // checkpoint tables take precedence over live discovery so the first RELATION can reveal a
+ // source/sink schema gap that occurred after the checkpoint.
+ private final List<CatalogTable> relationSchemaBaseline;
+
public PostgresSourceFetchTaskContext(
JdbcSourceConfig sourceConfig,
JdbcDataSourceDialect dataSourceDialect,
PostgresConnection dataConnection,
- Collection<TableChanges.TableChange> engineHistory) {
+ Collection<TableChanges.TableChange> engineHistory,
+ List<CatalogTable> relationSchemaBaseline) {
super(sourceConfig, dataSourceDialect);
this.dataConnection = dataConnection;
this.metadataProvider = PostgresObjectUtils.newEventMetadataProvider();
this.engineHistory = engineHistory;
+ this.relationSchemaBaseline = relationSchemaBaseline;
this.postgresValueConverterBuilder =
newPostgresValueConverterBuilder(
getDbzConnectorConfig(),
@@ -127,6 +143,7 @@ public class PostgresSourceFetchTaskContext extends JdbcSourceFetchTaskContext {
@Override
public void configure(SourceSplitBase sourceSplitBase) {
super.registerDatabaseHistory(sourceSplitBase, dataConnection);
+ lastRelationSchemas.clear();
// initial stateful objects
final PostgresConnectorConfig connectorConfig = getDbzConnectorConfig();
@@ -243,6 +260,10 @@ public class PostgresSourceFetchTaskContext extends JdbcSourceFetchTaskContext {
// .buffering()
.build();
+ if (connectorConfig.isSchemaChangesHistoryEnabled()) {
+ databaseSchema.setRelationChangeListener(this::dispatchRelationSchemaChange);
+ }
+
this.dispatcher =
new JdbcSourceEventDispatcher<>(
connectorConfig,
@@ -326,6 +347,53 @@ public class PostgresSourceFetchTaskContext extends JdbcSourceFetchTaskContext {
return databaseSchema;
}
+ /** Enqueue a synthetic schema record when a streaming RELATION differs from tracked state. */
+ private void dispatchRelationSchemaChange(Table table) {
+ Table previousRelation = lastRelationSchemas.put(table.id(), table);
+ if (previousRelation != null
+ && RelationAwarePostgresSchema.hasSameRelationSchema(previousRelation, table)) {
+ return;
+ }
+ if (previousRelation == null && hasSameBaselineSchema(table)) {
+ return;
+ }
+
+ SourceRecord record =
+ PostgresRelationSchemaRecord.create(
+ table,
+ partition.getSourcePartition(),
+ new HashMap<>(offsetContext.getOffset()),
+ topicSelector.topicNameFor(table.id()));
+ try {
+ queue.enqueue(new DataChangeEvent(record));
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new DebeziumException(
+ "Interrupted while dispatching PostgreSQL relation change for " + table.id(),
+ e);
+ }
+ }
+
+ /** Compare the first RELATION for a table with initial or checkpoint-restored catalog state. */
+ private boolean hasSameBaselineSchema(Table relation) {
+ return relationSchemaBaseline.stream()
+ .filter(
+ table ->
+ Objects.equals(
+ table.getTablePath().getSchemaName(),
+ PostgresRelationSchemaChangeResolver
+ .relationSchemaName(relation))
+ && Objects.equals(
+ table.getTablePath().getTableName(),
+ relation.id().table()))
+ .findFirst()
+ .map(
+ table ->
+ PostgresRelationSchemaChangeResolver.hasSameCatalogSchema(
+ table, relation))
+ .orElse(false);
+ }
+
@Override
public TableId getTableId(SourceRecord record) {
Struct value = (Struct) record.value();
@@ -367,6 +435,10 @@ public class PostgresSourceFetchTaskContext extends JdbcSourceFetchTaskContext {
@Override
public void close() {
try {
+ if (Objects.nonNull(databaseSchema)) {
+ databaseSchema.setRelationChangeListener(null);
+ databaseSchema.close();
+ }
if (Objects.nonNull(dataConnection)) {
this.dataConnection.close();
}
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/utils/PostgresTypeUtils.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/utils/PostgresTypeUtils.java
index ef41c6a4b1..62cf1cb1e3 100644
--- a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/utils/PostgresTypeUtils.java
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/main/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/utils/PostgresTypeUtils.java
@@ -36,8 +36,22 @@ public class PostgresTypeUtils {
.precision((long) column.length())
.scale(column.scale().orElse(0))
.build();
- org.apache.seatunnel.api.table.catalog.Column seaTunnelColumn =
- PostgresTypeConverter.INSTANCE.convert(typeDefine);
- return seaTunnelColumn.getDataType();
+ return PostgresTypeConverter.INSTANCE.convert(typeDefine).getDataType();
+ }
+
+ /** Convert a pgoutput RELATION column with the metadata required by schema evolution. */
+ public static BasicTypeDefine convertRelationColumnToTypeDefine(Column column) {
+ return BasicTypeDefine.builder()
+ .name(column.name())
+ .columnType(column.typeName())
+ .dataType(column.typeName())
+ .sqlType(column.jdbcType())
+ .length(column.length() < 0 ? null : (long) column.length())
+ .precision(column.length() < 0 ? null : (long) column.length())
+ .scale(column.scale().orElse(0))
+ .nullable(column.isOptional())
+ .defaultValue(column.defaultValueExpression().orElse(null))
+ .comment(column.comment())
+ .build();
}
}
diff --git a/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaChangeResolverTest.java b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaChangeResolverTest.java
new file mode 100644
index 0000000000..35ced0289b
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-cdc/connector-cdc-postgres/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/source/PostgresRelationSchemaChangeResolverTest.java
@@ -0,0 +1,226 @@
+/*
+ * 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.connectors.seatunnel.cdc.postgres.source;
+
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.catalog.PhysicalColumn;
+import org.apache.seatunnel.api.table.catalog.TableIdentifier;
+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.AlterTableColumnsEvent;
+import org.apache.seatunnel.api.table.schema.event.SchemaChangeEvent;
+import org.apache.seatunnel.api.table.schema.exception.SchemaEvolutionException;
+import org.apache.seatunnel.api.table.schema.exception.SchemaValidationException;
+import org.apache.seatunnel.api.table.type.BasicType;
+
+import org.apache.kafka.connect.source.SourceRecord;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import io.debezium.relational.Column;
+import io.debezium.relational.Table;
+import io.debezium.relational.TableId;
+
+import java.sql.Types;
+import java.util.Arrays;
+import java.util.Collections;
+
+class PostgresRelationSchemaChangeResolverTest {
+
+ private static final String DATABASE_NAME = "postgres";
+ private static final String SCHEMA_NAME = "inventory";
+ private static final String TABLE_NAME = "customers";
+ private static final TableIdentifier TABLE_IDENTIFIER =
+ TableIdentifier.of(null, DATABASE_NAME, SCHEMA_NAME, TABLE_NAME);
+
+ private final PostgresRelationSchemaChangeResolver resolver =
+ new PostgresRelationSchemaChangeResolver();
+
+ @Test
+ void shouldResolveAddedColumnsFromRelationRecord() {
+ SourceRecord record =
+ createRecord(
+ intColumn("id", 1),
+ varcharColumn("name", 2, 64),
+ varcharColumn("email", 3, 128),
+ booleanColumn("enabled", 4));
+
+ Assertions.assertTrue(resolver.support(record));
+ SchemaChangeEvent event =
+ resolver.resolve(record, Collections.singletonList(createCatalogTable()));
+
+ Assertions.assertInstanceOf(AlterTableColumnsEvent.class, event);
+ AlterTableColumnsEvent columnsEvent = (AlterTableColumnsEvent) event;
+ Assertions.assertEquals(2, columnsEvent.getEvents().size());
+
+ AlterTableAddColumnEvent emailEvent =
+ (AlterTableAddColumnEvent) columnsEvent.getEvents().get(0);
+ Assertions.assertEquals("email", emailEvent.getColumn().getName());
+ Assertions.assertEquals(BasicType.STRING_TYPE, emailEvent.getColumn().getDataType());
+ Assertions.assertEquals("name", emailEvent.getAfterColumn());
+
+ AlterTableAddColumnEvent enabledEvent =
+ (AlterTableAddColumnEvent) columnsEvent.getEvents().get(1);
+ Assertions.assertEquals("enabled", enabledEvent.getColumn().getName());
+ Assertions.assertEquals(BasicType.BOOLEAN_TYPE, enabledEvent.getColumn().getDataType());
+ Assertions.assertEquals("email", enabledEvent.getAfterColumn());
+ }
+
+ @Test
+ void shouldIgnoreUnchangedRelationRecord() {
+ SourceRecord record = createRecord(intColumn("id", 1), varcharColumn("name", 2, 64));
+
+ SchemaChangeEvent event =
+ resolver.resolve(record, Collections.singletonList(createCatalogTable()));
+
+ Assertions.assertNull(event);
+ }
+
+ @Test
+ void shouldRejectNonAddColumnChanges() {
+ SourceRecord record = createRecord(intColumn("id", 1));
+
+ SchemaValidationException exception =
+ Assertions.assertThrows(
+ SchemaValidationException.class,
+ () ->
+ resolver.resolve(
+ record, Collections.singletonList(createCatalogTable())));
+
+ Assertions.assertTrue(exception.getMessage().contains("supports only ADD COLUMN"));
+ }
+
+ @Test
+ void shouldRejectRelationWhenCachedTableIsMissing() {
+ SourceRecord record = createRecord(intColumn("id", 1), varcharColumn("name", 2, 64));
+
+ SchemaValidationException exception =
+ Assertions.assertThrows(
+ SchemaValidationException.class,
+ () -> resolver.resolve(record, Collections.emptyList()));
+
+ Assertions.assertTrue(exception.getMessage().contains("Cannot find cached schema"));
+ }
+
+ @Test
+ void shouldFailFastWhenAddedColumnTypeCannotBeConverted() {
+ SourceRecord record =
+ createRecord(
+ intColumn("id", 1),
+ varcharColumn("name", 2, 64),
+ unsupportedArrayColumn("roles", 3));
+
+ SchemaEvolutionException exception =
+ Assertions.assertThrows(
+ SchemaEvolutionException.class,
+ () ->
+ resolver.resolve(
+ record, Collections.singletonList(createCatalogTable())));
+
+ Assertions.assertTrue(
+ exception
+ .getMessage()
+ .contains("Failed to resolve PostgreSQL RELATION schema change"));
+ Assertions.assertNotNull(exception.getCause());
+ }
+
+ private CatalogTable createCatalogTable() {
+ return CatalogTable.of(
+ TABLE_IDENTIFIER,
+ TableSchema.builder()
+ .column(
+ PhysicalColumn.builder()
+ .name("id")
+ .dataType(BasicType.INT_TYPE)
+ .nullable(false)
+ .sourceType("int4")
+ .build())
+ .column(
+ PhysicalColumn.builder()
+ .name("name")
+ .dataType(BasicType.STRING_TYPE)
+ .nullable(true)
+ .sourceType("varchar(64)")
+ .build())
+ .build(),
+ Collections.emptyMap(),
+ Collections.emptyList(),
+ null,
+ null);
+ }
+
+ private SourceRecord createRecord(Column... columns) {
+ Table relation =
+ Table.editor()
+ .tableId(new TableId(null, SCHEMA_NAME, TABLE_NAME))
+ .setPrimaryKeyNames(Collections.singletonList("id"))
+ .setColumns(Arrays.asList(columns))
+ .create();
+ return PostgresRelationSchemaRecord.create(
+ relation,
+ Collections.singletonMap("server", "postgres"),
+ Collections.singletonMap("lsn", 100L),
+ "postgres.inventory.customers");
+ }
+
+ private Column intColumn(String name, int position) {
+ return Column.editor()
+ .name(name)
+ .jdbcType(Types.INTEGER)
+ .nativeType(Types.INTEGER)
+ .type("int4", "int4")
+ .position(position)
+ .optional(false)
+ .create();
+ }
+
+ private Column varcharColumn(String name, int position, int length) {
+ return Column.editor()
+ .name(name)
+ .jdbcType(Types.VARCHAR)
+ .nativeType(Types.VARCHAR)
+ .type("varchar", "varchar(" + length + ")")
+ .length(length)
+ .position(position)
+ .optional(true)
+ .create();
+ }
+
+ private Column booleanColumn(String name, int position) {
+ return Column.editor()
+ .name(name)
+ .jdbcType(Types.BOOLEAN)
+ .nativeType(Types.BOOLEAN)
+ .type("bool", "bool")
+ .position(position)
+ .optional(false)
+ .create();
+ }
+
+ private Column unsupportedArrayColumn(String name, int position) {
+ return Column.editor()
+ .name(name)
+ .jdbcType(Types.ARRAY)
+ .nativeType(Types.ARRAY)
+ .type("_uuid", "uuid[]")
+ .position(position)
+ .optional(true)
+ .create();
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java
index a8963b7ec5..bd889c00ed 100644
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cdc/postgres/PostgresCDCIT.java
@@ -962,7 +962,7 @@ public class PostgresCDCIT extends TestSuiteBase implements TestResource {
value = {},
type = {EngineType.SPARK, EngineType.FLINK},
disabledReason = "Currently SPARK and FLINK do not support restore")
- public void testAddFieldWithRestore(TestContainer container)
+ public void testAddColumnSchemaEvolutionWithRestore(TestContainer container)
throws IOException, InterruptedException {
Long jobId = JobIdGenerator.newJobId();
String slotVariable = toSlotVariable(createSlotName());
@@ -998,9 +998,9 @@ public class PostgresCDCIT extends TestSuiteBase implements TestResource {
Assertions.assertEquals(0, container.savepointJob(String.valueOf(jobId)).getExitCode());
- // add field add insert source table data
+ // Change only the source table. The restored job must evolve the sink before writing
+ // the first row that contains the new column.
addFieldsForTable(POSTGRESQL_SCHEMA, SOURCE_TABLE_3);
- addFieldsForTable(POSTGRESQL_SCHEMA, SINK_TABLE_3);
insertSourceTableForAddFields(POSTGRESQL_SCHEMA, SOURCE_TABLE_3);
// Restore job
@@ -1032,7 +1032,17 @@ public class PostgresCDCIT extends TestSuiteBase implements TestResource {
query(
getQuerySQL(
POSTGRESQL_SCHEMA,
- SINK_TABLE_3)))));
+ SINK_TABLE_3))),
+ () ->
+ Assertions.assertIterableEquals(
+ Collections.singletonList(
+ Collections.singletonList(
+ "bigint")),
+ query(
+ getColumnDataTypeQuery(
+ POSTGRESQL_SCHEMA,
+ SINK_TABLE_3,
+ "f_big")))));
log.info("****************** container logs start ******************");
String containerLogs = container.getServerLogs();
@@ -1044,6 +1054,10 @@ public class PostgresCDCIT extends TestSuiteBase implements TestResource {
// Clear related content to ensure that multiple operations are not affected
clearTable(POSTGRESQL_SCHEMA, SOURCE_TABLE_3);
clearTable(POSTGRESQL_SCHEMA, SINK_TABLE_3);
+ // Drop the columns after deleting rows so the running CDC job does not observe a
+ // cleanup DML under the intentionally unsupported DROP COLUMN relation.
+ dropFieldIfExists(POSTGRESQL_SCHEMA, SOURCE_TABLE_3, "f_big");
+ dropFieldIfExists(POSTGRESQL_SCHEMA, SINK_TABLE_3, "f_big");
}
}
@@ -1454,10 +1468,19 @@ public class PostgresCDCIT extends TestSuiteBase implements TestResource {
}
private void addFieldsForTable(String database, String tableName) {
-
executeSql("ALTER TABLE " + database + "." + tableName + " ADD COLUMN f_big BIGINT");
}
+ private void dropFieldIfExists(String database, String tableName, String fieldName) {
+ executeSql(
+ "ALTER TABLE "
+ + database
+ + "."
+ + tableName
+ + " DROP COLUMN IF EXISTS "
+ + fieldName);
+ }
+
private void insertSourceTableForAddFields(String database, String tableName) {
executeSql(
"INSERT INTO "
@@ -1541,6 +1564,12 @@ public class PostgresCDCIT extends TestSuiteBase implements TestResource {
return String.format(SOURCE_SQL_TEMPLATE, database, tableName);
}
+ private String getColumnDataTypeQuery(String schemaName, String tableName, String columnName) {
+ return String.format(
+ "SELECT data_type FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s' AND column_name = '%s'",
+ schemaName, tableName, columnName);
+ }
+
@Override
@AfterAll
public void tearDown() {
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/resources/postgrescdc_to_postgres_test_add_Filed.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/resources/postgrescdc_to_postgres_test_add_Filed.conf
index b5aaad0076..1cdd274eb4 100644
--- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/resources/postgrescdc_to_postgres_test_add_Filed.conf
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-postgres-e2e/src/test/resources/postgrescdc_to_postgres_test_add_Filed.conf
@@ -36,7 +36,9 @@ source {
schema-names = ["inventory"]
table-names = ["postgres_cdc.inventory.postgres_cdc_table_3"]
url = "jdbc:postgresql://postgres_cdc_e2e:5432/postgres_cdc?loggerLevel=OFF"
- decoding.plugin.name = "decoderbufs"
+ decoding.plugin.name = "pgoutput"
+ schema-changes.enabled = true
+ schema-changes.include = ["add.column"]
slot.name = ${slot_name}
}
}