: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
chore(data-warehouse): dispatch direct-query materialization by engine (#71558)
Tom Owersad167387a254
diff --git a/products/data_warehouse/backend/direct_query_engines.py b/products/data_warehouse/backend/direct_query_engines.pynew file mode 100644index 000000000000..e8fea31c4f06--- /dev/null+++ b/products/data_warehouse/backend/direct_query_engines.py@@ -0,0 +1,247 @@+"""Engine-keyed adapters for direct-query table materialization.++The presentation layer must not branch on source type. Direct-query behaviour varies by SQL+*engine* (postgres/mysql/snowflake/redshift), not by source type, and the same engine can back+more than one source type, so it dispatches here via ``source.direct_engine``+(``DIRECT_ENGINE_BY_SOURCE_TYPE``). Each adapter bundles the engine-specific pieces of building a+live-query ``DataWarehouseTable``: resolving the upstream location, mapping columns, and+creating / reprojecting / hiding the row. Warehouse-domain orchestration (filtering enabled+columns, saving the row) stays in the view.+"""++from abc import ABC, abstractmethod+from typing import Any++from products.data_warehouse.backend.direct_mysql import hide_direct_mysql_table, upsert_direct_mysql_table+from products.data_warehouse.backend.direct_postgres import hide_direct_postgres_table, upsert_direct_postgres_table+from products.data_warehouse.backend.direct_redshift import hide_direct_redshift_table, upsert_direct_redshift_table+from products.data_warehouse.backend.direct_snowflake import hide_direct_snowflake_table, upsert_direct_snowflake_table+from products.data_warehouse.backend.mysql_helpers import get_mysql_source_location, reproject_direct_mysql_table+from products.data_warehouse.backend.postgres_helpers import (+ get_postgres_source_location,+ reproject_direct_postgres_table,+)+from products.data_warehouse.backend.redshift_helpers import (+ get_redshift_source_location,+ reproject_direct_redshift_table,+)+from products.data_warehouse.backend.snowflake_helpers import reproject_direct_snowflake_table+from products.warehouse_sources.backend.facade.api import (+ mysql_columns_to_dwh_columns,+ postgres_columns_to_dwh_columns,+ snowflake_columns_to_dwh_columns,+)+from products.warehouse_sources.backend.facade.models import ExternalDataSource++# `source_schema` is a warehouse_sources SourceSchema, the DWH table / column types are+# engine-specific unions; kept as `Any` at this boundary so the adapter stays a thin dispatcher.+SourceTableLocation = tuple[str | None, str, str]+++def _location_metadata(source_schema: Any) -> dict[str, Any]:+ return {+ "source_catalog": source_schema.source_catalog if source_schema else None,+ "source_schema": source_schema.source_schema if source_schema else None,+ "source_table_name": source_schema.source_table_name if source_schema else None,+ }+++class DirectQueryEngine(ABC):+ """One SQL engine's direct-query materialization ops. Registered by engine name."""++ engine: str+ # Postgres resolves its upstream `(catalog, schema, table)` location even in warehouse mode;+ # the other engines only need it in direct mode. Keeps the view off a source-type check.+ resolves_location_in_warehouse_mode: bool = False++ @abstractmethod+ def source_table_location(+ self,+ *,+ schema_name: str,+ source_schema: Any,+ default_schema: str | None,+ default_catalog: str | None = None,+ ) -> SourceTableLocation:+ """Resolve `(catalog, schema, table)` for a row. `catalog` is None for catalog-less engines."""+ raise NotImplementedError()++ @abstractmethod+ def columns_to_dwh_columns(self, source_columns: list[Any]) -> Any:+ raise NotImplementedError()++ @abstractmethod+ def upsert_table(+ self,+ existing_table: Any,+ *,+ schema_name: str,+ source: ExternalDataSource,+ columns: Any,+ source_catalog: str | None,+ source_schema: str,+ source_table_name: str,+ ) -> Any:+ raise NotImplementedError()++ @abstractmethod+ def reproject_table(self, schema_row: Any, *, source: ExternalDataSource, enabled_columns: list[str] | None) -> Any:+ raise NotImplementedError()++ @abstractmethod+ def hide_table(self, table: Any) -> None:+ raise NotImplementedError()+++class _PostgresEngine(DirectQueryEngine):+ engine = "postgres"+ resolves_location_in_warehouse_mode = True++ def source_table_location(self, *, schema_name, source_schema, default_schema, default_catalog=None):+ return get_postgres_source_location(+ schema_name=schema_name, schema_metadata=_location_metadata(source_schema), default_schema=default_schema+ )++ def columns_to_dwh_columns(self, source_columns):+ return postgres_columns_to_dwh_columns(source_columns)++ def upsert_table(+ self, existing_table, *, schema_name, source, columns, source_catalog, source_schema, source_table_name+ ):+ return upsert_direct_postgres_table(+ existing_table,+ schema_name=schema_name,+ source=source,+ columns=columns,+ source_catalog=source_catalog,+ source_schema=source_schema,+ source_table_name=source_table_name,+ )++ def reproject_table(self, schema_row, *, source, enabled_columns):+ return reproject_direct_postgres_table(schema_row, source=source, enabled_columns=enabled_columns)++ def hide_table(self, table):+ hide_direct_postgres_table(table)+++class _MySQLEngine(DirectQueryEngine):+ engine = "mysql"++ def source_table_location(self, *, schema_name, source_schema, default_schema, default_catalog=None):+ # MySQL has no catalog layer; `database` (passed as default_catalog) is the schema fallback.+ source_schema_name, source_table_name = get_mysql_source_location(+ schema_name=schema_name,+ schema_metadata=_location_metadata(source_schema),+ default_schema=default_schema or default_catalog,+ )+ return None, source_schema_name, source_table_name++ def columns_to_dwh_columns(self, source_columns):+ return mysql_columns_to_dwh_columns(source_columns)++ def upsert_table(+ self, existing_table, *, schema_name, source, columns, source_catalog, source_schema, source_table_name+ ):+ # MySQL has no catalog; `source_catalog` is ignored.+ return upsert_direct_mysql_table(+ existing_table,+ schema_name=schema_name,+ source=source,+ columns=columns,+ source_schema=source_schema,+ source_table_name=source_table_name,+ )++ def reproject_table(self, schema_row, *, source, enabled_columns):+ return reproject_direct_mysql_table(schema_row, source=source, enabled_columns=enabled_columns)++ def hide_table(self, table):+ hide_direct_mysql_table(table)+++class _SnowflakeEngine(DirectQueryEngine):+ engine = "snowflake"++ def source_table_location(self, *, schema_name, source_schema, default_schema, default_catalog=None):+ catalog = source_schema.source_catalog if source_schema and source_schema.source_catalog else default_catalog+ if source_schema and source_schema.source_schema and source_schema.source_table_name:+ return catalog, source_schema.source_schema, source_schema.source_table_name++ normalized_default_schema = (+ default_schema.strip() if isinstance(default_schema, str) and default_schema.strip() else None+ )+ if normalized_default_schema is None and "." in schema_name:+ inferred_schema, inferred_table_name = schema_name.split(".", 1)+ return catalog, inferred_schema, inferred_table_name++ return catalog, normalized_default_schema or "", schema_name++ def columns_to_dwh_columns(self, source_columns):+ return snowflake_columns_to_dwh_columns(source_columns)++ def upsert_table(+ self, existing_table, *, schema_name, source, columns, source_catalog, source_schema, source_table_name+ ):+ return upsert_direct_snowflake_table(+ existing_table,+ schema_name=schema_name,+ source=source,+ columns=columns,+ source_catalog=source_catalog,+ source_schema=source_schema,+ source_table_name=source_table_name,+ )++ def reproject_table(self, schema_row, *, source, enabled_columns):+ return reproject_direct_snowflake_table(schema_row, source=source, enabled_columns=enabled_columns)++ def hide_table(self, table):+ hide_direct_snowflake_table(table)+++class _RedshiftEngine(DirectQueryEngine):+ engine = "redshift"++ def source_table_location(self, *, schema_name, source_schema, default_schema, default_catalog=None):+ return get_redshift_source_location(+ schema_name=schema_name,+ schema_metadata=_location_metadata(source_schema),+ default_catalog=default_catalog,+ default_schema=default_schema,+ )++ def columns_to_dwh_columns(self, source_columns):+ # Redshift information_schema types are Postgres-style, so reuse the Postgres mapper.+ return postgres_columns_to_dwh_columns(source_columns)++ def upsert_table(+ self, existing_table, *, schema_name, source, columns, source_catalog, source_schema, source_table_name+ ):+ return upsert_direct_redshift_table(+ existing_table,+ schema_name=schema_name,+ source=source,+ columns=columns,+ source_catalog=source_catalog,+ source_schema=source_schema,+ source_table_name=source_table_name,+ )++ def reproject_table(self, schema_row, *, source, enabled_columns):+ return reproject_direct_redshift_table(schema_row, source=source, enabled_columns=enabled_columns)++ def hide_table(self, table):+ hide_direct_redshift_table(table)+++_ENGINES: dict[str, DirectQueryEngine] = {+ engine.engine: engine for engine in (_PostgresEngine(), _MySQLEngine(), _SnowflakeEngine(), _RedshiftEngine())+}+++def get_direct_query_engine(engine: str | None) -> DirectQueryEngine | None:+ """Adapter for a source's ``direct_engine``, or None for non-direct-capable sources."""+ if engine is None:+ return None+ return _ENGINES.get(engine)diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex cb0a8e16808e..8078a46a8436 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -79,6 +79,7 @@ _LAZY = {"upsert_direct_snowflake_table": "direct_snowflake","hide_direct_redshift_table": "direct_redshift","upsert_direct_redshift_table": "direct_redshift",+ "get_direct_query_engine": "direct_query_engines","reconcile_refresh_name_substitutions": "postgres_warehouse_migration","github_repositories_for_job_inputs": "github_warehouse_repos","reconcile_github_repositories": "github_warehouse_repos",diff --git a/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt b/products/data_warehouse/backend/presentation/source_agnostic_baseline.txtindex 4897b2ec6e17..f9becda19849 100644--- a/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt+++ b/products/data_warehouse/backend/presentation/source_agnostic_baseline.txt@@ -9,17 +9,10 @@## Each line is `<count>\t<token>\t<relpath>`. Migrate a family to a capability# mixin (see .../sources/common/capabilities.py), then regenerate to shrink.-1 is_direct_postgres products/data_warehouse/backend/presentation/views/external_data_source.py-2 ExternalDataSourceType.MYSQL products/data_warehouse/backend/presentation/views/external_data_source.py+1 ExternalDataSourceType.MYSQL products/data_warehouse/backend/presentation/views/external_data_source.py2 ExternalDataSourceType.POSTGRES products/data_warehouse/backend/presentation/views/external_data_schema.py-3 ExternalDataSourceType.REDSHIFT products/data_warehouse/backend/presentation/views/external_data_source.py-3 ExternalDataSourceType.SNOWFLAKE products/data_warehouse/backend/presentation/views/external_data_source.py-3 is_direct_mysql products/data_warehouse/backend/presentation/views/external_data_source.py-3 is_direct_postgres products/data_warehouse/backend/presentation/views/external_data_schema.py-3 is_direct_redshift products/data_warehouse/backend/presentation/views/external_data_schema.py-3 is_direct_redshift products/data_warehouse/backend/presentation/views/external_data_source.py-3 is_direct_snowflake products/data_warehouse/backend/presentation/views/external_data_schema.py-3 is_direct_snowflake products/data_warehouse/backend/presentation/views/external_data_source.py+2 ExternalDataSourceType.REDSHIFT products/data_warehouse/backend/presentation/views/external_data_source.py+2 ExternalDataSourceType.SNOWFLAKE products/data_warehouse/backend/presentation/views/external_data_source.py4 ExternalDataSourceType.GITHUB products/data_warehouse/backend/presentation/views/external_data_source.py+5 ExternalDataSourceType.POSTGRES products/data_warehouse/backend/presentation/views/external_data_source.py6 ExternalDataSourceType.CUSTOM products/data_warehouse/backend/presentation/views/external_data_source.py-6 ExternalDataSourceType.POSTGRES products/data_warehouse/backend/presentation/views/external_data_source.pydiff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.pyindex ebf7ac430e4e..cd83e1913ccb 100644--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py@@ -26,20 +26,13 @@ from products.data_warehouse.backend.facade.api import (cancel_external_data_workflow,create_and_register_webhook,external_data_workflow_exists,+ get_direct_query_engine,get_or_create_webhook_hog_function,get_postgres_source_location,- hide_direct_mysql_table,- hide_direct_postgres_table,- hide_direct_redshift_table,- hide_direct_snowflake_table,is_any_external_data_schema_paused,is_cdc_enabled_for_team,pause_external_data_schedule,reconcile_webhook_events,- reproject_direct_mysql_table,- reproject_direct_postgres_table,- reproject_direct_redshift_table,- reproject_direct_snowflake_table,sync_cdc_extraction_schedule,sync_external_data_job_workflow,trigger_external_data_workflow,@@ -971,35 +964,21 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):)if source.is_direct_query:+ direct_engine_adapter = get_direct_query_engine(source.direct_engine)# Direct-mode lifecycle hooks that need a fresh DataWarehouseTable projection:# (1) row is being re-exposed (should_sync flipping False → True);# (2) the column-picker selection changed on an already-exposed row.newly_exposed = should_sync is True and instance.should_sync is Falseprojection_needs_refresh = enabled_columns_changed and instance.table is not None and instance.should_sync- if newly_exposed or projection_needs_refresh:- if source.is_direct_postgres:- reproject = reproject_direct_postgres_table- elif source.is_direct_snowflake:- reproject = reproject_direct_snowflake_table- elif source.is_direct_redshift:- reproject = reproject_direct_redshift_table- else:- reproject = reproject_direct_mysql_table- validated_data["table"] = reproject(+ if direct_engine_adapter is not None and (newly_exposed or projection_needs_refresh):+ validated_data["table"] = direct_engine_adapter.reproject_table(instance,source=source,enabled_columns=validated_data.get("enabled_columns", instance.enabled_columns),)- if should_sync is False and instance.should_sync is True:- if source.is_direct_postgres:- hide_direct_postgres_table(instance.table)- elif source.is_direct_snowflake:- hide_direct_snowflake_table(instance.table)- elif source.is_direct_redshift:- hide_direct_redshift_table(instance.table)- else:- hide_direct_mysql_table(instance.table)+ if direct_engine_adapter is not None and should_sync is False and instance.should_sync is True:+ direct_engine_adapter.hide_table(instance.table)elif enabled_columns_changed and instance.table is not None and instance.should_sync:# Warehouse mode: hide newly-disabled columns from HogQL immediately. Restoration# (reset to None or re-enabling a column) is deferred to the next sync — Delta may@@ -1544,14 +1523,9 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):instance: ExternalDataSchema = self.get_object()if instance.source.is_direct_query:- if instance.source.is_direct_postgres:- hide_direct_postgres_table(instance.table)- elif instance.source.is_direct_snowflake:- hide_direct_snowflake_table(instance.table)- elif instance.source.is_direct_redshift:- hide_direct_redshift_table(instance.table)- else:- hide_direct_mysql_table(instance.table)+ direct_engine_adapter = get_direct_query_engine(instance.source.direct_engine)+ if direct_engine_adapter is not None:+ direct_engine_adapter.hide_table(instance.table)instance.should_sync = Falseinstance.save(update_fields=["should_sync", "updated_at"])return Response(status=status.HTTP_200_OK)diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.pyindex 08241d36c253..67b0b343c230 100644--- a/products/data_warehouse/backend/presentation/views/external_data_source.py+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py@@ -77,10 +77,9 @@ from products.data_warehouse.backend.facade.api import (delete_webhook_and_hog_function,detect_schema_clear_transition as detect_sql_schema_clear_transition,ensure_cdc_slot_cleanup_schedule,- get_mysql_source_location,+ get_direct_query_engine,get_or_create_webhook_hog_function,get_postgres_source_location,- get_redshift_source_location,get_webhook_url,github_repositories_for_job_inputs,is_any_external_data_schema_paused,@@ -98,10 +97,6 @@ from products.data_warehouse.backend.facade.api import (sync_discover_schemas_schedule,sync_external_data_job_workflow,trigger_external_data_source_workflow,- upsert_direct_mysql_table,- upsert_direct_postgres_table,- upsert_direct_redshift_table,- upsert_direct_snowflake_table,)from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfigfrom products.data_warehouse.backend.presentation.views.external_data_schema import (@@ -117,12 +112,7 @@ from products.data_warehouse.backend.presentation.views.source_api_versions impoapi_version_deprecation_payload,)from products.revenue_analytics.backend.facade.api import ensure_person_join, remove_person_join-from products.warehouse_sources.backend.facade.api import (- mysql_columns_to_dwh_columns,- postgres_columns_to_dwh_columns,- snowflake_columns_to_dwh_columns,- validate_source_prefix,-)+from products.warehouse_sources.backend.facade.api import validate_source_prefixfrom products.warehouse_sources.backend.facade.models import (CustomOAuth2Integration,DataWarehouseTable,@@ -479,62 +469,6 @@ def get_postgres_source_table_location()-def get_mysql_source_table_location(- *,- schema_name: str,- source_schema: SourceSchema | None,- default_schema: str | None,-) -> tuple[str, str]:- return get_mysql_source_location(- schema_name=schema_name,- schema_metadata={- "source_schema": source_schema.source_schema if source_schema else None,- "source_table_name": source_schema.source_table_name if source_schema else None,- },- default_schema=default_schema,- )---def get_snowflake_source_table_location(- *,- schema_name: str,- source_schema: SourceSchema | None,- default_schema: str | None,- default_catalog: str | None = None,-) -> tuple[str | None, str, str]:- catalog = source_schema.source_catalog if source_schema and source_schema.source_catalog else default_catalog- if source_schema and source_schema.source_schema and source_schema.source_table_name:- return catalog, source_schema.source_schema, source_schema.source_table_name-- normalized_default_schema = (- default_schema.strip() if isinstance(default_schema, str) and default_schema.strip() else None- )- if normalized_default_schema is None and "." in schema_name:- inferred_schema, inferred_table_name = schema_name.split(".", 1)- return catalog, inferred_schema, inferred_table_name-- return catalog, normalized_default_schema or "", schema_name---def get_redshift_source_table_location(- *,- schema_name: str,- source_schema: SourceSchema | None,- default_schema: str | None,- default_catalog: str | None = None,-) -> tuple[str | None, str, str]:- return get_redshift_source_location(- schema_name=schema_name,- schema_metadata={- "source_catalog": source_schema.source_catalog if source_schema else None,- "source_schema": source_schema.source_schema if source_schema else None,- "source_table_name": source_schema.source_table_name if source_schema else None,- },- default_catalog=default_catalog,- default_schema=default_schema,- )--CUSTOM_SOURCE_LIMIT_MESSAGE = f"You can create at most {MAX_CUSTOM_SOURCES_PER_TEAM} custom sources per project."DIRECT_QUERY_UNSUPPORTED_SOURCE_MESSAGE = ("Direct query mode is currently supported only for Postgres, MySQL, Snowflake, and Redshift sources."@@ -2093,9 +2027,6 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiif created_via == ExternalDataSource.CreatedVia.WIZARD and is_wizard_self_driving_program(request):created_via = ExternalDataSource.CreatedVia.SELF_DRIVINGis_direct_query = access_method == ExternalDataSource.AccessMethod.DIRECT- is_direct_mysql = is_direct_query and source_type == ExternalDataSourceType.MYSQL- is_direct_snowflake = is_direct_query and source_type == ExternalDataSourceType.SNOWFLAKE- is_direct_redshift = is_direct_query and source_type == ExternalDataSourceType.REDSHIFTif is_direct_query and source_type not in direct_capable_source_types():return Response(@@ -2338,6 +2269,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidata={"message": cdc_error},)+ # Direct-query table materialization is engine-specific; dispatch on the engine, not the+ # source type. None for non-direct-capable sources.+ direct_engine_adapter = get_direct_query_engine(new_source_model.direct_engine)+# Create all ExternalDataSchema objects and enable syncing for active schemasfor schema in payload_schemas:sync_type = schema.get("sync_type")@@ -2382,35 +2317,14 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMiximetadata_source_catalog: str | Nonemetadata_source_schema: str | Nonemetadata_source_table_name: str | None- if source_type_model == ExternalDataSourceType.POSTGRES:- metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (- get_postgres_source_table_location(- schema_name=schema_name,- source_schema=source_schema,- default_schema=default_source_schema,- )- )- elif is_direct_mysql:- # Direct mode needs a resolved source location for the live-query table; warehouse- # mode keeps storing whatever the source reported to avoid changing sync routing.- metadata_source_catalog = None- metadata_source_schema, metadata_source_table_name = get_mysql_source_table_location(- schema_name=schema_name,- source_schema=source_schema,- default_schema=default_source_schema or source_config.to_dict().get("database"),- )- elif is_direct_snowflake:+ # Direct mode needs a resolved source location for the live-query table; warehouse mode+ # keeps storing whatever the source reported to avoid changing sync routing (except+ # Postgres, which resolves in both modes — carried by the adapter flag).+ if direct_engine_adapter is not None and (+ is_direct_query or direct_engine_adapter.resolves_location_in_warehouse_mode+ ):metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (- get_snowflake_source_table_location(- schema_name=schema_name,- source_schema=source_schema,- default_schema=default_source_schema,- default_catalog=default_source_catalog,- )- )- elif is_direct_redshift:- metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (- get_redshift_source_table_location(+ direct_engine_adapter.source_table_location(schema_name=schema_name,source_schema=source_schema,default_schema=default_source_schema,@@ -2562,10 +2476,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixirow_filters=row_filters,)- # The CDC path is Postgres-only, and the direct paths are engine-specific —- # `get_postgres_source_table_location` / `get_mysql_source_table_location` guarantee- # non-None schema/table in their branches above. `cast` narrows for mypy without a- # runtime check. The adapter no-ops for self-managed / no-publication.+ # The CDC path is Postgres-only, and the engine adapter's `source_table_location`+ # guarantees non-None schema/table when it resolves above. `cast` narrows for mypy+ # without a runtime check. The adapter no-ops for self-managed / no-publication.if is_cdc_schema and should_sync and cdc_enabled and cdc_adapter is not None:cdc_adapter.add_table(new_source_model,@@ -2573,74 +2486,20 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixicast(str, metadata_source_table_name),)- if new_source_model.is_direct_postgres and should_sync:+ if direct_engine_adapter is not None and is_direct_query and should_sync:# Apply the picker's column subset on the very first DataWarehouseTable build,# not just on subsequent updates — otherwise users see all columns in HogQL until- # they hit save again or a refresh runs.- schema_model.table = upsert_direct_postgres_table(- None,- schema_name=schema_name,- source=new_source_model,- columns=filter_dwh_columns_by_enabled_columns(- postgres_columns_to_dwh_columns(source_schema.columns if source_schema else []),- enabled_columns,- source_schema.detected_primary_keys if source_schema else None,- incremental_field,- # Direct-postgres columns are keyed by raw, case-sensitive source names.- normalize=False,- ),- source_catalog=metadata_source_catalog,- source_schema=cast(str, metadata_source_schema),- source_table_name=cast(str, metadata_source_table_name),- )- schema_model.save(update_fields=["table"])- elif new_source_model.is_direct_mysql and should_sync:- schema_model.table = upsert_direct_mysql_table(- None,- schema_name=schema_name,- source=new_source_model,- columns=filter_dwh_columns_by_enabled_columns(- mysql_columns_to_dwh_columns(source_schema.columns if source_schema else []),- enabled_columns,- source_schema.detected_primary_keys if source_schema else None,- incremental_field,- # Direct-mysql columns are keyed by raw, case-sensitive source names.- normalize=False,- ),- source_schema=cast(str, metadata_source_schema),- source_table_name=cast(str, metadata_source_table_name),- )- schema_model.save(update_fields=["table"])- elif new_source_model.is_direct_snowflake and should_sync:- schema_model.table = upsert_direct_snowflake_table(- None,- schema_name=schema_name,- source=new_source_model,- columns=filter_dwh_columns_by_enabled_columns(- snowflake_columns_to_dwh_columns(source_schema.columns if source_schema else []),- enabled_columns,- source_schema.detected_primary_keys if source_schema else None,- incremental_field,- # Direct-snowflake columns are keyed by raw, case-sensitive source names.- normalize=False,- ),- source_catalog=metadata_source_catalog,- source_schema=cast(str, metadata_source_schema),- source_table_name=cast(str, metadata_source_table_name),- )- schema_model.save(update_fields=["table"])- elif new_source_model.is_direct_redshift and should_sync:- schema_model.table = upsert_direct_redshift_table(+ # they hit save again or a refresh runs. Columns are keyed by raw, case-sensitive+ # source names (`normalize=False`).+ schema_model.table = direct_engine_adapter.upsert_table(None,schema_name=schema_name,source=new_source_model,columns=filter_dwh_columns_by_enabled_columns(- # Redshift information_schema types are Postgres-style, so reuse the Postgres mapper.- postgres_columns_to_dwh_columns(source_schema.columns if source_schema else []),+ direct_engine_adapter.columns_to_dwh_columns(source_schema.columns if source_schema else []),enabled_columns,source_schema.detected_primary_keys if source_schema else None,incremental_field,- # Direct-redshift columns are keyed by raw source names.normalize=False,),source_catalog=metadata_source_catalog,diff --git a/products/data_warehouse/backend/test/test_direct_query_engines.py b/products/data_warehouse/backend/test/test_direct_query_engines.pynew file mode 100644index 000000000000..ca10698f0749--- /dev/null+++ b/products/data_warehouse/backend/test/test_direct_query_engines.py@@ -0,0 +1,94 @@+from types import SimpleNamespace++from parameterized import parameterized++from products.data_warehouse.backend.direct_query_engines import get_direct_query_engine+++def _source_schema(*, catalog=None, schema=None, table=None):+ return SimpleNamespace(source_catalog=catalog, source_schema=schema, source_table_name=table)+++class TestDirectQueryEngineRegistry:+ @parameterized.expand(["postgres", "mysql", "snowflake", "redshift"])+ def test_known_engine_resolves(self, engine: str):+ adapter = get_direct_query_engine(engine)+ assert adapter is not None+ assert adapter.engine == engine++ @parameterized.expand([("none", None), ("unknown", "bigquery")])+ def test_non_direct_engine_returns_none(self, _name: str, engine):+ assert get_direct_query_engine(engine) is None++ @parameterized.expand(+ [+ # Only Postgres resolves its upstream location in warehouse mode; the view keys the+ # warehouse-vs-direct decision off this flag instead of a source-type check.+ ("postgres", True),+ ("mysql", False),+ ("snowflake", False),+ ("redshift", False),+ ]+ )+ def test_resolves_location_in_warehouse_mode(self, engine: str, expected: bool):+ adapter = get_direct_query_engine(engine)+ assert adapter is not None+ assert adapter.resolves_location_in_warehouse_mode is expected++ @parameterized.expand(+ [+ # Explicit metadata wins for every engine; MySQL has no catalog layer so it always+ # returns None there even when catalog metadata is present.+ ("postgres", ("db", "public", "users")),+ ("snowflake", ("db", "public", "users")),+ ("redshift", ("db", "public", "users")),+ ("mysql", (None, "public", "users")),+ ]+ )+ def test_source_table_location_uses_explicit_metadata(self, engine: str, expected: tuple):+ adapter = get_direct_query_engine(engine)+ assert adapter is not None+ location = adapter.source_table_location(+ schema_name="ignored",+ source_schema=_source_schema(catalog="db", schema="public", table="users"),+ default_schema=None,+ default_catalog=None,+ )+ assert location == expected++ def test_mysql_falls_back_to_default_catalog_as_schema(self):+ # MySQL has no schema config field, so `database` (passed as default_catalog) is the+ # schema fallback when no default_schema is given.+ adapter = get_direct_query_engine("mysql")+ assert adapter is not None+ location = adapter.source_table_location(+ schema_name="orders",+ source_schema=None,+ default_schema=None,+ default_catalog="shop_db",+ )+ assert location == (None, "shop_db", "orders")++ def test_snowflake_splits_dotted_name_when_no_default_schema(self):+ # Snowflake infers schema from a dotted `schema.table` name only when no default schema+ # is configured — the bespoke resolution this migration preserved.+ adapter = get_direct_query_engine("snowflake")+ assert adapter is not None+ location = adapter.source_table_location(+ schema_name="analytics.events",+ source_schema=None,+ default_schema=None,+ default_catalog="WAREHOUSE",+ )+ assert location == ("WAREHOUSE", "analytics", "events")++ def test_snowflake_default_schema_takes_precedence_over_dot_split(self):+ adapter = get_direct_query_engine("snowflake")+ assert adapter is not None+ location = adapter.source_table_location(+ schema_name="analytics.events",+ source_schema=None,+ default_schema="public",+ default_catalog=None,+ )+ assert location == (None, "public", "analytics.events")