Repository navigation
[DebeziumIO] Enable Schema Change Events in DebeziumIO JSON Output - #41331
ilyasahsan123 wants to merge 22 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@@ 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
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
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? |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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>
b641698 to
c87208d
Compare
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>
|
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. |
|
Thanks Ilyas, all three points are addressed and the description reads well now. With both flags unset |
Thanks, @tkaymak! I really appreciate you taking the time to review the pull request. |
|
Hi @Abacn, when you have a moment, could you please take a look at this pull request? Thanks |
Addresses #41330
What does this PR do?
When a DDL statement such as
ALTER TABLEruns in the source database, the MySQL, Oracle, SQL Server and Db2 connectors emit a schema change event. Debezium does this by default, becauseinclude.schema.changesdefaults totrue.readAsJson()already outputs these events, but it maps them like a data change event: onlymetadatawith a nullbeforeandafter. 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)onDebeziumIO.Read. It is wired the same way aswithFullMetadata(#40702):withSchemaChangeEvents(true)schema_change_events=Truedebeziumio.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,beforeandafterand gain:databaseName: database the DDL statement was applied toschemaName: schema the DDL statement was applied to (null for MySQL)ddl: the DDL statementts_ms: time the connector processed the event, in millisecondstableChanges: each table created, altered or dropped. Each entry hastype(CREATE,ALTERorDROP),idandtable.tableholdsdefaultCharsetName,comment,primaryKeyColumnNamesandcolumns. Each column keeps all 15 attributes Debezium emits, including nulls. For aDROP,tableis null.Example
Statement run on the source database (MySQL
inventory.customerstable from the Debezium tutorial):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 TABLEwith the flag onFor a
DROP, Debezium only sets the table id, sotableis 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:
Python:
Go:
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.