Debezium connector for SQL Server

Overview

The Debezium SQL Server connector is based on the change data capture feature that is available in SQL Server 2016 Service Pack 1 (SP1) and later Standard edition or Enterprise edition. The SQL Server capture process monitors designated databases and tables, and stores the changes into specifically created change tables that have stored procedure facades.

To enable the Debezium SQL Server connector to capture change event records for database operations, you must first enable change data capture on the SQL Server database. CDC must be enabled on both the database and on each table that you want to capture. After you set up CDC on the source database, the connector can capture row-level INSERT, UPDATE, and DELETE operations that occur in the database. The connector writes event records for each source table to a Kafka topic especially dedicated to that table. One topic exists for each captured table. Client applications read the Kafka topics for the database tables that they follow, and can respond to the row-level events they consume from those topics.

The first time that the connector connects to a SQL Server database or cluster, it takes a consistent snapshot of the schemas for all tables for which it is configured to capture changes, and streams this state to Kafka. After the snapshot is complete, the connector continuously captures subsequent row-level changes that occur. By first establishing a consistent view of all of the data, the connector can continue reading without having lost any of the changes that were made while the snapshot was taking place.

The Debezium SQL Server connector is tolerant of failures. As the connector reads changes and produces events, it periodically records the position of events in the database log (LSN / Log Sequence Number). If the connector stops for any reason (including communication failures, network problems, or crashes), after a restart the connector resumes reading the SQL Server CDC tables from the last point that it read.

Offsets are committed periodically. They are not committed at the time that a change event occurs. As a result, following an outage, duplicate events might be generated.

Fault tolerance also applies to snapshots. That is, if the connector stops during a snapshot, the connector begins a new snapshot when it restarts.

How the SQL Server connector works

To optimally configure and run a Debezium SQL Server connector, it is helpful to understand how the connector performs snapshots, streams change events, determines Kafka topic names, and uses metadata.

Snapshots

SQL Server CDC is not designed to store a complete history of database changes. For the Debezium SQL Server connector to establish a baseline for the current state of the database, it uses a process called snapshotting.

You can configure how the connector creates snapshots. By default, the connector’s snapshot mode is set to initial. Based on this initial snapshot mode, the first time that the connector starts, it performs an initial consistent snapshot of the database. This initial snapshot captures the structure and data for any tables that match the criteria defined by the include and exclude properties that are configured for the connector (for example, table.include.list, column.include.list, table.exclude.list, and so forth).

When the connector creates a snapshot, it completes the following tasks:

  1. Determines the tables to be captured.
  2. Obtains a lock on the SQL Server tables for which CDC is enabled to prevent structural changes from occurring during creation of the snapshot. The level of the lock is determined by snapshot.isolation.mode configuration option.
  3. Reads the maximum log sequence number (LSN) position in the server’s transaction log.
  4. Captures the structure of all relevant tables.
  5. Releases the locks obtained in Step 2, if necessary. In most cases, locks are held for only a short period of time.
  6. Scans the SQL Server source tables and schemas to be captured based on the LSN position that was read in Step 3, generates a READ event for each row in the table, and writes the events to the Kafka topic for the table.
  7. Records the successful completion of the snapshot in the connector offsets.

The resulting initial snapshot captures the current state of each row in the tables that are enabled for CDC. From this baseline state, the connector captures subsequent changes as they occur.

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 1. 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

  • Signaling is enabled.

  • 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

  1. 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 2. 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 SQL Server does not support schema changes while an incremental snapshot is running.

Reading the change data tables

When the connector first starts, it takes a structural snapshot of the structure of the captured tables and persists this information to its internal database history topic. The connector then identifies a change table for each source table, and completes the following steps.

  1. For each change table, the connector read all of the changes that were created between the last stored maximum LSN and the current maximum LSN.
  2. The connector sorts the changes that it reads in ascending order, based on the values of their commit LSN and change LSN. This sorting order ensures that the changes are replayed by Debezium in the same order in which they occurred in the database.
  3. The connector passes the commit and change LSNs as offsets to Kafka Connect.
  4. The connector stores the maximum LSN and restarts the process from Step 1.

After a restart, the connector resumes processing from the last offset (commit and change LSNs) that it read.

The connector is able to detect whether CDC is enabled or disabled for included source tables and adjust its behavior.

Limitations

SQL Server specifically requires the base object to be a table in order to create a change capture instance. As consequence, capturing changes from indexed views (aka. materialized views) is not supported by SQL Server and hence Debezium SQL Server connector.

Topic names

By default, the SQL Server connector writes 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 server, 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, if fulfillment is the server name, and dbo is the schema name, and the database contains tables with the names products, products_on_hand, customers, and orders, the connector would stream change event records to the following Kafka topics:

  • fulfillment.dbo.products
  • fulfillment.dbo.products_on_hand
  • fulfillment.dbo.customers
  • fulfillment.dbo.orders

The connector applies similar naming conventions to label its internal database history topics, schema change topics, and 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.

Schema change topic

For each table for which CDC is enabled, the Debezium SQL Server connector stores a history of the schema change events that are applied to captured tables in the database. The connector writes schema change events to a Kafka topic named *<serverName>*, where *serverName* is the logical server name that is specified in the database.server.name configuration property.

Messages that the connector sends to the schema change topic contain a payload, and, optionally, also contain the schema of the change event message. The payload of a schema change event message includes the following elements:

databaseName

The name of the database to which the statements are applied. The value of databaseName serves as the message key.

tableChanges

A structured representation of the entire table schema after the schema change. The tableChanges field contains an array that includes entries for each column of the table. Because the structured representation presents data in JSON or Avro format, consumers can easily read messages without first processing them through a DDL parser.

When the connector is configured to capture a table, it stores the history of the table’s schema changes not only in the schema change topic, but also in an internal database history topic. The internal database history topic is for connector use only and it is not intended for direct use by consuming applications. Ensure that applications that require notifications about schema changes consume that information only from the schema change topic.
The format of the messages that a connector emits to its schema change topic is in an incubating state and can change without notice.

Debezium emits a message to the schema change topic when the following events occur:

  • You enable CDC for a table.
  • You disable CDC for a table.
  • You alter the structure of a table for which CDC is enabled by following the schema evolution procedure.

Example: Message emitted to the SQL Server connector schema change topic

The following example shows a message in the schema change topic. The message contains a logical representation of the table schema.

1. {
2. "schema": {
3. ...
4. },
5. "payload": {
6. "source": {
7. "version": "1.9.6.Final",
8. "connector": "sqlserver",
9. "name": "server1",
10. "ts_ms": 1588252618953,
11. "snapshot": "true",
12. "db": "testDB",
13. "schema": "dbo",
14. "table": "customers",
15. "change_lsn": null,
16. "commit_lsn": "00000025:00000d98:00a2",
17. "event_serial_no": null
18. },
19. "databaseName": "testDB", (1)
20. "schemaName": "dbo",
21. "ddl": null, (2)
22. "tableChanges": [ (3)
23. {
24. "type": "CREATE", (4)
25. "id": "\"testDB\".\"dbo\".\"customers\"", (5)
26. "table": { (6)
27. "defaultCharsetName": null,
28. "primaryKeyColumnNames": [ (7)
29. "id"
30. ],
31. "columns": [ (8)
32. {
33. "name": "id",
34. "jdbcType": 4,
35. "nativeType": null,
36. "typeName": "int identity",
37. "typeExpression": "int identity",
38. "charsetName": null,
39. "length": 10,
40. "scale": 0,
41. "position": 1,
42. "optional": false,
43. "autoIncremented": false,
44. "generated": false
45. },
46. {
47. "name": "first_name",
48. "jdbcType": 12,
49. "nativeType": null,
50. "typeName": "varchar",
51. "typeExpression": "varchar",
52. "charsetName": null,
53. "length": 255,
54. "scale": null,
55. "position": 2,
56. "optional": false,
57. "autoIncremented": false,
58. "generated": false
59. },
60. {
61. "name": "last_name",
62. "jdbcType": 12,
63. "nativeType": null,
64. "typeName": "varchar",
65. "typeExpression": "varchar",
66. "charsetName": null,
67. "length": 255,
68. "scale": null,
69. "position": 3,
70. "optional": false,
71. "autoIncremented": false,
72. "generated": false
73. },
74. {
75. "name": "email",
76. "jdbcType": 12,
77. "nativeType": null,
78. "typeName": "varchar",
79. "typeExpression": "varchar",
80. "charsetName": null,
81. "length": 255,
82. "scale": null,
83. "position": 4,
84. "optional": false,
85. "autoIncremented": false,
86. "generated": false
87. }
88. ]
89. }
90. }
91. ]
92. }
93. }

Table 3. Descriptions of fields in messages emitted to the schema change topic

| Item | Field name | Description |

| --- | --- | --- | | 1 | databaseName schemaName | Identifies the database and the schema that contain the change. | | 2 | ddl | Always null for the SQL Server connector. For other connectors, this field contains the DDL responsible for the schema change. This DDL is not available to SQL Server connectors. | | 3 | tableChanges | An array of one or more items that contain the schema changes generated by a DDL command. | | 4 | type | Describes the kind of change. The value is one of the following: - CREATE - table created - ALTER - table modified - DROP - table deleted | | 5 | id | Full identifier of the table that was created, altered, or dropped. | | 6 | table | Represents table metadata after the applied change. | | 7 | primaryKeyColumnNames | List of columns that compose the table’s primary key. | | 8 | columns | Metadata for each column in the changed table. |

In messages that the connector sends to the schema change topic, the key is the name of the database that contains the schema change. In the following example, the payload field contains the key:

1. {
2. "schema": {
3. "type": "struct",
4. "fields": [
5. {
6. "type": "string",
7. "optional": false,
8. "field": "databaseName"
9. }
10. ],
11. "optional": false,
12. "name": "io.debezium.connector.sqlserver.SchemaChangeKey"
13. },
14. "payload": {
15. "databaseName": "testDB"
16. }
17. }

Data change events

The Debezium SQL Server 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, the connector streams change event records to topics with names that are the same as the event’s originating table. See topic names.

The SQL Server 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 database 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 database 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

A change event’s key contains the schema for the changed table’s key and the changed row’s actual key. Both the schema and its corresponding payload contain a field for each column in the changed table’s primary key (or unique key constraint) at the time the connector created the event.

Consider the following customers table, which is followed by an example of a change event key for this table.

Example table

1. CREATE TABLE customers (
2. id INTEGER IDENTITY(1001,1) NOT NULL PRIMARY KEY,
3. first_name VARCHAR(255) NOT NULL,
4. last_name VARCHAR(255) NOT NULL,
5. email VARCHAR(255) NOT NULL UNIQUE
6. );

Example change event key

Every change event that captures a change to the customers table has the same event key schema. For as long as the customers table has the previous definition, every change event that captures a change to the customers table has the following key structure, which in JSON, looks like this:

1. {
2. "schema": { (1)
3. "type": "struct",
4. "fields": [ (2)
5. {
6. "type": "int32",
7. "optional": false,
8. "field": "id"
9. }
10. ],
11. "optional": false, (3)
12. "name": "server1.dbo.customers.Key" (4)
13. },
14. "payload": { (5)
15. "id": 1004
16. }
17. }

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 | fields | Specifies each field that is expected in the payload, including each field’s name, type, and whether it is required. In this example, there is one required field named id of type int32. | | 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 | server1.dbo.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-schema-name.table-name.Key. In this example: - server1 is the name of the connector that generated this event. - dbo is the database schema for the table that was changed. - customers is the table that was updated. | | 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 1004. |

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. This makes sense since 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 INTEGER IDENTITY(1001,1) NOT NULL PRIMARY KEY,
3. first_name VARCHAR(255) NOT NULL,
4. last_name VARCHAR(255) NOT NULL,
5. email VARCHAR(255) NOT NULL UNIQUE
6. );

The value portion of a change event for a change to this table is described for each event type.

create events

The following example shows the value portion of a change event that the connector generates for an operation that creates data in the customers table:

1. {
2. "schema": { (1)
3. "type": "struct",
4. "fields": [
5. {
6. "type": "struct",
7. "fields": [
8. {
9. "type": "int32",
10. "optional": false,
11. "field": "id"
12. },
13. {
14. "type": "string",
15. "optional": false,
16. "field": "first_name"
17. },
18. {
19. "type": "string",
20. "optional": false,
21. "field": "last_name"
22. },
23. {
24. "type": "string",
25. "optional": false,
26. "field": "email"
27. }
28. ],
29. "optional": true,
30. "name": "server1.dbo.customers.Value", (2)
31. "field": "before"
32. },
33. {
34. "type": "struct",
35. "fields": [
36. {
37. "type": "int32",
38. "optional": false,
39. "field": "id"
40. },
41. {
42. "type": "string",
43. "optional": false,
44. "field": "first_name"
45. },
46. {
47. "type": "string",
48. "optional": false,
49. "field": "last_name"
50. },
51. {
52. "type": "string",
53. "optional": false,
54. "field": "email"
55. }
56. ],
57. "optional": true,
58. "name": "server1.dbo.customers.Value",
59. "field": "after"
60. },
61. {
62. "type": "struct",
63. "fields": [
64. {
65. "type": "string",
66. "optional": false,
67. "field": "version"
68. },
69. {
70. "type": "string",
71. "optional": false,
72. "field": "connector"
73. },
74. {
75. "type": "string",
76. "optional": false,
77. "field": "name"
78. },
79. {
80. "type": "int64",
81. "optional": false,
82. "field": "ts_ms"
83. },
84. {
85. "type": "boolean",
86. "optional": true,
87. "default": false,
88. "field": "snapshot"
89. },
90. {
91. "type": "string",
92. "optional": false,
93. "field": "db"
94. },
95. {
96. "type": "string",
97. "optional": false,
98. "field": "schema"
99. },
100. {
101. "type": "string",
102. "optional": false,
103. "field": "table"
104. },
105. {
106. "type": "string",
107. "optional": true,
108. "field": "change_lsn"
109. },
110. {
111. "type": "string",
112. "optional": true,
113. "field": "commit_lsn"
114. },
115. {
116. "type": "int64",
117. "optional": true,
118. "field": "event_serial_no"
119. }
120. ],
121. "optional": false,
122. "name": "io.debezium.connector.sqlserver.Source", (3)
123. "field": "source"
124. },
125. {
126. "type": "string",
127. "optional": false,
128. "field": "op"
129. },
130. {
131. "type": "int64",
132. "optional": true,
133. "field": "ts_ms"
134. }
135. ],
136. "optional": false,
137. "name": "server1.dbo.customers.Envelope" (4)
138. },
139. "payload": { (5)
140. "before": null, (6)
141. "after": { (7)
142. "id": 1005,
143. "first_name": "john",
144. "last_name": "doe",
145. "email": "john.doe@example.org"
146. },
147. "source": { (8)
148. "version": "1.9.6.Final",
149. "connector": "sqlserver",
150. "name": "server1",
151. "ts_ms": 1559729468470,
152. "snapshot": false,
153. "db": "testDB",
154. "schema": "dbo",
155. "table": "customers",
156. "change_lsn": "00000027:00000758:0003",
157. "commit_lsn": "00000027:00000758:0005",
158. "event_serial_no": "1"
159. },
160. "op": "c", (9)
161. "ts_ms": 1559729471739 (10)
162. }
163. }

Table 6. Descriptions of create event value fields

| Item | Field name | Description |

| --- | --- | --- | | 1 | schema | The value’s schema, which describes the structure of the value’s payload. A change event’s value schema is the same in every change event that the connector generates for a particular table. | | 2 | name | In the schema section, each name field specifies the schema for a field in the value’s payload. server1.dbo.customers.Value is the schema for the payload’s before and after fields. This schema is specific to the customers table. Names of schemas for before and after fields are of the form logicalName.database-schemaName.tableName.Value, which ensures that the schema name is unique in the database. This means that when using the Avro converter, the resulting Avro schema for each table in each logical source has its own evolution and history. | | 3 | name | io.debezium.connector.sqlserver.Source is the schema for the payload’s source field. This schema is specific to the SQL Server connector. The connector uses it for all events that it generates. | | 4 | name | server1.dbo.customers.Envelope is the schema for the overall structure of the payload, where server1 is the connector name, dbo is the database schema name, and customers is the table. | | 5 | payload | The value’s actual data. This is the information that the change event is providing. It may appear that the JSON representations of the events are much larger than the rows they describe. This is because the JSON representation must include the schema and the payload portions of the message. However, by using the Avro converter, you can significantly decrease the size of the messages that the connector streams to Kafka topics. | | 6 | before | An optional field that specifies the state of the row before the event occurred. When the op field is c for create, as it is in this example, the before field is null since this change event is for new content. | | 7 | after | An optional field that specifies the state of the row after the event occurred. In this example, the after field contains the values of the new row’s id, first_name, last_name, and email columns. | | 8 | source | Mandatory field that describes the source metadata for the event. This field contains information that you can use to compare this event with other events, with regard to the origin of the events, the order in which the events occurred, and whether events were part of the same transaction. The source metadata includes: - Debezium version - Connector type and name - Database and schema names - Timestamp for when the change was made in the database - If the event was part of a snapshot - Name of the table that contains the new row - Server log offsets | | 9 | op | Mandatory string that describes the type of operation that caused the connector to generate the event. In this example, c indicates that the operation created a row. Valid values are: - c = create - u = update - d = delete - r = read (applies to only snapshots) | | 10 | ts_ms | Optional field that displays the time at which the connector processed the event. In the event message envelope, the time is based on the system clock in the JVM running the Kafka Connect task. In the source object, ts_ms indicates the time when a change was committed in the database. By comparing the value for payload.source.ts_ms with the value for payload.ts_ms, you can determine the lag between the source database update and Debezium. |

update events

The value of a change event for an update in the sample customers table has the same schema as a create event for that table. Likewise, the event value’s payload has the same structure. However, the event value payload contains different values in an update event. Here is an example of a change event value in an event that the connector generates for an update in the customers table:

1. {
2. "schema": { ... },
3. "payload": {
4. "before": { (1)
5. "id": 1005,
6. "first_name": "john",
7. "last_name": "doe",
8. "email": "john.doe@example.org"
9. },
10. "after": { (2)
11. "id": 1005,
12. "first_name": "john",
13. "last_name": "doe",
14. "email": "noreply@example.org"
15. },
16. "source": { (3)
17. "version": "1.9.6.Final",
18. "connector": "sqlserver",
19. "name": "server1",
20. "ts_ms": 1559729995937,
21. "snapshot": false,
22. "db": "testDB",
23. "schema": "dbo",
24. "table": "customers",
25. "change_lsn": "00000027:00000ac0:0002",
26. "commit_lsn": "00000027:00000ac0:0007",
27. "event_serial_no": "2"
28. },
29. "op": "u", (4)
30. "ts_ms": 1559729998706  (5)
31. }
32. }

Table 7. Descriptions of update event value fields

| Item | Field name | Description |

| --- | --- | --- | | 1 | before | An optional field that specifies the state of the row before the event occurred. In an update event value, the before field contains a field for each table column and the value that was in that column before the database commit. In this example, the email value is john.doe@example.org. | | 2 | after | An optional field that specifies the state of the row after the event occurred. You can compare the before and after structures to determine what the update to this row was. In the example, the email value is now noreply@example.org. | | 3 | source | Mandatory field that describes the source metadata for the event. The source field structure has the same fields as in a create event, but some values are different, for example, the sample update event has a different offset. The source metadata includes: - Debezium version - Connector type and name - Database and schema names - Timestamp for when the change was made in the database - If the event was part of a snapshot - Name of the table that contains the new row - Server log offsets The event_serial_no field differentiates events that have the same commit and change LSN. Typical situations for when this field has a value other than 1: - update events have the value set to 2 because the update generates two events in the CDC change table of SQL Server ([see the source documentation for details](https://docs.microsoft.

(本文超出站点单文档体积上限,已截断)