Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/en/connectors/source/PostgreSQL-CDC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down Expand Up @@ -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

```
Expand Down
24 changes: 24 additions & 0 deletions docs/zh/connectors/source/PostgreSQL-CDC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) 获取详细信息。 |

Expand Down Expand Up @@ -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"]
}
}
```

### 支持自定义表的主键

```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,25 @@

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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
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;
Expand Down Expand Up @@ -133,6 +134,11 @@ private void deserializeSchemaChangeRecord(
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@
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(),
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,6 @@ public PostgresSourceConfig create(int subtask) {
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));
}
Expand Down Expand Up @@ -111,6 +109,10 @@ public PostgresSourceConfig create(int subtask) {
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
Expand Down
Loading
Loading