: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): multi-schema warehouse import foundation (#62160)
Daniel RC361973752260
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/typings.py b/posthog/temporal/data_imports/pipelines/pipeline/typings.pyindex 03027f0e250f..013b0bf98a16 100644--- a/posthog/temporal/data_imports/pipelines/pipeline/typings.py+++ b/posthog/temporal/data_imports/pipelines/pipeline/typings.py@@ -57,6 +57,9 @@ class SourceInputs:logger: FilteringBoundLoggerreset_pipeline: boolenabled_columns: Optional[list[str]] = None+ # Multi-schema import context, read by `resolve_source_location`.+ schema_metadata: Optional[dict[str, Any]] = None+ dwh_storage_key: Optional[str] = Noneclass PipelineResult(TypedDict):diff --git a/posthog/temporal/data_imports/sources/common/sql/location.py b/posthog/temporal/data_imports/sources/common/sql/location.pynew file mode 100644index 000000000000..68431dc3c890--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/location.py@@ -0,0 +1,77 @@+"""Shared per-row routing for multi-schema SQL warehouse import.++`resolve_source_location` is the single source-agnostic router every SQL driver's `build_pipeline`+delegates to, so the Postgres routing logic isn't re-derived per source.+"""++from __future__ import annotations++from typing import NamedTuple, Optional++from posthog.temporal.data_imports.naming_convention import NamingConvention+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+++class ResolvedSourceLocation(NamedTuple):+ """Where a single warehouse-import row reads from + the Delta subdir it writes to.++ `schema` is the per-row namespace; the database is fixed per connection (use `config.database`).+ """++ schema: Optional[str]+ table_name: str+ response_name: str+++def normalize_namespace(value: object) -> Optional[str]:+ """Empty / whitespace-only namespace means "all namespaces" — never an empty predicate."""+ if not isinstance(value, str):+ return None+ stripped = value.strip()+ return stripped or None+++def _str_or_none(value: object) -> Optional[str]:+ return value if isinstance(value, str) else None+++def fill_missing_from_dotted_name(+ schema: Optional[str], table: Optional[str], display_name: str+) -> tuple[Optional[str], Optional[str]]:+ """Fill a missing `schema`/`table` by splitting a dotted `display_name` (`analytics.users`).++ Shared by the resolver and the migration so the rule can't drift between them.+ """+ if (not schema or not table) and "." in display_name:+ inferred_schema, _, inferred_table = display_name.partition(".")+ schema = schema or normalize_namespace(inferred_schema)+ table = table or inferred_table or None+ return schema, table+++def resolve_source_location(+ inputs: SourceInputs,+ *,+ config_namespace: Optional[str],+ default: Optional[str] = None,+) -> ResolvedSourceLocation:+ """Resolve `(schema, table_name, response_name)` for one warehouse-import row.++ Namespace + table priority: per-schema `schema_metadata` → dotted `schema_name` self-heal →+ `config_namespace` → `default`. `response_name` (the Delta subdir) uses `dwh_storage_key` when+ present, so a migrated row keeps its legacy path — no S3 rewrite, no orphaned data.+ """+ metadata = inputs.schema_metadata if isinstance(inputs.schema_metadata, dict) else {}+ source_schema = normalize_namespace(metadata.get("source_schema"))+ source_table_name = _str_or_none(metadata.get("source_table_name"))+ source_schema, source_table_name = fill_missing_from_dotted_name(+ source_schema, source_table_name, inputs.schema_name+ )++ schema = source_schema or normalize_namespace(config_namespace) or default+ table_name = source_table_name or inputs.schema_name++ storage_key = inputs.dwh_storage_key if isinstance(inputs.dwh_storage_key, str) and inputs.dwh_storage_key else None+ response_name = NamingConvention.normalize_identifier(storage_key or inputs.schema_name)++ return ResolvedSourceLocation(schema=schema, table_name=table_name, response_name=response_name)diff --git a/posthog/temporal/data_imports/sources/common/sql/tests/test_location.py b/posthog/temporal/data_imports/sources/common/sql/tests/test_location.pynew file mode 100644index 000000000000..7de20879b1c4--- /dev/null+++ b/posthog/temporal/data_imports/sources/common/sql/tests/test_location.py@@ -0,0 +1,158 @@+from typing import Any++from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.sql.location import (+ fill_missing_from_dotted_name,+ normalize_namespace,+ resolve_source_location,+)+++def _source_inputs(+ schema_name: str = "users",+ *,+ source_schema: str | None = None,+ source_table_name: str | None = None,+ **overrides: Any,+) -> SourceInputs:+ # Mirror how a real schema row stashes the SQL location keys inside the generic `schema_metadata`.+ metadata: dict[str, Any] = {}+ if source_schema is not None:+ metadata["source_schema"] = source_schema+ if source_table_name is not None:+ metadata["source_table_name"] = source_table_name+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-1",+ "source_id": "source-1",+ "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-1",+ "logger": MagicMock(),+ "reset_pipeline": False,+ "schema_metadata": metadata or None,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestResolveSourceLocation:+ @parameterized.expand(+ [+ # (name, schema_name, source_schema, source_table_name, config_namespace, default, exp_schema, exp_table)+ ("metadata wins over config", "users", "analytics", "users", "public", "public", "analytics", "users"),+ ("dotted name self-heals", "analytics.users", None, None, None, None, "analytics", "users"),+ ("config namespace fallback", "users", None, None, "dbo", "public", "dbo", "users"),+ ("default fallback when config blank", "users", None, None, "", "public", "public", "users"),+ ("empty metadata + dotted self-heals", "sales.orders", "", "", None, None, "sales", "orders"),+ ("whitespace config normalizes to default", "users", None, None, " ", "public", "public", "users"),+ ("all blank yields None schema", "users", "", "", "", None, None, "users"),+ ]+ )+ def test_schema_and_table_resolution(+ self,+ _name: str,+ schema_name: str,+ source_schema: str | None,+ source_table_name: str | None,+ config_namespace: str | None,+ default: str | None,+ exp_schema: str | None,+ exp_table: str,+ ) -> None:+ inputs = _source_inputs(+ schema_name=schema_name,+ source_schema=source_schema,+ source_table_name=source_table_name,+ )+ location = resolve_source_location(inputs, config_namespace=config_namespace, default=default)+ assert location.schema == exp_schema+ assert location.table_name == exp_table++ def test_metadata_takes_precedence_over_dotted_name(self) -> None:+ # A pinned location routes the query; the dotted display name is not re-split.+ inputs = _source_inputs(schema_name="analytics.users", source_schema="reporting", source_table_name="events")+ location = resolve_source_location(inputs, config_namespace="public")+ assert location.schema == "reporting"+ assert location.table_name == "events"++ def test_never_emits_empty_string_schema(self) -> None:+ inputs = _source_inputs(schema_name="users", source_schema="", source_table_name="")+ location = resolve_source_location(inputs, config_namespace="", default=None)+ assert location.schema is None # driver treats None as "all namespaces", never `WHERE schema = ''`++ def test_response_name_derived_from_schema_name_when_no_storage_key(self) -> None:+ inputs = _source_inputs(schema_name="analytics.users")+ location = resolve_source_location(inputs, config_namespace=None)+ assert location.response_name == "analytics_users"++ def test_storage_key_preserves_legacy_delta_path(self) -> None:+ # Migrated row keeps the legacy Delta subdir (`users`, not `public_users`) or its data is orphaned.+ inputs = _source_inputs(schema_name="public.users", dwh_storage_key="users")+ location = resolve_source_location(inputs, config_namespace=None)+ assert location.response_name == "users"+ assert location.schema == "public"+ assert location.table_name == "users"++ def test_storage_key_is_normalized(self) -> None:+ inputs = _source_inputs(schema_name="public.My Table", dwh_storage_key="My Table")+ location = resolve_source_location(inputs, config_namespace=None)+ assert location.response_name == "my_table"++ def test_cross_namespace_duplicates_stay_distinct(self) -> None:+ analytics = resolve_source_location(_source_inputs(schema_name="analytics.users"), config_namespace=None)+ sales = resolve_source_location(_source_inputs(schema_name="sales.users"), config_namespace=None)+ assert (analytics.schema, analytics.table_name) == ("analytics", "users")+ assert (sales.schema, sales.table_name) == ("sales", "users")+ assert analytics.response_name != sales.response_name+ assert {analytics.response_name, sales.response_name} == {"analytics_users", "sales_users"}++ def test_single_schema_legacy_row_is_byte_identical(self) -> None:+ # No metadata, no storage key, non-dotted name: resolves exactly like the pre-multi-schema path.+ inputs = _source_inputs(schema_name="users")+ location = resolve_source_location(inputs, config_namespace="public", default="public")+ assert location == ("public", "users", "users")+++class TestSelfHealHelpers:+ @parameterized.expand(+ [+ ("value", "public", "public"),+ ("trims", " dbo ", "dbo"),+ ("empty to none", "", None),+ ("whitespace to none", " ", None),+ ("non-string to none", None, None),+ ]+ )+ def test_normalize_namespace(self, _name: str, value: str | None, expected: str | None) -> None:+ assert normalize_namespace(value) == expected++ @parameterized.expand(+ [+ # (name, schema, table, display_name, exp_schema, exp_table)+ ("both present, no heal", "analytics", "users", "analytics.users", "analytics", "users"),+ ("missing both, dotted heals", None, None, "analytics.users", "analytics", "users"),+ ("missing schema only", None, "users", "sales.orders", "sales", "users"),+ ("missing table only", "reporting", None, "x.events", "reporting", "events"),+ ("empty schema treated as missing", "", None, "sales.orders", "sales", "orders"),+ ("not dotted, no heal", None, None, "users", None, None),+ ]+ )+ def test_fill_missing_from_dotted_name(+ self,+ _name: str,+ schema: str | None,+ table: str | None,+ display_name: str,+ exp_schema: str | None,+ exp_table: str | None,+ ) -> None:+ assert fill_missing_from_dotted_name(schema, table, display_name) == (exp_schema, exp_table)diff --git a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py b/posthog/temporal/data_imports/workflow_activities/import_data_sync.pyindex 2c9f7f3e129d..16e500792e72 100644--- a/posthog/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/posthog/temporal/data_imports/workflow_activities/import_data_sync.py@@ -161,6 +161,8 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelinjob_id=inputs.run_id,reset_pipeline=reset_pipeline,enabled_columns=schema.enabled_columns,+ schema_metadata=schema.schema_metadata,+ dwh_storage_key=schema.dwh_storage_key,)new_source = SourceRegistry.get_source(source_type)diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex afcae7b20211..6200c54209b7 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -86,10 +86,15 @@ from products.data_warehouse.backend.external_data_source.webhooks import (from products.data_warehouse.backend.models.revenue_analytics_config import ExternalDataSourceRevenueAnalyticsConfigfrom products.data_warehouse.backend.postgres_helpers import get_postgres_source_location, reconcile_postgres_schemasfrom products.data_warehouse.backend.postgres_warehouse_migration import (- apply_on_schema_clear as apply_postgres_warehouse_schema_clear_migration,- detect_schema_clear_transition as detect_postgres_schema_clear_transition,reconcile_refresh_name_substitutions as reconcile_postgres_refresh_name_substitutions,)+from products.data_warehouse.backend.sql_warehouse_migration import (+ apply_on_refresh as apply_sql_warehouse_refresh_migration,+ apply_on_schema_clear as apply_sql_warehouse_schema_clear_migration,+ detect_schema_clear_transition as detect_sql_schema_clear_transition,+ is_multi_schema_capable_sql_source,+ source_namespace_is_blank,+)from products.data_warehouse.backend.types import DataWarehouseManagedViewSetKind, ExternalDataSourceTypefrom products.revenue_analytics.backend.joins import ensure_person_join, remove_person_joinfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -877,14 +882,14 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerif not is_valid:raise ValidationError(f"Invalid source config: {', '.join(errors)}")- # Postgres: clearing `job_inputs.schema` migrates legacy rows before the config change lands.- old_schema = detect_postgres_schema_clear_transition(+ # Clearing a multi-schema source's namespace migrates legacy rows to qualified naming.+ old_schema = detect_sql_schema_clear_transition(source_type=instance.source_type,existing_job_inputs=existing_job_inputs,incoming_job_inputs=incoming_job_inputs,)if old_schema is not None:- apply_postgres_warehouse_schema_clear_migration(instance, old_schema)+ apply_sql_warehouse_schema_clear_migration(instance, old_schema)source_config: Config = source.parse_config(new_job_inputs)validated_data["job_inputs"] = source_config.to_dict()@@ -1782,7 +1787,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif instance.is_direct_postgres and connection_metadata != instance.connection_metadata:instance.connection_metadata = connection_metadatainstance.save(update_fields=["connection_metadata", "updated_at"])- # Postgres-only: dedupe + migrate legacy rows so sync_old_schemas doesn't create duplicates.+ # Migrate/dedupe legacy rows before sync_old_schemas; non-Postgres only once namespace cleared.name_substitutions: dict[str, str] = {}if instance.source_type == ExternalDataSourceType.POSTGRES:name_substitutions = reconcile_postgres_refresh_name_substitutions(@@ -1790,6 +1795,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource_schemas=schemas,team_id=self.team_id,)+ elif source_namespace_is_blank(instance) and is_multi_schema_capable_sql_source(instance.source_type):+ name_substitutions = apply_sql_warehouse_refresh_migration(source=instance, team_id=self.team_id)if name_substitutions:schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}diff --git a/products/data_warehouse/backend/postgres_helpers.py b/products/data_warehouse/backend/postgres_helpers.pyindex 5906e7c9041d..97e2a6f32073 100644--- a/products/data_warehouse/backend/postgres_helpers.py+++ b/products/data_warehouse/backend/postgres_helpers.py@@ -15,6 +15,7 @@ from django.db.models import Qimport structlogfrom posthog.temporal.data_imports.sources.common.schema import SourceSchema+from posthog.temporal.data_imports.sources.common.sql.location import normalize_namespacefrom posthog.temporal.data_imports.sources.common.sql.metadata import (extract_available_column_names,sql_schema_metadata as _sql_schema_metadata,@@ -52,13 +53,6 @@ type PostgresDwhColumns = dict[str, dict[str, Any]]type PostgresSourceLocation = tuple[str | None, str, str]-def _normalize_default_schema(default_schema: str | None) -> str | None:- if not isinstance(default_schema, str):- return None- normalized = default_schema.strip()- return normalized or None--def postgres_schema_metadata(columns: list[tuple[str, str, bool]],foreign_keys: list[tuple[str, str, str]] | None = None,@@ -108,7 +102,7 @@ def get_postgres_source_location(source_catalog = schema_metadata.get("source_catalog") if isinstance(schema_metadata, dict) else Nonesource_schema = schema_metadata.get("source_schema") if isinstance(schema_metadata, dict) else Nonesource_table_name = schema_metadata.get("source_table_name") if isinstance(schema_metadata, dict) else None- normalized_default = _normalize_default_schema(default_schema)+ normalized_default = normalize_namespace(default_schema)if isinstance(source_schema, str) and isinstance(source_table_name, str):return source_catalog if isinstance(source_catalog, str) else None, source_schema, source_table_namediff --git a/products/data_warehouse/backend/postgres_warehouse_migration.py b/products/data_warehouse/backend/postgres_warehouse_migration.pyindex ae2d12f96447..51307712df82 100644--- a/products/data_warehouse/backend/postgres_warehouse_migration.py+++ b/products/data_warehouse/backend/postgres_warehouse_migration.py@@ -1,126 +1,19 @@-"""Migrate pre-PR Postgres warehouse rows to qualified naming without re-syncing.+"""Postgres-specific refresh reconciliation.-Legacy rows are renamed in place (`example_table` → `public.example_table`) and tagged with-`dwh_storage_key=<original_name>` so `pipeline_sync` and `source_for_pipeline` keep writing/reading-at the legacy Delta path — no S3 rewrite, no orphaned data.--Triggered from PATCH (schema cleared) and refresh_schemas (idempotent reconcile).+The source-agnostic migration lives in `sql_warehouse_migration.py`; this keeps only the Postgres ++direct-query plumbing — combining the rename helper with the shared `apply_on_refresh` into one+substitution dict for `sync_old_schemas_with_new_schemas`."""from __future__ import annotations-from typing import Any-from posthog.temporal.data_imports.sources.common.schema import SourceSchema-from products.data_warehouse.backend.postgres_helpers import (- _normalize_default_schema,- rename_postgres_schemas_to_match_source_schemas,-)+from products.data_warehouse.backend.postgres_helpers import rename_postgres_schemas_to_match_source_schemas+from products.data_warehouse.backend.sql_warehouse_migration import apply_on_refreshfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSource-def _qualify_legacy_row(- row: Any,- *,- target_source_schema: str,- target_source_table_name: str | None = None,- duplicate_to_drop: Any | None = None,-) -> str | None:- """Rename `row` to qualified form, stash `dwh_storage_key`, optionally drop a duplicate.- Returns the new name, or None if a duplicate with its own data blocked the rename.- """- sync_type_config = row.sync_type_config or {}- existing_metadata_raw = sync_type_config.get("schema_metadata")- existing_metadata: dict[str, Any] = dict(existing_metadata_raw) if isinstance(existing_metadata_raw, dict) else {}-- effective_source_schema = existing_metadata.get("source_schema") or target_source_schema- effective_source_table_name = existing_metadata.get("source_table_name") or target_source_table_name or row.name- qualified_name = f"{effective_source_schema}.{effective_source_table_name}"-- # Don't soft-delete a duplicate that already owns synced data; let the user resolve manually.- if duplicate_to_drop is not None and duplicate_to_drop.id != row.id:- if duplicate_to_drop.table_id is not None:- return None- duplicate_to_drop.soft_delete()-- merged_metadata: dict[str, Any] = dict(existing_metadata)- merged_metadata.setdefault("source_catalog", existing_metadata.get("source_catalog"))- merged_metadata["source_schema"] = effective_source_schema- merged_metadata["source_table_name"] = effective_source_table_name- merged_metadata.setdefault("columns", [])- merged_metadata.setdefault("foreign_keys", [])-- new_sync_type_config: dict[str, Any] = {**sync_type_config, "schema_metadata": merged_metadata}- if "dwh_storage_key" not in sync_type_config:- new_sync_type_config["dwh_storage_key"] = row.name-- row.name = qualified_name- row.sync_type_config = new_sync_type_config- row.save(update_fields=["name", "sync_type_config", "updated_at"])- return qualified_name---def apply_on_schema_clear(source: ExternalDataSource, old_schema: str) -> None:- """Pin legacy rows to the OLD schema before the next refresh sees `default_schema=None` and- misroutes them to `"public"`.- """- from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema-- rows = list(ExternalDataSchema.objects.filter(team_id=source.team_id, source_id=source.id, deleted=False))- rows_by_name = {row.name: row for row in rows}-- for row in rows:- if "." in row.name:- continue- existing_metadata = (row.sync_type_config or {}).get("schema_metadata") or {}- effective_schema = existing_metadata.get("source_schema") if isinstance(existing_metadata, dict) else None- effective_table = existing_metadata.get("source_table_name") if isinstance(existing_metadata, dict) else None- qualified_name = f"{effective_schema or old_schema}.{effective_table or row.name}"- _qualify_legacy_row(- row,- target_source_schema=old_schema,- duplicate_to_drop=rows_by_name.get(qualified_name),- )---def detect_schema_clear_transition(- *,- source_type: str,- existing_job_inputs: dict[str, Any],- incoming_job_inputs: dict[str, Any],-) -> str | None:- """Return the old schema if this PATCH is clearing Postgres `job_inputs.schema`, else None."""- if source_type != "Postgres":- return None- if "schema" not in incoming_job_inputs:- return None- incoming = incoming_job_inputs.get("schema")- if isinstance(incoming, str) and incoming.strip():- return None- existing = existing_job_inputs.get("schema")- if not (isinstance(existing, str) and existing.strip()):- return None- return existing.strip()---def _extract_source_location_from_row(row: Any) -> tuple[str | None, str | None]:- """`(source_schema, source_table_name)` — metadata first, dotted name fallback, else `(None, None)`."""- metadata = (row.sync_type_config or {}).get("schema_metadata")- source_schema: str | None = None- source_table_name: str | None = None- if isinstance(metadata, dict):- if isinstance(metadata.get("source_schema"), str):- source_schema = metadata["source_schema"]- if isinstance(metadata.get("source_table_name"), str):- source_table_name = metadata["source_table_name"]- if (not source_schema or not source_table_name) and "." in row.name:- inferred_schema, _, inferred_table = row.name.partition(".")- source_schema = source_schema or inferred_schema or None- source_table_name = source_table_name or inferred_table or None- return source_schema, source_table_name--def reconcile_refresh_name_substitutions(*,source: ExternalDataSource,@@ -151,71 +44,3 @@ def reconcile_refresh_name_substitutions(name_substitutions = {k: v for k, v in name_substitutions.items() if k != v}return name_substitutions---def apply_on_refresh(*, source: ExternalDataSource, team_id: int) -> dict[str, str]:- """Idempotent reconcile — qualifies legacy rows, drops refresh-created duplicates.-- Matches legacy → qualified by `source_table_name` (not full location) because a legacy row- falls back to `"public"` when `job_inputs.schema` is blank, missing the actual schema.- Returns `{old_name: new_name}` for callers feeding `sync_old_schemas_with_new_schemas`.- """- from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema-- rows = list(- ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related("table")- )-- qualified_rows_by_table_name: dict[str, list[tuple[str, ExternalDataSchema]]] = {}- unqualified_rows: list[ExternalDataSchema] = []- for row in rows:- if "." in row.name:- source_schema, source_table_name = _extract_source_location_from_row(row)- if source_schema and source_table_name:- qualified_rows_by_table_name.setdefault(source_table_name, []).append((source_schema, row))- else:- unqualified_rows.append(row)-- default_schema = _normalize_default_schema((source.job_inputs or {}).get("schema"))- name_substitutions: dict[str, str] = {}-- for legacy in unqualified_rows:- legacy_metadata_source_schema, legacy_metadata_source_table_name = _extract_source_location_from_row(legacy)- qualified_matches = qualified_rows_by_table_name.get(legacy.name, [])-- # Disambiguate multi-match using legacy's own pinned metadata.- if len(qualified_matches) > 1 and legacy_metadata_source_schema is not None:- filtered = [m for m in qualified_matches if m[0] == legacy_metadata_source_schema]- if len(filtered) == 1:- qualified_matches = filtered-- target_source_schema: str | None- target_source_table_name: str | None = legacy_metadata_source_table_name- duplicate: Any | None = None-- if len(qualified_matches) == 1:- target_source_schema, duplicate = qualified_matches[0]- elif len(qualified_matches) > 1:- # Ambiguous — let the user resolve via the UI.- continue- elif legacy_metadata_source_schema is not None:- target_source_schema = legacy_metadata_source_schema- elif default_schema is not None:- target_source_schema = default_schema- else:- continue-- original_name = legacy.name- new_name = _qualify_legacy_row(- legacy,- target_source_schema=target_source_schema,- target_source_table_name=target_source_table_name,- duplicate_to_drop=duplicate,- )- if new_name is None:- continue- if duplicate is not None and duplicate.id != legacy.id:- name_substitutions[duplicate.name] = new_name- name_substitutions[original_name] = new_name-- return name_substitutionsdiff --git a/products/data_warehouse/backend/sql_warehouse_migration.py b/products/data_warehouse/backend/sql_warehouse_migration.pynew file mode 100644index 000000000000..969dfa9f5d4a--- /dev/null+++ b/products/data_warehouse/backend/sql_warehouse_migration.py@@ -0,0 +1,215 @@+"""Migrate pre-multi-schema SQL warehouse rows to qualified naming without re-syncing.++Legacy rows are renamed in place (`users` → `public.users`) and tagged `dwh_storage_key=<original>`+so sync keeps reading/writing the legacy Delta path. Source-agnostic — gated only by the namespace+field being blank-able; Postgres direct-query plumbing stays in `postgres_warehouse_migration.py`.+"""++from __future__ import annotations++from typing import Any++from posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.sql.base import SQLSource+from posthog.temporal.data_imports.sources.common.sql.location import fill_missing_from_dotted_name, normalize_namespace++from products.data_warehouse.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+++def _source_has_optional_schema_field(source: Any) -> bool:+ """True when `source` is a SQL source whose `schema` namespace field is optional (blank-able)."""+ if not isinstance(source, SQLSource):+ return False+ try:+ fields = source.get_source_config.fields+ except (AttributeError, TypeError):+ return False+ return any(+ getattr(field, "name", None) == "schema" and getattr(field, "required", True) is False for field in fields+ )+++def is_multi_schema_capable_sql_source(source_type: ExternalDataSourceType | str) -> bool:+ """True when the registered source for `source_type` has an optional (blank-able) `schema` field.++ The optional field is the opt-in marker (Postgres today). Resolved via `get_all_sources`, not the+ test-mockable `get_source`, so the gate stays config-driven.+ """+ try:+ resolved_type = ExternalDataSourceType(source_type)+ except ValueError:+ return False+ return _source_has_optional_schema_field(SourceRegistry.get_all_sources().get(resolved_type))+++def source_namespace_is_blank(source: ExternalDataSource) -> bool:+ """True when the source's `job_inputs.schema` is unset — i.e. it's in multi-schema mode."""+ schema = (source.job_inputs or {}).get("schema")+ return not (isinstance(schema, str) and schema.strip())+++def _qualify_legacy_row(+ row: Any,+ *,+ target_source_schema: str,+ target_source_table_name: str | None = None,+ duplicate_to_drop: Any | None = None,+) -> str | None:+ """Rename `row` to qualified form, stash `dwh_storage_key`, optionally drop a duplicate.+ Returns the new name, or None if a duplicate with its own data blocked the rename.+ """+ sync_type_config = row.sync_type_config or {}+ existing_metadata_raw = sync_type_config.get("schema_metadata")+ existing_metadata: dict[str, Any] = dict(existing_metadata_raw) if isinstance(existing_metadata_raw, dict) else {}++ effective_source_schema = existing_metadata.get("source_schema") or target_source_schema+ effective_source_table_name = existing_metadata.get("source_table_name") or target_source_table_name or row.name+ qualified_name = f"{effective_source_schema}.{effective_source_table_name}"++ # Don't soft-delete a duplicate that already owns synced data; let the user resolve manually.+ if duplicate_to_drop is not None and duplicate_to_drop.id != row.id:+ if duplicate_to_drop.table_id is not None:+ return None+ duplicate_to_drop.soft_delete()++ merged_metadata: dict[str, Any] = dict(existing_metadata)+ merged_metadata.setdefault("source_catalog", existing_metadata.get("source_catalog"))+ merged_metadata["source_schema"] = effective_source_schema+ merged_metadata["source_table_name"] = effective_source_table_name+ merged_metadata.setdefault("columns", [])+ merged_metadata.setdefault("foreign_keys", [])++ new_sync_type_config: dict[str, Any] = {**sync_type_config, "schema_metadata": merged_metadata}+ if "dwh_storage_key" not in sync_type_config:+ new_sync_type_config["dwh_storage_key"] = row.name++ row.name = qualified_name+ row.sync_type_config = new_sync_type_config+ row.save(update_fields=["name", "sync_type_config", "updated_at"])+ return qualified_name+++def apply_on_schema_clear(source: ExternalDataSource, old_schema: str) -> None:+ """Pin legacy rows to the OLD schema before the next refresh sees `default_schema=None` and+ misroutes them to `"public"`.+ """+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema++ rows = list(ExternalDataSchema.objects.filter(team_id=source.team_id, source_id=source.id, deleted=False))+ rows_by_name = {row.name: row for row in rows}++ for row in rows:+ if "." in row.name:+ continue+ existing_metadata = (row.sync_type_config or {}).get("schema_metadata") or {}+ effective_schema = existing_metadata.get("source_schema") if isinstance(existing_metadata, dict) else None+ effective_table = existing_metadata.get("source_table_name") if isinstance(existing_metadata, dict) else None+ qualified_name = f"{effective_schema or old_schema}.{effective_table or row.name}"+ _qualify_legacy_row(+ row,+ target_source_schema=old_schema,+ duplicate_to_drop=rows_by_name.get(qualified_name),+ )+++def detect_schema_clear_transition(+ *,+ source_type: ExternalDataSourceType | str,+ existing_job_inputs: dict[str, Any],+ incoming_job_inputs: dict[str, Any],+) -> str | None:+ """Return the old schema if this PATCH clears a multi-schema SQL source's `job_inputs.schema`."""+ if "schema" not in incoming_job_inputs:+ return None+ incoming = incoming_job_inputs.get("schema")+ if isinstance(incoming, str) and incoming.strip():+ return None+ existing = existing_job_inputs.get("schema")+ if not (isinstance(existing, str) and existing.strip()):+ return None+ # Cheap dict/string checks first; only pay the registry/config capability lookup on a real clear.+ if not is_multi_schema_capable_sql_source(source_type):+ return None+ return existing.strip()+++def _extract_source_location_from_row(row: Any) -> tuple[str | None, str | None]:+ """`(source_schema, source_table_name)` — metadata first, dotted name fallback, else `(None, None)`."""+ metadata = (row.sync_type_config or {}).get("schema_metadata")+ source_schema: str | None = None+ source_table_name: str | None = None+ if isinstance(metadata, dict):+ if isinstance(metadata.get("source_schema"), str):+ source_schema = metadata["source_schema"]+ if isinstance(metadata.get("source_table_name"), str):+ source_table_name = metadata["source_table_name"]+ return fill_missing_from_dotted_name(source_schema, source_table_name, row.name)+++def apply_on_refresh(*, source: ExternalDataSource, team_id: int) -> dict[str, str]:+ """Idempotent reconcile — qualifies legacy rows, drops refresh-created duplicates.++ Matches legacy → qualified by `source_table_name` (not full location) because a legacy row+ falls back to `"public"` when `job_inputs.schema` is blank, missing the actual schema.+ Returns `{old_name: new_name}` for callers feeding `sync_old_schemas_with_new_schemas`.+ """+ from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema++ rows = list(+ ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related("table")+ )++ qualified_rows_by_table_name: dict[str, list[tuple[str, ExternalDataSchema]]] = {}+ unqualified_rows: list[ExternalDataSchema] = []+ for row in rows:+ if "." in row.name:+ source_schema, source_table_name = _extract_source_location_from_row(row)+ if source_schema and source_table_name:+ qualified_rows_by_table_name.setdefault(source_table_name, []).append((source_schema, row))+ else:+ unqualified_rows.append(row)++ default_schema = normalize_namespace((source.job_inputs or {}).get("schema"))+ name_substitutions: dict[str, str] = {}++ for legacy in unqualified_rows:+ legacy_metadata_source_schema, legacy_metadata_source_table_name = _extract_source_location_from_row(legacy)+ qualified_matches = qualified_rows_by_table_name.get(legacy.name, [])++ # Disambiguate multi-match using legacy's own pinned metadata.+ if len(qualified_matches) > 1 and legacy_metadata_source_schema is not None:+ filtered = [m for m in qualified_matches if m[0] == legacy_metadata_source_schema]+ if len(filtered) == 1:+ qualified_matches = filtered++ target_source_schema: str | None+ target_source_table_name: str | None = legacy_metadata_source_table_name+ duplicate: Any | None = None++ if len(qualified_matches) == 1:+ target_source_schema, duplicate = qualified_matches[0]+ elif len(qualified_matches) > 1:+ # Ambiguous — let the user resolve via the UI.+ continue+ elif legacy_metadata_source_schema is not None:+ target_source_schema = legacy_metadata_source_schema+ elif default_schema is not None:+ target_source_schema = default_schema+ else:+ continue++ original_name = legacy.name+ new_name = _qualify_legacy_row(+ legacy,+ target_source_schema=target_source_schema,+ target_source_table_name=target_source_table_name,+ duplicate_to_drop=duplicate,+ )+ if new_name is None:+ continue+ if duplicate is not None and duplicate.id != legacy.id:+ name_substitutions[duplicate.name] = new_name+ name_substitutions[original_name] = new_name++ return name_substitutionsdiff --git a/products/data_warehouse/backend/test/test_sql_warehouse_migration.py b/products/data_warehouse/backend/test/test_sql_warehouse_migration.pynew file mode 100644index 000000000000..2f10e3368fc7--- /dev/null+++ b/products/data_warehouse/backend/test/test_sql_warehouse_migration.py@@ -0,0 +1,216 @@+"""Source-agnostic warehouse migration: capability detection + qualify-in-place on non-Postgres rows.++Postgres end-to-end lives in `api/test/test_postgres_warehouse_migration.py`.+"""++import uuid+from types import SimpleNamespace+from typing import Any, cast++from posthog.test.base import BaseTest+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.temporal.data_imports.sources.common.sql.base import SQLSource++from products.data_warehouse.backend.sql_warehouse_migration import (+ _source_has_optional_schema_field,+ apply_on_refresh,+ apply_on_schema_clear,+ detect_schema_clear_transition,+ is_multi_schema_capable_sql_source,+ source_namespace_is_blank,+)+from products.data_warehouse.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource+++def _sql_source_stub(*, schema_required: bool | None, has_schema_field: bool = True) -> Any:+ source = MagicMock(spec=SQLSource)+ fields = [SimpleNamespace(name="host", required=True)]+ if has_schema_field:+ fields.append(SimpleNamespace(name="schema", required=schema_required))+ source.get_source_config = SimpleNamespace(fields=fields)+ return source+++class TestMultiSchemaCapability:+ @parameterized.expand(+ [+ ("optional schema field", False, True, True),+ ("required schema field", True, True, False),+ ("no schema field", None, False, False),+ ]+ )+ def test_optional_schema_field_introspection(+ self, _name: str, schema_required: bool | None, has_schema_field: bool, expected: bool+ ) -> None:+ source = _sql_source_stub(schema_required=schema_required, has_schema_field=has_schema_field)+ assert _source_has_optional_schema_field(source) is expected++ def test_non_sql_source_is_not_capable(self) -> None:+ assert _source_has_optional_schema_field(object()) is False+ assert _source_has_optional_schema_field(None) is False++ @parameterized.expand(+ [+ # Postgres has an optional `schema` (qualifies today); MySQL/unknown never do.+ ("postgres", ExternalDataSourceType.POSTGRES, 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),+ ]+ )+ def test_capability_by_source_type(+ self, _name: str, source_type: ExternalDataSourceType | str, expected: bool+ ) -> None:+ assert is_multi_schema_capable_sql_source(source_type) is expected++ @parameterized.expand(+ [+ ("set", {"schema": "dbo"}, False),+ ("blank", {"schema": ""}, True),+ ("whitespace", {"schema": " "}, True),+ ("missing", {}, True),+ ("none", None, True),+ ]+ )+ def test_source_namespace_is_blank(self, _name: str, job_inputs: dict[str, Any] | None, expected: bool) -> None:+ assert source_namespace_is_blank(cast(ExternalDataSource, SimpleNamespace(job_inputs=job_inputs))) is expected+++class TestDetectSchemaClearTransition:+ @parameterized.expand(+ [+ ("clears to empty string", "public", "", "public"),+ ("clears to whitespace", "public", " ", "public"),+ ("still set", "public", "analytics", None),+ ("already blank", "", "", None),+ ]+ )+ def test_capable_source_transitions(self, _name: str, existing: str, incoming: str, expected: str | None) -> None:+ result = detect_schema_clear_transition(+ source_type=ExternalDataSourceType.POSTGRES,+ existing_job_inputs={"schema": existing},+ incoming_job_inputs={"schema": incoming},+ )+ assert result == expected++ def test_incoming_without_schema_key_is_no_transition(self) -> None:+ result = detect_schema_clear_transition(+ source_type=ExternalDataSourceType.POSTGRES,+ existing_job_inputs={"schema": "public"},+ incoming_job_inputs={"host": "localhost"},+ )+ assert result is None++ def test_incapable_source_never_transitions(self) -> None:+ result = detect_schema_clear_transition(+ source_type=ExternalDataSourceType.MYSQL,+ existing_job_inputs={"schema": "public"},+ incoming_job_inputs={"schema": ""},+ )+ assert result is None+++class TestQualifyNonPostgresRows(BaseTest):+ def _source(self, *, schema: str) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="MSSQL",+ created_by=self.user,+ prefix="legacy",+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,+ job_inputs={"host": "localhost", "database": "warehouse", "schema": schema},+ )++ def test_apply_on_schema_clear_qualifies_mssql_rows(self) -> None:+ source = self._source(schema="dbo")+ row = ExternalDataSchema.objects.create(+ team_id=self.team.pk, source_id=source.pk, name="users", should_sync=True+ )++ apply_on_schema_clear(source, "dbo")++ row.refresh_from_db()+ assert row.name == "dbo.users"+ # dwh_storage_key locks the Delta path to the legacy folder so existing data is preserved.+ assert row.sync_type_config.get("dwh_storage_key") == "users"+ metadata = row.sync_type_config.get("schema_metadata") or {}+ assert metadata.get("source_schema") == "dbo"+ assert metadata.get("source_table_name") == "users"++ def test_apply_on_refresh_qualifies_using_pinned_metadata(self) -> None:+ # Blank namespace (post-clear): a legacy row pinned to its old schema qualifies on refresh.+ source = self._source(schema="")+ row = ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source_id=source.pk,+ name="orders",+ should_sync=True,+ sync_type_config={"schema_metadata": {"source_schema": "sales", "source_table_name": "orders"}},+ )++ substitutions = apply_on_refresh(source=source, team_id=self.team.pk)++ row.refresh_from_db()+ assert row.name == "sales.orders"+ assert substitutions == {"orders": "sales.orders"}+ assert row.sync_type_config.get("dwh_storage_key") == "orders"++ def test_apply_on_refresh_is_noop_for_already_qualified_rows(self) -> None:+ source = self._source(schema="")+ ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source_id=source.pk,+ name="sales.orders",+ should_sync=True,+ sync_type_config={+ "dwh_storage_key": "orders",+ "schema_metadata": {"source_schema": "sales", "source_table_name": "orders"},+ },+ )++ substitutions = apply_on_refresh(source=source, team_id=self.team.pk)++ assert substitutions == {}+ names = list(+ ExternalDataSchema.objects.filter(team_id=self.team.pk, source_id=source.pk, deleted=False).values_list(+ "name", flat=True+ )+ )+ assert names == ["sales.orders"]++ def test_cross_namespace_duplicate_table_names_stay_distinct(self) -> None:+ # Same table name in two schemas must coexist; refresh must not collapse them.+ source = self._source(schema="")+ for namespace in ("dbo", "sales"):+ ExternalDataSchema.objects.create(+ team_id=self.team.pk,+ source_id=source.pk,+ name=f"{namespace}.users",+ should_sync=True,+ sync_type_config={+ "dwh_storage_key": f"{namespace}_users",+ "schema_metadata": {"source_schema": namespace, "source_table_name": "users"},+ },+ )++ substitutions = apply_on_refresh(source=source, team_id=self.team.pk)++ assert substitutions == {}+ names = set(+ ExternalDataSchema.objects.filter(team_id=self.team.pk, source_id=source.pk, deleted=False).values_list(+ "name", flat=True+ )+ )+ assert names == {"dbo.users", "sales.users"}diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.pyindex fd3f6ffdda4c..22322d8ddd3a 100644--- a/products/warehouse_sources/backend/models/external_data_schema.py+++ b/products/warehouse_sources/backend/models/external_data_schema.py@@ -238,6 +238,12 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldreturn metadatareturn None+ @property+ def dwh_storage_key(self) -> str | None:+ if self.sync_type_config:+ return self.sync_type_config.get("dwh_storage_key")+ return None+@propertydef foreign_keys(self) -> list[dict[str, str]] | None:metadata = self.schema_metadata