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.

feat(data-warehouse): add multi-schema warehouse import for Snowflake (#62961)

Daniel RC53f5037f6968
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 38cf7c3d1558..b8081dad5da3 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -1222,9 +1222,9 @@ class SnowflakeSourceConfig(config.Config):
database: str
warehouse: str
auth_type: SnowflakeAuthTypeConfig
- schema: str
connection_string: str | None = None
role: str | None = None
+ schema: str | None = None
@config.config
diff --git a/posthog/temporal/data_imports/sources/snowflake/snowflake.py b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
index cd0c7d8a6f7d..b4316cd115a5 100644
--- a/posthog/temporal/data_imports/sources/snowflake/snowflake.py
+++ b/posthog/temporal/data_imports/sources/snowflake/snowflake.py
@@ -22,7 +22,6 @@ from cryptography.hazmat.primitives import serialization
from structlog.types import FilteringBoundLogger
from posthog.exceptions_capture import capture_exception
-from posthog.temporal.data_imports.naming_convention import NamingConvention
from posthog.temporal.data_imports.pipelines.helpers import (
incremental_type_to_initial_value,
incremental_type_to_operator,
@@ -33,8 +32,9 @@ from posthog.temporal.data_imports.sources.common.sql import (
compute_projected_columns,
format_projected_select_clause,
)
-from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation
+from posthog.temporal.data_imports.sources.common.sql.implementation import SourceMetadata, SQLSourceImplementation
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_location
from posthog.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig
from products.data_warehouse.backend.types import IncrementalFieldType
@@ -65,6 +65,34 @@ def filter_snowflake_incremental_fields(
_SNOWFLAKE_IDENTIFIER_QUOTER = AnsiIdentifierQuoter()
+# Snowflake exposes one metadata schema per database; everything else is user data.
+SNOWFLAKE_SYSTEM_SCHEMA = "INFORMATION_SCHEMA"
+
+
+def _split_display_name(display_name: str, default_schema: Optional[str]) -> tuple[Optional[str], str]:
+ """Split a `schema.table` display name into `(schema, table)`.
+
+ Multi-schema discovery qualifies every table as `schema.table`; a single-schema
+ source keeps bare table names and falls back to the configured schema. The dotted
+ form mirrors `resolve_source_location`'s self-heal so listing keys and per-row
+ routing agree.
+ """
+ if "." in display_name:
+ schema, _, table = display_name.partition(".")
+ return (normalize_namespace(schema) or default_schema), table
+ return default_schema, display_name
+
+
+def _display_by_pair(tables: list[str], default_schema: Optional[str]) -> dict[tuple[str, str], str]:
+ """Map each resolvable `(schema, table)` back to its display name, dropping unresolved rows."""
+ pairs: dict[tuple[str, str], str] = {}
+ for display_name in tables:
+ schema, table = _split_display_name(display_name, default_schema)
+ if schema is None:
+ continue
+ pairs[(schema, table)] = display_name
+ return pairs
+
def _build_query(
database: str,
@@ -164,9 +192,10 @@ class SnowflakeImplementation(
disk, matching the streaming-side helper that the pre-refactor
code used.
- Uses `config.schema` as the session schema. All listing queries
- use fully qualified `information_schema.<table>` references so
- the session schema does not affect their results.
+ Uses `config.schema` as the session schema when set; a blank schema
+ (multi-schema import) leaves the session schema unset. All listing and
+ sync queries fully qualify their references so the session schema does
+ not affect their results.
"""
auth_connect_args: dict[str, Any] = {}
@@ -195,7 +224,9 @@ class SnowflakeImplementation(
account=config.account_id,
warehouse=config.warehouse,
database=config.database,
- schema=config.schema,
+ # A blank schema (multi-schema import) must reach the connector as None, not "" —
+ # `schema=""` would try `USE SCHEMA ""`, an invalid identifier, and fail at connect time.
+ schema=normalize_namespace(config.schema),
role=config.role,
**auth_connect_args,
) as connection:
@@ -211,26 +242,49 @@ class SnowflakeImplementation(
config: SnowflakeSourceConfig,
names: list[str] | None,
) -> dict[str, list[tuple[str, str, bool]]]:
+ selected_schema = normalize_namespace(config.schema)
+ qualify = selected_schema is None
+
with conn.cursor() as cursor:
if cursor is None:
raise Exception("Can't create cursor to Snowflake")
- cursor.execute(
- "SELECT table_name, column_name, data_type, is_nullable"
- " FROM information_schema.columns"
- " WHERE table_schema = %(schema)s"
- " ORDER BY table_name ASC",
- {"schema": config.schema},
- )
+ if selected_schema is not None:
+ cursor.execute(
+ "SELECT table_schema, table_name, column_name, data_type, is_nullable"
+ " FROM information_schema.columns"
+ " WHERE table_schema = %(schema)s"
+ " ORDER BY table_schema ASC, table_name ASC",
+ {"schema": selected_schema},
+ )
+ else:
+ cursor.execute(
+ "SELECT table_schema, table_name, column_name, data_type, is_nullable"
+ " FROM information_schema.columns"
+ " WHERE table_schema != %(system_schema)s"
+ " ORDER BY table_schema ASC, table_name ASC",
+ {"system_schema": SNOWFLAKE_SYSTEM_SCHEMA},
+ )
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_name = f"{table_schema}.{table_name}" if qualify else table_name
+ schema_list[display_name].append((column_name, data_type, is_nullable == "YES"))
if names is not None:
- names_set = set(names)
- schema_list = collections.defaultdict(list, {k: v for k, v in schema_list.items() if k in names_set})
+ # Match qualified (`schema.table`) and bare (`table`) names — a row requested by its
+ # qualified name can still map to a bare discovery key (or vice versa) mid-migration.
+ available = dict(schema_list)
+ filtered: dict[str, list[tuple[str, str, bool]]] = {}
+ for name in names:
+ if name in available:
+ filtered[name] = available[name]
+ elif "." in name:
+ _schema, _, unqualified = name.partition(".")
+ if unqualified in available:
+ filtered[name] = available[unqualified]
+ return filtered
return dict(schema_list)
@@ -240,41 +294,60 @@ class SnowflakeImplementation(
config: SnowflakeSourceConfig,
tables: list[str],
) -> dict[str, list[str] | None]:
- """Detect primary keys for all tables by iterating SHOW PRIMARY KEYS.
+ """Detect primary keys for the given (possibly multi-schema) tables.
+
+ Batches one `SHOW PRIMARY KEYS IN SCHEMA` per distinct namespace rather
+ than one per table, so a blank-namespace discovery over a wide catalog
+ stays bounded by schema count instead of table count.
- Permission-sensitive — some Snowflake roles can't see
- catalog-level PK metadata. Swallow and log per-table failures so
- schema discovery keeps working without PKs.
+ Permission-sensitive — some Snowflake roles can't see catalog-level PK
+ metadata. Swallow and log per-schema failures so schema discovery keeps
+ working without PKs.
"""
result: dict[str, list[str] | None] = dict.fromkeys(tables)
if not tables:
return result
+ display_by_pair = _display_by_pair(tables, normalize_namespace(config.schema))
+
try:
with conn.cursor() as cursor:
if cursor is None:
raise Exception("Can't create cursor to Snowflake")
- for tbl in tables:
+ for schema in sorted({schema for schema, _table in display_by_pair}):
try:
cursor.execute(
- "SHOW PRIMARY KEYS IN IDENTIFIER(%s)",
- (f"{config.database}.{config.schema}.{tbl}",),
+ f"SHOW PRIMARY KEYS IN SCHEMA {_SNOWFLAKE_IDENTIFIER_QUOTER.quote_qualified(config.database, schema)}"
+ )
+ table_index = next(
+ (i for i, row in enumerate(cursor.description) if row.name == "table_name"), -1
)
-
column_index = next(
(i for i, row in enumerate(cursor.description) if row.name == "column_name"), -1
)
- if column_index == -1:
+ sequence_index = next(
+ (i for i, row in enumerate(cursor.description) if row.name == "key_sequence"), -1
+ )
+ if table_index == -1 or column_index == -1:
continue
- keys = [row[column_index] for row in cursor]
- if keys:
- result[tbl] = keys
+ keys_by_table: dict[str, list[tuple[int, str]]] = collections.defaultdict(list)
+ for row in cursor:
+ sequence = row[sequence_index] if sequence_index != -1 else 0
+ keys_by_table[row[table_index]].append((sequence, row[column_index]))
+
+ for table, ordered in keys_by_table.items():
+ display_name = display_by_pair.get((schema, table))
+ if display_name is None:
+ continue
+ keys = [column for _sequence, column in sorted(ordered, key=lambda pair: pair[0])]
+ if keys:
+ result[display_name] = keys
except Exception as e:
structlog.get_logger().warning(
- "Failed to detect primary keys for Snowflake table",
- table=tbl,
+ "Failed to detect primary keys for Snowflake schema",
+ schema=schema,
exc_info=e,
)
continue
@@ -300,35 +373,72 @@ class SnowflakeImplementation(
if not tables:
return {}
- result: dict[str, set[str]] = {table: set() for table in tables}
+ display_by_pair = _display_by_pair(tables, normalize_namespace(config.schema))
+ result: dict[str, set[str]] = {display_name: set() for display_name in tables}
+ if not display_by_pair:
+ return result
+
+ schemas = {schema for schema, _table in display_by_pair}
+ table_names = {table for _schema, table in display_by_pair}
try:
with conn.cursor() as cursor:
if cursor is None:
raise Exception("Can't create cursor to Snowflake")
- placeholders = ",".join(["%s"] * len(tables))
+ schema_placeholders = ",".join(["%s"] * len(schemas))
+ table_placeholders = ",".join(["%s"] * len(table_names))
cursor.execute(
f"""
- SELECT TABLE_NAME, CLUSTERING_KEY
+ SELECT TABLE_SCHEMA, TABLE_NAME, CLUSTERING_KEY
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_CATALOG = %s
- AND TABLE_SCHEMA = %s
- AND TABLE_NAME IN ({placeholders})
+ AND TABLE_SCHEMA IN ({schema_placeholders})
+ AND TABLE_NAME IN ({table_placeholders})
""",
- (config.database, config.schema, *tables),
+ (config.database, *schemas, *table_names),
)
- for table_name, clustering_key in cursor:
+ for table_schema, table_name, clustering_key in cursor:
+ display_name = display_by_pair.get((table_schema, table_name))
+ if display_name is None:
+ continue
leading = _parse_clustering_key_leading_column(clustering_key)
if leading is not None:
- result.setdefault(table_name, set()).add(leading)
+ result[display_name].add(leading)
except Exception as e:
structlog.get_logger().warning("Failed to detect clustering keys for Snowflake schemas", exc_info=e)
return None
return result
+ def get_source_metadata(
+ self,
+ conn: snowflake.connector.SnowflakeConnection,
+ config: SnowflakeSourceConfig,
+ tables: list[str],
+ ) -> SourceMetadata:
+ """Stamp catalog/schema/table per discovered table so per-row routing can pin a namespace.
+
+ The catalog is the connection's database (constant, display-only); the
+ schema and unqualified table come from the `schema.table` display name,
+ falling back to the configured schema for a single-schema source.
+ """
+ default_schema = normalize_namespace(config.schema)
+ catalog_by_table: dict[str, str | None] = {}
+ schema_by_table: dict[str, str | None] = {}
+ table_name_by_table: dict[str, str | None] = {}
+ for display_name in tables:
+ schema, table = _split_display_name(display_name, default_schema)
+ catalog_by_table[display_name] = config.database
+ schema_by_table[display_name] = schema
+ table_name_by_table[display_name] = table
+ return SourceMetadata(
+ catalog_by_table=catalog_by_table,
+ schema_by_table=schema_by_table,
+ table_name_by_table=table_name_by_table,
+ )
+
def get_incremental_filter(self) -> IncrementalFieldFilter:
return filter_snowflake_incremental_fields
@@ -394,12 +504,18 @@ class SnowflakeImplementation(
# ------------------------------------------------------------------
def build_pipeline(self, config: SnowflakeSourceConfig, inputs: SourceInputs) -> SourceResponse:
- table_name = inputs.schema_name
+ # Per-row routing: a multi-schema row pins its own namespace via `schema_metadata`,
+ # a legacy single-schema row falls back to `config.schema`. The database is fixed
+ # per connection. `response_name` preserves the legacy Delta subdir (`dwh_storage_key`).
+ location = resolve_source_location(inputs, config_namespace=config.schema)
+ table_name = location.table_name
+ schema = location.schema
if not table_name:
raise ValueError("Table name is missing")
+ if not schema:
+ raise ValueError("Schema is missing")
database = config.database
- schema = config.schema
logger = inputs.logger
should_use_incremental_field = inputs.should_use_incremental_field
incremental_field = inputs.incremental_field
@@ -455,6 +571,6 @@ class SnowflakeImplementation(
# The pipeline normalizes timestamps to `us` downstream regardless.
yield from streaming_cursor.fetch_arrow_batches(force_microsecond_precision=True)
- name = NamingConvention.normalize_identifier(table_name)
-
- return SourceResponse(name=name, items=get_rows, primary_keys=primary_keys, rows_to_sync=rows_to_sync)
+ return SourceResponse(
+ name=location.response_name, items=get_rows, primary_keys=primary_keys, rows_to_sync=rows_to_sync
+ )
diff --git a/posthog/temporal/data_imports/sources/snowflake/source.py b/posthog/temporal/data_imports/sources/snowflake/source.py
index 1c1143ed3c3b..1ddb681230be 100644
--- a/posthog/temporal/data_imports/sources/snowflake/source.py
+++ b/posthog/temporal/data_imports/sources/snowflake/source.py
@@ -160,10 +160,10 @@ class SnowflakeSource(SQLSource[SnowflakeSourceConfig]):
),
SourceFieldInputConfig(
name="schema",
- label="Schema",
+ label="Schema (optional)",
type=SourceFieldInputConfigType.TEXT,
- required=True,
- placeholder="public",
+ required=False,
+ placeholder="leave blank to list tables from all schemas",
secret=False,
),
],
diff --git a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
index 187da0c8034e..1f140d5c01d6 100644
--- a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
+++ b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py
@@ -11,6 +11,7 @@ from posthog.temporal.data_imports.sources.snowflake.snowflake import (
SnowflakeImplementation,
_build_query,
_parse_clustering_key_leading_column,
+ _split_display_name,
filter_snowflake_incremental_fields,
)
@@ -109,6 +110,23 @@ def test_parse_clustering_key_leading_column(clustering_key, expected):
assert _parse_clustering_key_leading_column(clustering_key) == expected
+ "display_name,default_schema,expected",
+ [
+ # Bare name uses the configured schema (single-schema source).
+ ("users", "PUBLIC", ("PUBLIC", "users")),
+ ("users", None, (None, "users")),
+ # Qualified name splits; the dotted schema wins over the default.
+ ("analytics.users", "PUBLIC", ("analytics", "users")),
+ ("analytics.users", None, ("analytics", "users")),
+ # Whitespace-only dotted prefix normalizes away and falls back to the default.
+ (" .users", "PUBLIC", ("PUBLIC", "users")),
+ ],
+)
+def test_split_display_name(display_name, default_schema, expected):
+ assert _split_display_name(display_name, default_schema) == expected
+
+
class TestFilterIncrementalFields:
@pytest.mark.parametrize(
"data_type,expected",
@@ -234,6 +252,22 @@ class TestConnect:
# Sanity-check it's a DER-encoded PKCS8 blob the connector can parse.
serialization.load_der_private_key(kwargs["private_key"], password=None, backend=default_backend())
+ @pytest.mark.parametrize("blank", ["", " ", None])
+ def test_blank_schema_reaches_connector_as_none(self, impl, blank):
+ # `schema=""` would make the connector try `USE SCHEMA ""` (invalid) — normalize to None.
+ with patch("snowflake.connector.connect") as mock_connect:
+ mock_connect.return_value.__enter__.return_value = MagicMock()
+ with impl.connect(_make_config(schema=blank)):
+ pass
+ assert mock_connect.call_args.kwargs["schema"] is None
+
+ def test_set_schema_reaches_connector(self, impl):
+ with patch("snowflake.connector.connect") as mock_connect:
+ mock_connect.return_value.__enter__.return_value = MagicMock()
+ with impl.connect(_make_config(schema="SALES")):
+ pass
+ assert mock_connect.call_args.kwargs["schema"] == "SALES"
+
# ---------------------------------------------------------------------------
# Listing methods — they take a pre-opened connection
@@ -249,46 +283,122 @@ def _conn_with_cursor(cursor: MagicMock) -> MagicMock:
class TestGetColumns:
def test_groups_columns_by_table(self, impl, cursor):
cursor.fetchall.return_value = [
- ("users", "id", "NUMBER", "NO"),
- ("users", "email", "VARCHAR", "YES"),
- ("orders", "id", "NUMBER", "NO"),
+ ("PUBLIC", "users", "id", "NUMBER", "NO"),
+ ("PUBLIC", "users", "email", "VARCHAR", "YES"),
+ ("PUBLIC", "orders", "id", "NUMBER", "NO"),
]
conn = _conn_with_cursor(cursor)
result = impl.get_columns(conn, _make_config(), names=None)
+ # Single-schema source keeps bare table names.
assert set(result.keys()) == {"users", "orders"}
assert ("id", "NUMBER", False) in result["users"]
assert ("email", "VARCHAR", True) in result["users"]
def test_filters_by_names(self, impl, cursor):
cursor.fetchall.return_value = [
- ("users", "id", "NUMBER", "NO"),
- ("orders", "id", "NUMBER", "NO"),
+ ("PUBLIC", "users", "id", "NUMBER", "NO"),
+ ("PUBLIC", "orders", "id", "NUMBER", "NO"),
]
conn = _conn_with_cursor(cursor)
result = impl.get_columns(conn, _make_config(), names=["users"])
assert list(result.keys()) == ["users"]
+ def test_single_schema_filters_by_configured_schema(self, impl, cursor):
+ cursor.fetchall.return_value = []
+ conn = _conn_with_cursor(cursor)
+ impl.get_columns(conn, _make_config(schema="SALES"), names=None)
+ sql = cursor.execute.call_args.args[0]
+ params = cursor.execute.call_args.args[1]
+ assert "table_schema = %(schema)s" in sql
+ assert params == {"schema": "SALES"}
+
+ @pytest.mark.parametrize("blank", ["", " ", None])
+ def test_blank_schema_discovers_all_namespaces_qualified(self, impl, cursor, blank):
+ cursor.fetchall.return_value = [
+ ("analytics", "users", "id", "NUMBER", "NO"),
+ ("sales", "users", "id", "NUMBER", "NO"),
+ ("sales", "orders", "id", "NUMBER", "NO"),
+ ]
+ conn = _conn_with_cursor(cursor)
+ result = impl.get_columns(conn, _make_config(schema=blank), names=None)
+ # Same table name in two schemas must stay distinct and qualified.
+ assert set(result.keys()) == {"analytics.users", "sales.users", "sales.orders"}
+ sql = cursor.execute.call_args.args[0]
+ assert "table_schema != %(system_schema)s" in sql
+ assert cursor.execute.call_args.args[1] == {"system_schema": "INFORMATION_SCHEMA"}
+
+ def test_blank_schema_filters_by_qualified_names(self, impl, cursor):
+ cursor.fetchall.return_value = [
+ ("analytics", "users", "id", "NUMBER", "NO"),
+ ("sales", "users", "id", "NUMBER", "NO"),
+ ]
+ conn = _conn_with_cursor(cursor)
+ result = impl.get_columns(conn, _make_config(schema=""), names=["sales.users"])
+ assert list(result.keys()) == ["sales.users"]
+
+ def test_qualified_name_falls_back_to_bare_discovery_key(self, impl, cursor):
+ # Mid-migration a row may be requested qualified while a configured-schema source still
+ # discovers it bare — keep the requested (qualified) key, mapped to the bare columns.
+ cursor.fetchall.return_value = [("PUBLIC", "users", "id", "NUMBER", "NO")]
+ conn = _conn_with_cursor(cursor)
+ result = impl.get_columns(conn, _make_config(schema="PUBLIC"), names=["PUBLIC.users"])
+ assert result == {"PUBLIC.users": [("id", "NUMBER", False)]}
+
+
+def _pk_description() -> list[MagicMock]:
+ """`SHOW PRIMARY KEYS IN SCHEMA` description: table_name, column_name, key_sequence at 0,1,2."""
+ cols = []
+ for col_name in ("table_name", "column_name", "key_sequence"):
+ desc = MagicMock()
+ desc.name = col_name
+ cols.append(desc)
+ return cols
+
class TestGetPrimaryKeys:
def test_extracts_pk_column_names(self, impl, cursor):
- cursor.description = [MagicMock(name="column_name")]
- cursor.description[0].name = "column_name"
- cursor.__iter__.return_value = iter([("id",)])
+ cursor.description = _pk_description()
+ cursor.__iter__.return_value = iter([("t", "id", 1)])
conn = _conn_with_cursor(cursor)
out = impl.get_primary_keys(conn, _make_config(), tables=["t"])
assert out["t"] == ["id"]
+ # Batched per schema, not per table.
+ sql = cursor.execute.call_args.args[0]
+ assert "SHOW PRIMARY KEYS IN SCHEMA" in sql
+ assert '"DB"."PUBLIC"' in sql
+
+ def test_orders_composite_key_by_sequence(self, impl, cursor):
+ cursor.description = _pk_description()
+ cursor.__iter__.return_value = iter([("t", "b", 2), ("t", "a", 1)])
+ conn = _conn_with_cursor(cursor)
+ out = impl.get_primary_keys(conn, _make_config(), tables=["t"])
+ assert out["t"] == ["a", "b"]
- def test_swallows_per_table_failure(self, impl, cursor):
- # Per-table failure leaves the None placeholder so schema discovery keeps going
+ def test_swallows_per_schema_failure(self, impl, cursor):
+ # Per-schema failure leaves the None placeholder so schema discovery keeps going
cursor.execute.side_effect = Exception("permission denied")
conn = _conn_with_cursor(cursor)
out = impl.get_primary_keys(conn, _make_config(), tables=["t"])
assert out == {"t": None}
+ def test_multi_schema_routes_keys_to_qualified_display_names(self, impl, cursor):
+ cursor.description = _pk_description()
+ # One SHOW per distinct schema, in sorted order: analytics, then sales.
+ cursor.__iter__.side_effect = [
+ iter([("users", "id", 1)]),
+ iter([("users", "uuid", 1), ("orders", "id", 1)]),
+ ]
+ conn = _conn_with_cursor(cursor)
+ out = impl.get_primary_keys(
+ conn, _make_config(schema=""), tables=["analytics.users", "sales.users", "sales.orders"]
+ )
+ assert out == {"analytics.users": ["id"], "sales.users": ["uuid"], "sales.orders": ["id"]}
+ assert cursor.execute.call_count == 2
+
class TestGetLeadingIndexColumns:
def test_returns_leading_column_set_per_table(self, impl, cursor):
- cursor.__iter__.return_value = iter([("users", "LINEAR(created_at)"), ("orders", None)])
+ cursor.__iter__.return_value = iter([("PUBLIC", "users", "LINEAR(created_at)"), ("PUBLIC", "orders", None)])
conn = _conn_with_cursor(cursor)
out = impl.get_leading_index_columns(conn, _make_config(), tables=["users", "orders"])
assert out is not None
@@ -301,6 +411,34 @@ class TestGetLeadingIndexColumns:
conn = _conn_with_cursor(cursor)
assert impl.get_leading_index_columns(conn, _make_config(), tables=["t"]) is None
+ def test_multi_schema_maps_clustering_keys_to_qualified_names(self, impl, cursor):
+ # Same table name across schemas must not cross-contaminate clustering keys.
+ cursor.__iter__.return_value = iter(
+ [
+ ("analytics", "users", "LINEAR(created_at)"),
+ ("sales", "users", "LINEAR(signed_up)"),
+ ]
+ )
+ conn = _conn_with_cursor(cursor)
+ out = impl.get_leading_index_columns(conn, _make_config(schema=""), tables=["analytics.users", "sales.users"])
+ assert out is not None
+ assert out["analytics.users"] == {"CREATED_AT"}
+ assert out["sales.users"] == {"SIGNED_UP"}
+
+
+class TestGetSourceMetadata:
+ def test_single_schema_pins_configured_namespace(self, impl):
+ meta = impl.get_source_metadata(MagicMock(), _make_config(schema="PUBLIC"), tables=["users"])
+ assert meta.catalog_by_table == {"users": "DB"}
+ assert meta.schema_by_table == {"users": "PUBLIC"}
+ assert meta.table_name_by_table == {"users": "users"}
+
+ def test_multi_schema_splits_qualified_display_names(self, impl):
+ meta = impl.get_source_metadata(MagicMock(), _make_config(schema=""), tables=["analytics.users", "sales.users"])
+ assert meta.catalog_by_table == {"analytics.users": "DB", "sales.users": "DB"}
+ assert meta.schema_by_table == {"analytics.users": "analytics", "sales.users": "sales"}
+ assert meta.table_name_by_table == {"analytics.users": "users", "sales.users": "users"}
+
# ---------------------------------------------------------------------------
# Per-cursor metadata methods
@@ -366,8 +504,40 @@ class TestBuildPipeline:
with patch("snowflake.connector.connect", return_value=mock_connection):
response = impl.build_pipeline(_make_config(), _make_inputs(schema_name="messages"))
+ assert response.name == "messages"
assert response.primary_keys == ["id"]
assert response.rows_to_sync == 5
assert list(response.items()) == [b"batch-1", b"batch-2"]
# Pin a single timestamp unit so mixed ns/us batches don't break pyarrow assembly.
streaming_cursor.fetch_arrow_batches.assert_called_once_with(force_microsecond_precision=True)
+
+ def test_multi_schema_row_routes_to_qualified_namespace(self, impl):
+ # A blank-namespace source pins each row's schema via the dotted schema_name.
+ metadata_cursor = MagicMock()
+ metadata_cursor.__enter__.return_value = metadata_cursor
+ desc = MagicMock()
+ desc.name = "column_name"
+ metadata_cursor.description = [desc]
+ metadata_cursor.__iter__.return_value = iter([("id",)])
+ metadata_cursor.fetchone.return_value = (3,)
+
+ streaming_cursor = MagicMock()
+ streaming_cursor.__enter__.return_value = streaming_cursor
+ streaming_cursor.fetch_arrow_batches.return_value = iter([b"batch-1"])
+
+ cursors = iter([metadata_cursor, streaming_cursor])
+ mock_connection = MagicMock()
+ mock_connection.__enter__.return_value = mock_connection
+ mock_connection.cursor.side_effect = lambda: next(cursors)
+
+ with patch("snowflake.connector.connect", return_value=mock_connection):
+ response = impl.build_pipeline(_make_config(schema=""), _make_inputs(schema_name="analytics.users"))
+ # Delta subdir keeps the qualified, normalized name so cross-schema duplicates stay distinct.
+ assert response.name == "analytics_users"
+ assert list(response.items()) == [b"batch-1"]
+
+ # PK probe and streaming query both target DB.analytics.users (resolved schema, unqualified table).
+ pk_param = metadata_cursor.execute.call_args_list[0].args[1]
+ assert pk_param == ("DB.analytics.users",)
+ stream_param = streaming_cursor.execute.call_args.args[1]
+ assert stream_param == ("DB.analytics.users",)
diff --git a/posthog/temporal/data_imports/sources/tests/test_generated_configs.py b/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
index 212cb9467b19..4c25fc7e2988 100644
--- a/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
+++ b/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
@@ -1,3 +1,5 @@
+import pytest
+
from posthog.temporal.data_imports.sources.generated_configs import (
BigQuerySourceConfig,
ChargebeeSourceConfig,
@@ -315,6 +317,30 @@ def test_snowflake_config():
assert config.auth_type.passphrase == ""
+ "schema_override,expected_schema",
+ [
+ # A blank schema flips the source into multi-schema discovery; the config stores the raw
+ # value (absent/""/whitespace) verbatim — drivers normalize it via `normalize_namespace`.
+ ({}, None),
+ ({"schema": ""}, ""),
+ ({"schema": " "}, " "),
+ ],
+)
+def test_snowflake_config_without_schema(schema_override, expected_schema):
+ config = SnowflakeSourceConfig.from_dict(
+ {
+ "account_id": "account_id",
+ "database": "database",
+ "warehouse": "warehouse",
+ "auth_type": {"selection": "password", "user": "user", "password": "password"},
+ **schema_override,
+ }
+ )
+
+ assert config.schema == expected_schema
+
+
def test_stripe_config():
config = StripeSourceConfig.from_dict(
{"auth_method": {"selection": "api_key", "stripe_secret_key": "api_key"}, "stripe_account_id": "acct_id"}
diff --git a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py b/products/data_warehouse/backend/test/test_sql_warehouse_migration.py
index b242f072a845..ee0575be5079 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,13 @@ class TestMultiSchemaCapability:
@parameterized.expand(
[
- # These have an optional `schema` and qualify across namespaces; MySQL/unknown never do.
+ # Postgres, Snowflake, and MSSQL have an optional `schema` (qualify today); MySQL/unknown never do.
("postgres", ExternalDataSourceType.POSTGRES, True),
+ ("snowflake", ExternalDataSourceType.SNOWFLAKE, 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),
]
)
def test_capability_by_source_type(