Debezium connector for PostgreSQL
Overview
PostgreSQL’s logical decoding feature was introduced in version 9.4. It is a mechanism that allows the extraction of the changes that were committed to the transaction log and the processing of these changes in a user-friendly manner with the help of an output plug-in. The output plug-in enables clients to consume the changes.
The PostgreSQL connector contains two main parts that work together to read and process database changes:
-
A logical decoding output plug-in. You might need to install the output plug-in that you choose to use. You must configure a replication slot that uses your chosen output plug-in before running the PostgreSQL server. The plug-in can be one of the following:
-
decoderbufs is based on Protobuf and maintained by the Debezium community.
- wal2json is based on JSON and maintained by the wal2json community (deprecated, scheduled for removal in Debezium 2.0).
pgoutputis the standard logical decoding output plug-in in PostgreSQL 10+. It is maintained by the PostgreSQL community, and used by PostgreSQL itself for logical replication. This plug-in is always present so no additional libraries need to be installed. The Debezium connector interprets the raw replication event stream directly into change events.- Java code (the actual Kafka Connect connector) that reads the changes produced by the chosen logical decoding output plug-in. It uses PostgreSQL’s streaming replication protocol, by means of the PostgreSQL JDBC driver
The connector produces a change event for every row-level insert, update, and delete operation that was captured and sends change event records for each table in a separate Kafka topic. Client applications read the Kafka topics that correspond to the database tables of interest, and can react to every row-level event they receive from those topics.
PostgreSQL normally purges write-ahead log (WAL) segments after some period of time. This means that the connector does not have the complete history of all changes that have been made to the database. Therefore, when the PostgreSQL connector first connects to a particular PostgreSQL database, it starts by performing a consistent snapshot of each of the database schemas. After the connector completes the snapshot, it continues streaming changes from the exact point at which the snapshot was made. This way, the connector starts with a consistent view of all of the data, and does not omit any changes that were made while the snapshot was being taken.
The connector is tolerant of failures. As the connector reads changes and produces events, it records the WAL position for each event. If the connector stops for any reason (including communication failures, network problems, or crashes), upon restart the connector continues reading the WAL where it last left off. This includes snapshots. If the connector stops during a snapshot, the connector begins a new snapshot when it restarts.
The connector relies on and reflects the PostgreSQL logical decoding feature, which has the following limitations: - Logical decoding does not support DDL changes. This means that the connector is unable to report DDL change events back to consumers. - Logical decoding replication slots are supported on only primary servers. When there is a cluster of PostgreSQL servers, the connector can run on only the active primary server. It cannot run on hot or warm standby replicas. If the primary server fails or is demoted, the connector stops. After the primary server has recovered, you can restart the connector. If a different PostgreSQL server has been promoted to primary, adjust the connector configuration before restarting the connector. Behavior when things go wrong describes what the connector does when there is a problem. |
| Debezium currently supports databases with UTF-8 character encoding only. With a single byte character encoding, it is not possible to correctly process strings that contain extended ASCII code characters. |
How the connector works
To optimally configure and run a Debezium PostgreSQL connector, it is helpful to understand how the connector performs snapshots, streams change events, determines Kafka topic names, and uses metadata.
Security
To use the Debezium connector to stream changes from a PostgreSQL database, the connector must operate with specific privileges in the database. Although one way to grant the necessary privileges is to provide the user with superuser privileges, doing so potentially exposes your PostgreSQL data to unauthorized access. Rather than granting excessive privileges to the Debezium user, it is best to create a dedicated Debezium replication user to which you grant specific privileges.
For more information about configuring privileges for the Debezium PostgreSQL user, see Setting up permissions. For more information about PostgreSQL logical replication security, see the PostgreSQL documentation.
Snapshots
Most PostgreSQL servers are configured to not retain the complete history of the database in the WAL segments. This means that the PostgreSQL connector would be unable to see the entire history of the database by reading only the WAL. Consequently, the first time that the connector starts, it performs an initial consistent snapshot of the database. The default behavior for performing a snapshot consists of the following steps. You can change this behavior by setting the snapshot.mode connector configuration property to a value other than initial.
- Start a transaction with a SERIALIZABLE, READ ONLY, DEFERRABLE isolation level to ensure that subsequent reads in this transaction are against a single consistent version of the data. Any changes to the data due to subsequent
INSERT,UPDATE, andDELETEoperations by other clients are not visible to this transaction. - Read the current position in the server’s transaction log.
- Scan the database tables and schemas, generate a
READevent for each row and write that event to the appropriate table-specific Kafka topic. - Commit the transaction.
- Record the successful completion of the snapshot in the connector offsets.
If the connector fails, is rebalanced, or stops after Step 1 begins but before Step 5 completes, upon restart the connector begins a new snapshot. After the connector completes its initial snapshot, the PostgreSQL connector continues streaming from the position that it read in Step 2. This ensures that the connector does not miss any updates. If the connector stops again for any reason, upon restart, the connector continues streaming changes from where it previously left off.
Table 1. Options for the snapshot.mode connector configuration property
| Option | Description |
|---|---|
always |
The connector always performs a snapshot when it starts. After the snapshot completes, the connector continues streaming changes from step 3 in the above sequence. This mode is useful in these situations: - It is known that some WAL segments have been deleted and are no longer available. - After a cluster failure, a new primary has been promoted. The always snapshot mode ensures that the connector does not miss any changes that were made after the new primary had been promoted but before the connector was restarted on the new primary. |
never |
The connector never performs snapshots. When a connector is configured this way, its behavior when it starts is as follows. If there is a previously stored LSN in the Kafka offsets topic, the connector continues streaming changes from that position. If no LSN has been stored, the connector starts streaming changes from the point in time when the PostgreSQL logical replication slot was created on the server. The never snapshot mode is useful only when you know all data of interest is still reflected in the WAL. |
initial_only |
The connector performs a database snapshot and stops before streaming any change event records. If the connector had started but did not complete a snapshot before stopping, the connector restarts the snapshot process and stops when the snapshot completes. |
exported |
Deprecated, all modes are lockless. |
custom |
The custom snapshot mode lets you inject your own implementation of the io.debezium.connector.postgresql.spi.Snapshotter interface. Set the snapshot.custom.class configuration property to the class on the classpath of your Kafka Connect cluster or included in the JAR if using the EmbeddedEngine. For more details, see custom snapshotter SPI. |
Ad hoc snapshots
By default, a connector runs an initial snapshot operation only after it starts for the first time. Following this initial snapshot, under normal circumstances, the connector does not repeat the snapshot process. Any future change event data that the connector captures comes in through the streaming process only.
However, in some situations the data that the connector obtained during the initial snapshot might become stale, lost, or incomplete. To provide a mechanism for recapturing table data, Debezium includes an option to perform ad hoc snapshots. The following changes in a database might be cause for performing an ad hoc snapshot:
- The connector configuration is modified to capture a different set of tables.
- Kafka topics are deleted and must be rebuilt.
- Data corruption occurs due to a configuration error or some other problem.
You can re-run a snapshot for a table for which you previously captured a snapshot by initiating a so-called ad-hoc snapshot. Ad hoc snapshots require the use of signaling tables. You initiate an ad hoc snapshot by sending a signal request to the Debezium signaling table.
When you initiate an ad hoc snapshot of an existing table, the connector appends content to the topic that already exists for the table. If a previously existing topic was removed, Debezium can create a topic automatically if automatic topic creation is enabled.
Ad hoc snapshot signals specify the tables to include in the snapshot. The snapshot can capture the entire contents of the database, or capture only a subset of the tables in the database.
You specify the tables to capture by sending an execute-snapshot message to the signaling table. Set the type of the execute-snapshot signal to incremental, and provide the names of the tables to include in the snapshot, as described in the following table:
Table 2. Example of an ad hoc execute-snapshot signal record
| Field | Default | Value |
| --- | --- | --- |
| type | incremental | Specifies the type of snapshot that you want to run. Setting the type is optional. Currently, you can request only incremental snapshots. |
| data-collections | N/A | An array that contains the fully-qualified names of the table to be snapshotted. The format of the names is the same as for the signal.data.collection configuration option. |
Triggering an ad hoc snapshot
You initiate an ad hoc snapshot by adding an entry with the execute-snapshot signal type to the signaling table. After the connector processes the message, it begins the snapshot operation. The snapshot process reads the first and last primary key values and uses those values as the start and end point for each table. Based on the number of entries in the table, and the configured chunk size, Debezium divides the table into chunks, and proceeds to snapshot each chunk, in succession, one at a time.
Currently, the execute-snapshot action type triggers incremental snapshots only. For more information, see Incremental snapshots.
Incremental snapshots
To provide flexibility in managing snapshots, Debezium includes a supplementary snapshot mechanism, known as incremental snapshotting. Incremental snapshots rely on the Debezium mechanism for sending signals to a Debezium connector. Incremental snapshots are based on the DDD-3 design document.
In an incremental snapshot, instead of capturing the full state of a database all at once, as in an initial snapshot, Debezium captures each table in phases, in a series of configurable chunks. You can specify the tables that you want the snapshot to capture and the size of each chunk. The chunk size determines the number of rows that the snapshot collects during each fetch operation on the database. The default chunk size for incremental snapshots is 1 KB.
As an incremental snapshot proceeds, Debezium uses watermarks to track its progress, maintaining a record of each table row that it captures. This phased approach to capturing data provides the following advantages over the standard initial snapshot process:
- You can run incremental snapshots in parallel with streamed data capture, instead of postponing streaming until the snapshot completes. The connector continues to capture near real-time events from the change log throughout the snapshot process, and neither operation blocks the other.
- If the progress of an incremental snapshot is interrupted, you can resume it without losing any data. After the process resumes, the snapshot begins at the point where it stopped, rather than recapturing the table from the beginning.
- You can run an incremental snapshot on demand at any time, and repeat the process as needed to adapt to database updates. For example, you might re-run a snapshot after you modify the connector configuration to add a table to its table.include.list property.
Incremental snapshot process
When you run an incremental snapshot, Debezium sorts each table by primary key and then splits the table into chunks based on the configured chunk size. Working chunk by chunk, it then captures each table row in a chunk. For each row that it captures, the snapshot emits a READ event. That event represents the value of the row when the snapshot for the chunk began.
As a snapshot proceeds, it’s likely that other processes continue to access the database, potentially modifying table records. To reflect such changes, INSERT, UPDATE, or DELETE operations are committed to the transaction log as per usual. Similarly, the ongoing Debezium streaming process continues to detect these change events and emits corresponding change event records to Kafka.
How Debezium resolves collisions among records with the same primary key
In some cases, the UPDATE or DELETE events that the streaming process emits are received out of sequence. That is, the streaming process might emit an event that modifies a table row before the snapshot captures the chunk that contains the READ event for that row. When the snapshot eventually emits the corresponding READ event for the row, its value is already superseded. To ensure that incremental snapshot events that arrive out of sequence are processed in the correct logical order, Debezium employs a buffering scheme for resolving collisions. Only after collisions between the snapshot events and the streamed events are resolved does Debezium emit an event record to Kafka.
Snapshot window
To assist in resolving collisions between late-arriving READ events and streamed events that modify the same table row, Debezium employs a so-called snapshot window. The snapshot windows demarcates the interval during which an incremental snapshot captures data for a specified table chunk. Before the snapshot window for a chunk opens, Debezium follows its usual behavior and emits events from the transaction log directly downstream to the target Kafka topic. But from the moment that the snapshot for a particular chunk opens, until it closes, Debezium performs a de-duplication step to resolve collisions between events that have the same primary key..
For each data collection, the Debezium emits two types of events, and stores the records for them both in a single destination Kafka topic. The snapshot records that it captures directly from a table are emitted as READ operations. Meanwhile, as users continue to update records in the data collection, and the transaction log is updated to reflect each commit, Debezium emits UPDATE or DELETE operations for each change.
As the snapshot window opens, and Debezium begins processing a snapshot chunk, it delivers snapshot records to a memory buffer. During the snapshot windows, the primary keys of the READ events in the buffer are compared to the primary keys of the incoming streamed events. If no match is found, the streamed event record is sent directly to Kafka. If Debezium detects a match, it discards the buffered READ event, and writes the streamed record to the destination topic, because the streamed event logically supersede the static snapshot event. After the snapshot window for the chunk closes, the buffer contains only READ events for which no related transaction log events exist. Debezium emits these remaining READ events to the table’s Kafka topic.
The connector repeats the process for each snapshot chunk.
Triggering an incremental snapshot
Currently, the only way to initiate an incremental snapshot is to send an ad hoc snapshot signal to the signaling table on the source database. You submit signals to the table as SQL INSERT queries. After Debezium detects the change in the signaling table, it reads the signal, and runs the requested snapshot operation.
The query that you submit specifies the tables to include in the snapshot, and, optionally, specifies the kind of snapshot operation. Currently, the only valid option for snapshots operations is the default value, incremental.
To specify the tables to include in the snapshot, provide a data-collections array that lists the tables, for example,
{"data-collections": ["public.MyFirstTable", "public.MySecondTable"]}
The data-collections array for an incremental snapshot signal has no default value. If the data-collections array is empty, Debezium detects that no action is required and does not perform a snapshot.
If the name of a table that you want to include in a snapshot contains a dot (.) in the name of the database, schema, or table, to add the table to the data-collections array, you must escape each part of the name in double quotes. For example, to include a table that exists in the public schema and that has the name My.Table, use the following format: “public”.”My.Table”. |
Prerequisites
-
A signaling data collection exists on the source database and the connector is configured to capture it.
- The signaling data collection is specified in the signal.data.collection property.
Procedure
- Send a SQL query to add the ad hoc incremental snapshot request to the signaling table:
1. INSERT INTO _<signalTable>_ (id, type, data) VALUES (_'<id>'_, _'<snapshotType>'_, '{"data-collections": ["_<tableName>_","_<tableName>_"],"type":"_<snapshotType>_"}');
For example,
1. INSERT INTO myschema.debezium_signal (id, type, data) VALUES('ad-hoc-1', 'execute-snapshot', '{"data-collections": ["schema1.table1", "schema2.table2"],"type":"incremental"}');
The values of the id,type, and data parameters in the command correspond to the fields of the signaling table.
The following table describes the these parameters:
Table 3. Descriptions of fields in a SQL command for sending an incremental snapshot signal to the signaling table
| Value | Description |
| --- | --- |
| myschema.debezium_signal | Specifies the fully-qualified name of the signaling table on the source database |
| ad-hoc-1 | The id parameter specifies an arbitrary string that is assigned as the id identifier for the signal request. Use this string to identify logging messages to entries in the signaling table. Debezium does not use this string. Rather, during the snapshot, Debezium generates its own id string as a watermarking signal. |
| execute-snapshot | Specifies type parameter specifies the operation that the signal is intended to trigger. |
| data-collections | A required component of the data field of a signal that specifies an array of table names to include in the snapshot. The array lists tables by their fully-qualified names, using the same format as you use to specify the name of the connector’s signaling table in the signal.data.collection configuration property. |
| incremental | An optional type component of the data field of a signal that specifies the kind of snapshot operation to run. Currently, the only valid option is the default value, incremental. Specifying a type value in the SQL query that you submit to the signaling table is optional. If you do not specify a value, the connector runs an incremental snapshot. |
The following example, shows the JSON for an incremental snapshot event that is captured by a connector.
Example: Incremental snapshot event message
1. {
2. "before":null,
3. "after": {
4. "pk":"1",
5. "value":"New data"
6. },
7. "source": {
8. ...
9. "snapshot":"incremental" (1)
10. },
11. "op":"r", (2)
12. "ts_ms":"1620393591654",
13. "transaction":null
14. }
| Item | Field name | Description |
|---|---|---|
| 1 | snapshot |
Specifies the type of snapshot operation to run. Currently, the only valid option is the default value, incremental. Specifying a type value in the SQL query that you submit to the signaling table is optional. If you do not specify a value, the connector runs an incremental snapshot. |
| 2 | op |
Specifies the event type. The value for snapshot events is r, signifying a READ operation. |
The Debezium connector for PostgreSQL does not support schema changes while an incremental snapshot is running. If a schema change is performed before the incremental snapshot start but after sending the signal then passthrough config option database.autosave is set to conservative to correctly process the schema change. |
Custom snapshotter SPI
For more advanced uses, you can provide an implementation of the io.debezium.connector.postgresql.spi.Snapshotter interface. This interface allows control of most of the aspects of how the connector performs snapshots. This includes whether or not to take a snapshot, the options for opening the snapshot transaction, and whether to take locks.
Following is the full API for the interface. All built-in snapshot modes implement this interface.
1. /**
2. * This interface is used to determine details about the snapshot process:
3. *
4. * Namely:
5. * - Should a snapshot occur at all
6. * - Should streaming occur
7. * - What queries should be used to snapshot
8. *
9. * While many default snapshot modes are provided with Debezium,
10. * a custom implementation of this interface can be provided by the implementor, which
11. * can provide more advanced functionality, such as partial snapshots.
12. *
13. * Implementations must return true for either {@link #shouldSnapshot()} or {@link #shouldStream()}
14. * or true for both.
15. */
16. @Incubating
17. public interface Snapshotter {
19. void init(PostgresConnectorConfig config, OffsetState sourceInfo,
20. SlotState slotState);
22. /**
23. * @return true if the snapshotter should take a snapshot
24. */
25. boolean shouldSnapshot();
27. /**
28. * @return true if the snapshotter should stream after taking a snapshot
29. */
30. boolean shouldStream();
32. /**
33. *
34. * @return true if streaming should resume from the start of the snapshot
35. * transaction, or false for when a connector resumes and takes a snapshot,
36. * streaming should resume from where streaming previously left off.
37. */
38. default boolean shouldStreamEventsStartingFromSnapshot() {
39. return true;
40. }
41. /**
42. * Generate a valid postgres query string for the specified table, or an empty {@link Optional}
43. * to skip snapshotting this table (but that table will still be streamed from)
44. *
45. * @param tableId the table to generate a query for
46. * @param snapshotSelectColumns the columns to be used in the snapshot select based on the column
47. * include/exclude filters
48. * @return a valid query string, or none to skip snapshotting this table
49. */
50. Optional<String> buildSnapshotQuery(TableId tableId, List<String> snapshotSelectColumns);
52. /**
53. * Return a new string that set up the transaction for snapshotting
54. *
55. * @param newSlotInfo if a new slow was created for snapshotting, this contains information from
56. * the `create_replication_slot` command
57. */
58. default String snapshotTransactionIsolationLevelStatement(SlotCreationResult newSlotInfo) {
59. // we're using the same isolation level that pg_backup uses
60. return "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE;";
61. }
63. /**
64. * Returns a SQL statement for locking the given tables during snapshotting, if required by the specific snapshotter
65. * implementation.
66. */
67. default Optional<String> snapshotTableLockingStatement(Duration lockTimeout, Set<TableId> tableIds) {
68. String lineSeparator = System.lineSeparator();
69. StringBuilder statements = new StringBuilder();
70. statements.append("SET lock_timeout = ").append(lockTimeout.toMillis()).append(";").append(lineSeparator);
71. // we're locking in ACCESS SHARE MODE to avoid concurrent schema changes while we're taking the snapshot
72. // this does not prevent writes to the table, but prevents changes to the table's schema....
73. // DBZ-298 Quoting name in case it has been quoted originally; it doesn't do harm if it hasn't been quoted
74. tableIds.forEach(tableId -> statements.append("LOCK TABLE ")
75. .append(tableId.toDoubleQuotedString())
76. .append(" IN ACCESS SHARE MODE;")
77. .append(lineSeparator));
78. return Optional.of(statements.toString());
79. }
81. /**
82. * Lifecycle hook called once the snapshot phase is finished.
83. */
84. default void snapshotCompleted() {
85. // no operation
86. }
87. }
Streaming changes
The PostgreSQL connector typically spends the vast majority of its time streaming changes from the PostgreSQL server to which it is connected. This mechanism relies on PostgreSQL’s replication protocol. This protocol enables clients to receive changes from the server as they are committed in the server’s transaction log at certain positions, which are referred to as Log Sequence Numbers (LSNs).
Whenever the server commits a transaction, a separate server process invokes a callback function from the logical decoding plug-in. This function processes the changes from the transaction, converts them to a specific format (Protobuf or JSON in the case of Debezium plug-in) and writes them on an output stream, which can then be consumed by clients.
The Debezium PostgreSQL connector acts as a PostgreSQL client. When the connector receives changes it transforms the events into Debezium create, update, or delete events that include the LSN of the event. The PostgreSQL connector forwards these change events in records to the Kafka Connect framework, which is running in the same process. The Kafka Connect process asynchronously writes the change event records in the same order in which they were generated to the appropriate Kafka topic.
Periodically, Kafka Connect records the most recent offset in another Kafka topic. The offset indicates source-specific position information that Debezium includes with each event. For the PostgreSQL connector, the LSN recorded in each change event is the offset.
When Kafka Connect gracefully shuts down, it stops the connectors, flushes all event records to Kafka, and records the last offset received from each connector. When Kafka Connect restarts, it reads the last recorded offset for each connector, and starts each connector at its last recorded offset. When the connector restarts, it sends a request to the PostgreSQL server to send the events starting just after that position.
| The PostgreSQL connector retrieves schema information as part of the events sent by the logical decoding plug-in. However, the connector does not retrieve information about which columns compose the primary key. The connector obtains this information from the JDBC metadata (side channel). If the primary key definition of a table changes (by adding, removing or renaming primary key columns), there is a tiny period of time when the primary key information from JDBC is not synchronized with the change event that the logical decoding plug-in generates. During this tiny period, a message could be created with an inconsistent key structure. To prevent this inconsistency, update primary key structures as follows: 1. Put the database or an application into a read-only mode. 2. Let Debezium process all remaining events. 3. Stop Debezium. 4. Update the primary key definition in the relevant table. 5. Put the database or the application into read/write mode. 6. Restart Debezium. |
PostgreSQL 10+ logical decoding support (pgoutput)
As of PostgreSQL 10+, there is a logical replication stream mode, called pgoutput that is natively supported by PostgreSQL. This means that a Debezium PostgreSQL connector can consume that replication stream without the need for additional plug-ins. This is particularly valuable for environments where installation of plug-ins is not supported or not allowed.
See Setting up PostgreSQL for more details.
Topic names
By default, the PostgreSQL connector writes change events for all INSERT, UPDATE, and DELETE operations that occur in a table to a single Apache Kafka topic that is specific to that table. The connector uses the following convention to name change event topics:
serverName.schemaName.tableName
The following list provides definitions for the components of the default name:
serverName
The logical name of the connector, as specified by the database.server.name configuration property.
schemaName
The name of the database schema in which the change event occurred.
tableName
The name of the database table in which the change event occurred.
For example, suppose that fulfillment is the logical server name in the configuration for a connector that is capturing changes in a PostgreSQL installation that has a postgres database and an inventory schema that contains four tables: products, products_on_hand, customers, and orders. The connector would stream records to these four Kafka topics:
fulfillment.inventory.productsfulfillment.inventory.products_on_handfulfillment.inventory.customersfulfillment.inventory.orders
Now suppose that the tables are not part of a specific schema but were created in the default public PostgreSQL schema. The names of the Kafka topics would be:
fulfillment.public.productsfulfillment.public.products_on_handfulfillment.public.customersfulfillment.public.orders
The connector applies similar naming conventions to label its transaction metadata topics.
If the default topic name do not meet your requirements, you can configure custom topic names. To configure custom topic names, you specify regular expressions in the logical topic routing SMT. For more information about using the logical topic routing SMT to customize topic naming, see Topic routing.
Meta information
In addition to a database change event, each record produced by a PostgreSQL connector contains some metadata. Metadata includes where the event occurred on the server, the name of the source partition and the name of the Kafka topic and partition where the event should go, for example:
1. "sourcePartition": {
2. "server": "fulfillment"
3. },
4. "sourceOffset": {
5. "lsn": "24023128",
6. "txId": "555",
7. "ts_ms": "1482918357011"
8. },
9. "kafkaPartition": null
sourcePartitionalways defaults to the setting of thedatabase.server.nameconnector configuration property.-
sourceOffsetcontains information about the location of the server where the event occurred: -
lsnrepresents the PostgreSQL Log Sequence Number oroffsetin the transaction log. txIdrepresents the identifier of the server transaction that caused the event.ts_msrepresents the server time at which the transaction was committed in the form of the number of milliseconds since the epoch.kafkaPartitionwith a setting ofnullmeans that the connector does not use a specific Kafka partition. The PostgreSQL connector uses only one Kafka Connect partition and it places the generated events into one Kafka partition.
Transaction metadata
Debezium can generate events that represent transaction boundaries and that enrich data change event messages.
| Limits on when Debezium receives transaction metadata Debezium registers and receives metadata only for transactions that occur after you deploy the connector. Metadata for transactions that occur before you deploy the connector is not available. |
For every transaction BEGIN and END, Debezium generates an event that contains the following fields:
status-BEGINorENDid- string representation of unique transaction identifierevent_count(forENDevents) - total number of events emitted by the transactiondata_collections(forENDevents) - an array of pairs ofdata_collectionandevent_countthat provides the number of events emitted by changes originating from given data collection
Example
1. {
2. "status": "BEGIN",
3. "id": "571",
4. "event_count": null,
5. "data_collections": null
6. }
8. {
9. "status": "END",
10. "id": "571",
11. "event_count": 2,
12. "data_collections": [
13. {
14. "data_collection": "s1.a",
15. "event_count": 1
16. },
17. {
18. "data_collection": "s2.a",
19. "event_count": 1
20. }
21. ]
22. }
Unless overridden via the transaction.topic option, transaction events are written to the topic named *database.server.name*.transaction.
Change data event enrichment
When transaction metadata is enabled the data message Envelope is enriched with a new transaction field. This field provides information about every event in the form of a composite of fields:
id- string representation of unique transaction identifiertotal_order- absolute position of the event among all events generated by the transactiondata_collection_order- the per-data collection position of the event among all events that were emitted by the transaction
Following is an example of a message:
1. {
2. "before": null,
3. "after": {
4. "pk": "2",
5. "aa": "1"
6. },
7. "source": {
8. ...
9. },
10. "op": "c",
11. "ts_ms": "1580390884335",
12. "transaction": {
13. "id": "571",
14. "total_order": "1",
15. "data_collection_order": "1"
16. }
17. }
Data change events
The Debezium PostgreSQL connector generates a data change event for each row-level INSERT, UPDATE, and DELETE operation. Each event contains a key and a value. The structure of the key and the value depends on the table that was changed.
Debezium and Kafka Connect are designed around continuous streams of event messages. However, the structure of these events may change over time, which can be difficult for consumers to handle. To address this, each event contains the schema for its content or, if you are using a schema registry, a schema ID that a consumer can use to obtain the schema from the registry. This makes each event self-contained.
The following skeleton JSON shows the basic four parts of a change event. However, how you configure the Kafka Connect converter that you choose to use in your application determines the representation of these four parts in change events. A schema field is in a change event only when you configure the converter to produce it. Likewise, the event key and event payload are in a change event only if you configure a converter to produce it. If you use the JSON converter and you configure it to produce all four basic change event parts, change events have this structure:
1. {
2. "schema": { (1)
3. ...
4. },
5. "payload": { (2)
6. ...
7. },
8. "schema": { (3)
9. ...
10. },
11. "payload": { (4)
12. ...
13. },
14. }
Table 4. Overview of change event basic content
| Item | Field name | Description |
| --- | --- | --- |
| 1 | schema | The first schema field is part of the event key. It specifies a Kafka Connect schema that describes what is in the event key’s payload portion. In other words, the first schema field describes the structure of the primary key, or the unique key if the table does not have a primary key, for the table that was changed. It is possible to override the table’s primary key by setting the message.key.columns connector configuration property. In this case, the first schema field describes the structure of the key identified by that property. |
| 2 | payload | The first payload field is part of the event key. It has the structure described by the previous schema field and it contains the key for the row that was changed. |
| 3 | schema | The second schema field is part of the event value. It specifies the Kafka Connect schema that describes what is in the event value’s payload portion. In other words, the second schema describes the structure of the row that was changed. Typically, this schema contains nested schemas. |
| 4 | payload | The second payload field is part of the event value. It has the structure described by the previous schema field and it contains the actual data for the row that was changed. |
By default behavior is that the connector streams change event records to topics with names that are the same as the event’s originating table.
| Starting with Kafka 0.10, Kafka can optionally record the event key and value with the timestamp at which the message was created (recorded by the producer) or written to the log by Kafka. |
| The PostgreSQL connector ensures that all Kafka Connect schema names adhere to the Avro schema name format. This means that the logical server name must start with a Latin letter or an underscore, that is, a-z, A-Z, or *. Each remaining character in the logical server name and each character in the schema and table names must be a Latin letter, a digit, or an underscore, that is, a-z, A-Z, 0-9, or *. If there is an invalid character it is replaced with an underscore character. This can lead to unexpected conflicts if the logical server name, a schema name, or a table name contains invalid characters, and the only characters that distinguish names from one another are invalid and thus replaced with underscores. |
Change event keys
For a given table, the change event’s key has a structure that contains a field for each column in the primary key of the table at the time the event was created. Alternatively, if the table has REPLICA IDENTITY set to FULL or USING INDEX there is a field for each unique key constraint.
Consider a customers table defined in the public database schema and the example of a change event key for that table.
Example table
1. CREATE TABLE customers (
2. id SERIAL,
3. first_name VARCHAR(255) NOT NULL,
4. last_name VARCHAR(255) NOT NULL,
5. email VARCHAR(255) NOT NULL,
6. PRIMARY KEY(id)
7. );
Example change event key
If the database.server.name connector configuration property has the value PostgreSQL_server, every change event for the customers table while it has this definition has the same key structure, which in JSON looks like this:
1. {
2. "schema": { (1)
3. "type": "struct",
4. "name": "PostgreSQL_server.public.customers.Key", (2)
5. "optional": false, (3)
6. "fields": [ (4)
7. {
8. "name": "id",
9. "index": "0",
10. "schema": {
11. "type": "INT32",
12. "optional": "false"
13. }
14. }
15. ]
16. },
17. "payload": { (5)
18. "id": "1"
19. },
20. }
Table 5. Description of change event key
| Item | Field name | Description |
| --- | --- | --- |
| 1 | schema | The schema portion of the key specifies a Kafka Connect schema that describes what is in the key’s payload portion. |
| 2 | PostgreSQL_server.inventory.customers.Key | Name of the schema that defines the structure of the key’s payload. This schema describes the structure of the primary key for the table that was changed. Key schema names have the format connector-name.database-name.table-name.Key. In this example: - PostgreSQL_server is the name of the connector that generated this event. - inventory is the database that contains the table that was changed. - customers is the table that was updated. |
| 3 | optional | Indicates whether the event key must contain a value in its payload field. In this example, a value in the key’s payload is required. A value in the key’s payload field is optional when a table does not have a primary key. |
| 4 | fields | Specifies each field that is expected in the payload, including each field’s name, index, and schema. |
| 5 | payload | Contains the key for the row for which this change event was generated. In this example, the key, contains a single id field whose value is 1. |
Although the column.exclude.list and column.include.list connector configuration properties allow you to capture only a subset of table columns, all columns in a primary or unique key are always included in the event’s key. |
| If the table does not have a primary or unique key, then the change event’s key is null. The rows in a table without a primary or unique key constraint cannot be uniquely identified. |
Change event values
The value in a change event is a bit more complicated than the key. Like the key, the value has a schema section and a payload section. The schema section contains the schema that describes the Envelope structure of the payload section, including its nested fields. Change events for operations that create, update or delete data all have a value payload with an envelope structure.
Consider the same sample table that was used to show an example of a change event key:
1. CREATE TABLE customers (
2. id SERIAL,
3. first_name VARCHAR(255) NOT NULL,
4. last_name VARCHAR(255) NOT NULL,
5. email VARCHAR(255) NOT NULL,
6. PRIMARY KEY(id)
7. );
The value portion of a change event for a change to this table varies according to the REPLICA IDENTITY setting and the operation that the event is for.
Replica identity
[REPLICA IDENTITY](https://ww
(本文超出站点单文档体积上限,已截断)
