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): read redshift primary keys from pg_catalog (#102453)

posthog[bot]4d0ea551c700
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index 9bf1a8ef9a3e..be9182cc90ae 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -25,6 +25,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import {
+ AvailableColumn,
DataWarehouseSyncInterval,
ExternalDataSchemaSourceSummary,
ExternalDataSource,
@@ -386,6 +387,20 @@ function SyncMethodSection({ sourceId, schema }: { sourceId: string; schema: Ext
const loading = schemaIncrementalFieldsLoading || !schemaIncrementalFields
+ // Only offer these as merge keys when the source reported them. Without source metadata the API
+ // fills the list from the synced table instead, whose names went through the snake_case naming
+ // convention, so `createdAt` reads back as `created_at` and a key picked from it names a column
+ // the source query cannot resolve. That is also the state where the API accepts a keyless
+ // incremental switch, so there is no refusal left without a remedy.
+ const storedColumns: AvailableColumn[] = schema.source_column_metadata_available
+ ? (schema.available_columns ?? []).map((column) => ({
+ field: column.name,
+ label: column.name,
+ type: column.data_type ?? '',
+ nullable: column.is_nullable ?? false,
+ }))
+ : []
+
const persistSyncMethod = async (
syncType: ExternalDataSourceSchema['sync_type'],
incrementalField: string | null,
@@ -482,7 +497,7 @@ function SyncMethodSection({ sourceId, schema }: { sourceId: string; schema: Ext
incremental_fields: schemaIncrementalFields.incremental_fields,
supports_webhooks: schemaIncrementalFields.supports_webhooks ?? false,
primary_key_columns: schema.primary_key_columns ?? null,
- available_columns: [],
+ available_columns: storedColumns,
detected_primary_keys: null,
}}
availableColumns={schemaIncrementalFields.available_columns ?? []}
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx
index 484ef76646ed..5955c9e83ca3 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.test.tsx
@@ -1,7 +1,11 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
import { ExternalDataSourceSyncSchema } from '~/types'
import { SyncTypeLabelMap } from '../../../utils'
-import { getInitialRadioState, getSaveDisabledReason, shouldOfferXmin } from './SyncMethodForm'
+import { SyncMethodForm, getInitialRadioState, getSaveDisabledReason, shouldOfferXmin } from './SyncMethodForm'
const baseSchema: ExternalDataSourceSyncSchema = {
table: 'orders',
@@ -48,4 +52,35 @@ describe('SyncMethodForm', () => {
])('preselects incremental only when the key resolves: %s', (_, keyResolvable, expected) => {
expect(getInitialRadioState({ ...baseSchema, xmin_available: false }, true, true, keyResolvable)).toBe(expected)
})
+
+ describe('primary key picker', () => {
+ afterEach(cleanup)
+
+ // The API refuses an incremental switch without a merge key whenever it knows the
+ // schema's columns. Discovery returning none must not hide the picker that sets one,
+ // or the refusal has no remedy.
+ it('offers the stored columns when discovery returned none', () => {
+ render(
+ <SyncMethodForm
+ schema={{
+ ...baseSchema,
+ sync_type: 'incremental',
+ incremental_available: true,
+ incremental_field: 'updated_at',
+ incremental_fields: [
+ { field: 'updated_at', field_type: 'datetime', label: 'updated_at', type: 'datetime' },
+ ],
+ detected_primary_keys: null,
+ available_columns: [{ field: 'order_id', label: 'order_id', type: 'bigint', nullable: false }],
+ }}
+ availableColumns={[]}
+ primaryKeyDetectionSupported
+ onClose={() => {}}
+ onSave={() => {}}
+ />
+ )
+
+ expect(screen.getByText(/select one or more columns to use as the primary key/i)).toBeInTheDocument()
+ })
+ })
})
diff --git a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
index 9a4aec2756b8..2a18b6670b4c 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SyncMethodForm.tsx
@@ -208,7 +208,11 @@ export const SyncMethodForm = forwardRef<SyncMethodFormHandle, SyncMethodFormPro
const appendSyncSupported = getAppendOnlySyncSupported(schema)
const cdcSyncSupported = getCdcSyncSupported(schema)
- const columns = availableColumns ?? schema.available_columns ?? []
+ // An empty discovered list means "not discovered", not "this relation has no columns": a
+ // Redshift materialized view under a restricted role is listed from the stored metadata alone.
+ // The API judges an incremental switch against that stored list, so the key picker offers it
+ // too — otherwise the switch is refused with no way to satisfy it.
+ const columns = availableColumns?.length ? availableColumns : (schema.available_columns ?? [])
const resolvedDetectedPks = detectedPrimaryKeys ?? schema.detected_primary_keys ?? null
// A key is only asked for when the source reads keys off the table and the columns are
// known. A source that declares its key in code resolves it at sync time, and with no
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
index 1909bf8d227c..ad2d45d20e1b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/redshift.py
@@ -162,6 +162,62 @@ _CATALOG_COLUMNS_SQL = """
_TYPE_MODIFIER_PATTERN = re.compile(r"\((\d+)(?:,\s*(\d+))?\)")
+# `information_schema.table_constraints` is filtered on the connecting role's privileges, the same
+# way `information_schema.columns` is, and a Redshift materialized view never appears in it at all.
+# A key read from there is therefore missing for exactly the relations that most need one, so the
+# declared key comes from `pg_catalog` instead — the catalog the Postgres source already reads.
+_CATALOG_PRIMARY_KEYS_SQL = sql.SQL("""
+ SELECT n.nspname, c.relname, con.conkey
+ FROM pg_catalog.pg_constraint con
+ JOIN pg_catalog.pg_class c ON c.oid = con.conrelid
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ WHERE con.contype = 'p' AND {where}""")
+
+# Redshift holds the key as column numbers and has neither `array_position` nor `unnest`, so the
+# names are resolved and put back in declared order in Python.
+_CATALOG_KEY_COLUMN_NAMES_SQL = sql.SQL("""
+ SELECT n.nspname, c.relname, a.attnum, a.attname
+ FROM pg_catalog.pg_attribute a
+ JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
+ WHERE a.attnum > 0 AND NOT a.attisdropped AND {where}""")
+
+_CONSTRAINT_KEY_POSITION_PATTERN = re.compile(r"\d+")
+
+
+def _parse_constraint_key(raw: Any) -> list[int]:
+ """Column numbers of a primary key, in declared order.
+
+ `conkey` arrives as a sequence when the driver knows the array type, and as the catalog's own
+ text form (`1 2`) when it does not, so both are read the same way.
+ """
+ if isinstance(raw, list | tuple):
+ return [int(position) for position in raw]
+ return [int(position) for position in _CONSTRAINT_KEY_POSITION_PATTERN.findall(str(raw or ""))]
+
+
+# nosemgrep: tuple-return-prefer-dataclass -- the pair keys the mapping, so no caller reads it positionally
+def _primary_keys_from_catalog(cursor: psycopg.Cursor, where: sql.Composable) -> dict[tuple[str, str], list[str]]:
+ """Declared primary keys of the relations `where` selects, each in declared column order."""
+ cursor.execute(_CATALOG_PRIMARY_KEYS_SQL.format(where=where))
+ key_positions = {(schema, table): _parse_constraint_key(conkey) for schema, table, conkey in cursor.fetchall()}
+ if not key_positions:
+ return {}
+
+ cursor.execute(_CATALOG_KEY_COLUMN_NAMES_SQL.format(where=where))
+ names_by_relation: dict[tuple[str, str], dict[int, str]] = {}
+ for schema, table, attnum, attname in cursor.fetchall():
+ names_by_relation.setdefault((schema, table), {})[int(attnum)] = attname
+
+ keys: dict[tuple[str, str], list[str]] = {}
+ for relation, positions in key_positions.items():
+ names = names_by_relation.get(relation, {})
+ columns = [names[position] for position in positions if position in names]
+ if columns:
+ keys[relation] = columns
+ return keys
+
+
@frozen
class _CatalogColumn:
"""One `pg_catalog` column, normalized to what `information_schema.columns` would report."""
@@ -538,38 +594,15 @@ def _retry_on_transient_connection_drop(
time.sleep(min(2 * attempt, 30))
-def _reads_primary_keys(cursor: psycopg.Cursor, schema: str) -> bool | None:
- """Can this connection read primary-key constraints in `schema` at all?
-
- `information_schema.table_constraints` exposes only the objects the role holds privileges on,
- so an empty result for one table means either "no key is declared" or "no privilege to see the
- one that is", and the two need opposite advice. Finding a key on any table in the schema
- settles it: the role can read the view, so an empty per-table result is a real absence.
-
- `None` when the probe itself fails, which settles nothing either way.
- """
- query = sql.SQL("""
- SELECT 1
- FROM information_schema.table_constraints
- WHERE table_schema = {schema} AND constraint_type = 'PRIMARY KEY'
- LIMIT 1""").format(schema=sql.Literal(schema))
- try:
- return cursor.execute(query).fetchone() is not None
- except Exception:
- _recover_after_failed_probe(cursor.connection)
- return None
-
-
def _no_primary_key_warning(
- cursor: psycopg.Cursor,
- schema: str,
table_name: str,
table_type: Literal["table", "view", "materialized_view"] | None,
) -> str:
"""The warning for a table whose primary-key lookup came back empty.
- Each branch states only what the empty result actually establishes, so the operator is never
- sent after a key that cannot exist or that we merely failed to read.
+ The lookup reads `pg_catalog`, which applies no privilege filter, and a failed read raises
+ rather than returning nothing. An empty result is therefore a real absence, so each branch can
+ name the remedies instead of sending the operator after a key we merely failed to read.
"""
if table_type in ("view", "materialized_view"):
relation = "materialized view" if table_type == "materialized_view" else "view"
@@ -578,16 +611,9 @@ def _no_primary_key_warning(
"Select a primary key manually to enable incremental sync, or use full table replication instead."
)
- if _reads_primary_keys(cursor, schema):
- return (
- f"No primary key is set on {table_name}. Select one manually to enable incremental sync, "
- "or use full table replication instead."
- )
-
return (
- f"Could not determine a primary key for {table_name}. Either none is set, or PostHog's role "
- f"cannot read constraints in schema {schema}. Check the role has SELECT on the table. You can "
- "also select a primary key manually, or use full table replication instead."
+ f"No primary key is set on {table_name}. Select one manually to enable incremental sync, "
+ "or use full table replication instead."
)
@@ -1098,17 +1124,15 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
config: RedshiftSourceConfig,
tables: list[str],
) -> dict[str, list[str] | None]:
- """Detect primary keys for all tables in a single query, each in declared column order.
+ """Detect primary keys for all tables from `pg_catalog`, each in declared column order.
- Permission-sensitive — some Redshift deployments restrict access
- to `information_schema.table_constraints`. Swallow and log any
- failure so schema discovery keeps working without PKs.
+ Swallow and log any failure so schema discovery keeps working without PKs.
A swallowed failure returns every table as `None`, which the base
contract cannot distinguish from "declares no key". The sync path
- re-runs the lookup per table and says which it is
- (`_no_primary_key_warning`); surfacing the difference at discovery
- needs a channel on `SourceSchema` that does not exist yet.
+ re-runs the lookup per table, where a failure raises instead of being
+ swallowed; surfacing the difference at discovery needs a channel on
+ `SourceSchema` that does not exist yet.
"""
result: dict[str, list[str] | None] = dict.fromkeys(tables)
if not tables:
@@ -1117,37 +1141,24 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
selected_schema = normalize_namespace(config.schema)
index = self._index_display_names(tables, selected_schema)
+ where = sql.SQL("n.nspname = ANY({schemas}) AND c.relname = ANY({names})").format(
+ schemas=sql.Literal(index.schemas), names=sql.Literal(index.bare_tables)
+ )
try:
with conn.cursor() as cursor:
- cursor.execute(
- sql.SQL("""
- SELECT tc.table_schema, tc.table_name, kcu.column_name
- FROM information_schema.table_constraints tc
- JOIN information_schema.key_column_usage kcu
- ON tc.constraint_name = kcu.constraint_name
- AND tc.table_schema = kcu.table_schema
- AND tc.table_name = kcu.table_name
- WHERE tc.table_schema = ANY({schemas})
- AND tc.table_name = ANY({names})
- AND tc.constraint_type = 'PRIMARY KEY'
- ORDER BY tc.table_schema, tc.table_name, kcu.ordinal_position
- """).format(schemas=sql.Literal(index.schemas), names=sql.Literal(index.bare_tables))
- )
- rows = cursor.fetchall()
+ keys_by_relation = _primary_keys_from_catalog(cursor, where)
except Exception as e:
+ _recover_after_failed_probe(conn)
structlog.get_logger().warning(
"Primary keys for Redshift schemas are undetermined, not absent: the detection query failed",
exc_info=e,
)
return result
- pks: dict[str, list[str]] = collections.defaultdict(list)
- for table_schema, table_name, column_name in rows:
- display = index.display_by_pair.get((table_schema, table_name))
+ for relation, pk_cols in keys_by_relation.items():
+ display = index.display_by_pair.get(relation)
if display is not None:
- pks[display].append(column_name)
- for display, pk_cols in pks.items():
- result[display] = pk_cols
+ result[display] = pk_cols
return result
@staticmethod
@@ -1394,35 +1405,21 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco
) -> list[str] | None:
"""Return the primary-key column names for a single table in declared order, or None.
- `table_type` only shapes the warning on an empty result, which is ambiguous on its own:
- see `_no_primary_key_warning` for what each case establishes.
+ Reads `pg_catalog`, the same catalog discovery reads, so a key found when the table was
+ listed is still found here. `table_type` only shapes the warning on an empty result: a view
+ holds no key at all, so its message names different remedies.
"""
- query = sql.SQL("""
- SELECT
- kcu.column_name
- FROM
- information_schema.table_constraints tc
- JOIN
- information_schema.key_column_usage kcu
- ON tc.constraint_name = kcu.constraint_name
- AND tc.table_schema = kcu.table_schema
- WHERE
- tc.table_schema = {schema}
- AND tc.table_name = {table}
- AND tc.constraint_type = 'PRIMARY KEY'
- ORDER BY
- kcu.ordinal_position""").format(schema=sql.Literal(schema), table=sql.Literal(table_name))
-
+ where = sql.SQL("n.nspname = {schema} AND c.relname = {table}").format(
+ schema=sql.Literal(schema), table=sql.Literal(table_name)
+ )
if logger is not None:
- _explain_query(cursor, query, logger)
- logger.debug(f"Running query: {query.as_string()}")
- cursor.execute(query)
- rows = cursor.fetchall()
- if len(rows) > 0:
- return [row[0] for row in rows]
+ logger.debug(f"Running query: {_CATALOG_PRIMARY_KEYS_SQL.format(where=where).as_string()}")
+ primary_key = _primary_keys_from_catalog(cursor, where).get((schema, table_name))
+ if primary_key:
+ return primary_key
if logger is not None:
- logger.warning(_no_primary_key_warning(cursor, schema, table_name, table_type))
+ logger.warning(_no_primary_key_warning(table_name, table_type))
return None
@staticmethod
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
index edd6515f2c00..37674b832549 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/redshift/tests/test_redshift.py
@@ -1,4 +1,4 @@
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import date
from typing import Any
@@ -59,6 +59,18 @@ from products.warehouse_sources.backend.types import IncrementalFieldType
# ---------------------------------------------------------------------------
+def _catalog_primary_key_rows(
+ constraints: list[tuple[str, str, Any]], attributes: list[tuple[str, str, int, str]]
+) -> Callable[[], list[tuple[Any, ...]]]:
+ """`fetchall` side effect for the two `pg_catalog` reads a key lookup makes."""
+ rows: list[list[tuple[Any, ...]]] = [list(constraints), list(attributes)]
+
+ def fetchall() -> list[tuple[Any, ...]]:
+ return rows.pop(0) if rows else []
+
+ return fetchall
+
+
def _make_config(**overrides) -> RedshiftSourceConfig:
defaults: dict = {
"host": "localhost",
@@ -341,9 +353,23 @@ class TestGetPrimaryKeysForTable:
assert impl.get_primary_keys_for_table(cursor, "public", "t") is None
def test_returns_pk_column_names(self, impl, cursor):
- cursor.fetchall.return_value = [("id",), ("email",)]
+ cursor.fetchall.side_effect = _catalog_primary_key_rows(
+ [("public", "t", "1 2")],
+ [("public", "t", 1, "id"), ("public", "t", 2, "email"), ("public", "t", 3, "created_at")],
+ )
assert impl.get_primary_keys_for_table(cursor, "public", "t") == ["id", "email"]
+ def test_reads_the_key_from_pg_catalog(self, impl, cursor):
+ # `information_schema` is privilege-filtered and holds no row at all for a materialized
+ # view, so a key read from there is missing for the relations that most need one.
+ cursor.fetchall.return_value = []
+
+ impl.get_primary_keys_for_table(cursor, "public", "t")
+
+ query = cursor.execute.call_args_list[0].args[0].as_string()
+ assert "pg_catalog.pg_constraint" in query
+ assert "information_schema" not in query
+
@pytest.mark.parametrize(
"table_type,expected_phrase",
[
@@ -364,51 +390,28 @@ class TestGetPrimaryKeysForTable:
assert expected_phrase in warning
assert "full table replication" in warning
- def test_warns_that_a_table_declares_no_key_when_the_role_can_read_constraints(self, impl, cursor, logger):
- # A key found elsewhere in the schema proves the role can read `table_constraints`, so this
- # table's empty result is a real absence and the message can say so outright.
+ def test_warns_that_a_table_declares_no_key(self, impl, cursor, logger):
+ # `pg_catalog` applies no privilege filter, and a failed read raises rather than returning
+ # nothing, so an empty result is a real absence. Hedging it sends the operator after a
+ # permission that cannot be the cause, and the suggested fix does not apply.
cursor.fetchall.return_value = []
- cursor.execute.return_value = cursor
- cursor.fetchone.return_value = (1,)
-
- impl.get_primary_keys_for_table(cursor, "public", "t", logger, "table")
-
- assert "No primary key is set on t" in logger.warning.call_args.args[0]
-
- @pytest.mark.parametrize("probe_outcome", ["sees_nothing", "probe_fails"])
- def test_does_not_claim_a_table_is_keyless_when_detection_is_undetermined(
- self, impl, cursor, logger, probe_outcome
- ):
- # The reported bug: an unreadable key and an absent key both produce zero rows, and the
- # message asserted the second. Asserting absence here sends the operator to set keys by
- # hand for a condition they may not have.
- cursor.fetchall.return_value = []
- cursor.execute.return_value = cursor
- cursor.fetchone.return_value = None
- if probe_outcome == "probe_fails":
- # Only the privilege probe is a LIMIT 1, so this fails it without counting calls.
- def fail_the_probe(query, *args):
- if "LIMIT 1" in query.as_string():
- raise Exception("permission denied")
- return cursor
-
- cursor.execute.side_effect = fail_the_probe
impl.get_primary_keys_for_table(cursor, "public", "t", logger, "table")
warning = logger.warning.call_args.args[0]
- assert "Could not determine a primary key" in warning
- assert "No primary key is set" not in warning
-
- def test_orders_composite_key_columns_by_declared_position(self, impl, cursor):
- # Without ORDER BY, Redshift returns the constraint's columns in arbitrary order and a
- # composite key is assembled wrong, which silently corrupts incremental merge matching.
- cursor.fetchall.return_value = [("a",), ("b",)]
+ assert "No primary key is set on t" in warning
+ assert "full table replication" in warning
- impl.get_primary_keys_for_table(cursor, "public", "t")
+ @pytest.mark.parametrize("conkey", ["2 1", "{2,1}", [2, 1]])
+ def test_orders_composite_key_columns_by_declared_position(self, impl, cursor, conkey):
+ # The catalog holds the key as column numbers, in whichever form the driver hands back.
+ # Sorting by column number instead assembles a composite key wrong, which silently
+ # corrupts incremental merge matching.
+ cursor.fetchall.side_effect = _catalog_primary_key_rows(
+ [("public", "t", conkey)], [("public", "t", 1, "a"), ("public", "t", 2, "b")]
+ )
- assert "ORDER BY" in cursor.execute.call_args.args[0].as_string()
- assert "kcu.ordinal_position" in cursor.execute.call_args.args[0].as_string()
+ assert impl.get_primary_keys_for_table(cursor, "public", "t") == ["b", "a"]
class TestGetTableMetadata:
@@ -1209,11 +1212,14 @@ class TestGetPrimaryKeys:
conn = MagicMock()
cur = MagicMock()
cur.__enter__.return_value = cur
- cur.fetchall.return_value = [
- ("public", "users", "id"),
- ("public", "users", "tenant_id"),
- ("public", "orders", "id"),
- ]
+ cur.fetchall.side_effect = _catalog_primary_key_rows(
+ [("public", "users", "1 2"), ("public", "orders", "1")],
+ [
+ ("public", "users", 1, "id"),
+ ("public", "users", 2, "tenant_id"),
+ ("public", "orders", 1, "id"),
+ ],
+ )
conn.cursor.return_value = cur
result = impl.get_primary_keys(conn, _make_config(), ["users", "orders", "items"])
@@ -1223,7 +1229,10 @@ class TestGetPrimaryKeys:
conn = MagicMock()
cur = MagicMock()
cur.__enter__.return_value = cur
- cur.fetchall.return_value = [("analytics", "users", "id"), ("public", "users", "uid")]
+ cur.fetchall.side_effect = _catalog_primary_key_rows(
+ [("analytics", "users", "1"), ("public", "users", "1")],
+ [("analytics", "users", 1, "id"), ("public", "users", 1, "uid")],
+ )
conn.cursor.return_value = cur
result = impl.get_primary_keys(conn, _make_config(schema=""), ["analytics.users", "public.users"])
@@ -1240,15 +1249,37 @@ class TestGetPrimaryKeys:
result = impl.get_primary_keys(conn, _make_config(schema=""), ["users"])
assert result == {"users": None}
+ def test_reads_the_key_from_pg_catalog(self, impl):
+ # Discovery reads columns from `pg_catalog` because `information_schema` is
+ # privilege-filtered; the key has to come from the same place or a relation lists its
+ # columns and still reports no key it could merge on.
+ conn = MagicMock()
+ cur = MagicMock()
+ cur.__enter__.return_value = cur
+ cur.fetchall.return_value = []
+ conn.cursor.return_value = cur
+
+ impl.get_primary_keys(conn, _make_config(), ["users"])
+
+ query = cur.execute.call_args_list[0].args[0].as_string()
+ assert "pg_catalog.pg_constraint" in query
+ assert "information_schema" not in query
+
def test_swallows_errors_and_returns_none_per_table(self, impl):
+ # Discovery runs every probe on one transactional connection, so the aborted transaction
+ # has to go here: the row-count and sortkey probes that follow would otherwise fail on
+ # `InFailedSqlTransaction` and lose metadata this failure never touched.
conn = MagicMock()
cur = MagicMock()
cur.__enter__.return_value = cur
cur.execute.side_effect = Exception("denied")
conn.cursor.return_value = cur
+ conn.info.transaction_status = TransactionStatus.INERROR
result = impl.get_primary_keys(conn, _make_config(), ["users"])
+
assert result == {"users": None}
+ conn.rollback.assert_called_once()
class TestGetRowCounts: