Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(warehouse-sources): remove the old key when a cdc update changes it (#108577)

Daniel RC038868b13d60
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
index 3642075743bc..c31d49c98f21 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/activities.py
@@ -194,6 +194,8 @@ class CDCExtractActivity:
self.cdc_schemas: list[ExternalDataSchema] = []
self.schema_by_name: dict[str, ExternalDataSchema] = {}
self.pk_columns_by_table: dict[str, list[str]] = {}
+ # Merge keys that no two source rows can share, the only ones `_split_key_change` splits on.
+ self.split_key_columns: dict[str, list[str]] = {}
# Missing entry = sync all columns; otherwise the set is the projection (always includes PKs).
self.enabled_columns_by_table: dict[str, set[str]] = {}
self.adapter: typing.Any = None
@@ -591,6 +593,20 @@ class CDCExtractActivity:
self._update_schema_sync_type_config(schema, updates={"primary_key_columns": queried_pks[schema.name]})
self.log.info("pk_columns_loaded", tables=list(self.pk_columns_by_table.keys()))
+ enforced_keys = self._query_enforced_unique_keys(list(cdc_table_names))
+ self.split_key_columns = {
+ table: key_columns
+ for table, key_columns in self.pk_columns_by_table.items()
+ if any(unique_columns <= set(key_columns) for unique_columns in enforced_keys.get(table, []))
+ }
+ self.log.info("cdc_key_change_split_tables", tables=sorted(self.split_key_columns))
+ self.reader.set_key_change_columns(
+ {
+ event_name: self.split_key_columns[schema_name]
+ for event_name, schema_name in self._build_event_name_map().items()
+ if schema_name in self.split_key_columns
+ }
+ )
for schema in self.cdc_schemas:
enabled = schema.enabled_columns
@@ -616,6 +632,24 @@ class CDCExtractActivity:
defaulting to the source's namespace matches how the tables are resolved when they are added
to the publication.
"""
+ resolved: dict[str, list[str]] = {}
+ for namespace, relations_by_name in self._catalog_names(table_names).items():
+ queried = self.reader.get_primary_key_columns(namespace, list(relations_by_name))
+ for relation, pk_columns in queried.items():
+ resolved[relations_by_name[relation]] = pk_columns
+ return resolved
+
+ def _query_enforced_unique_keys(self, table_names: list[str]) -> dict[str, list[frozenset[str]]]:
+ """Enforced unique column sets per schema name, see `get_enforced_unique_keys`."""
+ resolved: dict[str, list[frozenset[str]]] = {}
+ for namespace, relations_by_name in self._catalog_names(table_names).items():
+ queried = self.reader.get_enforced_unique_keys(namespace, list(relations_by_name))
+ for relation, unique_keys in queried.items():
+ resolved[relations_by_name[relation]] = unique_keys
+ return resolved
+
+ def _catalog_names(self, table_names: list[str]) -> dict[str, dict[str, str]]:
+ """Group schema names by source namespace, mapping each bare relation name back to its schema name."""
assert self.source is not None
default_namespace = (self.source.job_inputs or {}).get("schema", "public")
names_by_namespace: dict[str, dict[str, str]] = {}
@@ -624,13 +658,7 @@ class CDCExtractActivity:
if not dot:
namespace, relation = default_namespace, name
names_by_namespace.setdefault(namespace, {})[relation] = name
-
- resolved: dict[str, list[str]] = {}
- for namespace, relations_by_name in names_by_namespace.items():
- queried = self.reader.get_primary_key_columns(namespace, list(relations_by_name))
- for relation, pk_columns in queried.items():
- resolved[relations_by_name[relation]] = pk_columns
- return resolved
+ return names_by_namespace
def _project_event_columns(self, event: ChangeEvent) -> ChangeEvent:
retained = self.enabled_columns_by_table.get(event.table_name)
@@ -652,6 +680,32 @@ class CDCExtractActivity:
omitted_columns=filtered_omitted,
)
+ def _split_key_change(self, event: ChangeEvent) -> tuple[ChangeEvent, ...]:
+ """Turn an update that changes the merge key into a delete of the old key and an insert of the new one.
+
+ Merged on its new key alone, the update leaves the old key's row live in the consolidated
+ table and open in the history table. The delete carries only the old key, like a Postgres
+ delete under the default replica identity, so delete enrichment fills the rest of the row.
+ Only tables in `split_key_columns` split; `get_enforced_unique_keys` says why.
+ """
+ if event.previous_values is None:
+ return (event,)
+ # The batcher neither writes the previous values nor counts them toward its flush size.
+ current = dataclasses.replace(event, previous_values=None)
+ key_columns = self.split_key_columns.get(event.table_name, [])
+ if not any(column in event.previous_values for column in key_columns):
+ return (current,)
+ old_key = {column: event.previous_values.get(column, event.columns.get(column)) for column in key_columns}
+ removed = ChangeEvent(
+ operation="D",
+ table_name=event.table_name,
+ position_serialized=event.position_serialized,
+ timestamp=event.timestamp,
+ columns=old_key,
+ column_types=event.column_types,
+ )
+ return (removed, dataclasses.replace(current, operation="I"))
+
def _qualified_table_name(self, schema: ExternalDataSchema) -> str:
default_schema = (self.source.job_inputs or {}).get("schema") if self.source else None
return cdc_qualified_table_name(schema, default_schema)
@@ -731,8 +785,8 @@ class CDCExtractActivity:
if canonical_name != event.table_name:
event = dataclasses.replace(event, table_name=canonical_name)
- event = self._project_event_columns(event)
- self.batcher.add(event)
+ for change in self._split_key_change(event):
+ self.batcher.add(self._project_event_columns(change))
# A change in position_serialized proves the previous transaction fully
# yielded — all of its events are now buffered or flushed. Record its end LSN
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
index 97e4ea579f60..955a9c2d810e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_extract_activity.py
@@ -1,5 +1,5 @@
import uuid
-from collections.abc import Iterator
+from collections.abc import Iterable, Iterator, Mapping
from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
@@ -30,6 +30,7 @@ from products.warehouse_sources.backend.temporal.data_imports.cdc.activities imp
cleanup_orphan_slots_activity,
)
from products.warehouse_sources.backend.temporal.data_imports.cdc.batcher import (
+ CDC_OP_COLUMN,
CDC_SEQ_COLUMN,
CDC_SEQ_PROVENANCE,
ChangeEventBatcher,
@@ -53,6 +54,7 @@ def _make_event(
table: str = "users",
position: str = "0/100",
columns: dict | None = None,
+ previous_values: dict[str, object] | None = None,
) -> ChangeEvent:
return ChangeEvent(
operation=op,
@@ -60,6 +62,7 @@ def _make_event(
position_serialized=position,
timestamp=datetime(2025, 6, 15, 12, 0, 0, tzinfo=UTC),
columns=columns or {"id": 1, "name": "Alice"},
+ previous_values=previous_values,
)
@@ -1503,6 +1506,12 @@ class _ScriptedReader:
def get_decoder_key_columns(self, table):
return []
+ def get_enforced_unique_keys(self, schema: str, tables: list[str]) -> dict[str, list[frozenset[str]]]:
+ return {}
+
+ def set_key_change_columns(self, columns_by_table: Mapping[str, Iterable[str]]) -> None:
+ pass
+
def clear_truncated_tables(self):
self.truncated_tables = []
@@ -1778,6 +1787,54 @@ class TestBufferedIngressCapture:
capture.reader.confirm_position.assert_called_once_with("0/200")
assert schema.sync_type_config["cdc_last_log_position"] == "0/200"
+ @parameterized.expand(
+ [
+ ("key_changed", ["id"], [{"id"}], True, {"id": 1}, [("D", 1, None), ("I", 2, 7)]),
+ (
+ "one_column_of_a_composite_key_changed",
+ ["id", "tenant_id"],
+ [{"id"}],
+ True,
+ {"id": 1},
+ [("D", 1, 7), ("I", 2, 7)],
+ ),
+ ("other_column_changed", ["id"], [{"id"}], True, {"name": "Alice"}, [("U", 2, 7)]),
+ ("no_enforced_unique_index", ["id"], [], False, {"id": 1}, [("U", 2, 7)]),
+ ("unique_index_wider_than_the_merge_key", ["id"], [{"id", "tenant_id"}], False, {"id": 1}, [("U", 2, 7)]),
+ ]
+ )
+ def test_an_update_that_changes_the_key_removes_the_old_key(
+ self,
+ _name: str,
+ primary_key: list[str],
+ enforced_unique_keys: list[set[str]],
+ qualifies: bool,
+ previous_values: dict[str, object],
+ expected_rows: list[tuple[str, int, int | None]],
+ ) -> None:
+ source = _make_source()
+ schema = _make_schema("users", cdc_mode="streaming", source=source)
+ schema.sync_type_config["primary_key_columns"] = primary_key
+ update = _make_event(
+ op="U",
+ position="0/200",
+ columns={"id": 2, "tenant_id": 7, "name": "Bob"},
+ previous_values=previous_values,
+ )
+
+ with _capture_harness(source, [schema], [update]) as capture:
+ capture.reader.get_enforced_unique_keys.return_value = {
+ "users": [frozenset(columns) for columns in enforced_unique_keys]
+ }
+ capture.extract()
+
+ buffered = capture.buffer.write_batch.call_args.kwargs["table"]
+ rows = zip(*(buffered.column(name).to_pylist() for name in (CDC_OP_COLUMN, "id", "tenant_id")))
+ assert list(rows) == expected_rows
+ key_change_columns = capture.reader.set_key_change_columns.call_args.args[0]
+ assert key_change_columns.get("public.users") == (primary_key if qualifies else None)
+ assert set(buffered.column(CDC_SEQ_COLUMN).to_pylist()) == {0x200}
+
def test_wal_events_reach_the_schema_they_belong_to(self):
# WAL events are always schema-qualified, but a schema's `name` may be stored bare. An exact
# name match would drop every change for that schema, and the table would go stale despite a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
index ca40cc0e6ef5..f8f77b57d783 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/types.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import json
-from collections.abc import Iterator, Mapping
+from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal, Protocol, Self
@@ -108,6 +108,10 @@ class ChangeEvent:
# still hold their previous value — downstream must fill them from the last known
# row state instead of writing NULL.
omitted_columns: frozenset[str] = frozenset()
+ # Old values of the key columns an UPDATE changed, set only when the change stream sent the old
+ # value of every key column the reader was given (Postgres: the old key tuple, or the whole old
+ # row under REPLICA IDENTITY FULL). Capture uses them to remove the old key.
+ previous_values: Mapping[str, object] | None = None
class CDCStreamReader(Protocol):
@@ -128,6 +132,10 @@ class CDCStreamReader(Protocol):
def get_primary_key_columns(self, schema_name: str, table_names: list[str]) -> dict[str, list[str]]: ...
+ def get_enforced_unique_keys(self, schema_name: str, table_names: list[str]) -> dict[str, list[frozenset[str]]]: ...
+
+ def set_key_change_columns(self, columns_by_table: Mapping[str, Iterable[str]]) -> None: ...
+
def get_decoder_key_columns(self, table_name: str) -> list[str]: ...
@property
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
index 8e779bbb7119..99d3ac4c5ea8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/decoder.py
@@ -38,6 +38,8 @@ from typing import IO, Any
import pyarrow as pa
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.cdc.errors import CDCTransactionTooLargeError
from products.warehouse_sources.backend.temporal.data_imports.cdc.types import ChangeEvent
from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.cdc.position import PgLSN
@@ -151,17 +153,18 @@ class RelationColumn:
type_modifier: int
-_REPLICA_IDENTITY_FULL = 2
+_REPLICA_IDENTITY_FULL = ord("f")
-@dataclass
+@frozen
class Relation:
"""Cached relation (table) metadata from an R message."""
relation_id: int
schema_name: str
table_name: str
- replica_identity: int # 0=default, 1=nothing, 2=full, 3=index
+ # pg_class.relreplident sent as one character: d=default, n=nothing, f=full, i=index.
+ replica_identity: int
columns: list[RelationColumn] = field(default_factory=list)
# Arrow type per column, derived once from the column OIDs. Stamped onto every
# ChangeEvent so the batcher types all-null micro-batches consistently.
@@ -207,6 +210,10 @@ class PgOutputDecoder:
# so a caller that handles truncates mid-transaction never purges ahead of the changes before
# them.
self._tx_truncated_tables: list[str] = []
+ # Per qualified table name, the key columns whose old values an update reports. Under REPLICA
+ # IDENTITY FULL the old row holds every column, and keeping the rest would grow every spilled
+ # transaction for values nothing reads.
+ self._key_change_columns: dict[str, frozenset[str]] = {}
self._last_commit_end_lsn: str | None = None
def decode_message(self, data: bytes, lsn: str) -> Iterable[ChangeEvent]:
@@ -411,6 +418,11 @@ class PgOutputDecoder:
if marker in ("K", "O"):
offset += 1
old_columns, offset = _skip_tuple(payload, offset, relation)
+ if marker == "K":
+ # The old key tuple sends every column outside the replica identity as NULL, and
+ # those NULLs are not the old values.
+ key_names = {col.name for col in relation.columns if col.flags & 1}
+ old_columns = {name: value for name, value in old_columns.items() if name in key_names}
# New tuple starts with 'N'
if chr(payload[offset]) != "N":
@@ -427,6 +439,16 @@ class PgOutputDecoder:
columns[col_name] = old_columns[col_name]
omitted.discard(col_name)
+ key_change_columns = self._key_change_columns.get(relation.qualified_name, frozenset())
+ previous_values = {
+ name: value
+ for name, value in old_columns.items()
+ if name in key_change_columns and name in columns and columns[name] != value
+ }
+ # A key column outside the old tuple has no old value, and capture would fill it with the new
+ # value, which builds an old key that never existed. The update then stays an upsert.
+ if not key_change_columns.issubset(old_columns):
+ previous_values = {}
self._buffer_event(
ChangeEvent(
operation="U",
@@ -436,6 +458,7 @@ class PgOutputDecoder:
columns=columns,
column_types=relation.column_arrow_types,
omitted_columns=frozenset(omitted),
+ previous_values=previous_values or None,
)
)
@@ -491,6 +514,9 @@ class PgOutputDecoder:
# --- Helpers ---
+ def set_key_change_columns(self, columns_by_table: Mapping[str, Iterable[str]]) -> None:
+ self._key_change_columns = {table: frozenset(columns) for table, columns in columns_by_table.items()}
+
def get_key_columns(self, table_name: str) -> list[str]:
"""Return the column names forming the replica identity key, or [] if there is no usable one.
@@ -501,7 +527,7 @@ class PgOutputDecoder:
relation = self._find_relation_by_name(table_name)
if relation is None:
return []
- # replica_identity 2 = FULL, which flags every column as part of the key. That names no key:
+ # REPLICA IDENTITY FULL flags every column as part of the key. That names no key:
# merging on every column makes each row version its own key, so updates accumulate instead
# of replacing. Checked by identity rather than by "all columns flagged", so a table whose
# declared PK genuinely covers every column still works.
@@ -565,6 +591,7 @@ class PgOutputDecoder:
event.columns,
sorted(event.omitted_columns),
type_index[key],
+ event.previous_values,
],
ensure_ascii=False,
separators=(",", ":"),
@@ -589,7 +616,7 @@ def _replay_spilled_transaction(
try:
spill.file.seek(0)
for line in spill.file:
- operation, table_name, timestamp, columns, omitted, type_index = json.loads(line)
+ operation, table_name, timestamp, columns, omitted, type_index, previous_values = json.loads(line)
yield ChangeEvent(
operation=operation,
table_name=table_name,
@@ -598,6 +625,7 @@ def _replay_spilled_transaction(
columns=columns,
column_types=types[type_index],
omitted_columns=frozenset(omitted),
+ previous_values=previous_values,
)
for event in tail:
yield dataclass_replace(event, position_serialized=end_lsn)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
index ea0244c0b918..059bbe9ac7ae 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/stream_reader.py
@@ -8,7 +8,7 @@ approach — batch reads on a schedule.
from __future__ import annotations
import time
-from collections.abc import Callable, Iterator
+from collections.abc import Callable, Iterable, Iterator, Mapping
from contextlib import AbstractContextManager, suppress
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
@@ -25,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
_connect_with_dropped_retry,
_is_connection_dropped_error,
_safe_close_connection,
+ get_enforced_unique_keys,
get_primary_key_columns,
)
@@ -342,6 +343,15 @@ class PgCDCStreamReader:
raise RuntimeError("Not connected. Call connect() first.")
return get_primary_key_columns(self._conn, schema_name, table_names)
+ def get_enforced_unique_keys(self, schema_name: str, table_names: list[str]) -> dict[str, list[frozenset[str]]]:
+ """Column sets that no two rows of a table can hold at the same time, per table."""
+ if self._conn is None:
+ raise RuntimeError("Not connected. Call connect() first.")
+ return get_enforced_unique_keys(self._conn, schema_name, table_names)
+
+ def set_key_change_columns(self, columns_by_table: Mapping[str, Iterable[str]]) -> None:
+ self._decoder.set_key_change_columns(columns_by_table)
+
@property
def truncated_tables(self) -> list[str]:
"""Tables that received a TRUNCATE during the last read_changes() call."""
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
index 193dd81602e1..ffeae0fc7373 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/cdc/tests/test_decoder.py
@@ -62,7 +62,8 @@ def _make_relation(
schema: str,
table: str,
columns: list[tuple[str, int, int]],
- replica_identity: int = 0,
+ replica_identity: int = ord("d"),
+ key_columns: set[str] | None = None,
) -> bytes:
"""Build a Relation (R) message.
@@ -76,7 +77,7 @@ def _make_relation(
data += struct.pack("!H", len(columns))
for col_name, type_oid, type_mod in columns:
- flags = 1 # part of key by default
+ flags = 1 if key_columns is None or col_name in key_columns else 0
data += struct.pack("!B", flags)
data += _make_cstring(col_name)
data += struct.pack("!I", type_oid)
@@ -209,14 +210,43 @@ class TestPgOutputDecoder:
assert event.columns["id"] == 42
assert event.columns["name"] == "Bob"
- def test_update_with_old_key(self):
- decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1), ("name", _OID_TEXT, -1)])
+ @parameterized.expand(
+ [
+ ("key_changed", b"K", [("t", "41"), None], ["id"], {"id": 41}),
+ ("key_unchanged", b"K", [("t", "42"), None], ["id"], None),
+ ("full_identity_row_keeps_only_the_key", b"O", [("t", "41"), ("t", "Alice")], ["id"], {"id": 41}),
+ ("no_old_tuple", b"K", None, ["id"], None),
+ ("table_without_a_splittable_key", b"K", [("t", "41"), None], None, None),
+ ("key_column_outside_the_identity", b"K", [("t", "41"), None], ["id", "name"], None),
+ (
+ "full_identity_row_covers_a_wider_key",
+ b"O",
+ [("t", "41"), ("t", "Alice")],
+ ["id", "name"],
+ {"id": 41, "name": "Alice"},
+ ),
+ ]
+ )
+ def test_update_with_old_key(
+ self,
+ _name: str,
+ old_marker: bytes,
+ old_values: list[tuple[str, str] | None] | None,
+ key_change_columns: list[str] | None,
+ expected_previous: dict[str, object] | None,
+ ) -> None:
+ decoder = PgOutputDecoder()
+ if key_change_columns is not None:
+ decoder.set_key_change_columns({"public.users": key_change_columns})
+ columns = [("id", _OID_INT4, -1), ("name", _OID_TEXT, -1)]
+ decoder.decode_message(_make_relation(1, "public", "users", columns, key_columns={"id"}), "0/100")
begin = _make_begin()
update = _make_update(
1,
new_values=[("t", "42"), ("t", "Bob")],
- old_values=[("t", "42"), ("t", "Alice")],
+ old_values=old_values,
+ old_marker=old_marker,
)
commit = _make_commit()
@@ -226,7 +256,8 @@ class TestPgOutputDecoder:
assert len(events) == 1
assert events[0].operation == "U"
- assert events[0].columns["name"] == "Bob"
+ assert events[0].columns == {"id": 42, "name": "Bob"}
+ assert events[0].previous_values == expected_previous
def test_delete_event(self):
decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1), ("name", _OID_TEXT, -1)])
@@ -312,24 +343,39 @@ class TestPgOutputDecoder:
assert "big_text" not in events[0].columns
assert events[0].omitted_columns == frozenset({"big_text"})
- def test_unchanged_toast_filled_from_replica_identity_full_old_tuple(self):
- # With REPLICA IDENTITY FULL the old tuple carries the TOAST value; since the
- # column is unchanged, the old value IS the current value — no marker needed.
- decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1), ("big_text", _OID_TEXT, -1)])
+ @parameterized.expand(
+ [
+ # With REPLICA IDENTITY FULL the old tuple carries the TOAST value; since the
+ # column is unchanged, the old value IS the current value — no marker needed.
+ ("full_identity_old_row", b"O", ("t", "big toasted value"), {"big_text": "big toasted value"}, set()),
+ ("old_key_tuple", b"K", None, {}, {"big_text"}),
+ ]
+ )
+ def test_unchanged_toast_filled_only_from_a_real_old_value(
+ self,
+ _name: str,
+ old_marker: bytes,
+ old_big_text: tuple[str, str] | None,
+ expected_filled: dict[str, str],
+ expected_omitted: set[str],
+ ) -> None:
+ decoder = PgOutputDecoder()
+ columns = [("id", _OID_INT4, -1), ("big_text", _OID_TEXT, -1)]
+ decoder.decode_message(_make_relation(1, "public", "users", columns, key_columns={"id"}), "0/100")
decoder.decode_message(_make_begin(), "0/100")
update = _make_update(
1,
- new_values=[("t", "1"), ("u", "")],
- old_values=[("t", "1"), ("t", "big toasted value")],
- old_marker=b"O",
+ new_values=[("t", "2"), ("u", "")],
+ old_values=[("t", "1"), old_big_text],
+ old_marker=old_marker,
)
decoder.decode_message(update, "0/150")
events = list(decoder.decode_message(_make_commit(), "0/200"))
assert len(events) == 1
- assert events[0].columns["big_text"] == "big toasted value"
- assert events[0].omitted_columns == frozenset()
+ assert events[0].columns == {"id": 2, **expected_filled}
+ assert events[0].omitted_columns == frozenset(expected_omitted)
def test_transaction_buffering(self):
decoder = self._setup_decoder_with_relation(columns=[("id", _OID_INT4, -1)])
@@ -543,7 +589,8 @@ class TestTransactionBufferGuard:
def _decoder_with_relation(self) -> PgOutputDecoder:
decoder = PgOutputDecoder()
- decoder.decode_message(_make_relation(1, "public", "users", self._COLUMNS), "0/1")
+ decoder.set_key_change_columns({"public.users": ["id"]})
+ decoder.decode_message(_make_relation(1, "public", "users", self._COLUMNS, key_columns={"id"}), "0/1")
return decoder
def _row(self, i: int) -> list[tuple[str, str] | None]:
@@ -559,8 +606,10 @@ class TestTransactionBufferGuard:
retyped = [("id", _OID_INT4, -1), ("name", _OID_TEXT, -1), ("active", _OID_BOOL, -1), ("score", _OID_TEXT, -1)]
return [
*(_make_insert(1, self._row(i)) for i in range(4)),
- _make_update(1, [("t", "2"), ("u", ""), ("t", "f"), ("t", "9.5")]),
- _make_relation(1, "public", "users", retyped),
+ _make_update(
+ 1, [("t", "2"), ("u", ""), ("t", "f"), ("t", "9.5")], old_values=[("t", "1"), None, None, None]
+ ),
+ _make_relation(1, "public", "users", retyped, key_columns={"id"}),
*(_make_insert(1, self._row(i)) for i in range(4, 7)),
]
@@ -576,6 +625,7 @@ class TestTransactionBufferGuard:
assert spilled == in_memory
assert {e.position_serialized for e in spilled} == {"0/500"}
assert spilled[4].omitted_columns == frozenset({"name"})
+ assert spilled[4].previous_values == {"id": 1}
assert spilled[0].column_types != spilled[-1].column_types
assert [e.columns["id"] for e in follow_up] == [100]
@@ -674,13 +724,13 @@ class TestTransactionBufferGuard:
class TestReplicaIdentityKeyColumns:
- def _decoder_with(self, replica_identity: int = 0, key_flags: tuple[int, ...] = (1, 0, 0)) -> PgOutputDecoder:
+ def _decoder_with(self, key_flags: tuple[int, ...] = (1, 0, 0)) -> PgOutputDecoder:
decoder = PgOutputDecoder()
decoder._relations[1] = Relation(
relation_id=1,
schema_name="cdc_test",
table_name="orders",
- replica_identity=replica_identity,
+ replica_identity=ord("d"),
columns=[
RelationColumn(flags=flags, name=name, type_oid=_OID_INT8, type_modifier=-1)
for flags, name in zip(key_flags, ["id", "tenant_id", "total"])
@@ -701,11 +751,13 @@ class TestReplicaIdentityKeyColumns:
def test_full_replica_identity_yields_no_key(self):
# FULL flags every column, so adopting it as the key would make the merge key the whole row
# and every update would insert instead of replace.
- decoder = self._decoder_with(replica_identity=2, key_flags=(1, 1, 1))
+ decoder = PgOutputDecoder()
+ columns = [("id", _OID_INT8, -1), ("tenant_id", _OID_INT8, -1), ("total", _OID_INT8, -1)]
+ decoder.decode_message(_make_relation(1, "cdc_test", "orders", columns, replica_identity=ord("f")), "0/1")
assert decoder.get_key_columns("cdc_test.orders") == []
def test_declared_key_covering_every_column_survives(self):
- decoder = self._decoder_with(replica_identity=0, key_flags=(1, 1, 1))
+ decoder = self._decoder_with(key_flags=(1, 1, 1))
assert decoder.get_key_columns("cdc_test.orders") == ["id", "tenant_id", "total"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 33a98d755e08..e30f207a1191 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -1027,6 +1027,45 @@ def get_primary_key_columns(conn: psycopg.Connection, schema: str, table_names:
return result
+def get_enforced_unique_keys(
+ conn: psycopg.Connection, schema: str, table_names: list[str]
+) -> dict[str, list[frozenset[str]]]:
+ """Column sets of each table's unique indexes that Postgres enforces on every row as it is written.
+
+ A deferrable constraint is checked only at the end of the statement or transaction, a partial index
+ leaves the rows outside its predicate free, and an expression index constrains no plain column. A
+ nullable key column lets any number of rows hold NULL there. Those are left out, so a set returned
+ here can never be held by two rows at once.
+ """
+ if not table_names:
+ return {}
+ with conn.cursor() as cur:
+ cur.execute(
+ """
+ SELECT c.relname, array_agg(a.attname::text)
+ FROM pg_index i
+ JOIN pg_class c ON c.oid = i.indrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN pg_attribute a
+ ON a.attrelid = c.oid AND a.attnum = ANY((i.indkey::int2[])[0:i.indnkeyatts - 1])
+ WHERE i.indisunique
+ AND i.indimmediate
+ AND i.indisvalid
+ AND i.indpred IS NULL
+ AND i.indexprs IS NULL
+ AND n.nspname = %s
+ AND c.relname = ANY(%s)
+ GROUP BY c.relname, i.indexrelid
+ HAVING bool_and(a.attnotnull)
+ """,
+ (schema, table_names),
+ )
+ keys: dict[str, list[frozenset[str]]] = {}
+ for table, columns in cur:
+ keys.setdefault(table, []).append(frozenset(columns))
+ return keys
+
+
def get_leading_index_columns(
conn: psycopg.Connection, schema: str, table_names: list[str]
) -> dict[str, set[str]] | None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index 508eda1126a2..696c801c7f7c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -144,6 +144,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.p
_tunnel_with_handshake_translation,
_xmin_capable_tables_from_conn,
filter_postgres_incremental_fields,
+ get_enforced_unique_keys,
get_foreign_keys,
get_leading_index_columns,
get_postgres_row_count,
@@ -8178,6 +8179,48 @@ class TestGetLeadingIndexColumns:
assert result is None
+class TestGetEnforcedUniqueKeys:
+ @pytest.mark.django_db
+ def test_returns_only_the_unique_indexes_postgres_checks_on_every_row(self) -> None:
+ with django_connection.cursor() as cursor:
+ for ddl in (
+ "CREATE TABLE uk_plain_pk (id int PRIMARY KEY, v text)",
+ "CREATE TABLE uk_deferrable_pk (id int PRIMARY KEY DEFERRABLE, v text)",
+ "CREATE TABLE uk_pk_and_deferrable_unique (id int PRIMARY KEY, pos int UNIQUE DEFERRABLE)",
+ "CREATE TABLE uk_no_key (id int, v text)",
+ "CREATE TABLE uk_partial (id int, active bool)",
+ "CREATE UNIQUE INDEX ON uk_partial (id) WHERE active",
+ "CREATE TABLE uk_expression (email text)",
+ "CREATE UNIQUE INDEX ON uk_expression (lower(email))",
+ "CREATE TABLE uk_covering (a int NOT NULL, b int NOT NULL, c int)",
+ "CREATE UNIQUE INDEX ON uk_covering (a, b) INCLUDE (c)",
+ "CREATE TABLE uk_nullable (id int PRIMARY KEY, code text UNIQUE)",
+ ):
+ cursor.execute(ddl)
+ django_connection.ensure_connection()
+ result = get_enforced_unique_keys(
+ cast(Any, django_connection.connection),
+ "public",
+ [
+ "uk_plain_pk",
+ "uk_deferrable_pk",
+ "uk_pk_and_deferrable_unique",
+ "uk_no_key",
+ "uk_partial",
+ "uk_expression",
+ "uk_covering",
+ "uk_nullable",
+ ],
+ )
+
+ assert result == {
+ "uk_plain_pk": [frozenset({"id"})],
+ "uk_pk_and_deferrable_unique": [frozenset({"id"})],
+ "uk_covering": [frozenset({"a", "b"})],
+ "uk_nullable": [frozenset({"id"})],
+ }
+
+
class TestHasDuplicatePrimaryKeys:
@pytest.mark.django_db
def test_returns_false_when_no_primary_keys(self):