: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 import for MSSQL source (#62962)
Daniel RCb4df78301c96
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 77511e9d93ec..eb60b9a2e727 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -773,9 +773,9 @@ class MSSQLSourceConfig(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/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.pyindex 8c96e3427bd3..a41522516ea8 100644--- a/posthog/temporal/data_imports/sources/mssql/mssql.py+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py@@ -20,7 +20,6 @@ import structlogfrom 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,@@ -41,8 +40,13 @@ from posthog.temporal.data_imports.sources.common.sql import (format_projected_select_clause,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 MSSQLSourceConfigfrom products.data_warehouse.backend.types import IncrementalFieldType@@ -55,6 +59,47 @@ __all__ = [_IDENTIFIER_QUOTER = BracketIdentifierQuoter()+# Schemas every MSSQL database ships with that never hold user tables. `db_*` covers the+# fixed database roles (db_owner, db_datareader, …), which also surface as schemas.+SYSTEM_MSSQL_SCHEMAS = ("sys", "guest", "INFORMATION_SCHEMA")+++def _non_system_schema_clause(column: str) -> tuple[str, dict[str, str]]:+ """Predicate excluding MSSQL system schemas + the fixed `db_*` database roles.++ `db[_]%` brackets the `_` so it matches literally (it is a LIKE wildcard otherwise);+ `%%` survives pymssql's pyformat paramstyle since a params dict is always passed.+ """+ params = {f"sys_schema_{index}": name for index, name in enumerate(SYSTEM_MSSQL_SCHEMAS)}+ placeholders = ", ".join(f"%(sys_schema_{index})s" for index in range(len(SYSTEM_MSSQL_SCHEMAS)))+ clause = f"{column} NOT IN ({placeholders}) AND {column} NOT LIKE 'db[_]%%'"+ return clause, params+++def _unqualified_table(display: str) -> str:+ """The table part of a qualified `schema.table` (or the whole name if unqualified)."""+ return display.partition(".")[2] or display+++def _filter_qualified_tables(+ all_tables: dict[str, list[tuple[str, str, bool]]], names: list[str]+) -> dict[str, list[tuple[str, str, bool]]]:+ """Keep only the requested tables from a qualified (`schema.table`) discovery.++ Matches a qualified name directly; a legacy bare `table` (a pre-migration row whose+ name isn't qualified yet) matches every discovered `*.table`.+ """+ filtered: dict[str, list[tuple[str, str, bool]]] = {}+ for name in names:+ if name in all_tables:+ filtered[name] = all_tables[name]+ continue+ if "." not in name:+ for display, columns in all_tables.items():+ if display.partition(".")[2] == name:+ filtered[display] = columns+ return filtered+def filter_mssql_incremental_fields(columns: list[tuple[str, str, bool]],@@ -227,28 +272,52 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conconfig: MSSQLSourceConfig,names: list[str] | None,) -> dict[str, list[tuple[str, str, bool]]]:- params: dict[str, Any] = {"schema": config.schema}+ """Discover columns per table.++ With a namespace set, lists that one schema and keys by bare table name (the+ single-schema fast path). With a blank namespace, lists every non-system schema+ and keys by qualified `schema.table` so duplicate table names stay distinct.+ """+ selected_schema = normalize_namespace(config.schema)+ qualify = selected_schema is None++ params: dict[str, Any] = {}+ if selected_schema is not None:+ schema_clause = "table_schema = %(schema)s"+ params["schema"] = selected_schema+ else:+ schema_clause, sys_params = _non_system_schema_clause("table_schema")+ params.update(sys_params)++ # Single-schema names are bare and can be pushed into SQL; multi-schema names arrive+ # qualified (`schema.table`), so they're filtered in Python after discovery.names_filter = ""- if names:+ if names and not qualify:params["names"] = tuple(names)names_filter = "AND table_name IN %(names)s"with conn.cursor(as_dict=False) as cursor:cursor.execute(- "SELECT table_name, column_name, data_type, is_nullable"+ "SELECT table_schema, table_name, column_name, data_type, is_nullable"" FROM information_schema.columns"- f" WHERE table_schema = %(schema)s {names_filter}"- " ORDER BY table_name ASC",+ f" WHERE {schema_clause} {names_filter}"+ " ORDER BY table_schema ASC, table_name ASC",params,)schema_list: dict[str, list[tuple[str, str, bool]]] = collections.defaultdict(list)for row in cursor:- if row:- schema_list[row[0]].append((row[1], row[2], row[3] == "YES"))+ if not row:+ continue+ table_schema, table_name, column_name, data_type, is_nullable = row+ display = f"{table_schema}.{table_name}" if qualify else table_name+ schema_list[display].append((column_name, data_type, is_nullable == "YES"))- return dict(schema_list)+ columns_by_table = dict(schema_list)+ if names and qualify:+ return _filter_qualified_tables(columns_by_table, names)+ return columns_by_tabledef get_primary_keys(self,@@ -260,44 +329,88 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.ConPermission-sensitive — some MSSQL deployments restrict access to`sys.indexes` / `sys.tables`. Swallow and log any failure so- schema discovery keeps working without PKs.+ schema discovery keeps working without PKs. With a blank namespace,+ scans every non-system schema and keys by qualified `schema.table`."""result: dict[str, list[str] | None] = dict.fromkeys(tables)if not tables:return result+ selected_schema = normalize_namespace(config.schema)+ base_query = """+ SELECT s.name AS schema_name, t.name AS table_name, c.name AS column_name+ FROM sys.indexes i+ JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id+ JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id+ JOIN sys.tables t ON i.object_id = t.object_id+ JOIN sys.schemas s ON t.schema_id = s.schema_id+ WHERE i.is_primary_key = 1+ """+ # Bound the scan by table name server-side even in multi-schema mode (where two+ # schemas can share a name → false positives the `if display in result` guard drops).+ params: dict[str, Any] = {}+ if selected_schema is not None:+ schema_clause = "s.name = %(schema)s"+ params["schema"] = selected_schema+ params["names"] = tuple(tables)+ else:+ schema_clause, sys_params = _non_system_schema_clause("s.name")+ params.update(sys_params)+ params["names"] = tuple({_unqualified_table(table) for table in tables})+ query = base_query + f" AND {schema_clause} AND t.name IN %(names)s ORDER BY s.name, t.name, ic.key_ordinal"+try:with conn.cursor(as_dict=False) as cursor:- cursor.execute(- """- SELECT t.name AS table_name, c.name AS column_name- FROM sys.indexes i- JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id- JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id- JOIN sys.tables t ON i.object_id = t.object_id- JOIN sys.schemas s ON t.schema_id = s.schema_id- WHERE i.is_primary_key = 1- AND s.name = %(schema)s- AND t.name IN %(names)s- ORDER BY t.name, ic.key_ordinal- """,- {"schema": config.schema, "names": tuple(tables)},- )+ cursor.execute(query, params)rows = cursor.fetchall()except Exception as e:structlog.get_logger().warning("Failed to detect primary keys for MSSQL schemas", exc_info=e)return resultpks: dict[str, list[str]] = collections.defaultdict(list)- for table_name, column_name in rows or []:- pks[table_name].append(column_name)- for table_name, pk_cols in pks.items():- result[table_name] = pk_cols+ for schema_name, table_name, column_name in rows or []:+ display = f"{schema_name}.{table_name}" if selected_schema is None else table_name+ if display in result:+ pks[display].append(column_name)+ for display, pk_cols in pks.items():+ result[display] = pk_colsreturn resultdef get_incremental_filter(self) -> IncrementalFieldFilter:return filter_mssql_incremental_fields+ def get_source_metadata(+ self,+ conn: pymssql.Connection,+ config: MSSQLSourceConfig,+ tables: list[str],+ ) -> SourceMetadata:+ """Per-table catalog/schema/table-name overrides for the qualified display names.++ `catalog` is the connected database (display only); `schema` is the source+ namespace; `table` is unqualified. Persisted into `schema_metadata` so per-row+ sync routes to the right namespace without re-querying the catalog.+ """+ selected_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 in tables:+ schema: str | None+ if selected_schema is None and "." in display:+ schema, _, table = display.partition(".")+ else:+ schema = selected_schema+ table = display+ catalog_by_table[display] = config.database+ schema_by_table[display] = schema+ table_name_by_table[display] = 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_leading_index_columns(self,conn: pymssql.Connection,@@ -325,27 +438,39 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conresult: dict[str, set[str]] = {table: set() for table in tables}+ selected_schema = normalize_namespace(config.schema)+ base_query = """+ SELECT s.name AS schema_name, t.name AS table_name, c.name AS column_name+ FROM sys.indexes i+ JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id+ JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id+ JOIN sys.tables t ON i.object_id = t.object_id+ JOIN sys.schemas s ON t.schema_id = s.schema_id+ WHERE ic.key_ordinal = 1+ AND ic.is_included_column = 0+ AND i.has_filter = 0+ AND i.is_disabled = 0+ """+ # Bound the scan by table name server-side even in multi-schema mode; the+ # `if display in result` guard drops any same-name false positives.+ params: dict[str, Any] = {}+ if selected_schema is not None:+ schema_clause = "s.name = %(schema)s"+ params["schema"] = selected_schema+ params["names"] = tuple(tables)+ else:+ schema_clause, sys_params = _non_system_schema_clause("s.name")+ params.update(sys_params)+ params["names"] = tuple({_unqualified_table(table) for table in tables})+ query = base_query + f" AND {schema_clause} AND t.name IN %(names)s"+try:with conn.cursor(as_dict=False) as cursor:- cursor.execute(- """- SELECT t.name AS table_name, c.name AS column_name- FROM sys.indexes i- JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id- JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id- JOIN sys.tables t ON i.object_id = t.object_id- JOIN sys.schemas s ON t.schema_id = s.schema_id- WHERE ic.key_ordinal = 1- AND ic.is_included_column = 0- AND i.has_filter = 0- AND i.is_disabled = 0- AND s.name = %(schema)s- AND t.name IN %(names)s- """,- {"schema": config.schema, "names": tuple(tables)},- )- for table_name, column_name in cursor.fetchall() or []:- result.setdefault(table_name, set()).add(column_name)+ cursor.execute(query, params)+ for schema_name, table_name, column_name in cursor.fetchall() or []:+ display = f"{schema_name}.{table_name}" if selected_schema is None else table_name+ if display in result:+ result[display].add(column_name)except Exception as e:structlog.get_logger().warning("Failed to detect leading index columns for MSSQL schemas", exc_info=e)return None@@ -562,11 +687,19 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Con# ------------------------------------------------------------------def build_pipeline(self, config: MSSQLSourceConfig, inputs: SourceInputs) -> SourceResponse:- table_name = inputs.schema_name+ # Resolve the per-row namespace + table from `schema_metadata` (multi-schema) or the+ # config namespace (legacy single-schema). `response_name` keeps the legacy Delta path.+ # No fallback namespace: every real source either has a config schema or carries+ # per-row metadata, so a missing schema means a genuinely broken row — fail loudly+ # rather than guess a namespace and sync the wrong table.+ location = resolve_source_location(inputs, config_namespace=config.schema)+ schema = location.schema+ table_name = location.table_nameif not table_name:raise ValueError("Table name is missing")+ if not schema:+ raise ValueError("Schema is missing")- schema = config.schemalogger = inputs.loggershould_use_incremental_field = inputs.should_use_incremental_fieldincremental_field = inputs.incremental_field@@ -636,10 +769,8 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conyield 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/mssql/source.py b/posthog/temporal/data_imports/sources/mssql/source.pyindex cfd626292130..60a5f9be8b47 100644--- a/posthog/temporal/data_imports/sources/mssql/source.py+++ b/posthog/temporal/data_imports/sources/mssql/source.py@@ -125,7 +125,7 @@ class MSSQLSource(SQLSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatabasename="schema",label="Schema",type=SourceFieldInputConfigType.TEXT,- required=True,+ required=False,placeholder="dbo",secret=False,),diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql_multi_schema.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql_multi_schema.pynew file mode 100644index 000000000000..15fc424387dd--- /dev/null+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql_multi_schema.py@@ -0,0 +1,298 @@+import pytest+from unittest.mock import MagicMock++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.sql import Table+from posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfig+from posthog.temporal.data_imports.sources.mssql.mssql import (+ MSSQLColumn,+ MSSQLImplementation,+ _filter_qualified_tables,+ _non_system_schema_clause,+)+++def _make_config(**overrides) -> MSSQLSourceConfig:+ defaults: dict = {+ "host": "localhost",+ "port": 1433,+ "database": "warehouse",+ "user": "u",+ "password": "p",+ "schema": "dbo",+ }+ defaults.update(overrides)+ return MSSQLSourceConfig.from_dict(defaults)+++def _make_inputs(schema_name: str = "messages", **overrides) -> SourceInputs:+ defaults: dict = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++def _conn_with_rows(rows: list[tuple]) -> tuple[MagicMock, MagicMock]:+ """A mock connection whose single cursor yields `rows` for both iteration and fetchall."""+ cursor = MagicMock()+ cursor.__enter__.return_value = cursor+ cursor.__iter__.return_value = iter(rows)+ cursor.fetchall.return_value = rows+ conn = MagicMock()+ conn.cursor.return_value = cursor+ return conn, cursor+++def impl() -> MSSQLImplementation:+ return MSSQLImplementation()+++# ---------------------------------------------------------------------------+# Pure helpers+# ---------------------------------------------------------------------------+++class TestNonSystemSchemaClause:+ def test_excludes_system_schemas_and_db_roles(self):+ clause, params = _non_system_schema_clause("table_schema")+ assert "table_schema NOT IN" in clause+ # `db[_]%%` brackets the underscore (literal match) and doubles the `%` for pyformat.+ assert "table_schema NOT LIKE 'db[_]%%'" in clause+ assert set(params.values()) == {"sys", "guest", "INFORMATION_SCHEMA"}+++class TestFilterQualifiedTables:+ def test_matches_qualified_name_directly(self):+ all_tables = {"dbo.users": [("id", "int", False)], "sales.users": [("uid", "int", False)]}+ assert _filter_qualified_tables(all_tables, ["dbo.users"]) == {"dbo.users": [("id", "int", False)]}++ def test_legacy_bare_name_matches_every_namespace(self):+ all_tables = {"dbo.users": [("id", "int", False)], "sales.users": [("uid", "int", False)]}+ assert set(_filter_qualified_tables(all_tables, ["users"]).keys()) == {"dbo.users", "sales.users"}++ def test_unknown_name_dropped(self):+ all_tables = {"dbo.users": [("id", "int", False)]}+ assert _filter_qualified_tables(all_tables, ["dbo.missing"]) == {}+++# ---------------------------------------------------------------------------+# Discovery — blank namespace vs single-namespace fast path+# ---------------------------------------------------------------------------+++class TestGetColumns:+ def test_multi_schema_qualifies_and_keeps_duplicates_distinct(self, impl):+ rows = [+ ("dbo", "users", "id", "int", "NO"),+ ("dbo", "users", "email", "varchar", "YES"),+ ("sales", "users", "id", "bigint", "NO"),+ ]+ conn, cursor = _conn_with_rows(rows)+ result = impl.get_columns(conn, _make_config(schema=""), None)+ assert set(result.keys()) == {"dbo.users", "sales.users"}+ assert result["dbo.users"] == [("id", "int", False), ("email", "varchar", True)]+ assert result["sales.users"] == [("id", "bigint", False)]+ sql, params = cursor.execute.call_args.args+ assert "table_schema NOT LIKE 'db[_]%%'" in sql+ assert set(params.values()) == {"sys", "guest", "INFORMATION_SCHEMA"}++ def test_single_schema_keeps_bare_names(self, impl):+ rows = [("dbo", "users", "id", "int", "NO")]+ conn, cursor = _conn_with_rows(rows)+ result = impl.get_columns(conn, _make_config(schema="dbo"), None)+ assert set(result.keys()) == {"users"}+ sql, params = cursor.execute.call_args.args+ assert "table_schema = %(schema)s" in sql+ assert params["schema"] == "dbo"++ def test_single_schema_pushes_names_filter(self, impl):+ rows = [("dbo", "users", "id", "int", "NO")]+ conn, cursor = _conn_with_rows(rows)+ impl.get_columns(conn, _make_config(schema="dbo"), ["users"])+ sql, params = cursor.execute.call_args.args+ assert "table_name IN %(names)s" in sql+ assert params["names"] == ("users",)++ def test_multi_schema_filters_qualified_names_in_python(self, impl):+ rows = [+ ("dbo", "users", "id", "int", "NO"),+ ("sales", "users", "uid", "int", "NO"),+ ]+ conn, cursor = _conn_with_rows(rows)+ result = impl.get_columns(conn, _make_config(schema=""), ["sales.users"])+ assert set(result.keys()) == {"sales.users"}+ # Names aren't pushed into SQL in multi-schema mode (they arrive qualified).+ sql, _params = cursor.execute.call_args.args+ assert "table_name IN" not in sql+++class TestGetSourceMetadata:+ @pytest.mark.parametrize(+ "schema,tables,expected_schema,expected_table",+ [+ (+ "",+ ["dbo.users", "sales.orders"],+ {"dbo.users": "dbo", "sales.orders": "sales"},+ {"dbo.users": "users", "sales.orders": "orders"},+ ),+ ("dbo", ["users"], {"users": "dbo"}, {"users": "users"}),+ ],+ )+ def test_splits_namespace(self, impl, schema, tables, expected_schema, expected_table):+ meta = impl.get_source_metadata(MagicMock(), _make_config(schema=schema), tables)+ assert meta.schema_by_table == expected_schema+ assert meta.table_name_by_table == expected_table+ assert meta.catalog_by_table == dict.fromkeys(tables, "warehouse")+++class TestGetPrimaryKeys:+ def test_multi_schema_keys_by_qualified_name(self, impl):+ rows = [("dbo", "users", "id"), ("sales", "users", "uid")]+ conn, cursor = _conn_with_rows(rows)+ result = impl.get_primary_keys(conn, _make_config(schema=""), ["dbo.users", "sales.users"])+ assert result == {"dbo.users": ["id"], "sales.users": ["uid"]}+ sql, params = cursor.execute.call_args.args+ assert "db[_]" in sql+ # Scan is bounded server-side by the unqualified table names.+ assert "t.name IN %(names)s" in sql+ assert params["names"] == ("users",)++ def test_single_schema_keys_by_bare_name(self, impl):+ rows = [("dbo", "users", "id"), ("dbo", "users", "email")]+ conn, cursor = _conn_with_rows(rows)+ result = impl.get_primary_keys(conn, _make_config(schema="dbo"), ["users"])+ assert result == {"users": ["id", "email"]}+ sql, params = cursor.execute.call_args.args+ assert "s.name = %(schema)s" in sql+ assert params["schema"] == "dbo"+++class TestGetLeadingIndexColumns:+ @pytest.mark.parametrize(+ "schema,tables,rows,expected",+ [+ (+ "",+ ["dbo.users", "sales.orders"],+ [("dbo", "users", "created_at"), ("sales", "orders", "ts")],+ {"dbo.users": {"created_at"}, "sales.orders": {"ts"}},+ ),+ ("dbo", ["users"], [("dbo", "users", "created_at")], {"users": {"created_at"}}),+ ],+ )+ def test_keys_by_namespace(self, impl, schema, tables, rows, expected):+ conn, cursor = _conn_with_rows(rows)+ result = impl.get_leading_index_columns(conn, _make_config(schema=schema), tables)+ assert result == expected+ sql, _params = cursor.execute.call_args.args+ assert "t.name IN %(names)s" in sql+++# ---------------------------------------------------------------------------+# Per-row routing in build_pipeline+# ---------------------------------------------------------------------------+++def routing_mocks(mocker):+ """Capture the (schema, table) the streaming-metadata methods receive, mocking the connection."""+ captured: dict[str, tuple[str, str]] = {}++ def fake_metadata(self, cursor, schema, table_name):+ captured["metadata"] = (schema, table_name)+ return Table(+ name=table_name,+ parents=(schema,),+ columns=[MSSQLColumn(name="id", data_type="int", nullable=False)],+ )++ def fake_pks(self, cursor, schema, table_name):+ captured["pks"] = (schema, table_name)+ return ["id"]++ mocker.patch.object(MSSQLImplementation, "get_table_metadata", fake_metadata)+ mocker.patch.object(MSSQLImplementation, "get_primary_keys_for_table", fake_pks)+ mocker.patch.object(MSSQLImplementation, "get_rows_to_sync", return_value=0)+ mocker.patch.object(MSSQLImplementation, "get_chunk_size", return_value=1000)+ mocker.patch.object(MSSQLImplementation, "get_partition_settings", return_value=None)++ streaming_cursor = MagicMock()+ streaming_cursor.__enter__.return_value = streaming_cursor+ streaming_cursor.description = [("id",)]+ streaming_cursor.fetchmany.return_value = []++ metadata_cursor = MagicMock()+ metadata_cursor.__enter__.return_value = metadata_cursor++ state = {"metadata_done": False}++ def cursor_factory(*args, **kwargs):+ if not state["metadata_done"]:+ state["metadata_done"] = True+ return metadata_cursor+ return streaming_cursor++ mock_connection = MagicMock()+ mock_connection.__enter__.return_value = mock_connection+ mock_connection.cursor.side_effect = cursor_factory++ mocker.patch(+ "posthog.temporal.data_imports.sources.mssql.mssql.pymssql.connect",+ return_value=mock_connection,+ )+ return captured+++class TestBuildPipelineRouting:+ def test_routes_per_row_namespace_from_metadata(self, routing_mocks):+ inputs = _make_inputs(+ schema_name="analytics.users",+ schema_metadata={"source_schema": "analytics", "source_table_name": "users"},+ )+ response = MSSQLImplementation().build_pipeline(_make_config(schema=""), inputs)+ assert routing_mocks["metadata"] == ("analytics", "users")+ assert routing_mocks["pks"] == ("analytics", "users")+ # S3 subdir is the single-underscore normalization of the dotted display name.+ assert response.name == "analytics_users"++ def test_self_heals_dotted_name_without_metadata(self, routing_mocks):+ inputs = _make_inputs(schema_name="analytics.users")+ MSSQLImplementation().build_pipeline(_make_config(schema=""), inputs)+ assert routing_mocks["metadata"] == ("analytics", "users")++ def test_preserves_legacy_storage_key(self, routing_mocks):+ # A migrated single-schema row keeps its old Delta subdir via dwh_storage_key.+ inputs = _make_inputs(+ schema_name="analytics.users",+ schema_metadata={"source_schema": "analytics", "source_table_name": "users"},+ dwh_storage_key="users",+ )+ response = MSSQLImplementation().build_pipeline(_make_config(schema=""), inputs)+ assert response.name == "users"++ def test_legacy_single_schema_fallback(self, routing_mocks):+ inputs = _make_inputs(schema_name="messages")+ response = MSSQLImplementation().build_pipeline(_make_config(schema="dbo"), inputs)+ assert routing_mocks["metadata"] == ("dbo", "messages")+ assert response.name == "messages"++ def test_raises_when_namespace_indeterminate(self, routing_mocks):+ # Blank config schema, no metadata, bare name — nothing resolves a namespace, so the+ # row is broken: fail loudly rather than guess.+ inputs = _make_inputs(schema_name="messages")+ with pytest.raises(ValueError, match="Schema is missing"):+ MSSQLImplementation().build_pipeline(_make_config(schema=""), inputs)diff --git a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py b/products/data_warehouse/backend/test/test_sql_warehouse_migration.pyindex 2f10e3368fc7..2fcc70041709 100644--- a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py+++ b/products/data_warehouse/backend/test/test_sql_warehouse_migration.py@@ -56,13 +56,13 @@ class TestMultiSchemaCapability:@parameterized.expand([- # Postgres has an optional `schema` (qualifies today); MySQL/unknown never do.+ # Postgres and MSSQL have an optional `schema` (qualify today); MySQL/unknown never do.("postgres", ExternalDataSourceType.POSTGRES, 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.- ("mssql", ExternalDataSourceType.MSSQL, False),("snowflake", ExternalDataSourceType.SNOWFLAKE, False),("redshift", ExternalDataSourceType.REDSHIFT, False),]