

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 了解 CDC 記錄
<a name="cdc-record-format"></a>

**重要**  
此功能以 AWS 預覽版形式提供，可能會有所變更。如需詳細資訊，請參閱 [AWS 服務條款](https://aws.amazon.com/service-terms/)中的第 2 節 Beta 版和預覽版。若要進一步了解 CDC 串流的定價，請參閱 [Aurora DSQL 定價頁面](https://aws.amazon.com/rds/aurora/dsql/pricing/)。  
在一般可用性之前，我們會將新的操作類型 (`"op": "u"` 用於更新） 新增至串流承載。為了確保您的應用程式在不修改的情況下處理這些變更，請套用`after`承載，將任何無法辨識`op`的值視為 upsert。如需詳細資訊，請參閱 [了解 CDC 記錄](#cdc-record-format)。

Aurora DSQL CDC 會以 JSON 記錄的形式交付每個變更。記錄使用具有操作類型的信封結構、資料列影像前後，以及來源中繼資料。

## 記錄如何映射至 Amazon Kinesis
<a name="cdc-kinesis-mapping"></a>

Aurora DSQL 會將每個 CDC 記錄寫入為單一 Kinesis 記錄。Kinesis 記錄`Data`的欄位包含 JSON 承載。Aurora DSQL 使用隨機 Kinesis 分割區索引鍵，將 CDC 記錄平均分散到碎片。若要讀取所有變更，請使用 Kinesis 資料串流上的所有碎片。如果記錄超過 Kinesis 記錄大小限制，Aurora DSQL 會將其分割為多個 Kinesis 記錄。如需詳細資訊，請參閱[處理過大的記錄](#cdc-oversized-records)。

**注意**  
Kinesis `Data` 記錄有一個 Blob。主要索引鍵值會出現在 JSON 承載的刪除`before`欄位中，或是插入和更新`after`欄位。若要擷取主索引鍵以進行下游處理，請從承載中的適當欄位讀取。

## 承載中的主索引鍵
<a name="cdc-primary-key-payload"></a>

對於具有主索引鍵的資料表，主索引鍵資料欄值會出現在承載中：
+ 對於**插入**和**更新**，承載包含主索引鍵資料欄以及 `after` 欄位中的所有其他資料欄。
+ 對於**刪除**，主索引鍵資料欄會出現在 `before` 欄位中。

例如，請考慮具有複合主索引鍵的資料表：

```
CREATE TABLE order_items (
    order_id INT,
    item_id INT,
    quantity INT,
    price NUMERIC,
    PRIMARY KEY (order_id, item_id)
);
```

此資料表上的刪除會產生承載，其中 `"before": {"order_id": 1001, "item_id": 42}`。

## 記錄承載
<a name="cdc-record-payload"></a>

承載使用下列 JSON 信封格式。

**INSERT 範例**  
下列範例顯示插入操作的 CDC 記錄：

```
{
    "type": "full",
    "op": "c",
    "before": null,
    "after": {"order_id": 1001, "item_id": 42, "quantity": 5, "price": "29.99"},
    "source": {
        "version": "1.0",
        "ts_ms": 1705318200000,
        "ts_ns": 1705318200000000000,
        "txId": "ffthunp5stx6ffs2vyfqoatmfu",
        "schema": "public",
        "table": "order_items",
        "db": "postgres",
        "cluster": "kmabugltfmjdaj2siqr2qbxgju"
    },
    "ts_ms": 1705318200125,
    "ts_ns": 1705318200125483291
}
```

**UPDATE 範例**  
下列範例顯示 Aurora DSQL 開始發出 之後， `UPDATE`陳述式產生的 CDC 記錄會是什麼樣子`op: "u"`：

**重要**  
目前，Aurora DSQL `op: "c"`會同時發出插入和更新。後續版本會發出`op: "u"`更新和`op: "c"`插入。設計您的應用程式來處理 `c`、 和 `u`，`d`讓您的消費者在整個轉換過程中繼續工作。

```
{
    "type": "full",
    "op": "u",
    "before": null,
    "after": {"order_id": 1001, "item_id": 42, "quantity": 10, "price": "29.99"},
    "source": {
        "version": "1.0",
        "ts_ms": 1705318300000,
        "ts_ns": 1705318300000000000,
        "txId": "qvtiesgmd55cvlfukm3dfuotji",
        "schema": "public",
        "table": "order_items",
        "db": "postgres",
        "cluster": "kmabugltfmjdaj2siqr2qbxgju"
    },
    "ts_ms": 1705318300125,
    "ts_ns": 1705318300125483291
}
```

**DELETE 範例**  
對於具有主索引鍵的資料表上的刪除， `before` 欄位包含已刪除資料列的主索引鍵值：

```
{
    "type": "full",
    "op": "d",
    "before": {"order_id": 1001, "item_id": 42},
    "after": null,
    "source": {
        "version": "1.0",
        "ts_ms": 1705318400000,
        "ts_ns": 1705318400000000000,
        "txId": "xyzabc123def456ghi789jklmno",
        "schema": "public",
        "table": "order_items",
        "db": "postgres",
        "cluster": "kmabugltfmjdaj2siqr2qbxgju"
    },
    "ts_ms": 1705318400125,
    "ts_ns": 1705318400125483291
}
```

## 承載欄位
<a name="cdc-payload-fields"></a>


| 欄位 | Description (描述) | 
| --- |--- |
| type | The record type. 完整 for a complete record that includes inline before and after values. 區塊 for a main record that references fragment records for one or both images. fragment for an individual piece of a chunked image. For details, see [處理過大的記錄](#cdc-oversized-records). | 
| 操作 | Operation type. c = create (insert), u = update, d = delete. Currently Aurora DSQL emits c for both inserts and updates. A subsequent release will emit u for updates, and c for inserts. Design your app to handle all three values. | 
| before | For deletes on tables with a primary key, contains the primary key values of the deleted row. Aurora DSQL sets this field to null for inserts, updates, and deletes on tables without a primary key. | 
| after | The full row state after the change, including all columns. Aurora DSQL sets this field to null for deletes. | 
| 區塊 | Present only when type is 區塊. Contains reassembly metadata for the before image, the after image, or both. Aurora DSQL omits the chunked image from the top-level before or after field and places it under 區塊 instead. For details, see [處理過大的記錄](#cdc-oversized-records). | 
| source.version | The CDC source metadata format version. The current version is 1.0. | 
| source.ts\_ms | The transaction commit timestamp in milliseconds since the Unix epoch, Coordinated Universal Time (UTC). | 
| source.ts\_ns | Transaction commit timestamp in nanoseconds, UTC. The highest precision timestamp available. Use this field to establish a total order of transactions. | 
| source.txId | A unique transaction identifier, encoded as base32. All records from the same transaction share the same txId value. Use this field to group records that belong to the same transaction. | 
| source.schema | The PostgreSQL schema name (for example, public). | 
| source.table | The table name. | 
| source.db | The database name. Always postgres for Aurora DSQL. | 
| source.cluster | The Aurora DSQL cluster identifier. | 
| ts\_ms | The time at which the CDC system processed the record, in milliseconds, UTC. The difference between ts\_ms and source.ts\_ms is a measure of replication lag. | 
| ts\_ns | The time at which the CDC system processed the record, in nanoseconds, UTC. | 

## 格式詳細資訊
<a name="cdc-format-behavior"></a>

下列詳細資訊說明 Aurora DSQL CDC 如何格式化記錄。設計您的應用程式來處理這些行為。
+ **插入和更新的完整後置影像。**Aurora DSQL 會在 `after` 欄位中包含所有寫入的完整資料列狀態。`before` 欄位`null`適用於插入和更新。目前，插入和更新都使用 `op: "c"`，但後續版本將發出`op: "u"`以進行更新。設計您的應用程式以`source.ts_ns`使用每個主索引鍵進行排序，而不是依賴 `op` 欄位來區分插入和更新。
+ **僅限變更後資料列狀態。**CDC 記錄包含每次變更後的完整資料列狀態。不包含更新前的資料列狀態。對於具有主索引鍵的資料表上的刪除， `before` 欄位包含主索引鍵值。
+ **序列化為字串的數值類型。**Aurora DSQL 會將 `numeric`和 `decimal`值序列化為 JSON 字串，以保留精確的精確度。
+ **編碼為 Base64 的二進位資料。**Aurora DSQL 會將`bytea`值編碼為 Base64 字串。
+ **特殊浮點和數值。**Aurora DSQL 會將 NaN 和 ±Infinity 序列化為字串 `"NaN"`、 `"Infinity"`和 `"-Infinity"`。這適用於 `real`、 `double precision`和 `numeric`類型。
+ **序列化為 JSON 字串的 JSON 資料欄。**Aurora DSQL 會將`json`資料欄值序列化為 JSON 字串，其中包含存放在資料欄中的原始 JSON 文字。剖析應用程式中的字串值 （例如，在 JavaScript `JSON.parse`或 Python `json.loads` 中使用 )，以存取基礎 JSON 值。
+ **發出為 null 的溢位值。**如果在序列化期間無法在目標 JSON 類型中表示值，Aurora DSQL `null`會為該資料欄發出 JSON。這適用於其總微秒超過 64 位元帶正負號整數範圍 (±9，223，372，036，854，775，807 微秒，大約為 ±292，271 年） `interval`的值。設計您的應用程式，以處理資料庫結構描述中不可為 null 的資料欄中的意外`null`值。
+ **將過大的記錄分割為區塊。**如果記錄超過 Amazon Kinesis 記錄大小限制，Aurora DSQL 會將受影響的 `before`或 `after` 映像分割為片段，並將其做為單獨的 Kinesis 記錄交付，如此您仍然會收到變更。設計您的應用程式以重新組合映像。如需詳細資訊，請參閱[處理過大的記錄](#cdc-oversized-records)。

## 處理過大的記錄
<a name="cdc-oversized-records"></a>

當 CDC 記錄的序列化 JSON 超過 9 MiB 時，Aurora DSQL 會分割 `before`和/或 `after` 映像，交付多個 Kinesis 記錄。每個記錄都包含指出其結構的最上層`type`欄位：`full`對於完整記錄，`chunked`對於參考片段的主要記錄，`fragment`對於區塊影像的個別部分。區塊主要記錄上的 `op`、`ts_ms`、 `source`和 `ts_ns` 欄位的行為與完整記錄上的相同。適用於單一 Kinesis 記錄的記錄已`type`設定為 `full`，且不需要任何額外的處理。

在重試期間， `chunk_id` 是穩定的。如果 Aurora DSQL 重新交付片段，它與原始交付的承載`chunk_id`相同，因此您的應用程式可以在相同的識別符下繼續緩衝，而無需處理先前嘗試的部分集合。

**主要記錄**  
區塊主要記錄會將分割影像的頂層`before`或`after`欄位取代為物件`chunked`，描述如何重新組合。下的每個項目`chunked`都有一個 `chunk_id`（連結片段至此記錄的識別符）、 `total_fragments` （構成該影像的片段數量） 和 `crc32c`（在重新組合影像文字上做為小數字串的 CRC32C 檢查總和）。如果一個影像內嵌，而另一個影像區塊化，內嵌影像仍會在最上層顯示為值或 `null`。

```
{
    "type": "chunked",
    "op": "c",
    "before": null,
    "after": null,
    "source": {
        "version": "1.0",
        "ts_ms": 1705318200000,
        "ts_ns": 1705318200000000000,
        "txId": "ffthunp5stx6ffs2vyfqoatmfu",
        "schema": "public",
        "table": "order_items",
        "db": "postgres",
        "cluster": "{{cluster-id}}"
    },
    "chunked": {
        "after": {
            "chunk_id": "{{chunk-id}}",
            "total_fragments": 3,
            "crc32c": "2073618257"
        }
    },
    "ts_ms": 1705318200125,
    "ts_ns": 1705318200125483291
}
```

**片段記錄**  
每個片段都是自己的 Kinesis 記錄，`type`其設定為 `fragment`和三個欄位： `chunk_id` 符合對應`chunked.before.chunk_id`或`chunked.after.chunk_id`主要記錄中的值、`index`影像中片段的零基位置，`data`以及影像在 UTF-8 字元邊界上分割的 JSON 文字區段 （每個片段`data`的值本身是有效的 UTF-8 字串）。由於 Aurora DSQL CDC 使用`UNORDERED`模式和隨機分割區索引鍵，片段和主要記錄可以按任何順序到達不同的碎片。若要讀取所有片段， 會使用 Kinesis 資料串流上的所有碎片。如需交付訂購的詳細資訊，請參閱 [排序](cdc-streams.md#cdc-ordering)。

```
{
    "type": "fragment",
    "chunk_id": "{{chunk-id}}",
    "index": 0,
    "data": "{{partial-JSON-text}}"
}
```

若要重新組合大型影像，請使用 `type``fragment`緩衝每個記錄`chunk_id`。當您收到具有 `type` 的主要記錄時`chunked`，請等到您在 `chunked.before`或 下`chunk_id`參考的每個`total_fragments`片段都有片段`chunked.after`，然後依`index`遞增排序片段，然後串連`data`字串。串連的結果是原始`before`或`after`物件做為 JSON 文字 - 剖析它以存取資料欄值。若要驗證交付完整性，請透過串連字串運算 CRC32C，並將結果與 `chunked.before.crc32c`或 進行比較`chunked.after.crc32c`。

## 資料類型序列化
<a name="cdc-data-types"></a>

下表說明 Aurora DSQL 如何序列化 CDC 記錄中的每個 PostgreSQL 資料類型。

### 整數類型
<a name="cdc-integer-types"></a>


| PostgreSQL 類型 | JSON 表示法 | 範例 | 
| --- |--- |--- |
| smallint (int2) | JSON number | 42 | 
| integer (int4) | JSON number | 1001 | 
| bigint (int8) | JSON number | 9223372036854775807 | 
| oid | JSON number (unsigned) | 16384 | 

在 JavaScript 環境中，`bigint`超過 ±2^53 的值可能會失去精確度。在這些情況下使用 BigInt 或任意精確度程式庫。

### 浮點類型
<a name="cdc-float-types"></a>


| PostgreSQL 類型 | JSON 表示法 | 範例 | 備註 | 
| --- |--- |--- |--- |
| real (float4) | JSON number | 3.14159 | NaN and ±Infinity are serialized as the strings 「NaN」, 「無限」, "-Infinity". | 
| double precision (float8) | JSON number | 3.141592653589793 | Same special value handling as real. | 
| numeric / decimal | JSON string | 「123.45」 | Always a string to preserve exact precision. NaN and ±Infinity are serialized as the strings 「NaN」, 「無限」, "-Infinity". | 

### Boolean
<a name="cdc-boolean-type"></a>


| PostgreSQL 類型 | JSON 表示法 | 範例 | 
| --- |--- |--- |
| boolean | JSON boolean | true or false | 

### 字元類型
<a name="cdc-character-types"></a>


| PostgreSQL 類型 | JSON 表示法 | 範例 | 
| --- |--- |--- |
| varchar / text | JSON string | 「您好，世界！」 | 
| bpchar (char(n)) | JSON string | 「ABC」 (trailing spaces stripped) | 
| name | JSON string | "pg\_class" | 
| "char" (single-byte) | JSON string | 「A」 | 

### 二進位
<a name="cdc-binary-type"></a>


| PostgreSQL 類型 | JSON 表示法 | 範例 | 
| --- |--- |--- |
| bytea | JSON string (Base64) | 「SGVsbG8gV29ybGQh」 | 

### 資料和時間類型
<a name="cdc-datetime-types"></a>


| PostgreSQL 類型 | JSON 表示法 | 範例 | 備註 | 
| --- |--- |--- |--- |
| date | JSON number (days since Unix epoch) | 19797 | \+無限 and -無限 are represented as sentinel day counts derived from epoch-offset arithmetic. These values don't correspond to meaningful calendar dates. | 
| time | JSON number (microseconds since midnight) | 52200123456 |  | 
| timetz | JSON number (microseconds since midnight, UTC) | 52200123456 | The local time is adjusted to UTC by applying the stored timezone offset (seconds west of UTC). The result is wrapped to the range [0, 86400000000) microseconds. | 
| timestamp | JSON number (microseconds since Unix epoch) | 1710510600123456 | ±Infinity maps to sentinel values: 9223372036825200000 for \+無限 and -9223372036832400000 for -無限. | 
| timestamptz | JSON number (microseconds since Unix epoch) | 1710510600123456 | Stored and emitted in UTC. Same ±infinity sentinel values as timestamp. | 
| 間隔 | JSON number (approximate total microseconds) | 2802603000000 | Months are approximated as 30.4375 days (2,629,800 seconds). The total is computed as （月 × 2，629，800 \+ 天 × 86，400) × 1，000，000 \+ 微秒. If the result exceeds the 64-bit signed integer range (±9,223,372,036,854,775,807 microseconds, approximately ±292,271 years), Aurora DSQL emits JSON null for the column. | 

### 其他類型
<a name="cdc-other-types"></a>


| PostgreSQL 類型 | JSON 表示法 | 範例 | 
| --- |--- |--- |
| uuid | JSON string (standard 8-4-4-4-12 hex format) | 「550e8400-e29b-41d4-a716-446655440000」 | 
| 類別向量 | JSON empty array | [] | 
| json | JSON string containing the raw JSON text | "{\\"key\\"：\\"value\\"}" | 

### NULL 值
<a name="cdc-null-values"></a>

對於任何資料類型，`NULL`資料欄值會以 JSON 表示`null`。

## CDC 記錄中的結構描述演變
<a name="cdc-schema-evolution"></a>

當您修改資料表的結構描述時，例如新增、捨棄或重新命名資料欄，CDC 記錄會反映從遞交 DDL 變更的交易開始的變更。在 DDL 變更之前遞交的交易記錄會使用先前的結構描述。例如：
+ 如果您新增資料欄，則先前交易的記錄不會包含新的資料欄。新增交易之後的記錄包含新資料欄。
+ 如果您捨棄資料欄，則捨棄交易中的記錄不會再包含該資料欄。
+ 如果您重新命名資料欄，重新命名交易之後的記錄會使用新的資料欄名稱。

透過檢查每個記錄的 `after`和 `before`欄位中存在的資料欄名稱，追蹤下游消費者的結構描述變更。每個記錄中`source.version`的欄位可識別 CDC 信封格式。