Skip to content

[DebeziumIO] Enable Schema Change Events in DebeziumIO JSON Output - #41331

Open
ilyasahsan123 wants to merge 22 commits into
apache:masterfrom
ilyasahsan123:support-change-schema-events
Open

ilyasahsan123 wants to merge 22 commits into
apache:masterfrom
ilyasahsan123:support-change-schema-events

Conversation

@ilyasahsan123

@ilyasahsan123 ilyasahsan123 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Addresses #41330

What does this PR do?

When a DDL statement such as ALTER TABLE runs in the source database, the MySQL, Oracle, SQL Server and Db2 connectors emit a schema change event. Debezium does this by default, because include.schema.changes defaults to true.

readAsJson() already outputs these events, but it maps them like a data change event: only metadata with a null before and after. The DDL statement and the changed tables are dropped, so users can't see what changed.

This PR adds an opt-in flag, withSchemaChangeEvents(true) on DebeziumIO.Read. It is wired the same way as withFullMetadata (#40702):

  • Java: withSchemaChangeEvents(true)
  • Python: schema_change_events=True
  • Go: debeziumio.SchemaChangeEvents()

Flag off (default): the output is the same as on master, so existing pipelines see no change.

Flag on: schema change events keep metadata, before and after and gain:

  • databaseName: database the DDL statement was applied to
  • schemaName: schema the DDL statement was applied to (null for MySQL)
  • ddl: the DDL statement
  • ts_ms: time the connector processed the event, in milliseconds
  • tableChanges: each table created, altered or dropped. Each entry has type (CREATE, ALTER or DROP), id and table. table holds defaultCharsetName, comment, primaryKeyColumnNames and columns. Each column keeps all 15 attributes Debezium emits, including nulls. For a DROP, table is null.

Example

Statement run on the source database (MySQL inventory.customers table from the Debezium tutorial):

ALTER TABLE inventory.customers MODIFY COLUMN first_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL;

1. Output with the flag off (default, same as master)

{
  "metadata": {
    "connector": "mysql",
    "version": "3.5.2.Final",
    "name": "dbserver1",
    "database": "inventory",
    "schema": "mysql-bin.000003",
    "table": "customers"
  },
  "before": null,
  "after": null
}

2. Output with withSchemaChangeEvents(true)

{
  "metadata": {
    "connector": "mysql",
    "version": "3.5.2.Final",
    "name": "dbserver1",
    "database": "inventory",
    "schema": "mysql-bin.000003",
    "table": "customers"
  },
  "before": null,
  "after": null,
  "databaseName": "inventory",
  "schemaName": null,
  "ddl": "ALTER TABLE inventory.customers MODIFY COLUMN first_name varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL",
  "ts_ms": 1794646017424,
  "tableChanges": [
    {
      "type": "ALTER",
      "id": "\"inventory\".\"customers\"",
      "table": {
        "defaultCharsetName": "utf8mb4",
        "comment": null,
        "primaryKeyColumnNames": ["id"],
        "columns": [
          {
            "name": "id",
            "jdbcType": 4,
            "nativeType": null,
            "typeName": "INT",
            "typeExpression": "INT",
            "charsetName": null,
            "length": null,
            "scale": null,
            "position": 1,
            "optional": false,
            "autoIncremented": true,
            "generated": true,
            "comment": null,
            "defaultValueExpression": null,
            "enumValues": null
          },
          {
            "name": "first_name",
            "jdbcType": 12,
            "nativeType": null,
            "typeName": "VARCHAR",
            "typeExpression": "VARCHAR",
            "charsetName": "utf8mb4",
            "length": 255,
            "scale": null,
            "position": 2,
            "optional": false,
            "autoIncremented": false,
            "generated": false,
            "comment": null,
            "defaultValueExpression": null,
            "enumValues": null
          },
          {
            "name": "last_name",
            "jdbcType": 12,
            "nativeType": null,
            "typeName": "VARCHAR",
            "typeExpression": "VARCHAR",
            "charsetName": "utf8mb4",
            "length": 255,
            "scale": null,
            "position": 3,
            "optional": false,
            "autoIncremented": false,
            "generated": false,
            "comment": null,
            "defaultValueExpression": null,
            "enumValues": null
          },
          {
            "name": "email",
            "jdbcType": 12,
            "nativeType": null,
            "typeName": "VARCHAR",
            "typeExpression": "VARCHAR",
            "charsetName": "utf8mb4",
            "length": 255,
            "scale": null,
            "position": 4,
            "optional": false,
            "autoIncremented": false,
            "generated": false,
            "comment": null,
            "defaultValueExpression": null,
            "enumValues": null
          }
        ]
      }
    }
  ]
}

3. A DROP TABLE with the flag on

For a DROP, Debezium only sets the table id, so table is null:

{
  "metadata": { "connector": "mysql", "version": "3.5.2.Final", "name": "dbserver1", "database": "inventory", "schema": "mysql-bin.000003", "table": "customers" },
  "before": null,
  "after": null,
  "databaseName": "inventory",
  "schemaName": null,
  "ddl": "DROP TABLE `inventory`.`customers`",
  "ts_ms": 1794646017424,
  "tableChanges": [
    { "type": "DROP", "id": "\"inventory\".\"customers\"", "table": null }
  ]
}

4. Enabling the flag

Java:

PCollection<String> events =
    pipeline.apply(
        DebeziumIO.readAsJson()
            .withConnectorConfiguration(
                DebeziumIO.ConnectorConfiguration.create()
                    .withUsername("debezium")
                    .withPassword("dbz")
                    .withConnectorClass(MySqlConnector.class)
                    .withHostName("localhost")
                    .withPort("3306")
                    .withConnectionProperty("database.server.id", "184054")
                    .withConnectionProperty("topic.prefix", "dbserver1")
                    .withConnectionProperty("database.include.list", "inventory"))
            .withSchemaChangeEvents(true));

Python:

from apache_beam.io.debezium import DriverClassName, ReadFromDebezium

events = pipeline | ReadFromDebezium(
    connector_class=DriverClassName.MYSQL,
    username="debezium",
    password="dbz",
    host="localhost",
    port="3306",
    connection_properties=[
        "database.server.id=184054",
        "topic.prefix=dbserver1",
        "database.include.list=inventory",
    ],
    schema_change_events=True)

Go:

events := debeziumio.Read(s, "debezium", "dbz", "localhost", "3306",
    debeziumio.MySQL, reflectx.String,
    debeziumio.ConnectionProperties([]string{
        "database.server.id=184054",
        "topic.prefix=dbserver1",
        "database.include.list=inventory",
    }),
    debeziumio.SchemaChangeEvents())

Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • If this contribution is large, please file an Apache Individual Contributor License Agreement.
  • Replace these instructions with a description of your change and why you have made it.
  • Mention the appropriate issue in your description (for example: addresses #123 or fixes #456).
  • Update CHANGES.md with noteworthy changes.

See CONTRIBUTING.md for more details.

@ilyasahsan123
ilyasahsan123 marked this pull request as draft November 14, 2026 08:59

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 Review Summary

This PR adds support for mapping Debezium schema change events into JSON in SourceRecordJson and includes both unit and MySQL integration tests. The implementation follows the existing TransactionEvent pattern cleanly, with a couple of small improvements suggested around connector key-schema matching and test null-safety.

🔍 General Feedback

  • Debezium's schema change key schema name is connector-specific (io.debezium.connector.<connector>.SchemaChangeKey), unlike TransactionMetadataKey which uses common. Matching the prefix/suffix (or pattern) would allow this feature to work across all historized relational connectors supported by DebeziumIO (MySQL, SQL Server, Oracle, Db2), especially since ChangeSchemaEvent already extracts schemaName.
  • Consider updating the class-level Javadoc on SourceRecordJson to document the new schema change event output format alongside the existing sections for data change and transaction metadata events.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.


private static final String SCHEMA_TRANSACTION_METADATA_EVENT_KEY_NAME =
"io.debezium.connector.common.TransactionMetadataKey";
public static final String SCHEMA_CHANGE_EVENT_KEY_NAME =

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low: SCHEMA_CHANGE_EVENT_KEY_NAME is an internal implementation detail of SourceRecordJson (just like SCHEMA_TRANSACTION_METADATA_EVENT_KEY_NAME above it) and should be private to avoid expanding the public API surface unnecessarily.

Suggested change
public static final String SCHEMA_CHANGE_EVENT_KEY_NAME =
private static final String SCHEMA_CHANGE_EVENT_KEY_NAME =

}

private static boolean isSchemaChangeEventKeyName(@Nullable Schema keySchema) {
return keySchema != null && SCHEMA_CHANGE_EVENT_KEY_NAME.equals(keySchema.name());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium: In Debezium's SchemaFactory, schema change key schemas are named io.debezium.connector.<connector>.SchemaChangeKey (e.g., mysql, sqlserver, oracle, db2). Since DebeziumIO supports multiple relational connectors and ChangeSchemaEvent already maps schemaName, consider matching any connector's SchemaChangeKey (e.g., checking prefix "io.debezium.connector." and suffix ".SchemaChangeKey") rather than only MySQL.

String customersId = "\"inventory\".\"customers\"";
JsonObject table = null;
for (String record : res) {
JsonObject event = JsonParser.parseString(record).getAsJsonObject();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Low: Because SourceRecordJson configures Gson with .serializeNulls(), event.has("tableChanges") will still return true if a schema change event has "tableChanges": null, causing event.getAsJsonArray("tableChanges") to throw an IllegalStateException. Also consider asserting assertNotNull(table) after the loop before dereferencing table.get("primaryKeyColumnNames") on line 447 so test failures produce a clear assertion error rather than a NullPointerException.

Suggested change
JsonObject event = JsonParser.parseString(record).getAsJsonObject();
if (!event.has("tableChanges") || event.get("tableChanges").isJsonNull()) {

@ilyasahsan123
ilyasahsan123 marked this pull request as ready for review November 14, 2026 12:37
@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @jrmccluskey for label go.
Backup reviewer: shunping (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

Note: If you would like to opt out of this review, comment assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

@ilyasahsan123

Copy link
Copy Markdown
Contributor Author

hi @Abacn @tkaymak,
when you have a moment, could you please take a look at this pull request?

thanks 😃

@tkaymak tkaymak left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, Ilyas. The mapping is clean and it follows the transaction event pattern well. I rebuilt the head version of SourceRecordJson from the diff and ran it against records built with the Debezium 3.5.2 schemas. ALTER, DROP with a null table, several table changes and an empty tableChanges list all map without errors.

There is one point I would like to settle before merge. The description says DebeziumIO skips these events today. I do not see that in the code. KafkaSourceConsumerFn maps every record, and on master a schema change record comes out as {"metadata":{...},"before":null,"after":null}. Debezium also defaults include.schema.changes to true, so for MySQL, Oracle and SQL Server users who never set the property, this PR changes the shape of records they already receive.

I would prefer that existing pipelines see no change at all. I suggest an opt in flag, withSchemaChangeEvents(true) on DebeziumIO.Read, false by default and wired like withFullMetadata from #40702, so schema_change_events in Python and SchemaChangeEvents() in Go. With the flag off, schema change records keep the shape they have on master. With the flag on, they keep metadata, before and after and gain databaseName, schemaName, ddl, ts_ms and tableChanges, so withFullMetadata(true) still applies and snapshot stays available. The transaction metadata change in #40785 needed no flag because provide.transaction.metadata defaults to false in Debezium.

Two small things on the description. The two examples show different statements, one sets first_name to TEXT and the other to varchar(255). The output example lists four attributes per column, the code emits all fifteen with nulls, plus defaultCharsetName and comment on the table.

The rest is inline and none of it blocks. Db2 is the one where I would like a decision.

Comment thread CHANGES.md Outdated
* Support for X source added (Java/Python) ([#X](https://github.com/apache/beam/issues/X)).
* Upgraded Iceberg dependency to 1.12.0 ([#40971](https://github.com/apache/beam/issues/40971)).
* (Java/Python/Go) DebeziumIO: `readAsJson()` now emits Debezium transaction metadata with `provide.transaction.metadata=true` (Python/Go via `connection_properties`) ([#40784](https://github.com/apache/beam/issues/40784)).
* (Java/Python/Go) DebeziumIO: `readAsJson()` now emits MySQL, Oracle and SQL Server schema change events with `include.schema.changes=true` (Python/Go via `connection_properties`) ([#41330](https://github.com/apache/beam/issues/41330)).

@tkaymak tkaymak Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The wording with include.schema.changes=true reads as opt in, but true is the Debezium default. With the flag from the summary, this line can name it, for example withSchemaChangeEvents(true) together with include.schema.changes=true. The same wording is in README.md:100, debezium.py:155 and debezium.go:151, where the Python and Go docs would name schema_change_events and SchemaChangeEvents().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Understood. I have updated README.md and CHANGES.md in line with your direction

this.transactionEvent = this.loadTransactionEvent();
this.changeSchemaEvent = null;
this.metadataExtras = Collections.emptyMap();
} else if (isSchemaChangeEventKeyName(sourceRecord.keySchema())) {

@tkaymak tkaymak Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On master these records fall through to the data branch and are emitted with metadata and null before and after. They are not skipped. Behind the flag, please keep metadata, before and after in this payload, so withFullMetadata(true) still applies and snapshot, file and pos are not lost.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You make a valid point, and I will address your concern.

ImmutableSet.of(
"io.debezium.connector.mysql.SchemaChangeKey",
"io.debezium.connector.oracle.SchemaChangeKey",
"io.debezium.connector.sqlserver.SchemaChangeKey");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Db2 is in Connectors and uses the same schemas with the key name io.debezium.connector.db2.SchemaChangeKey. With this list a Db2 schema change still comes out in the old data shape, I ran that. Debezium has SchemaFactory.get().isSchemaChangeSchema(schema), which covers every connector and returns true for the Db2 key. If the list of three is intended, please say in the docs what Db2 emits.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good point; I will support Db2 schema change events and adjust the logic for isSchemaChangeEvent as follows:

private static boolean isSchemaChangeEvent(@Nullable Schema keySchema) {
  return SchemaFactory.get().isSchemaChangeSchema(keySchema);
}

*
* <h3>Schema change events</h3>
*
* <p>With {@code include.schema.changes=true}, the MySQL, Oracle and SQL Server connectors also

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The snapshot emits these events as well. For MySQL that is one CREATE per captured table plus database level statements with an empty tableChanges. It is worth a sentence, since a pipeline that alerts on schema changes will see them at every initial snapshot.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point! I have revised the Javadoc to cover schema change events during the initial snapshot.

*
* @param type Kind of change: {@code CREATE}, {@code ALTER} or {@code DROP}
* @param id Fully qualified table id, for example {@code "inventory"."customers"}
* @param table Table definition after the change

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

table is null for a DROP, Debezium only sets the id there. Please mention it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid point! I've adjusted the Javadoc for the TableChange constructor

* Whether the record is a schema change event, emitted for each DDL statement when {@code
* include.schema.changes} is enabled. These are identified by their key schema name.
*/
private static boolean isSchemaChangeEventKeyName(@Nullable Schema keySchema) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit. The sibling is isTransactionMetadataEvent and this method takes a schema, so isSchemaChangeEvent would read better. Debezium and the Javadoc here say schema change, so SchemaChangeEvent would be more consistent than ChangeSchemaEvent.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with you. I will rename the method to isSchemaChangeEvent.

public void testChangeSchemaEvent() {
Schema keySchema =
SchemaBuilder.struct()
.name("io.debezium.connector.mysql.SchemaChangeKey")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add cases for a DROP with a null table, two entries in tableChanges, an empty list, and one Oracle or SQL Server key name. I ran these against the head code and they pass, so this is only about pinning the behaviour. SchemaFactory.get().schemaHistoryChangeSchema(SchemaNameAdjuster.NO_OP) gives you the real change, table and column schemas and saves about 45 lines.

.withConnectionProperty(
"schema.history.internal.store.only.captured.tables.ddl", "true"))
// The snapshot emits its schema change events before the customers rows.
.withMaxNumberOfRecords(10)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test reads the snapshot CREATE event, it never runs DDL. The use case in the issue is a live ALTER TABLE. A second table in table.include.list that the test alters would cover the binlog path without touching customers. The limit of 10 depends on how many schema events the snapshot emits before the rows, so a short comment with the count would help. By my reading of the Debezium snapshot source it is up to six. That count is inference, I did not run the IT.

@@ -1,4 +1,4 @@
{
"modification": 4,
"modification": 5,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could not find a Debezium test in the XVR Direct suite, so I think this trigger can go. That is inference from the Gradle files. The Debezium precommit already runs the new IT on any change under sdks/java/io/debezium.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have reverted the change. I bumped the modification version because I followed your earlier pull request regarding opt-in full metadata

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 58.08%. Comparing base (38eed1e) to head (f28d606).
⚠️ Report is 9 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41331      +/-   ##
============================================
- Coverage     58.08%   58.08%   -0.01%     
  Complexity     2840     2840              
============================================
  Files          1210     1210              
  Lines        173375   173379       +4     
  Branches       2329     2329              
============================================
+ Hits         100709   100711       +2     
- Misses        69959    69960       +1     
- Partials       2707     2708       +1     
Flag Coverage Δ
go 29.25% <100.00%> (+<0.01%) ⬆️
python 80.72% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@kennknowles

Copy link
Copy Markdown
Member

CC @ahmedabu98

@ahmedabu98

Copy link
Copy Markdown
Contributor

@ilyasahsan123 have you considered adding a new side output PCollection that is dedicated for notable metadata events (e.g. schema change)? I'm wondering if that would be a more intuitive shape for sinks to work with.

The way it's handled now, a Sink would have to inspect each incoming element and identify if it is a data record or a metadata event. Nothing in the element says which kind it is, so it comes down to checking which keys are present

Also +1 to @tkaymak's suggestion to make this an opt-in feature to avoid disrupting existing pipelines

@ilyasahsan123
ilyasahsan123 force-pushed the support-change-schema-events branch from 5114a88 to b15a514 Compare November 24, 2026 07:16
@github-actions github-actions Bot added size/l L: 250-999 lines changed and removed size/m M: 50-249 lines changed labels Nov 24, 2026
@ilyasahsan123
ilyasahsan123 force-pushed the support-change-schema-events branch from 2b9eca4 to b641698 Compare November 25, 2026 05:47
@ilyasahsan123

Copy link
Copy Markdown
Contributor Author

Thanks for this, Ilyas. The mapping is clean and it follows the transaction event pattern well. I rebuilt the head version of SourceRecordJson from the diff and ran it against records built with the Debezium 3.5.2 schemas. ALTER, DROP with a null table, several table changes and an empty tableChanges list all map without errors.

Thanks for testing it, and for checking the edge cases too. That's very helpful.

There is one point I would like to settle before merge. The description says DebeziumIO skips these events today. I do not see that in the code. KafkaSourceConsumerFn maps every record, and on master a schema change record comes out as {"metadata":{...},"before":null,"after":null}. Debezium also defaults include.schema.changes to true, so for MySQL, Oracle and SQL Server users who never set the property, this PR changes the shape of records they already receive.

You're right, I was wrong about that. DebeziumIO does not skip these events. I've fixed the description and the README to say this.

I would prefer that existing pipelines see no change at all. I suggest an opt in flag, withSchemaChangeEvents(true) on DebeziumIO.Read, false by default and wired like withFullMetadata from #40702, so schema_change_events in Python and SchemaChangeEvents() in Go. With the flag off, schema change records keep the shape they have on master. With the flag on, they keep metadata, before and after and gain databaseName, schemaName, ddl, ts_ms and tableChanges, so withFullMetadata(true) still applies and snapshot stays available. The transaction metadata change in #40785 needed no flag because provide.transaction.metadata defaults to false in Debezium.

Agreed, and done. I added withSchemaChangeEvents(true) on DebeziumIO.Read. It's off by default and wired like withFullMetadata.

Two small things on the description. The two examples show different statements, one sets first_name to TEXT and the other to varchar(255). The output example lists four attributes per column, the code emits all fifteen with nulls, plus defaultCharsetName and comment on the table.

Thanks, fixed. The description now uses one statement (first_name varchar(255)) and the output example shows all 15 column attributes, plus defaultCharsetName and comment on the table.

The rest is inline and none of it blocks. Db2 is the one where I would like a decision.

I've included Db2.

@ilyasahsan123

Copy link
Copy Markdown
Contributor Author

@ilyasahsan123 have you considered adding a new side output PCollection that is dedicated for notable metadata events (e.g. schema change)? I'm wondering if that would be a more intuitive shape for sinks to work with.

The way it's handled now, a Sink would have to inspect each incoming element and identify if it is a data record or a metadata event. Nothing in the element says which kind it is, so it comes down to checking which keys are present

Also +1 to @tkaymak's suggestion to make this an opt-in feature to avoid disrupting existing pipelines

Thanks @ahmedabu98, agreed. A separate output is easier for sinks because they'd only get data records and wouldn't need to check keys.

Right now readAsJson() puts everything into one PCollection: data changes (before/after), schema changes (ddl, tableChanges), and transaction BEGIN/END events. To write to a destination like BigQuery, you have to strip out the non-data keys first (example)

My proposal is an opt-in variant that returns a result object with:

  • getRecords(): data change events only
  • getSchemaChanges(): schema change events with ddl, tableChanges, etc.

Okay if I open a separate PR for this?

@tkaymak tkaymak left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you Ilyas! I rebuilt the head SourceRecordJson and ran it next to the master version on data, schema change, transaction, heartbeat and tombstone records, and with the flag off the output is byte for byte the same. The registrar, Python and Go only set the flag when it is true, so the xlang default is unchanged too. With the flag on, schema change records keep metadata, before and after, full metadata still applies, and Db2 is covered.

A few small things are left:

  • The branch now conflicts with master in beam_PostCommit_Python.json
  • the PR description still shows the old text
  • and examples, perhaps the edit was not saved.

I left three inline notes, the only code issue is a flag combination in resolveFormatFunction.

The split output with getRecords() and getSchemaChanges() sounds good to me as a separate PR, that is for @ahmedabu98 to decide. I would keep the JSON shape from this PR for the schema change output and find a home for the transaction events too.

return fullMetadataMapper;
SourceRecordMapper<T> jsonMapper =
(SourceRecordMapper<T>)
new SourceRecordJson.SourceRecordJsonMapper(fullMetadata, schemaChangeEvents);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This builds the mapper from the two flags on Read only. With withFormatFunction(new SourceRecordJsonMapper(true)).withSchemaChangeEvents(true) full metadata is lost without an error, and the reverse case loses the schema change payload. Falling back to the flags of the existing mapper when the Read flag is null would avoid that.


/**
* Returns the format function to use, taking {@link #withFullMetadata(boolean)} into account.
* Adds the schema change payload ({@code databaseName}, {@code schemaName}, {@code ddl}, {@code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please mention that this only changes the JSON mapping, and that Debezium drops these events when include.schema.changes=false. The class Javadoc example above sets that property to false.

*
* @param databaseName Database the DDL statement was applied to
* @param schemaName Schema the DDL statement was applied to, null for MySQL
* @param ddl DDL statement that changed the schema

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For SQL Server and Db2, Debezium passes the literal "N/A" here, see SqlServerSchemaChangeEventEmitter and Db2SchemaChangeEventEmitter. Worth a few words, since CHANGES.md promises the DDL statement for all four connectors.

Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
…ython.json

Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
…Registrar

Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
…e events

Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
@ilyasahsan123
ilyasahsan123 force-pushed the support-change-schema-events branch from b641698 to c87208d Compare November 26, 2026 11:44
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
…events have no DDL

Signed-off-by: Ilyas Ahsan <meilyasahsan@gmail.com>
@ilyasahsan123

Copy link
Copy Markdown
Contributor Author

Thank you, @tkaymak! I have modified the PR description, resolved the conflict, and addressed your three concern. When you have a moment, kindly take another look.

@tkaymak

tkaymak commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Thanks Ilyas, all three points are addressed and the description reads well now. With both flags unset resolveFormatFunction returns the mapper untouched, so the default output stays the same. LGTM from my side, over to @ahmedabu98 for the review.

@ilyasahsan123

Copy link
Copy Markdown
Contributor Author

Thanks Ilyas, all three points are addressed and the description reads well now. With both flags unset resolveFormatFunction returns the mapper untouched, so the default output stays the same. LGTM from my side, over to @ahmedabu98 for the review.

Thanks, @tkaymak! I really appreciate you taking the time to review the pull request.

@ilyasahsan123

Copy link
Copy Markdown
Contributor Author

Hi @Abacn, when you have a moment, could you please take a look at this pull request? Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants