Files
semprini-data-product-templ…/source_aligned_cdc_data_product/flink/job.sql
T
paulandClaude Opus 5 866bcfe238 Add the source-aligned CDC template, and key the canonical template's topics
The first template of the source-aligned family: one data product per source
system, capturing a database by CDC and turning what it emits into what a
canonical product accepts. It runs on the Integration Bus, not in a domain, and
is deployed with the `data-bus` CLI.

What it produces, and what its tests hold it to: raw topics in the source's own
shape; deterministic identity, so a re-snapshot upserts rather than duplicating;
validation against the canonical product's rules before publishing, with what
fails going to the product's own dead-letter topic with the reason; keying by the
canonical identifier; provenance in headers; and an archive in the bus object
store that can be replayed back onto the raw topic.

The worked example captures an ERP customer table and delivers into Canonical
Party in the digital-core domain: 12 smoke checks, 37 unit tests, including a
poison record that is quarantined while the next record still arrives.

The canonical template's topics now declare the key producers must set, which is
the other half of that contract.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 10:54:39 +12:00

247 lines
11 KiB
SQL

-- {{product_name}}: the transform.
--
-- Reads the raw topic the CDC connector writes, and produces the canonical records
-- {{target_product_name}} accepts on its inbound topic. Everything a source-aligned product
-- exists for is here:
--
-- identity the source's own key becomes the canonical identifier, deterministically, so
-- re-snapshotting the table produces the same identifier and upserts rather than
-- duplicates.
-- semantics the source's codes become the model's enums, its names become the model's
-- fields — one mapping, written once, in the view below.
-- validation every record is checked against the rules {{target_product_name}} enforces, before it
-- is published. What fails goes to this product's dead-letter topic with the
-- reason, and never reaches the canonical product's Flink job, which would stop
-- the whole domain's ingestion on it.
-- provenance where each record came from, in headers, so the payload stays canonical.
-- archive every raw record is also written to the bus object store, partitioned by the day
-- the source committed it, because a Kafka topic is kept for days and a source
-- system's records have to be reproducible for longer than that.
--
-- ${BUS_KAFKA}, ${TARGET_BOOTSTRAP} and ${DLQ} are substituted by `data-bus deploy` from the
-- manifest; no address or credential is committed here.
SET 'pipeline.name' = '{{slug}}';
SET 'execution.checkpointing.interval' = '10 s';
SET 'table.local-time-zone' = 'UTC';
-- ---------------------------------------------------------------------------------------
-- The source's truth, as the connector wrote it.
--
-- REPLACE the columns with the source object's own, in the types Debezium produces for them:
-- a DATE arrives as days since 1970-01-01 (INT), a TIMESTAMPTZ as an ISO-8601 STRING, a
-- NUMERIC as a STRING unless decimal.handling.mode says otherwise. The __ columns are what the
-- connector adds, and every template keeps them: they are the record's provenance.
-- ---------------------------------------------------------------------------------------
CREATE TABLE {{system}}_{{source_object}}_raw (
id INT,
cust_name STRING,
cust_type STRING,
status_code STRING,
birth_date INT, -- Debezium encodes DATE as days since 1970-01-01
trading_name STRING,
`updated` STRING,
__op STRING,
__lsn BIGINT,
__source_ts_ms BIGINT
) WITH (
'connector' = 'kafka',
'topic' = 'raw.{{system}}.{{source_schema}}.{{source_object}}',
'properties.bootstrap.servers' = '${BUS_KAFKA}',
'properties.group.id' = '{{slug}}-transform',
'scan.startup.mode' = 'earliest-offset',
'format' = 'json',
'json.ignore-parse-errors' = 'false'
);
-- ---------------------------------------------------------------------------------------
-- {{target_product_name}}'s inbound topic. It belongs to the {{target_domain}} domain: this
-- product only publishes to it, keyed by {{target_key}}, in the schema registered for it.
--
-- REPLACE the columns with the target's inbound JSON Schema, which the canonical product
-- registered in Apicurio. Send what the source knows and leave the rest out; the ODS fills in
-- what it owns. Keep the headers column: provenance travels in headers, not in the payload.
-- ---------------------------------------------------------------------------------------
CREATE TABLE party_inbound (
party_id STRING,
party_type STRING,
legal_name STRING,
also_known_as STRING,
party_status STRING,
headers MAP<STRING, BYTES> METADATA
) WITH (
'connector' = 'kafka',
'topic' = '{{target_domain}}.{{target_product}}.{{target_table}}.inbound',
'properties.bootstrap.servers' = '${TARGET_BOOTSTRAP}',
'format' = 'json',
'json.timestamp-format.standard' = 'ISO-8601',
'key.format' = 'raw',
'key.fields' = 'party_id',
'value.fields-include' = 'ALL'
);
-- ---------------------------------------------------------------------------------------
-- This product's dead-letter topic.
-- ---------------------------------------------------------------------------------------
CREATE TABLE erp_dlq (
source_system STRING,
source_object STRING,
source_key STRING,
stage STRING,
reason STRING,
record STRING,
rejected_at TIMESTAMP_LTZ(3)
) WITH (
'connector' = 'kafka',
'topic' = '${DLQ}',
'properties.bootstrap.servers' = '${BUS_KAFKA}',
'format' = 'json',
'json.timestamp-format.standard' = 'ISO-8601',
'key.format' = 'raw',
'key.fields' = 'source_key',
'value.fields-include' = 'ALL'
);
-- ---------------------------------------------------------------------------------------
-- The raw archive in the bus object store: the same records as the raw topic, kept beyond its
-- retention and partitioned by capture day so a replay can ask for a date range. Files are
-- rolled often here so an archived record appears within a minute, which is what the tests
-- need; a busy product would roll on size, or every few minutes, to keep files large.
-- ---------------------------------------------------------------------------------------
CREATE TABLE {{system}}_{{source_object}}_archive (
id INT,
cust_name STRING,
cust_type STRING,
status_code STRING,
birth_date INT,
trading_name STRING,
`updated` STRING,
__op STRING,
__lsn BIGINT,
__source_ts_ms BIGINT,
dt STRING
) PARTITIONED BY (dt) WITH (
'connector' = 'filesystem',
'path' = '${ARCHIVE_PATH}',
'format' = 'json',
'sink.rolling-policy.rollover-interval' = '30 s',
'sink.rolling-policy.check-interval' = '10 s',
'sink.partition-commit.policy.kind' = 'success-file'
);
-- ---------------------------------------------------------------------------------------
-- The mapping, in one place: every record is mapped and judged once, so what is published and
-- what is rejected cannot drift apart. reason IS NULL is the definition of acceptable.
--
-- REPLACE the mapping and the reason: they are what this product is. The rules to check are
-- the ones the canonical product's ODS enforces — its NOT NULLs, its CHECK constraints, its
-- enums — because a record it refuses fails its Flink job's JDBC sink, and that takes down
-- every job on that TaskManager.
--
-- The identifier is a version 3 UUID over the text
-- '{{system}}:{{source_schema}}.{{source_object}}:<source key>': the MD5 of that name, with the
-- RFC 4122 version nibble set to 3 and the variant nibble to 'a'. Deterministic, so a
-- re-snapshot upserts the same record; derived from the source key, so no crosswalk table has
-- to be kept in step. semprini_data_bus.testing.deterministic_id computes the same value, and
-- the tests assert against it. Keep this expression as it stands unless the canonical
-- identifier already exists somewhere else, and say so in the product's README if you change it.
-- ---------------------------------------------------------------------------------------
CREATE TEMPORARY VIEW {{system}}_{{source_object}}_mapped AS
SELECT
id,
CONCAT(
SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 1, 8), '-',
SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 9, 4), '-',
'3', SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 14, 3), '-',
'a', SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 18, 3), '-',
SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 21, 12)
) AS party_id,
CASE cust_type WHEN 'I' THEN 'Person' WHEN 'O' THEN 'Company' END AS party_type,
TRIM(cust_name) AS legal_name,
trading_name AS also_known_as,
CASE status_code
WHEN 'A' THEN 'Active'
WHEN 'P' THEN 'Prospect'
WHEN 'S' THEN 'Suspended'
WHEN 'I' THEN 'Inactive'
WHEN 'C' THEN 'Closed'
END AS party_status,
-- Why this record cannot be published, or NULL if it can. The order is the order a person
-- would read it in: what happened to the record, then the fields, left to right.
CASE
WHEN __op = 'd' THEN
'delete: {{target_product_name}}''s inbound contract has no delete; remove the party through its own interface'
WHEN cust_name IS NULL OR CHAR_LENGTH(TRIM(cust_name)) = 0 THEN
'legal_name: cust_name is empty, and every Party must have a legal name'
WHEN cust_type IS NULL OR cust_type NOT IN ('I', 'O') THEN
'party_type: cust_type ' || COALESCE('''' || cust_type || '''', 'NULL')
|| ' is neither I (Person) nor O (Company)'
WHEN status_code IS NOT NULL AND status_code NOT IN ('A', 'P', 'S', 'I', 'C') THEN
'party_status: status_code ''' || status_code || ''' is not one of A, P, S, I, C'
END AS reason,
-- The original, so a rejected record can be corrected at the source and replayed.
JSON_OBJECT(
'id' VALUE id,
'cust_name' VALUE cust_name,
'cust_type' VALUE cust_type,
'status_code' VALUE status_code,
'birth_date' VALUE birth_date,
'trading_name' VALUE trading_name,
'updated' VALUE `updated`,
'__op' VALUE __op,
'__lsn' VALUE __lsn,
'__source_ts_ms' VALUE __source_ts_ms
) AS raw_record,
__lsn,
__source_ts_ms
FROM {{system}}_{{source_object}}_raw;
-- ---------------------------------------------------------------------------------------
-- One statement set, so both sinks run in one job and one checkpoint covers them.
-- A column captured but not published is normal: publish only what the target's inbound
-- contract accepts, and only to one table. A child record must not be published before its
-- parent exists, which Kafka cannot express across topics (see the template README, "What this
-- template does not do").
-- ---------------------------------------------------------------------------------------
EXECUTE STATEMENT SET
BEGIN
INSERT INTO party_inbound
SELECT
party_id,
party_type,
legal_name,
also_known_as,
party_status,
MAP[
'source_system', ENCODE('{{system}}', 'UTF-8'),
'source_object', ENCODE('{{source_schema}}.{{source_object}}', 'UTF-8'),
'source_key', ENCODE(CAST(id AS STRING), 'UTF-8'),
'source_lsn', ENCODE(COALESCE(CAST(__lsn AS STRING), ''), 'UTF-8'),
'capture_ts', ENCODE(COALESCE(CAST(__source_ts_ms AS STRING), ''), 'UTF-8'),
'produced_by', ENCODE('{{slug}}', 'UTF-8')
]
FROM {{system}}_{{source_object}}_mapped
WHERE reason IS NULL;
INSERT INTO {{system}}_{{source_object}}_archive
SELECT
id, cust_name, cust_type, status_code, birth_date, trading_name, `updated`,
__op, __lsn, __source_ts_ms,
DATE_FORMAT(TO_TIMESTAMP_LTZ(COALESCE(__source_ts_ms, 0), 3), 'yyyy-MM-dd')
FROM {{system}}_{{source_object}}_raw;
INSERT INTO erp_dlq
SELECT
'{{system}}',
'{{source_schema}}.{{source_object}}',
CAST(id AS STRING),
'transform',
reason,
raw_record,
CURRENT_TIMESTAMP
FROM {{system}}_{{source_object}}_mapped
WHERE reason IS NOT NULL;
END;