Repository navigation
[DebeziumIO] Enable Schema Change Events in DebeziumIO JSON Output - #41331
ilyasahsan123 wants to merge 18 commits into
Conversation
There was a problem hiding this comment.
📋 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), unlikeTransactionMetadataKeywhich usescommon. Matching the prefix/suffix (or pattern) would allow this feature to work across all historized relational connectors supported byDebeziumIO(MySQL, SQL Server, Oracle, Db2), especially sinceChangeSchemaEventalready extractsschemaName. - Consider updating the class-level Javadoc on
SourceRecordJsonto 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 = |
There was a problem hiding this comment.
🟢 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.
| 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()); |
There was a problem hiding this comment.
🟡 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(); |
There was a problem hiding this comment.
🟢 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.
| JsonObject event = JsonParser.parseString(record).getAsJsonObject(); | |
| if (!event.has("tableChanges") || event.get("tableChanges").isJsonNull()) { |
|
Assigning reviewers: R: @jrmccluskey for label go. Note: If you would like to opt out of this review, comment Available commands:
The PR bot will only process comments in the main thread (not review comments). |
There was a problem hiding this comment.
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.
| * 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)). |
There was a problem hiding this comment.
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().
There was a problem hiding this comment.
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())) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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"); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
table is null for a DROP, Debezium only sets the id there. Please mention it.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I agree with you. I will rename the method to isSchemaChangeEvent.
| public void testChangeSchemaEvent() { | ||
| Schema keySchema = | ||
| SchemaBuilder.struct() | ||
| .name("io.debezium.connector.mysql.SchemaChangeKey") |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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, | |||
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
I have reverted the change. I bumped the modification version because I followed your earlier pull request regarding opt-in full metadata
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
CC @ahmedabu98 |
|
@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 |
5114a88 to
b15a514
Compare
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
…ython.json Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
Signed-off-by: Ilyas Ahsan <[email protected]>
…Registrar Signed-off-by: Ilyas Ahsan <[email protected]>
…e events Signed-off-by: Ilyas Ahsan <[email protected]>
2b9eca4 to
b641698
Compare
Thanks for testing it, and for checking the edge cases too. That's very helpful.
You're right, I was wrong about that.
Agreed, and done. I added
Thanks, fixed. The description now uses one statement (
I've included Db2. |
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 My proposal is an opt-in variant that returns a result object with:
Okay if I open a separate PR for this? |
Addresses #41330
What does this PR do?
When a DDL statement such as
ALTER TABLEruns 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:
addresses #123orfixes #456).CHANGES.mdwith noteworthy changes.See CONTRIBUTING.md for more details.