Skip to content

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

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

ilyasahsan123 wants to merge 18 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, Debezium emits a schema change event. DebeziumIO currently skips these events. This PR makes DebeziumIO emit them, so users can react to schema changes that might break their downstream pipeline, for example by sending an alert, pausing the pipeline, or updating the target schema.

Example

Schema change event from Debezium:

{
  "source": { "connector": "mysql", "name": "tutorial", "db": "inventory", "table": "customers", "file": "mysql-bin.000003", "pos": 636 },
  "databaseName": "inventory",
  "ddl": "ALTER TABLE inventory.customers MODIFY COLUMN first_name TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL",
  "tableChanges": [
    {
      "type": "ALTER",
      "id": "\"inventory\".\"customers\"",
      "table": {
        "primaryKeyColumnNames": ["id"],
        "columns": [
          { "name": "id", "typeName": "INT", "position": 1 },
          { "name": "first_name", "typeName": "TEXT", "position": 2 },
          { "name": "last_name", "typeName": "VARCHAR", "length": 255, "position": 3 },
          { "name": "email", "typeName": "VARCHAR", "length": 255, "position": 4 }
        ]
      }
    }
  ]
}

A schema change event emitted by DebeziumIO with this change:

{
  "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": {
        "primaryKeyColumnNames": ["id"],
        "columns": [
          { "name": "id", "typeName": "INT", "position": 1 },
          { "name": "first_name", "typeName": "VARCHAR", "length": 255, "position": 2 },
          { "name": "last_name", "typeName": "VARCHAR", "length": 255, "position": 3 },
          { "name": "email", "typeName": "VARCHAR", "length": 255, "position": 4 }
        ]
      }
    }
  ]
}

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 59.22%. Comparing base (4af7196) to head (5114a88).
⚠️ Report is 134 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41331      +/-   ##
============================================
- Coverage     59.31%   59.22%   -0.10%     
  Complexity     4995     4995              
============================================
  Files          1463     1463              
  Lines        186618   186618              
  Branches       3729     3729              
============================================
- Hits         110700   110520     -180     
- Misses        72544    72726     +182     
+ Partials       3374     3372       -2     
Flag Coverage Δ
go 29.23% <ø> (+0.01%) ⬆️
python 80.51% <ø> (-0.23%) ⬇️

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?

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