: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add multi-schema warehouse import for Redshift (#62963)
Daniel RC9dc22205af44
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex bdfb6119e56f..38cf7c3d1558 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -1071,9 +1071,9 @@ class RedshiftSourceConfig(config.Config):database: struser: strpassword: str- schema: strport: int = config.value(converter=int)connection_string: str | None = None+ schema: str | None = Nonessh_tunnel: SSHTunnelConfig | None = Nonediff --git a/posthog/temporal/data_imports/sources/redshift/redshift.py b/posthog/temporal/data_imports/sources/redshift/redshift.pyindex 165328d94a17..a43e05c70fa3 100644--- a/posthog/temporal/data_imports/sources/redshift/redshift.py+++ b/posthog/temporal/data_imports/sources/redshift/redshift.py@@ -23,7 +23,6 @@ from psycopg.adapt import Loaderfrom structlog.types import FilteringBoundLoggerfrom posthog.exceptions_capture import capture_exception-from posthog.temporal.data_imports.naming_convention import NamingConventionfrom posthog.temporal.data_imports.pipelines.helpers import (incremental_type_to_initial_value,incremental_type_to_operator,@@ -44,8 +43,13 @@ from posthog.temporal.data_imports.sources.common.sql import (compute_projected_columns,project_arrow_columns,)-from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation, TableStats+from posthog.temporal.data_imports.sources.common.sql.implementation import (+ SourceMetadata,+ SQLSourceImplementation,+ TableStats,+)from posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter+from posthog.temporal.data_imports.sources.common.sql.location import normalize_namespace, resolve_source_locationfrom posthog.temporal.data_imports.sources.generated_configs import RedshiftSourceConfigfrom products.data_warehouse.backend.types import IncrementalFieldType@@ -72,6 +76,43 @@ _REDSHIFT_CONNECT_OPTS: dict[str, Any] = {}+# Schemas excluded from blank-namespace (all-schema) discovery. Redshift exposes the Postgres+# system catalogs plus `pg_automv` (auto-materialized views) and per-session `pg_temp_*` schemas.+SYSTEM_REDSHIFT_SCHEMAS = ["pg_catalog", "information_schema", "pg_internal", "pg_automv"]+++def _display_name(schema_name: str, table_name: str, *, qualify: bool) -> str:+ """Discovery key for a table: dotted `schema.table` in multi-schema mode, bare table otherwise."""+ return f"{schema_name}.{table_name}" if qualify else table_name+++def _split_display_name(display: str, selected_schema: Optional[str]) -> tuple[Optional[str], str]:+ """Inverse of `_display_name` — `(schema, unqualified_table)` for a discovery key.++ With a pinned `selected_schema` the key is the bare table. Otherwise it is the dotted+ `schema.table` that `get_columns` produced; a multi-schema key without a dot isn't expected+ (every multi-schema key is qualified at discovery), so the schema is reported as unknown+ (`None`) rather than guessed from the table name — never invent a schema we'd then query.+ """+ if selected_schema is not None:+ return selected_schema, display+ schema, dot, table = display.partition(".")+ if not dot:+ return None, display+ return schema, table+++def _named_placeholders(prefix: str, values: list[str]) -> tuple[str, dict[str, str]]:+ """Render `%(prefix_i)s` placeholders + params for an `IN (...)` list."""+ placeholders: list[str] = []+ params: dict[str, str] = {}+ for index, value in enumerate(values):+ key = f"{prefix}_{index}"+ placeholders.append(f"%({key})s")+ params[key] = value+ return ", ".join(placeholders), params++def filter_redshift_incremental_fields(columns: list[tuple[str, str, bool]],) -> list[tuple[str, IncrementalFieldType, bool]]:@@ -301,29 +342,72 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoconfig: RedshiftSourceConfig,names: list[str] | None,) -> dict[str, list[tuple[str, str, bool]]]:+ """List columns, keyed by the discovery display name.++ Pinned `schema` keeps the single-namespace fast path (bare table keys). A blank `schema`+ enumerates every non-system namespace and returns qualified `schema.table` keys so+ cross-schema duplicate table names stay distinct.+ """+ selected_schema = normalize_namespace(config.schema)+ qualify = selected_schema is None+with conn.cursor() as cursor:- params: dict = {"schema": config.schema}- names_filter = ""+ params: dict = {}+ where: list[str] = []+ if selected_schema is not None:+ params["schema"] = selected_schema+ where.append("table_schema = %(schema)s")+ else:+ placeholders, system_params = _named_placeholders("system_schema", SYSTEM_REDSHIFT_SCHEMAS)+ params.update(system_params)+ where.append(f"table_schema NOT IN ({placeholders})")+ where.append("table_schema NOT LIKE 'pg_temp_%%'")if names:- params["names"] = names- names_filter = "AND table_name = ANY(%(names)s)"+ name_clause, name_params = self._column_name_predicate(names, selected_schema)+ params.update(name_params)+ where.append(name_clause)cursor.execute(f"""- SELECT table_name, column_name, data_type, is_nullable+ SELECT table_schema, table_name, column_name, data_type, is_nullableFROM information_schema.columns- WHERE table_schema = %(schema)s {names_filter}- ORDER BY table_name ASC+ WHERE {" AND ".join(where)}+ ORDER BY table_schema ASC, table_name ASC""",params,)result = cursor.fetchall()schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)- for row in result:- schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))+ for table_schema, table_name, column_name, data_type, is_nullable in result:+ display = _display_name(table_schema, table_name, qualify=qualify)+ schema_list[display].append((column_name, data_type, is_nullable == "YES"))return dict(schema_list)+ @staticmethod+ def _column_name_predicate(names: list[str], selected_schema: Optional[str]) -> tuple[str, dict[str, str]]:+ """Build a WHERE fragment restricting `information_schema.columns` to the requested tables.++ Pinned schema → match by bare `table_name`. Blank schema → match each qualified+ `schema.table` on both parts (bare names fall back to any-schema for legacy self-heal).+ """+ clauses: list[str] = []+ params: dict[str, str] = {}+ for index, name in enumerate(names):+ if selected_schema is not None:+ params[f"name_{index}"] = name+ clauses.append(f"table_name = %(name_{index})s")+ continue+ schema, _, table = name.partition(".")+ if table:+ params[f"sch_{index}"] = schema+ params[f"tbl_{index}"] = table+ clauses.append(f"(table_schema = %(sch_{index})s AND table_name = %(tbl_{index})s)")+ else:+ params[f"name_{index}"] = name+ clauses.append(f"table_name = %(name_{index})s")+ return "(" + " OR ".join(clauses) + ")", params+def get_primary_keys(self,conn: psycopg.Connection,@@ -340,20 +424,23 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoif not tables:return result+ selected_schema = normalize_namespace(config.schema)+ display_by_pair, schemas, bare_tables = self._index_display_names(tables, selected_schema)+try:with conn.cursor() as cursor:cursor.execute(sql.SQL("""- SELECT tc.table_name, kcu.column_name+ SELECT tc.table_schema, tc.table_name, kcu.column_nameFROM information_schema.table_constraints tcJOIN information_schema.key_column_usage kcuON tc.constraint_name = kcu.constraint_nameAND tc.table_schema = kcu.table_schemaAND tc.table_name = kcu.table_name- WHERE tc.table_schema = {schema}+ WHERE tc.table_schema = ANY({schemas})AND tc.table_name = ANY({names})AND tc.constraint_type = 'PRIMARY KEY'- """).format(schema=sql.Literal(config.schema), names=sql.Literal(tables))+ """).format(schemas=sql.Literal(schemas), names=sql.Literal(bare_tables)))rows = cursor.fetchall()except Exception as e:@@ -361,12 +448,38 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoreturn resultpks: dict[str, list[str]] = collections.defaultdict(list)- for table_name, column_name in rows:- pks[table_name].append(column_name)- for table_name, pk_cols in pks.items():- result[table_name] = pk_cols+ for table_schema, table_name, column_name in rows:+ display = display_by_pair.get((table_schema, table_name))+ if display is not None:+ pks[display].append(column_name)+ for display, pk_cols in pks.items():+ result[display] = pk_colsreturn result+ @staticmethod+ def _index_display_names(+ tables: list[str], selected_schema: Optional[str]+ ) -> tuple[dict[tuple[str, str], str], list[str], list[str]]:+ """Map `(schema, table)` → display key, plus the distinct schemas and bare table names.++ Lets a single batch query (`schema = ANY(...) AND table = ANY(...)`) cover both the+ single-namespace and multi-namespace cases; results re-key to the display name by pair.+ A display whose schema is unknown (bare key in multi-schema mode) is dropped from the+ queryable schema list — it can't be matched to a result row, so it degrades to no metadata+ rather than querying a schema that doesn't exist.+ """+ display_by_pair: dict[tuple[str, str], str] = {}+ schemas: set[str] = set()+ bare_tables: set[str] = set()+ for display in tables:+ schema, table = _split_display_name(display, selected_schema)+ bare_tables.add(table)+ if schema is None:+ continue+ display_by_pair[(schema, table)] = display+ schemas.add(schema)+ return display_by_pair, sorted(schemas), sorted(bare_tables)+def get_row_counts(self,conn: psycopg.Connection,@@ -384,6 +497,9 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoif not tables:return {}+ selected_schema = normalize_namespace(config.schema)+ display_by_pair, schemas, bare_tables = self._index_display_names(tables, selected_schema)+result: dict[str, int | None] = {}try:with conn.cursor() as cursor:@@ -391,36 +507,47 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycosql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 30)) # 30 secs)- params: dict = {"schema": config.schema, "names": tables}+ params: dict = {"schemas": schemas, "names": bare_tables}cursor.execute("""- SELECT "table" AS table_name, tbl_rows AS row_count+ SELECT schema, "table" AS table_name, tbl_rows AS row_countFROM svv_table_info- WHERE schema = %(schema)s AND "table" = ANY(%(names)s)+ WHERE schema = ANY(%(schemas)s) AND "table" = ANY(%(names)s)""",params,)- for table_name, row_count in cursor.fetchall():- result[table_name] = int(row_count)+ for schema_name, table_name, row_count in cursor.fetchall():+ display = display_by_pair.get((schema_name, table_name))+ if display is not None:+ result[display] = int(row_count)cursor.execute(- "SELECT viewname FROM pg_views WHERE schemaname = %(schema)s AND viewname = ANY(%(names)s)",+ "SELECT schemaname, viewname FROM pg_views WHERE schemaname = ANY(%(schemas)s) AND viewname = ANY(%(names)s)",params,)- views = cursor.fetchall()+ view_pairs = [+ (schema_name, view_name)+ for schema_name, view_name in cursor.fetchall()+ if (schema_name, view_name) in display_by_pair+ ]- if views:+ if view_pairs:view_counts = [- sql.SQL("SELECT {view_name} AS table_name, COUNT(*) AS row_count FROM {schema}.{view}").format(- view_name=sql.Literal(view[0]),- schema=sql.Identifier(config.schema),- view=sql.Identifier(view[0]),+ sql.SQL(+ "SELECT {schema_lit} AS schema_name, {view_lit} AS table_name, COUNT(*) AS row_count FROM {schema}.{view}"+ ).format(+ schema_lit=sql.Literal(schema_name),+ view_lit=sql.Literal(view_name),+ schema=sql.Identifier(schema_name),+ view=sql.Identifier(view_name),)- for view in views+ for schema_name, view_name in view_pairs]cursor.execute(sql.SQL(" UNION ALL ").join(view_counts))- for row in cursor.fetchall():- result[row[0]] = int(row[1])+ for schema_name, table_name, row_count in cursor.fetchall():+ display = display_by_pair.get((schema_name, table_name))+ if display is not None:+ result[display] = int(row_count)except Exception:return {}@@ -455,6 +582,8 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoif not tables:return {}+ selected_schema = normalize_namespace(config.schema)+ display_by_pair, schemas, bare_tables = self._index_display_names(tables, selected_schema)result: dict[str, set[str]] = {table: set() for table in tables}try:@@ -462,36 +591,65 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco# pg_table_def only returns rows for schemas in search_path; without# this SET, schema=anything-other-than-public-or-the-username silently# returns zero rows and the helper marks every sortkey column as- # unindexed. Documented behavior: docs.aws.amazon.com/redshift/latest/dg/r_PG_TABLE_DEF.html- cursor.execute(sql.SQL("SET search_path TO {schema}").format(schema=sql.Identifier(config.schema)))+ # unindexed. Multi-schema discovery puts every discovered schema on the+ # path. Documented behavior: docs.aws.amazon.com/redshift/latest/dg/r_PG_TABLE_DEF.html+ cursor.execute(+ sql.SQL("SET search_path TO {schemas}").format(+ schemas=sql.SQL(", ").join(sql.Identifier(schema) for schema in schemas)+ )+ )cursor.execute(sql.SQL("""- SELECT tablename, "column", sortkey+ SELECT schemaname, tablename, "column", sortkeyFROM pg_table_def- WHERE schemaname = {schema}+ WHERE schemaname = ANY({schemas})AND tablename = ANY({names})AND sortkey != 0- """).format(schema=sql.Literal(config.schema), names=sql.Literal(tables))+ """).format(schemas=sql.Literal(schemas), names=sql.Literal(bare_tables)))- # Group rows by table so we can classify compound vs interleaved+ # Group rows by display name so we can classify compound vs interleaved# before deciding which columns count as indexed. Negative sortkey# values are the marker Redshift uses for interleaved sortkeys.- rows_by_table: dict[str, list[tuple[str, int]]] = {}- for table_name, column_name, sortkey_value in cursor.fetchall():- rows_by_table.setdefault(table_name, []).append((column_name, sortkey_value))-- for table_name, sortkey_rows in rows_by_table.items():+ rows_by_display: dict[str, list[tuple[str, int]]] = {}+ for schema_name, table_name, column_name, sortkey_value in cursor.fetchall():+ display = display_by_pair.get((schema_name, table_name))+ if display is None:+ continue+ rows_by_display.setdefault(display, []).append((column_name, sortkey_value))++ for display, sortkey_rows in rows_by_display.items():is_interleaved = any(sk < 0 for _, sk in sortkey_rows)if is_interleaved:- result[table_name] = {col for col, _ in sortkey_rows}+ result[display] = {col for col, _ in sortkey_rows}else:- result[table_name] = {col for col, sk in sortkey_rows if sk == 1}+ result[display] = {col for col, sk in sortkey_rows if sk == 1}except Exception as e:structlog.get_logger().warning("Failed to detect sortkeys for Redshift schemas", exc_info=e)return Nonereturn result+ def get_source_metadata(+ self,+ conn: psycopg.Connection,+ config: RedshiftSourceConfig,+ tables: list[str],+ ) -> SourceMetadata:+ """Stamp per-row namespace onto each schema so sync can route without re-querying.++ Redshift namespaces are connection-scoped (one database), so there is no catalog.+ Persisted into `schema_metadata` by `reconcile_schema_metadata` and read back by+ `resolve_source_location` during `build_pipeline`.+ """+ selected_schema = normalize_namespace(config.schema)+ metadata = SourceMetadata()+ for display in tables:+ schema, table = _split_display_name(display, selected_schema)+ metadata.catalog_by_table[display] = None+ metadata.schema_by_table[display] = schema+ metadata.table_name_by_table[display] = table+ return metadata+def get_incremental_filter(self) -> IncrementalFieldFilter:return filter_redshift_incremental_fields@@ -765,11 +923,15 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psyco# (`RedshiftSource.source_for_pipeline`) — keeping the ORM# lookup at the source layer lets the driver stay free of# Django model imports.- table_name = inputs.schema_name+ # Route this row to its own namespace: prefer the per-row `schema_metadata`, fall back to+ # the connection `schema`, then `public`. `response_name` keeps a migrated row on its+ # legacy Delta subdir (via `dwh_storage_key`) so qualifying the name never orphans data.+ location = resolve_source_location(inputs, config_namespace=config.schema, default="public")+ table_name = location.table_nameif not table_name:raise ValueError("Table name is missing")- schema = config.schema+ schema = location.schema or "public"logger = inputs.loggershould_use_incremental_field = inputs.should_use_incremental_fieldincremental_field = inputs.incremental_field@@ -891,10 +1053,8 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoyield table_from_iterator((dict(zip(column_names, row)) for row in rows), arrow_schema)- name = NamingConvention.normalize_identifier(table_name)-return SourceResponse(- name=name,+ name=location.response_name,items=get_rows,primary_keys=primary_keys,partition_count=partition_settings.partition_count if partition_settings else None,diff --git a/posthog/temporal/data_imports/sources/redshift/source.py b/posthog/temporal/data_imports/sources/redshift/source.pyindex 1885c48b37c6..6f0fea0ae399 100644--- a/posthog/temporal/data_imports/sources/redshift/source.py+++ b/posthog/temporal/data_imports/sources/redshift/source.py@@ -113,8 +113,8 @@ class RedshiftSource(SQLSource[RedshiftSourceConfig], SSHTunnelMixin, ValidateDaname="schema",label="Schema",type=SourceFieldInputConfigType.TEXT,- required=True,- placeholder="public",+ required=False,+ placeholder="Leave blank to import all schemas",secret=False,),SourceFieldSSHTunnelConfig(name="ssh_tunnel", label="Use SSH tunnel?"),diff --git a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.pyindex 2c52fc901428..0a221a6beda0 100644--- a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py+++ b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py@@ -312,18 +312,21 @@ class TestGetColumns:cur = MagicMock()cur.__enter__.return_value = curcur.fetchall.return_value = [- ("users", "id", "integer", "NO"),- ("users", "email", "varchar", "YES"),- ("orders", "id", "bigint", "NO"),+ ("public", "users", "id", "integer", "NO"),+ ("public", "users", "email", "varchar", "YES"),+ ("public", "orders", "id", "bigint", "NO"),]conn.cursor.return_value = curresult = impl.get_columns(conn, _make_config(), names=None)+ # Pinned schema → bare table keys (single-namespace fast path).assert result == {"users": [("id", "integer", False), ("email", "varchar", True)],"orders": [("id", "bigint", False)],}+ executed_sql = cur.execute.call_args.args[0]+ assert "table_schema = %(schema)s" in executed_sqldef test_returns_empty_when_no_rows(self, impl):conn = MagicMock()@@ -334,6 +337,43 @@ class TestGetColumns:assert impl.get_columns(conn, _make_config(), names=["foo"]) == {}+ def test_blank_schema_qualifies_and_excludes_system_schemas(self, impl):+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ # Same table name in two schemas must stay distinct.+ cur.fetchall.return_value = [+ ("analytics", "users", "id", "integer", "NO"),+ ("public", "users", "id", "bigint", "NO"),+ ]+ conn.cursor.return_value = cur++ result = impl.get_columns(conn, _make_config(schema=""), names=None)++ assert result == {+ "analytics.users": [("id", "integer", False)],+ "public.users": [("id", "bigint", False)],+ }+ executed_sql, executed_params = cur.execute.call_args.args+ assert "table_schema NOT IN" in executed_sql+ assert "pg_temp_%" in executed_sql+ assert set(executed_params.values()) >= {"pg_catalog", "information_schema", "pg_internal", "pg_automv"}++ def test_blank_schema_with_qualified_names_filters_by_pair(self, impl):+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ cur.fetchall.return_value = [("analytics", "users", "id", "integer", "NO")]+ conn.cursor.return_value = cur++ result = impl.get_columns(conn, _make_config(schema=""), names=["analytics.users"])++ assert result == {"analytics.users": [("id", "integer", False)]}+ executed_sql, executed_params = cur.execute.call_args.args+ assert "table_schema = %(sch_0)s AND table_name = %(tbl_0)s" in executed_sql+ assert executed_params["sch_0"] == "analytics"+ assert executed_params["tbl_0"] == "users"+class TestGetPrimaryKeys:def test_returns_empty_for_no_tables(self, impl):@@ -344,12 +384,37 @@ class TestGetPrimaryKeys:conn = MagicMock()cur = MagicMock()cur.__enter__.return_value = cur- cur.fetchall.return_value = [("users", "id"), ("users", "tenant_id"), ("orders", "id")]+ cur.fetchall.return_value = [+ ("public", "users", "id"),+ ("public", "users", "tenant_id"),+ ("public", "orders", "id"),+ ]conn.cursor.return_value = curresult = impl.get_primary_keys(conn, _make_config(), ["users", "orders", "items"])assert result == {"users": ["id", "tenant_id"], "orders": ["id"], "items": None}+ def test_blank_schema_keeps_same_table_name_distinct(self, impl):+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ cur.fetchall.return_value = [("analytics", "users", "id"), ("public", "users", "uid")]+ conn.cursor.return_value = cur++ result = impl.get_primary_keys(conn, _make_config(schema=""), ["analytics.users", "public.users"])+ assert result == {"analytics.users": ["id"], "public.users": ["uid"]}++ def test_blank_schema_bare_name_degrades_without_crashing(self, impl):+ # Unknown-schema key must not crash the batch query (None can't sort with str schemas).+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ cur.fetchall.return_value = []+ conn.cursor.return_value = cur++ result = impl.get_primary_keys(conn, _make_config(schema=""), ["users"])+ assert result == {"users": None}+def test_swallows_errors_and_returns_none_per_table(self, impl):conn = MagicMock()cur = MagicMock()@@ -361,6 +426,37 @@ class TestGetPrimaryKeys:assert result == {"users": None}+class TestGetRowCounts:+ def test_returns_empty_for_no_tables(self, impl):+ assert impl.get_row_counts(MagicMock(), _make_config(), []) == {}++ def test_blank_schema_counts_tables_and_views_per_namespace(self, impl):+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ # 1: SET statement_timeout, 2: svv_table_info, 3: pg_views, 4: UNION ALL view counts.+ cur.fetchall.side_effect = [+ [("analytics", "events", 500)], # svv_table_info (materialized tables)+ [("public", "events")], # pg_views (views aren't in svv_table_info)+ [("public", "events", 42)], # COUNT(*) per view+ ]+ conn.cursor.return_value = cur++ result = impl.get_row_counts(conn, _make_config(schema=""), ["analytics.events", "public.events"])++ # Same table name in two namespaces stays distinct; the view falls through to COUNT(*).+ assert result == {"analytics.events": 500, "public.events": 42}++ def test_returns_empty_on_exception(self, impl):+ conn = MagicMock()+ cur = MagicMock()+ cur.__enter__.return_value = cur+ cur.execute.side_effect = Exception("denied")+ conn.cursor.return_value = cur++ assert impl.get_row_counts(conn, _make_config(), ["users"]) == {}++class TestGetLeadingIndexColumns:def _make_conn(self, rows):conn = MagicMock()@@ -374,11 +470,11 @@ class TestGetLeadingIndexColumns:assert impl.get_leading_index_columns(MagicMock(), _make_config(), []) == {}def test_returns_leading_compound_sortkey(self, impl):- # tablename, column, sortkey+ # schemaname, tablename, column, sortkeyconn = self._make_conn([- ("messages", "created_at", 1),- ("messages", "user_id", 2),+ ("public", "messages", "created_at", 1),+ ("public", "messages", "user_id", 2),])result = impl.get_leading_index_columns(conn, _make_config(), ["messages"])@@ -387,14 +483,27 @@ class TestGetLeadingIndexColumns:def test_treats_interleaved_sortkey_as_indexed(self, impl):conn = self._make_conn([- ("messages", "a", -1),- ("messages", "b", 2),- ("messages", "c", -3),+ ("public", "messages", "a", -1),+ ("public", "messages", "b", 2),+ ("public", "messages", "c", -3),])result = impl.get_leading_index_columns(conn, _make_config(), ["messages"])assert result == {"messages": {"a", "b", "c"}}+ def test_blank_schema_classifies_sortkeys_per_namespace(self, impl):+ conn = self._make_conn(+ [+ ("analytics", "messages", "created_at", 1),+ ("public", "messages", "a", -1),+ ("public", "messages", "b", 2),+ ]+ )+ result = impl.get_leading_index_columns(+ conn, _make_config(schema=""), ["analytics.messages", "public.messages"]+ )+ assert result == {"analytics.messages": {"created_at"}, "public.messages": {"a", "b"}}+def test_tables_with_no_sortkey_are_empty(self, impl):conn = self._make_conn([])result = impl.get_leading_index_columns(conn, _make_config(), ["messages", "logs"])@@ -409,6 +518,27 @@ class TestGetLeadingIndexColumns:assert impl.get_leading_index_columns(conn, _make_config(), ["t"]) is None+class TestGetSourceMetadata:+ def test_pinned_schema_stamps_config_namespace(self, impl):+ metadata = impl.get_source_metadata(MagicMock(), _make_config(), ["users", "orders"])+ assert metadata.schema_by_table == {"users": "public", "orders": "public"}+ assert metadata.table_name_by_table == {"users": "users", "orders": "orders"}+ assert metadata.catalog_by_table == {"users": None, "orders": None}++ def test_blank_schema_splits_qualified_display_names(self, impl):+ metadata = impl.get_source_metadata(MagicMock(), _make_config(schema=""), ["analytics.users", "public.users"])+ assert metadata.schema_by_table == {"analytics.users": "analytics", "public.users": "public"}+ assert metadata.table_name_by_table == {"analytics.users": "users", "public.users": "users"}+ assert metadata.catalog_by_table == {"analytics.users": None, "public.users": None}++ def test_blank_schema_does_not_guess_namespace_for_bare_name(self, impl):+ # A bare key in multi-schema mode is unexpected (discovery always qualifies); never invent+ # a schema we'd then fail to query — leave it unknown so the resolver self-heals.+ metadata = impl.get_source_metadata(MagicMock(), _make_config(schema=""), ["users"])+ assert metadata.schema_by_table == {"users": None}+ assert metadata.table_name_by_table == {"users": "users"}++# ---------------------------------------------------------------------------# Source wiring — singleton + get_implementation + non-retryable errors# ---------------------------------------------------------------------------@@ -526,3 +656,70 @@ class TestBuildPipeline:impl = RedshiftImplementation()impl.build_pipeline(_make_config(), _make_inputs(), chunk_size_override=4242)mocked_chunk_size.assert_not_called()++ def test_routes_per_row_namespace_from_schema_metadata(self, build_pipeline_mocks, mocker):+ get_meta = mocker.patch.object(+ RedshiftImplementation,+ "get_table_metadata",+ return_value=Table(+ name="users",+ parents=("analytics",),+ columns=[RedshiftColumn(name="id", data_type="integer", nullable=False)],+ type="table",+ ),+ )+ impl = RedshiftImplementation()+ inputs = _make_inputs(+ schema_name="analytics.users",+ schema_metadata={"source_schema": "analytics", "source_table_name": "users"},+ )++ response = impl.build_pipeline(_make_config(schema=""), inputs)++ # Per-row schema + unqualified table threaded into the metadata query.+ assert get_meta.call_args.args[1] == "analytics"+ assert get_meta.call_args.args[2] == "users"+ # Delta subdir is the underscore-normalized qualified name.+ assert response.name == "analytics_users"++ def test_legacy_row_falls_back_to_config_schema(self, build_pipeline_mocks, mocker):+ get_meta = mocker.patch.object(+ RedshiftImplementation,+ "get_table_metadata",+ return_value=Table(+ name="messages",+ parents=("public",),+ columns=[RedshiftColumn(name="id", data_type="integer", nullable=False)],+ type="table",+ ),+ )+ impl = RedshiftImplementation()+ # No schema_metadata, bare table name, pinned config schema.+ response = impl.build_pipeline(_make_config(), _make_inputs(schema_name="messages"))++ assert get_meta.call_args.args[1] == "public"+ assert get_meta.call_args.args[2] == "messages"+ assert response.name == "messages"++ def test_dwh_storage_key_preserves_legacy_delta_path(self, build_pipeline_mocks, mocker):+ mocker.patch.object(+ RedshiftImplementation,+ "get_table_metadata",+ return_value=Table(+ name="users",+ parents=("analytics",),+ columns=[RedshiftColumn(name="id", data_type="integer", nullable=False)],+ type="table",+ ),+ )+ impl = RedshiftImplementation()+ inputs = _make_inputs(+ schema_name="analytics.users",+ schema_metadata={"source_schema": "analytics", "source_table_name": "users"},+ dwh_storage_key="users",+ )++ response = impl.build_pipeline(_make_config(schema=""), inputs)++ # Migrated row keeps its original subdir rather than moving to `analytics_users`.+ assert response.name == "users"diff --git a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py b/products/data_warehouse/backend/test/test_sql_warehouse_migration.pyindex 2fcc70041709..b242f072a845 100644--- a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py+++ b/products/data_warehouse/backend/test/test_sql_warehouse_migration.py@@ -56,15 +56,15 @@ class TestMultiSchemaCapability:@parameterized.expand([- # Postgres and MSSQL have an optional `schema` (qualify today); MySQL/unknown never do.+ # These have an optional `schema` and qualify across namespaces; MySQL/unknown never do.("postgres", ExternalDataSourceType.POSTGRES, True),+ ("redshift", ExternalDataSourceType.REDSHIFT, True),("mssql", ExternalDataSourceType.MSSQL, True),("mysql", ExternalDataSourceType.MYSQL, False),("unknown type", "NotARealSource", False),# Tripwires: these have a *required* `schema` today. If a follow-up makes one optional,# this flips True and forces a conscious update — the gate is no longer dormant for it.("snowflake", ExternalDataSourceType.SNOWFLAKE, False),- ("redshift", ExternalDataSourceType.REDSHIFT, False),])def test_capability_by_source_type(