Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): postgres warehouse parity with direct query (#57698)

Daniel RC7625dd92a770
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index cf03ebe231d2..9e9d7bfd3def 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5486,6 +5486,7 @@ const api = {
| 'sync_frequency'
| 'sync_time_of_day'
| 'cdc_table_mode'
+ | 'enabled_columns'
>[]
): Promise<ExternalDataSourceSchema[]> {
return await new ApiRequest().externalDataSource(sourceId).withAction('bulk_update_schemas').update({
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 9051f2e4f5e2..287b33febe1c 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5893,6 +5893,11 @@ export interface ExternalDataSourceSyncSchema {
primary_key_columns: string[] | null
available_columns: AvailableColumn[]
detected_primary_keys: string[] | null
+ /**
+ * User-selected source columns to sync. `null`/undefined = sync all columns.
+ * PK columns and the active incremental field are always retained server-side.
+ */
+ enabled_columns?: string[] | null
}
export interface ExternalDataSourceSchema extends SimpleExternalDataSourceSchema {
@@ -5909,6 +5914,12 @@ export interface ExternalDataSourceSchema extends SimpleExternalDataSourceSchema
should_sync_default?: boolean
primary_key_columns: string[] | null
cdc_table_mode?: 'consolidated' | 'cdc_only' | 'both'
+ /**
+ * User-selected source columns to sync. `null` means "sync all columns".
+ * Primary-key + active incremental columns are always retained even if not listed.
+ */
+ enabled_columns?: string[] | null
+ available_columns?: { name: string; data_type?: string; is_nullable?: boolean }[]
}
export enum ExternalDataSchemaStatus {
diff --git a/posthog/temporal/data_imports/cdc/activities.py b/posthog/temporal/data_imports/cdc/activities.py
index e43880d41d31..34e41f9365ff 100644
--- a/posthog/temporal/data_imports/cdc/activities.py
+++ b/posthog/temporal/data_imports/cdc/activities.py
@@ -27,6 +27,7 @@ from posthog.temporal.data_imports.cdc.batcher import (
deduplicate_table,
enrich_delete_rows,
)
+from posthog.temporal.data_imports.cdc.types import ChangeEvent
from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.common import SyncTypeLiteral
from posthog.temporal.data_imports.pipelines.pipeline_v3.kafka.producer import KafkaBatchProducer
from posthog.temporal.data_imports.pipelines.pipeline_v3.s3.writer import S3BatchWriter
@@ -100,6 +101,8 @@ class CDCExtractActivity:
self.cdc_schemas: list[ExternalDataSchema] = []
self.schema_by_name: dict[str, ExternalDataSchema] = {}
self.pk_columns_by_table: dict[str, list[str]] = {}
+ # Missing entry = sync all columns; otherwise the set is the projection (always includes PKs).
+ self.enabled_columns_by_table: dict[str, set[str]] = {}
self.write_trackers: dict[str, _WriteTracker] = {}
self.created_jobs: list[ExternalDataJob] = []
self.adapter: typing.Any = None
@@ -535,6 +538,35 @@ class CDCExtractActivity:
self.log.info("pk_columns_loaded", tables=list(self.pk_columns_by_table.keys()))
+ for schema in self.cdc_schemas:
+ enabled = schema.enabled_columns
+ # `None` = sync all; `[]` = retain PKs + incremental only. Match the
+ # invariant used by build_select_clause / pipeline_sync / filter_dwh_columns.
+ if isinstance(enabled, list):
+ retained: set[str] = {str(c) for c in enabled}
+ # PKs must stay even if the user dropped them from enabled_columns — merges break otherwise.
+ for pk in self.pk_columns_by_table.get(schema.name, []):
+ retained.add(pk)
+ inc = schema.incremental_field
+ if isinstance(inc, str) and inc:
+ retained.add(inc)
+ self.enabled_columns_by_table[schema.name] = retained
+
+ def _project_event_columns(self, event: ChangeEvent) -> ChangeEvent:
+ retained = self.enabled_columns_by_table.get(event.table_name)
+ if retained is None:
+ return event
+ filtered = {name: value for name, value in event.columns.items() if name in retained}
+ if filtered.keys() == event.columns.keys():
+ return event
+ return ChangeEvent(
+ operation=event.operation,
+ table_name=event.table_name,
+ position_serialized=event.position_serialized,
+ timestamp=event.timestamp,
+ columns=filtered,
+ )
+
# ------------------------------------------------------------------
# WAL read loop with periodic micro-batch flushes
# ------------------------------------------------------------------
@@ -558,6 +590,7 @@ class CDCExtractActivity:
if event.table_name not in cdc_table_names:
continue
+ event = self._project_event_columns(event)
self.batcher.add(event)
self.last_end_lsn = event.position_serialized
self.event_count += 1
diff --git a/posthog/temporal/data_imports/pipelines/common/load.py b/posthog/temporal/data_imports/pipelines/common/load.py
index 768fba8b1a83..979e73e28a99 100644
--- a/posthog/temporal/data_imports/pipelines/common/load.py
+++ b/posthog/temporal/data_imports/pipelines/common/load.py
@@ -370,6 +370,7 @@ async def run_post_load_operations(
row_count=row_count,
queryable_folder=queryable_folder,
table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ primary_keys=resource.primary_keys if resource is not None else None,
)
logger.debug("Finished validating schema and updating table")
diff --git a/posthog/temporal/data_imports/pipelines/helpers.py b/posthog/temporal/data_imports/pipelines/helpers.py
index 8e47d441385a..fc63530f1055 100644
--- a/posthog/temporal/data_imports/pipelines/helpers.py
+++ b/posthog/temporal/data_imports/pipelines/helpers.py
@@ -57,7 +57,11 @@ def incremental_type_to_operator(field_type: IncrementalFieldType) -> str:
def build_table_name(source: ExternalDataSource, schema_name: str):
- return f"{source.prefix or ''}{source.source_type}_{schema_name}".lower()
+ # Dots in `schema_name` would parse as `<table>.<column>` in HogQL, so any source that ever
+ # produces a dotted schema name (today: Postgres multi-schema like `public.auth_group`) needs
+ # them rewritten. No-op for pre-existing single-schema sources whose names never contained dots.
+ safe_schema_name = schema_name.replace(".", "__")
+ return f"{source.prefix or ''}{source.source_type}_{safe_schema_name}".lower()
def sync_revenue_analytics_views(schema: ExternalDataSchema, source: ExternalDataSource) -> None:
diff --git a/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py b/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py
index 5f349e3e6721..81cd2ca82842 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline/pipeline.py
@@ -437,6 +437,7 @@ class PipelineNonDLT(Generic[ResumableData]):
row_count=row_count,
queryable_folder=queryable_folder,
table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ primary_keys=self._resource.primary_keys,
)
await self._logger.adebug("Finished validating schema and updating table")
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_sync.py b/posthog/temporal/data_imports/pipelines/pipeline_sync.py
index 8ec969995ce8..8cf259cebd86 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_sync.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_sync.py
@@ -26,6 +26,7 @@ from posthog.temporal.data_imports.pipelines.helpers import build_table_name
from products.data_warehouse.backend.models.external_data_job import ExternalDataJob
from products.data_warehouse.backend.models.external_data_schema import ExternalDataSchema
from products.data_warehouse.backend.models.table import DataWarehouseTable
+from products.data_warehouse.backend.postgres_helpers import filter_dwh_columns_by_enabled_columns
from products.data_warehouse.backend.types import ExternalDataSourceType
LOGGER = get_logger(__name__)
@@ -139,6 +140,7 @@ async def validate_schema_and_update_table(
table_format: DataWarehouseTable.TableFormat,
queryable_folder: str,
table_schema_dict: Optional[dict[str, str]] = None,
+ primary_keys: Optional[list[str]] = None,
) -> None:
"""
Async version of validate_schema_and_update_table_sync.
@@ -176,8 +178,13 @@ async def validate_schema_and_update_table(
_schema_name: str = external_data_schema.name
incremental_or_append = external_data_schema.should_use_incremental_field
- table_name = build_table_name(job.pipeline, _schema_name)
- normalized_schema_name = NamingConvention.normalize_identifier(_schema_name)
+ # `dwh_storage_key` pins the Delta path to the original unqualified name for legacy
+ # warehouse rows that got renamed to qualified form during multi-schema migration.
+ storage_key = (external_data_schema.sync_type_config or {}).get("dwh_storage_key")
+ storage_schema_name = storage_key if isinstance(storage_key, str) and storage_key else _schema_name
+
+ table_name = build_table_name(job.pipeline, storage_schema_name)
+ normalized_schema_name = NamingConvention.normalize_identifier(storage_schema_name)
new_url_pattern = job.url_pattern_by_schema(normalized_schema_name)
# Check
@@ -237,6 +244,17 @@ async def validate_schema_and_update_table(
table_for_update = DataWarehouseTable.raw_objects.select_for_update().get(id=table_created.id)
existing_columns = table_for_update.columns or {}
columns = merge_columns(db_columns, table_schema_dict or {}, existing_columns)
+ # Project to enabled_columns so disabled columns the user already deselected don't
+ # creep back into HogQL via the Delta schema (which still contains them historically).
+ # Prefer source-detected PKs (always present) over the schema model's PKs (only set
+ # for CDC and user-picked incremental keys) so non-CDC schemas don't drop their PKs.
+ effective_primary_keys = primary_keys or external_data_schema.primary_key_columns
+ columns = filter_dwh_columns_by_enabled_columns(
+ columns,
+ external_data_schema.enabled_columns,
+ effective_primary_keys,
+ external_data_schema.incremental_field,
+ )
table_for_update.columns = columns
table_for_update.save(update_fields=["columns"])
# Keep local reference in sync
diff --git a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
index 2ab4c3553736..a7c843e8f52d 100644
--- a/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
+++ b/posthog/temporal/data_imports/pipelines/pipeline_v3/load/processor.py
@@ -165,6 +165,7 @@ async def _handle_partial_data_loading(
row_count=export_signal.cumulative_row_count,
queryable_folder=queryable_folder,
table_format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ primary_keys=export_signal.primary_keys,
)
logger.debug("partial_data_loading_complete", queryable_folder=queryable_folder)
diff --git a/posthog/temporal/data_imports/sources/common/sql.py b/posthog/temporal/data_imports/sources/common/sql.py
index fd542291863e..c5a636ce454c 100644
--- a/posthog/temporal/data_imports/sources/common/sql.py
+++ b/posthog/temporal/data_imports/sources/common/sql.py
@@ -8,6 +8,23 @@ import collections.abc
import pyarrow as pa
+def resolve_detected_primary_keys(
+ discovered_pk_columns: list[str] | None,
+ columns: collections.abc.Iterable[tuple[str, str, bool]],
+) -> list[str] | None:
+ """Pick the per-table primary key columns to advertise on a `SourceSchema`.
+
+ Returns the discovered list when present, otherwise falls back to `["id"]` if any column is
+ literally named `id` (the convention every SQL source we ingest from happens to follow), else
+ None. Used by Postgres / MySQL / MSSQL / Redshift discovery.
+ """
+ if discovered_pk_columns:
+ return discovered_pk_columns
+ if any(column[0] == "id" for column in columns):
+ return ["id"]
+ return None
+
+
@typing.runtime_checkable
class Column(typing.Protocol):
"""Protocol for `SQLSource` columns.
diff --git a/posthog/temporal/data_imports/sources/mssql/source.py b/posthog/temporal/data_imports/sources/mssql/source.py
index c040452f87ee..51f9402ea97d 100644
--- a/posthog/temporal/data_imports/sources/mssql/source.py
+++ b/posthog/temporal/data_imports/sources/mssql/source.py
@@ -17,6 +17,7 @@ from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleS
from posthog.temporal.data_imports.sources.common.mixins import SSHTunnelMixin, ValidateDatabaseHostMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.common.sql import resolve_detected_primary_keys
from posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfig
from posthog.temporal.data_imports.sources.mssql.mssql import (
filter_mssql_incremental_fields,
@@ -191,8 +192,7 @@ class MSSQLSource(SimpleSource[MSSQLSourceConfig], SSHTunnelMixin, ValidateDatab
supports_append=len(incremental_fields) > 0,
incremental_fields=incremental_fields,
columns=columns,
- detected_primary_keys=detected_pks.get(table_name)
- or (["id"] if any(col[0] == "id" for col in columns) else None),
+ detected_primary_keys=resolve_detected_primary_keys(detected_pks.get(table_name), columns),
)
)
diff --git a/posthog/temporal/data_imports/sources/mysql/source.py b/posthog/temporal/data_imports/sources/mysql/source.py
index 8040f1e9f255..8edf661606d1 100644
--- a/posthog/temporal/data_imports/sources/mysql/source.py
+++ b/posthog/temporal/data_imports/sources/mysql/source.py
@@ -20,6 +20,7 @@ from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleS
from posthog.temporal.data_imports.sources.common.mixins import SSHTunnelMixin, ValidateDatabaseHostMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.common.sql import resolve_detected_primary_keys
from posthog.temporal.data_imports.sources.generated_configs import MySQLSourceConfig
from posthog.temporal.data_imports.sources.mysql.mysql import (
filter_mysql_incremental_fields,
@@ -205,8 +206,7 @@ class MySQLSource(SimpleSource[MySQLSourceConfig], SSHTunnelMixin, ValidateDatab
supports_append=len(incremental_fields) > 0,
incremental_fields=incremental_fields,
columns=columns,
- detected_primary_keys=detected_pks.get(table_name)
- or (["id"] if any(col[0] == "id" for col in columns) else None),
+ detected_primary_keys=resolve_detected_primary_keys(detected_pks.get(table_name), columns),
)
)
diff --git a/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py b/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
index 493e12c5e8a5..57f53e58e560 100644
--- a/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
+++ b/posthog/temporal/data_imports/sources/postgres/partitioned_tables.py
@@ -21,6 +21,7 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (
QueryTimeoutException,
table_from_iterator,
)
+from posthog.temporal.data_imports.sources.postgres.query_builders import build_select_clause
from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
@@ -495,6 +496,9 @@ def build_partition_query(
incremental_field: Optional[str],
incremental_field_type: Optional[IncrementalFieldType],
db_incremental_field_last_value: Optional[Any],
+ *,
+ enabled_columns: Optional[list[str]] = None,
+ primary_keys: Optional[list[str]] = None,
) -> sql.Composed:
"""Build a SELECT against one child partition.
@@ -505,8 +509,11 @@ def build_partition_query(
pipeline can advance the incremental cursor per chunk via max() without risking
data loss on restart; the non-incremental branch returns a bare SELECT *.
"""
+ select_clause = build_select_clause(enabled_columns, primary_keys, incremental_field)
+
if not should_use_incremental_field:
- return sql.SQL("SELECT * FROM {schema}.{table}").format(
+ return sql.SQL("SELECT {cols} FROM {schema}.{table}").format(
+ cols=select_clause,
schema=sql.Identifier(child_schema),
table=sql.Identifier(child_name),
)
@@ -518,7 +525,8 @@ def build_partition_query(
db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)
operator = sql.SQL(incremental_type_to_operator(incremental_field_type))
- return sql.SQL("SELECT * FROM {schema}.{table} WHERE {field} {op} {last_value} ORDER BY {field} ASC").format(
+ return sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {field} {op} {last_value} ORDER BY {field} ASC").format(
+ cols=select_clause,
schema=sql.Identifier(child_schema),
table=sql.Identifier(child_name),
field=sql.Identifier(incremental_field),
diff --git a/posthog/temporal/data_imports/sources/postgres/postgres.py b/posthog/temporal/data_imports/sources/postgres/postgres.py
index 197facbc2336..5fb7efe91d1e 100644
--- a/posthog/temporal/data_imports/sources/postgres/postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/postgres.py
@@ -52,6 +52,7 @@ from posthog.temporal.data_imports.sources.postgres.partitioned_tables import (
iterate_partitions,
list_child_partitions,
)
+from posthog.temporal.data_imports.sources.postgres.query_builders import build_select_clause
from products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings
@@ -776,15 +777,25 @@ def _build_query(
add_sampling: Optional[bool] = False,
*,
upper_bound_inclusive: Optional[Any] = None,
+ enabled_columns: Optional[list[str]] = None,
+ primary_keys: Optional[list[str]] = None,
) -> sql.Composed:
+ select_clause = build_select_clause(enabled_columns, primary_keys, incremental_field)
+
if not should_use_incremental_field:
if add_sampling:
if table_type == "view":
- query = sql.SQL("SELECT * FROM {} WHERE random() < 0.01").format(sql.Identifier(schema, table_name))
+ query = sql.SQL("SELECT {cols} FROM {table} WHERE random() < 0.01").format(
+ cols=select_clause, table=sql.Identifier(schema, table_name)
+ )
else:
- query = sql.SQL("SELECT * FROM {} TABLESAMPLE SYSTEM (1)").format(sql.Identifier(schema, table_name))
+ query = sql.SQL("SELECT {cols} FROM {table} TABLESAMPLE SYSTEM (1)").format(
+ cols=select_clause, table=sql.Identifier(schema, table_name)
+ )
else:
- query = sql.SQL("SELECT * FROM {}").format(sql.Identifier(schema, table_name))
+ query = sql.SQL("SELECT {cols} FROM {table}").format(
+ cols=select_clause, table=sql.Identifier(schema, table_name)
+ )
if add_sampling:
query_with_limit = cast(LiteralString, f"{query.as_string()} LIMIT 1000")
@@ -809,8 +820,9 @@ def _build_query(
if add_sampling:
if table_type == "view":
query = sql.SQL(
- "SELECT * FROM {schema}.{table} WHERE {incremental_field} {op} {last_value} AND random() < 0.01"
+ "SELECT {cols} FROM {schema}.{table} WHERE {incremental_field} {op} {last_value} AND random() < 0.01"
).format(
+ cols=select_clause,
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
@@ -819,8 +831,9 @@ def _build_query(
)
else:
query = sql.SQL(
- "SELECT * FROM {schema}.{table} TABLESAMPLE SYSTEM (1) WHERE {incremental_field} {op} {last_value}"
+ "SELECT {cols} FROM {schema}.{table} TABLESAMPLE SYSTEM (1) WHERE {incremental_field} {op} {last_value}"
).format(
+ cols=select_clause,
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
@@ -828,7 +841,8 @@ def _build_query(
last_value=sql.Literal(db_incremental_field_last_value),
)
else:
- query = sql.SQL("SELECT * FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
+ query = sql.SQL("SELECT {cols} FROM {schema}.{table} WHERE {incremental_field} {op} {last_value}").format(
+ cols=select_clause,
schema=sql.Identifier(schema),
table=sql.Identifier(table_name),
incremental_field=sql.Identifier(incremental_field),
@@ -1461,6 +1475,22 @@ def _get_table(
return Table(name=table_name, parents=(schema,), columns=columns, type=table_type)
+def _project_table_columns(
+ table: Table[PostgreSQLColumn],
+ retained: list[str] | None,
+) -> Table[PostgreSQLColumn]:
+ """Return a new `Table` whose columns are filtered to `retained` (in source order).
+
+ `None` retained returns the table unchanged. Columns missing from `retained` are dropped from
+ the Arrow schema so projected SELECT output zips correctly into the schema."""
+ if retained is None:
+ return table
+
+ retained_set = set(retained)
+ filtered = [column for column in table.columns if column.name in retained_set]
+ return Table(name=table.name, parents=table.parents, columns=filtered, type=table.type, alias=table.alias)
+
+
def postgres_source(
tunnel: Callable[[], _GeneratorContextManager[tuple[str, int]]],
user: str,
@@ -1478,6 +1508,7 @@ def postgres_source(
incremental_field_type: Optional[IncrementalFieldType] = None,
require_ssl: bool = False,
is_initial_sync: bool = False,
+ enabled_columns: Optional[list[str]] = None,
) -> SourceResponse:
table_name = table_names[0]
if not table_name:
@@ -1521,39 +1552,20 @@ def postgres_source(
# `is_initial_sync or full_table_scan` gating used a few lines below for
# partitioned-table row estimation.
fresh_schema_being_created = is_initial_sync or db_incremental_field_last_value is None
- table = _get_table(
+ full_table = _get_table(
cursor,
schema,
table_name,
logger,
probe_unconstrained_numeric_scale=fresh_schema_being_created,
)
- logger.debug(f"Source schema: {table.to_arrow_schema()}")
- inner_query_with_limit = _build_query(
- schema,
- table_name,
- should_use_incremental_field,
- table.type,
- incremental_field,
- incremental_field_type,
- db_incremental_field_last_value,
- add_sampling=True,
- )
-
- count_query = _build_count_query(
- schema,
- table_name,
- should_use_incremental_field,
- incremental_field,
- incremental_field_type,
- db_incremental_field_last_value,
- )
cursor.execute(
sql.SQL("SET LOCAL statement_timeout = {timeout}").format(
timeout=sql.Literal(1000 * 60 * 10) # 10 mins
)
)
+
try:
logger.debug("Checking if source is a read replica...")
using_read_replica = _is_read_replica(cursor)
@@ -1562,6 +1574,56 @@ def postgres_source(
primary_keys = _get_primary_keys(cursor, schema, table_name, logger)
if primary_keys:
logger.debug(f"Found primary keys: {primary_keys}")
+
+ # Fallback on checking for an `id` field on the table. Resolve the PKs
+ # before building queries so chunk-size sampling and the actual reader
+ # project the same columns.
+ used_id_pk_fallback = False
+ if primary_keys is None and "id" in full_table:
+ logger.debug("Falling back to ['id'] for primary keys...")
+ primary_keys = ["id"]
+ used_id_pk_fallback = True
+
+ # Project both the Arrow schema and the SELECT clause so the cursor's row shape
+ # matches what downstream consumers expect.
+ retained_columns: list[str] | None = None
+ if enabled_columns is not None:
+ retained_set: set[str] = set(enabled_columns)
+ for pk in primary_keys or []:
+ retained_set.add(pk)
+ if incremental_field:
+ retained_set.add(incremental_field)
+ retained_columns = [column.name for column in full_table.columns if column.name in retained_set]
+ # Mirror build_select_clause's fallback: when nothing remains after projection
+ # the SQL emits `SELECT *`, so the Arrow schema must stay full-table to match.
+ if not retained_columns:
+ retained_columns = None
+
+ table = _project_table_columns(full_table, retained_columns)
+ logger.debug(f"Source schema: {table.to_arrow_schema()}")
+
+ inner_query_with_limit = _build_query(
+ schema,
+ table_name,
+ should_use_incremental_field,
+ table.type,
+ incremental_field,
+ incremental_field_type,
+ db_incremental_field_last_value,
+ add_sampling=True,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ )
+
+ count_query = _build_count_query(
+ schema,
+ table_name,
+ should_use_incremental_field,
+ incremental_field,
+ incremental_field_type,
+ db_incremental_field_last_value,
+ )
+
logger.debug("Checking if table is partitioned...")
is_partitioned = False
child_partitions: list = []
@@ -1642,11 +1704,7 @@ def postgres_source(
)
has_duplicate_primary_keys = False
-
- # Fallback on checking for an `id` field on the table
- if primary_keys is None and "id" in table:
- logger.debug("Falling back to ['id'] for primary keys...")
- primary_keys = ["id"]
+ if used_id_pk_fallback:
logger.debug("Checking duplicate primary keys...")
has_duplicate_primary_keys = _has_duplicate_primary_keys(
cursor, schema, table_name, primary_keys, logger
@@ -1731,6 +1789,8 @@ def postgres_source(
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
)
successive_errors = 0
@@ -1802,6 +1862,8 @@ def postgres_source(
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
)
yield from iterate_partitions(
@@ -1831,6 +1893,8 @@ def postgres_source(
incremental_field_type,
lo,
upper_bound_inclusive=hi,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
)
yield from iterate_date_windows(
@@ -1861,6 +1925,8 @@ def postgres_source(
incremental_field,
incremental_field_type,
db_incremental_field_last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
)
logger.debug(f"Postgres query: {query.as_string()}")
diff --git a/posthog/temporal/data_imports/sources/postgres/query_builders.py b/posthog/temporal/data_imports/sources/postgres/query_builders.py
new file mode 100644
index 000000000000..591cb10c5dc5
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/postgres/query_builders.py
@@ -0,0 +1,43 @@
+"""Shared SQL fragment builders used by both the row-level and partitioned read paths."""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from psycopg import sql
+
+
+def build_select_clause(
+ enabled_columns: Optional[list[str]],
+ primary_keys: Optional[list[str]],
+ incremental_field: Optional[str],
+) -> sql.Composable:
+ # `None` and `[]` are distinct: `None` means sync all (`SELECT *`), `[]` means PKs + incremental only.
+ if enabled_columns is None:
+ return sql.SQL("*")
+
+ retained: set[str] = set(enabled_columns)
+ for pk in primary_keys or []:
+ retained.add(pk)
+ if incremental_field:
+ retained.add(incremental_field)
+
+ seen: set[str] = set()
+ ordered: list[str] = []
+ for column in enabled_columns:
+ if column in retained and column not in seen:
+ seen.add(column)
+ ordered.append(column)
+ for column in primary_keys or []:
+ if column in retained and column not in seen:
+ seen.add(column)
+ ordered.append(column)
+ if incremental_field and incremental_field in retained and incremental_field not in seen:
+ ordered.append(incremental_field)
+
+ if not ordered:
+ # `enabled_columns=[]` on a table with no PKs / incremental field would otherwise emit
+ # `SELECT FROM …`. Fall back to `*` rather than blow up the sync with a syntax error.
+ return sql.SQL("*")
+
+ return sql.SQL(", ").join(sql.Identifier(column) for column in ordered)
diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.py
index d11d180dfe40..1cc0ff2f1dd3 100644
--- a/posthog/temporal/data_imports/sources/postgres/source.py
+++ b/posthog/temporal/data_imports/sources/postgres/source.py
@@ -17,11 +17,13 @@ from posthog.schema import (
)
from posthog.exceptions_capture import capture_exception
+from posthog.temporal.data_imports.naming_convention import NamingConvention
from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
from posthog.temporal.data_imports.sources.common.mixins import SSHTunnelMixin, ValidateDatabaseHostMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.common.sql import resolve_detected_primary_keys
from posthog.temporal.data_imports.sources.generated_configs import PostgresSourceConfig
from posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfig
from posthog.temporal.data_imports.sources.postgres.cdc.slot_manager import cdc_pg_connection, drop_slot_and_publication
@@ -127,10 +129,6 @@ class PostgresSource(SimpleSource[PostgresSourceConfig], SSHTunnelMixin, Validat
type=SourceFieldInputConfigType.TEXT,
required=False,
placeholder="public",
- caption=(
- "Required for warehouse imports. Leave blank only for direct Postgres queries "
- "to browse tables across all non-system schemas."
- ),
secret=False,
),
SourceFieldSSHTunnelConfig(name="ssh_tunnel", label="Use SSH tunnel?"),
@@ -367,8 +365,10 @@ class PostgresSource(SimpleSource[PostgresSourceConfig], SSHTunnelMixin, Validat
source_catalog=discovered_schema.source_catalog,
source_schema=discovered_schema.source_schema,
source_table_name=discovered_schema.source_table_name,
- detected_primary_keys=pk_columns_by_table.get(table_name)
- or (["id"] if any(col[0] == "id" for col in discovered_schema.columns) else None),
+ detected_primary_keys=resolve_detected_primary_keys(
+ pk_columns_by_table.get(table_name),
+ discovered_schema.columns,
+ ),
)
)
@@ -418,11 +418,6 @@ class PostgresSource(SimpleSource[PostgresSourceConfig], SSHTunnelMixin, Validat
access_method: str,
schema_name: Optional[str] = None,
) -> tuple[bool, str | None]:
- if access_method != "direct":
- schema = config.schema.strip() if isinstance(config.schema, str) else ""
- if not schema and not schema_name:
- return False, "Schema is required for warehouse imports."
-
return self.validate_credentials(config, team_id, schema_name=schema_name)
def get_connection_metadata(
@@ -495,6 +490,13 @@ class PostgresSource(SimpleSource[PostgresSourceConfig], SSHTunnelMixin, Validat
else None
)
+ # Self-heal qualified rows that don't have schema_metadata yet by splitting the dotted name,
+ # so we don't fall through to `config.schema or "public"` + the literal dotted table name.
+ if (not source_schema or not source_table_name) and "." in inputs.schema_name:
+ inferred_schema, inferred_table = inputs.schema_name.split(".", 1)
+ source_schema = source_schema or inferred_schema
+ source_table_name = source_table_name or inferred_table
+
# CDC streaming schemas are handled by CDCExtractionWorkflow, not here
if schema.is_cdc and schema.cdc_mode == "streaming":
raise CDCHandledExternally(
@@ -504,15 +506,16 @@ class PostgresSource(SimpleSource[PostgresSourceConfig], SSHTunnelMixin, Validat
# CDC snapshot schemas fall through to run initial full_refresh via postgres_source()
require_ssl = source_requires_ssl(schema.source, config)
- return postgres_source(
+ # Prefer the per-row `schema_metadata.source_schema` so multi-schema warehouse sources work
+ # without needing to encode the schema in `config.schema`. Falls back to `config.schema` for
+ # legacy single-schema warehouse sources whose rows haven't been reconciled yet.
+ response = postgres_source(
tunnel=ssh_tunnel,
user=config.user,
password=config.password,
database=config.database,
sslmode="prefer",
- # config.schema wins so warehouse-mode renames flow through without rewriting
- # schema_metadata. Falls back to source_schema for direct mode (browse-all).
- schema=config.schema or source_schema or "public",
+ schema=source_schema or config.schema or "public",
table_names=[source_table_name or inputs.schema_name],
should_use_incremental_field=inputs.should_use_incremental_field,
logger=inputs.logger,
@@ -523,4 +526,11 @@ class PostgresSource(SimpleSource[PostgresSourceConfig], SSHTunnelMixin, Validat
team_id=inputs.team_id,
require_ssl=require_ssl,
is_initial_sync=not schema.initial_sync_complete,
+ enabled_columns=schema.enabled_columns,
)
+ # `SourceResponse.name` must match `DataWarehouseTable.url_pattern` (both derived from the
+ # storage key when present, otherwise the row name) so HogQL reads from where we wrote.
+ storage_key = (schema.sync_type_config or {}).get("dwh_storage_key")
+ storage_schema_name = storage_key if isinstance(storage_key, str) and storage_key else inputs.schema_name
+ response.name = NamingConvention.normalize_identifier(storage_schema_name)
+ return response
diff --git a/posthog/temporal/data_imports/sources/postgres/test_postgres.py b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
index 490094f2ee29..d0a4a7ec41cd 100644
--- a/posthog/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/posthog/temporal/data_imports/sources/postgres/test_postgres.py
@@ -137,7 +137,194 @@ class TestPostgresSourceNonRetryableErrors:
is_non_retryable = any(pattern in error_msg for pattern in non_retryable.keys())
assert is_non_retryable, f"Unrepresentable decimal error should be non-retryable: {error_msg}"
- def test_validate_credentials_for_access_method_requires_schema_for_warehouse_imports(self, source):
+
+class TestPostgresSourceForPipelineSchemaResolution:
+ @pytest.fixture
+ def source(self):
+ return PostgresSource()
+
+ def _make_inputs(self, schema_name: str):
+ return mock.MagicMock(
+ schema_id="00000000-0000-0000-0000-000000000000",
+ schema_name=schema_name,
+ should_use_incremental_field=False,
+ incremental_field=None,
+ incremental_field_type=None,
+ db_incremental_field_last_value=None,
+ team_id=1,
+ logger=mock.MagicMock(),
+ )
+
+ def _make_config(self, schema: str | None = None):
+ return mock.MagicMock(
+ user="u",
+ password="p",
+ database="db",
+ schema=schema,
+ )
+
+ def _make_schema_model(
+ self,
+ name: str,
+ schema_metadata: dict | None = None,
+ source_model=None,
+ sync_type_config: dict | None = None,
+ ):
+ schema = mock.MagicMock()
+ schema.name = name
+ schema.id = "00000000-0000-0000-0000-000000000000"
+ schema.is_cdc = False
+ schema.cdc_mode = None
+ schema.initial_sync_complete = True
+ schema.enabled_columns = None
+ schema.chunk_size_override = None
+ schema.schema_metadata = schema_metadata
+ schema.sync_type_config = sync_type_config or {}
+ schema.source = source_model or mock.MagicMock()
+ return schema
+
+ def test_dotted_schema_name_without_metadata_routes_to_correct_source_schema(self, source):
+ # Repro: row created before this PR has name="poblic.example_table" and no schema_metadata.
+ # source_for_pipeline must not fall through to config.schema or "public" — that produces
+ # `SELECT FROM "public"."poblic.example_table"`, an undefined relation.
+ schema_model = self._make_schema_model("poblic.example_table", schema_metadata=None)
+ inputs = self._make_inputs("poblic.example_table")
+ config = self._make_config(schema=None)
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.models.external_data_schema.ExternalDataSchema.objects"
+ ) as objects_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.postgres_source") as postgres_source_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.source_requires_ssl", return_value=False),
+ mock.patch.object(source, "make_ssh_tunnel_func", return_value=lambda: None),
+ ):
+ objects_mock.select_related.return_value.get.return_value = schema_model
+ postgres_source_mock.return_value = mock.MagicMock()
+
+ source.source_for_pipeline(config, inputs)
+
+ assert postgres_source_mock.called, "postgres_source was not invoked"
+ kwargs = postgres_source_mock.call_args.kwargs
+ assert kwargs["schema"] == "poblic", f"expected schema='poblic', got {kwargs['schema']!r}"
+ assert kwargs["table_names"] == ["example_table"], (
+ f"expected table_names=['example_table'], got {kwargs['table_names']!r}"
+ )
+
+ def test_schema_metadata_wins_over_dotted_name_inference(self, source):
+ # Metadata is the source of truth — explicit pin always beats name-splitting.
+ schema_model = self._make_schema_model(
+ "weird.name",
+ schema_metadata={"source_schema": "real_schema", "source_table_name": "real_table"},
+ )
+ inputs = self._make_inputs("weird.name")
+ config = self._make_config(schema=None)
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.models.external_data_schema.ExternalDataSchema.objects"
+ ) as objects_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.postgres_source") as postgres_source_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.source_requires_ssl", return_value=False),
+ mock.patch.object(source, "make_ssh_tunnel_func", return_value=lambda: None),
+ ):
+ objects_mock.select_related.return_value.get.return_value = schema_model
+ postgres_source_mock.return_value = mock.MagicMock()
+
+ source.source_for_pipeline(config, inputs)
+ kwargs = postgres_source_mock.call_args.kwargs
+ assert kwargs["schema"] == "real_schema"
+ assert kwargs["table_names"] == ["real_table"]
+
+ def test_dwh_storage_key_drives_response_name_so_delta_writes_to_legacy_path(self, source):
+ # After `consolidate_postgres_legacy_rows` renames `example_table` → `public.example_table`,
+ # the row carries `dwh_storage_key="example_table"`. `validate_schema_and_update_table` uses
+ # that key for `url_pattern`, so `SourceResponse.name` MUST also derive from the storage key
+ # — otherwise Delta files land at `.../public__example_table/` while `DataWarehouseTable.url_pattern`
+ # points at `.../example_table/` and HogQL reads from an empty location.
+ from posthog.temporal.data_imports.naming_convention import NamingConvention
+
+ schema_model = self._make_schema_model(
+ "public.example_table",
+ schema_metadata={"source_schema": "public", "source_table_name": "example_table"},
+ sync_type_config={"dwh_storage_key": "example_table"},
+ )
+ inputs = self._make_inputs("public.example_table")
+ config = self._make_config(schema=None)
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.models.external_data_schema.ExternalDataSchema.objects"
+ ) as objects_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.postgres_source") as postgres_source_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.source_requires_ssl", return_value=False),
+ mock.patch.object(source, "make_ssh_tunnel_func", return_value=lambda: None),
+ ):
+ response = mock.MagicMock()
+ objects_mock.select_related.return_value.get.return_value = schema_model
+ postgres_source_mock.return_value = response
+
+ source.source_for_pipeline(config, inputs)
+
+ assert response.name == NamingConvention.normalize_identifier("example_table"), (
+ f"response.name must derive from dwh_storage_key to keep Delta writes anchored to the "
+ f"legacy folder; got {response.name!r}"
+ )
+
+ def test_response_name_uses_schema_name_when_no_storage_key(self, source):
+ # New (non-migrated) rows have no dwh_storage_key — response.name falls back to the row's
+ # current name so the Delta path matches `url_pattern` (also derived from the row's name).
+ from posthog.temporal.data_imports.naming_convention import NamingConvention
+
+ schema_model = self._make_schema_model(
+ "poblic.new_table",
+ schema_metadata={"source_schema": "poblic", "source_table_name": "new_table"},
+ sync_type_config={},
+ )
+ inputs = self._make_inputs("poblic.new_table")
+ config = self._make_config(schema=None)
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.models.external_data_schema.ExternalDataSchema.objects"
+ ) as objects_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.postgres_source") as postgres_source_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.source_requires_ssl", return_value=False),
+ mock.patch.object(source, "make_ssh_tunnel_func", return_value=lambda: None),
+ ):
+ response = mock.MagicMock()
+ objects_mock.select_related.return_value.get.return_value = schema_model
+ postgres_source_mock.return_value = response
+
+ source.source_for_pipeline(config, inputs)
+
+ assert response.name == NamingConvention.normalize_identifier("poblic.new_table")
+
+ def test_unqualified_name_falls_back_to_config_schema(self, source):
+ # Legacy row "example_table" with no metadata + config.schema="public" → ("public", "example_table").
+ schema_model = self._make_schema_model("example_table", schema_metadata=None)
+ inputs = self._make_inputs("example_table")
+ config = self._make_config(schema="public")
+
+ with (
+ mock.patch(
+ "products.data_warehouse.backend.models.external_data_schema.ExternalDataSchema.objects"
+ ) as objects_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.postgres_source") as postgres_source_mock,
+ mock.patch("posthog.temporal.data_imports.sources.postgres.source.source_requires_ssl", return_value=False),
+ mock.patch.object(source, "make_ssh_tunnel_func", return_value=lambda: None),
+ ):
+ objects_mock.select_related.return_value.get.return_value = schema_model
+ postgres_source_mock.return_value = mock.MagicMock()
+
+ source.source_for_pipeline(config, inputs)
+ kwargs = postgres_source_mock.call_args.kwargs
+ assert kwargs["schema"] == "public"
+ assert kwargs["table_names"] == ["example_table"]
+
+ def test_validate_credentials_for_access_method_allows_blank_schema_for_warehouse_imports(self, source):
+ # Multi-schema parity: warehouse mode now accepts blank `schema` (browse-all) just like
+ # direct mode. Each `ExternalDataSchema` row pins its own `(schema, table)` in metadata.
config = source.parse_config(
{
"host": "localhost",
@@ -149,10 +336,12 @@ class TestPostgresSourceNonRetryableErrors:
}
)
- valid, error = source.validate_credentials_for_access_method(config, team_id=1, access_method="warehouse")
+ with mock.patch.object(source, "validate_credentials", return_value=(True, None)) as validate_credentials:
+ valid, error = source.validate_credentials_for_access_method(config, team_id=1, access_method="warehouse")
- assert valid is False
- assert error == "Schema is required for warehouse imports."
+ assert valid is True
+ assert error is None
+ validate_credentials.assert_called_once_with(config, 1, schema_name=None)
def test_validate_credentials_for_access_method_allows_blank_schema_for_direct_queries(self, source):
config = source.parse_config(
@@ -492,6 +681,117 @@ class TestBuildQuery:
assert '"id"' in rendered
assert "LIMIT 1000" in rendered
+ @pytest.mark.parametrize(
+ "case_name,enabled_columns,primary_keys,should_use_incremental,incremental_field,incremental_type,last_value,must_contain,must_not_contain,ordered",
+ [
+ (
+ "explicit_list_includes_pk",
+ ["email", "name"],
+ ["id"],
+ False,
+ None,
+ None,
+ None,
+ ['"email"', '"name"', '"id"'],
+ ["SELECT *"],
+ None,
+ ),
+ (
+ "preserves_user_order_pk_appended",
+ ["zeta", "alpha"],
+ ["id"],
+ False,
+ None,
+ None,
+ None,
+ [],
+ None,
+ ['"zeta"', '"alpha"', '"id"'],
+ ),
+ (
+ "includes_incremental_field",
+ ["payload"],
+ ["id"],
+ True,
+ "updated_at",
+ IncrementalFieldType.Timestamp,
+ "2024-01-01",
+ ['"payload"', '"updated_at"', '"id"'],
+ None,
+ None,
+ ),
+ (
+ "none_is_select_star",
+ None,
+ ["id"],
+ False,
+ None,
+ None,
+ None,
+ ["SELECT *"],
+ None,
+ None,
+ ),
+ (
+ "empty_keeps_only_pks_and_incremental",
+ [],
+ ["id"],
+ False,
+ None,
+ None,
+ None,
+ ['"id"'],
+ ["SELECT *"],
+ None,
+ ),
+ # Guard against an invalid `SELECT FROM` when no columns can be retained.
+ (
+ "empty_with_no_pks_or_incremental_falls_back_to_star",
+ [],
+ None,
+ False,
+ None,
+ None,
+ None,
+ ["SELECT *"],
+ None,
+ None,
+ ),
+ ],
+ )
+ def test_enabled_columns_projection(
+ self,
+ case_name,
+ enabled_columns,
+ primary_keys,
+ should_use_incremental,
+ incremental_field,
+ incremental_type,
+ last_value,
+ must_contain,
+ must_not_contain,
+ ordered,
+ ):
+ query = _build_query(
+ "public",
+ "events" if should_use_incremental else "users",
+ should_use_incremental,
+ "table",
+ incremental_field,
+ incremental_type,
+ last_value,
+ enabled_columns=enabled_columns,
+ primary_keys=primary_keys,
+ )
+ rendered = self._render(query)
+ for substring in must_contain or []:
+ assert substring in rendered, f"[{case_name}] expected {substring!r} in {rendered!r}"
+ for substring in must_not_contain or []:
+ assert substring not in rendered, f"[{case_name}] expected {substring!r} NOT in {rendered!r}"
+ if ordered:
+ positions = [rendered.index(s) for s in ordered]
+ assert positions == sorted(positions), f"[{case_name}] expected {ordered} in order in {rendered!r}"
+
@pytest.mark.parametrize(
"field_type,last_value,expected_operator",
[
diff --git a/posthog/temporal/data_imports/sources/redshift/source.py b/posthog/temporal/data_imports/sources/redshift/source.py
index 6f8690ce2cf8..4af081de1b5d 100644
--- a/posthog/temporal/data_imports/sources/redshift/source.py
+++ b/posthog/temporal/data_imports/sources/redshift/source.py
@@ -18,6 +18,7 @@ from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleS
from posthog.temporal.data_imports.sources.common.mixins import SSHTunnelMixin, ValidateDatabaseHostMixin
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.common.sql import resolve_detected_primary_keys
from posthog.temporal.data_imports.sources.generated_configs import RedshiftSourceConfig
from posthog.temporal.data_imports.sources.redshift.redshift import (
filter_redshift_incremental_fields,
@@ -225,8 +226,7 @@ class RedshiftSource(SimpleSource[RedshiftSourceConfig], SSHTunnelMixin, Validat
incremental_fields=incremental_fields,
row_count=row_counts.get(table_name, None),
columns=columns,
- detected_primary_keys=detected_pks.get(table_name)
- or (["id"] if any(col[0] == "id" for col in columns) else None),
+ detected_primary_keys=resolve_detected_primary_keys(detected_pks.get(table_name), columns),
)
)
diff --git a/posthog/temporal/tests/data_imports/test_import_data.py b/posthog/temporal/tests/data_imports/test_import_data.py
index 4d73bb2950b0..fddfee1c9b43 100644
--- a/posthog/temporal/tests/data_imports/test_import_data.py
+++ b/posthog/temporal/tests/data_imports/test_import_data.py
@@ -102,6 +102,7 @@ async def test_job_inputs_with_whitespace(activity_environment, team, **kwargs):
team_id=team.id,
require_ssl=True,
is_initial_sync=True,
+ enabled_columns=None,
)
@@ -143,6 +144,7 @@ async def test_postgres_source_without_ssh_tunnel(activity_environment, team, **
team_id=team.id,
require_ssl=True,
is_initial_sync=True,
+ enabled_columns=None,
)
@@ -196,6 +198,7 @@ async def test_postgres_source_with_ssh_tunnel_disabled(activity_environment, te
team_id=team.id,
require_ssl=True,
is_initial_sync=True,
+ enabled_columns=None,
)
@@ -264,6 +267,7 @@ async def test_postgres_source_with_ssh_tunnel_enabled(activity_environment, tea
team_id=team.id,
require_ssl=True,
is_initial_sync=True,
+ enabled_columns=None,
)
diff --git a/products/data_warehouse/backend/api/external_data_schema.py b/products/data_warehouse/backend/api/external_data_schema.py
index 910a557ae197..7f999bb6a407 100644
--- a/products/data_warehouse/backend/api/external_data_schema.py
+++ b/products/data_warehouse/backend/api/external_data_schema.py
@@ -5,7 +5,7 @@ from typing import Any, Optional
import structlog
import temporalio
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import filters, serializers, status, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.request import Request
@@ -33,12 +33,7 @@ from products.data_warehouse.backend.data_load.service import (
trigger_external_data_workflow,
unpause_external_data_schedule,
)
-from products.data_warehouse.backend.direct_postgres import (
- get_direct_postgres_location,
- hide_direct_postgres_table,
- postgres_schema_metadata_to_dwh_columns,
- upsert_direct_postgres_table,
-)
+from products.data_warehouse.backend.direct_postgres import hide_direct_postgres_table
from products.data_warehouse.backend.external_data_source.webhooks import (
create_and_register_webhook,
get_or_create_webhook_hog_function,
@@ -49,6 +44,11 @@ from products.data_warehouse.backend.models.external_data_schema import (
sync_frequency_to_sync_frequency_interval,
)
from products.data_warehouse.backend.models.external_data_source import ExternalDataSource
+from products.data_warehouse.backend.postgres_helpers import (
+ filter_dwh_columns_by_enabled_columns as _filter_dwh_columns_by_enabled_columns,
+ get_postgres_source_location,
+ reproject_direct_postgres_table,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalFieldType
logger = structlog.get_logger(__name__)
@@ -106,6 +106,21 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
allow_null=True,
help_text="For CDC syncs: consolidated, cdc_only, or both.",
)
+ enabled_columns = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Names of source columns to sync. `null` (default) syncs all columns. "
+ "Primary-key columns and the active incremental field are always retained, "
+ "even if not listed here."
+ ),
+ )
+ available_columns = serializers.SerializerMethodField(
+ read_only=True,
+ help_text="Source-side column metadata (name, data type, nullable) discovered for this schema. "
+ "Empty until the source has been refreshed via `refresh_schemas`.",
+ )
class Meta:
model = ExternalDataSchema
@@ -128,6 +143,8 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"description",
"primary_key_columns",
"cdc_table_mode",
+ "enabled_columns",
+ "available_columns",
]
read_only_fields = [
@@ -139,6 +156,36 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
"latest_error",
"status",
"description",
+ "available_columns",
+ ]
+
+ @extend_schema_field(
+ {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string"},
+ "data_type": {"type": "string"},
+ "is_nullable": {"type": "boolean"},
+ },
+ "required": ["name"],
+ },
+ }
+ )
+ def get_available_columns(self, schema: ExternalDataSchema) -> list[dict[str, Any]]:
+ metadata = schema.schema_metadata or {}
+ columns = metadata.get("columns") if isinstance(metadata, dict) else None
+ if not isinstance(columns, list):
+ return []
+ return [
+ {
+ "name": column.get("name"),
+ "data_type": column.get("data_type"),
+ "is_nullable": column.get("is_nullable"),
+ }
+ for column in columns
+ if isinstance(column, dict) and isinstance(column.get("name"), str)
]
def get_status(self, schema: ExternalDataSchema) -> str | None:
@@ -204,6 +251,26 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
validated_data.pop("primary_key_columns", None)
validated_data.pop("cdc_table_mode", None)
+ if "enabled_columns" in validated_data:
+ enabled_columns = validated_data["enabled_columns"]
+ if enabled_columns is not None:
+ if not isinstance(enabled_columns, list) or not all(isinstance(c, str) for c in enabled_columns):
+ raise ValidationError("enabled_columns must be a list of column-name strings or null.")
+ metadata = instance.schema_metadata or {}
+ metadata_columns = metadata.get("columns") if isinstance(metadata, dict) else None
+ known = (
+ {col.get("name") for col in metadata_columns if isinstance(col, dict)}
+ if isinstance(metadata_columns, list)
+ else set()
+ )
+ if known:
+ unknown = [c for c in enabled_columns if c not in known]
+ if unknown:
+ raise ValidationError(
+ f"Unknown columns in enabled_columns: {sorted(unknown)}. "
+ "Run `Pull new schemas` to refresh available columns."
+ )
+
sync_type = data.get("sync_type")
if sync_type == ExternalDataSchema.SyncType.CDC:
@@ -330,26 +397,39 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
validated_data["sync_type_config"]["reset_pipeline"] = True
trigger_refresh = True
+ enabled_columns_changed = "enabled_columns" in validated_data and (
+ validated_data["enabled_columns"] != instance.enabled_columns
+ )
+
if source.is_direct_postgres:
- # We use "should_sync" to determine if the table should be exposed or hidden.
- if should_sync is True and instance.should_sync is False:
- source_catalog, source_schema, source_table_name = get_direct_postgres_location(
- schema_name=instance.name,
- schema_metadata=instance.schema_metadata,
- default_schema=(source.job_inputs or {}).get("schema"),
- )
- validated_data["table"] = upsert_direct_postgres_table(
- instance.table,
- schema_name=instance.name,
+ # 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 False
+ projection_needs_refresh = enabled_columns_changed and instance.table is not None and instance.should_sync
+ if newly_exposed or projection_needs_refresh:
+ validated_data["table"] = reproject_direct_postgres_table(
+ instance,
source=source,
- columns=postgres_schema_metadata_to_dwh_columns(instance.schema_metadata),
- source_catalog=source_catalog,
- source_schema=source_schema,
- source_table_name=source_table_name,
+ enabled_columns=validated_data.get("enabled_columns", instance.enabled_columns),
)
if should_sync is False and instance.should_sync is True:
hide_direct_postgres_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
+ # not contain the column yet, so exposing it now would surface all-NULL queries.
+ current_columns = instance.table.columns or {}
+ projected_columns = _filter_dwh_columns_by_enabled_columns(
+ current_columns,
+ validated_data["enabled_columns"],
+ instance.primary_key_columns,
+ instance.incremental_field,
+ )
+ if projected_columns != current_columns:
+ instance.table.columns = projected_columns
+ instance.table.save(update_fields=["columns"])
# CDC publication management: add/remove table when toggling should_sync
is_cdc = (sync_type == ExternalDataSchema.SyncType.CDC) or (
@@ -469,7 +549,7 @@ class ExternalDataSchemaSerializer(serializers.ModelSerializer):
return
pub_name = cdc_config.publication_name
- _, db_schema, source_table_name = get_direct_postgres_location(
+ _, db_schema, source_table_name = get_postgres_source_location(
schema_name=instance.name,
schema_metadata=instance.schema_metadata,
default_schema=(source.job_inputs or {}).get("schema"),
diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.py
index 7d4110d2069a..78417bf44ae2 100644
--- a/products/data_warehouse/backend/api/external_data_source.py
+++ b/products/data_warehouse/backend/api/external_data_source.py
@@ -66,13 +66,7 @@ from products.data_warehouse.backend.data_load.service import (
sync_external_data_job_workflow,
trigger_external_data_source_workflow,
)
-from products.data_warehouse.backend.direct_postgres import (
- get_direct_postgres_location,
- postgres_schema_metadata,
- reconcile_direct_postgres_schemas,
- rename_direct_postgres_schemas_to_match_source_schemas,
- upsert_direct_postgres_table,
-)
+from products.data_warehouse.backend.direct_postgres import upsert_direct_postgres_table
from products.data_warehouse.backend.external_data_source.webhooks import (
create_and_register_webhook,
delete_webhook_and_hog_function,
@@ -89,6 +83,17 @@ from products.data_warehouse.backend.models import (
from products.data_warehouse.backend.models.external_data_schema import sync_old_schemas_with_new_schemas
from products.data_warehouse.backend.models.revenue_analytics_config import ExternalDataSourceRevenueAnalyticsConfig
from products.data_warehouse.backend.models.util import postgres_columns_to_dwh_columns, validate_source_prefix
+from products.data_warehouse.backend.postgres_helpers import (
+ filter_dwh_columns_by_enabled_columns,
+ get_postgres_source_location,
+ postgres_schema_metadata,
+ reconcile_postgres_schemas,
+)
+from 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.types import DataWarehouseManagedViewSetKind, ExternalDataSourceType
from products.revenue_analytics.backend.joins import ensure_person_join, remove_person_join
@@ -269,7 +274,7 @@ def get_postgres_source_table_location(
source_schema: SourceSchema | None,
default_schema: str | None,
) -> tuple[str | None, str, str]:
- return get_direct_postgres_location(
+ return get_postgres_source_location(
schema_name=schema_name,
schema_metadata={
"source_catalog": source_schema.source_catalog if source_schema else None,
@@ -370,6 +375,13 @@ class ExternalDataSourceBulkUpdateSchemaSerializer(serializers.Serializer):
choices=["consolidated", "cdc_only", "both"],
help_text="How CDC-backed tables should be exposed.",
)
+ enabled_columns = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ allow_null=True,
+ allow_empty=True,
+ help_text="Columns to sync. Null means sync all columns.",
+ )
class ExternalDataSourceBulkUpdateSchemasSerializer(serializers.Serializer):
@@ -713,6 +725,15 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
if 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(
+ 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)
+
source_config: Config = source.parse_config(new_job_inputs)
validated_data["job_inputs"] = source_config.to_dict()
@@ -743,18 +764,23 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
with transaction.atomic():
ExternalDataSource._base_manager.filter(pk=updated_source.pk).select_for_update().get()
- rename_direct_postgres_schemas_to_match_source_schemas(
+ name_substitutions = reconcile_postgres_refresh_name_substitutions(
source=updated_source,
source_schemas=discovered_schemas,
team_id=instance.team_id,
)
+ if name_substitutions:
+ schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}
+ descriptions = {
+ name_substitutions.get(name, name): description for name, description in descriptions.items()
+ }
sync_old_schemas_with_new_schemas(
schema_names,
source_id=str(updated_source.id),
team_id=instance.team_id,
descriptions=descriptions,
)
- reconcile_direct_postgres_schemas(
+ reconcile_postgres_schemas(
source=updated_source,
source_schemas=discovered_schemas,
team_id=instance.team_id,
@@ -1084,6 +1110,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
primary_key_columns = schema.get("primary_key_columns")
sync_time_of_day = schema.get("sync_time_of_day")
should_sync = schema.get("should_sync", False)
+ payload_enabled_columns = schema.get("enabled_columns")
+ if isinstance(payload_enabled_columns, list):
+ # `[]` and `None` are distinct: `None` means sync all columns, `[]` means
+ # sync only the always-retained PK + incremental field.
+ enabled_columns: list[str] | None = [
+ str(column) for column in payload_enabled_columns if isinstance(column, str)
+ ]
+ else:
+ enabled_columns = None
if should_sync and requires_incremental_fields and incremental_field is None:
new_source_model.delete()
@@ -1108,7 +1143,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
default_schema=default_source_schema,
)
)
- resolved_source_catalog, resolved_source_schema, resolved_source_table_name = get_direct_postgres_location(
+ resolved_source_catalog, resolved_source_schema, resolved_source_table_name = get_postgres_source_location(
schema_name=schema_name,
schema_metadata={
"source_catalog": source_schema.source_catalog if source_schema else None,
@@ -1173,6 +1208,7 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
description=source_schema.description if source_schema else None,
label=schema_label_by_name.get(schema_name),
sync_frequency_interval=schema_sync_frequency_interval,
+ enabled_columns=enabled_columns,
)
# For CDC schemas with PostHog-managed mode, add table to publication
@@ -1187,11 +1223,19 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
)
if new_source_model.is_direct_postgres 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=postgres_columns_to_dwh_columns(source_schema.columns if source_schema else []),
+ 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,
+ ),
source_catalog=resolved_source_catalog,
source_schema=resolved_source_schema,
source_table_name=resolved_source_table_name,
@@ -1544,6 +1588,20 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
if instance.is_direct_postgres and connection_metadata != instance.connection_metadata:
instance.connection_metadata = connection_metadata
instance.save(update_fields=["connection_metadata", "updated_at"])
+ # Postgres-only: dedupe + migrate legacy rows so sync_old_schemas doesn't create duplicates.
+ name_substitutions: dict[str, str] = {}
+ if instance.source_type == ExternalDataSourceType.POSTGRES:
+ name_substitutions = reconcile_postgres_refresh_name_substitutions(
+ source=instance,
+ source_schemas=schemas,
+ team_id=self.team_id,
+ )
+
+ if name_substitutions:
+ schema_names = {name_substitutions.get(name, name): label for name, label in schema_names.items()}
+ descriptions = {
+ name_substitutions.get(name, name): description for name, description in descriptions.items()
+ }
schemas_created, schemas_deleted = sync_old_schemas_with_new_schemas(
schema_names,
source_id=str(instance.id),
@@ -1551,8 +1609,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
descriptions=descriptions,
)
- if instance.is_direct_postgres:
- reconciled_deleted_schemas = reconcile_direct_postgres_schemas(
+ # Persist schema_metadata for per-row routing + (direct mode) rebuild DataWarehouseTable.
+ if instance.source_type == ExternalDataSourceType.POSTGRES:
+ reconciled_deleted_schemas = reconcile_postgres_schemas(
source=instance,
source_schemas=schemas,
team_id=self.team_id,
diff --git a/products/data_warehouse/backend/api/test/test_external_data_source.py b/products/data_warehouse/backend/api/test/test_external_data_source.py
index 90ebc3f96645..01ab21b8e786 100644
--- a/products/data_warehouse/backend/api/test/test_external_data_source.py
+++ b/products/data_warehouse/backend/api/test/test_external_data_source.py
@@ -1144,6 +1144,8 @@ class TestExternalDataSource(APIBaseTest):
"description": schema.description,
"primary_key_columns": None,
"cdc_table_mode": "consolidated",
+ "enabled_columns": None,
+ "available_columns": [],
}
],
)
@@ -2364,6 +2366,130 @@ class TestExternalDataSource(APIBaseTest):
else:
assert schema.sync_type_config["primary_key_columns"] == expected_persisted
+ @parameterized.expand(
+ [
+ # Field omitted -> None: sync everything (default).
+ ("omitted_means_sync_all", "omitted", None),
+ # Explicit null -> None: also sync everything.
+ ("null_means_sync_all", None, None),
+ # Explicit empty list -> []: sync only PKs + incremental field. Critical:
+ # this must NOT collapse to None, since `[]` and `None` carry different
+ # semantics downstream (`build_select_clause`, `filter_columns_by_*`).
+ ("empty_list_means_pks_only", [], []),
+ # Subset list passes through verbatim.
+ ("subset_passes_through", ["email", "name"], ["email", "name"]),
+ ]
+ )
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_create_postgres_persists_enabled_columns_payload(
+ self,
+ _name: str,
+ payload_value: list[str] | None | str,
+ expected_persisted: list[str] | None,
+ mock_get_source,
+ ):
+ source_mock = mock_get_source.return_value
+ source_mock.validate_config.return_value = (True, [])
+ parsed_config = Mock()
+ parsed_config.schema = "public"
+ parsed_config.to_dict.return_value = {
+ "host": "localhost",
+ "port": 5432,
+ "database": "app",
+ "user": "user",
+ "password": "pass",
+ "schema": "public",
+ }
+ source_mock.parse_config.return_value = parsed_config
+ source_mock.validate_credentials.return_value = (True, None)
+ source_mock.get_schemas.return_value = [
+ SourceSchema(
+ name="events",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False), ("email", "text", True), ("name", "text", True)],
+ foreign_keys=[],
+ ),
+ ]
+
+ schema_payload: dict[str, t.Any] = {"name": "events", "should_sync": True, "sync_type": None}
+ if payload_value != "omitted":
+ schema_payload["enabled_columns"] = payload_value
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Postgres",
+ "payload": {
+ "host": "localhost",
+ "port": 5432,
+ "database": "app",
+ "user": "user",
+ "password": "pass",
+ "schema": "public",
+ "schemas": [schema_payload],
+ },
+ },
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.content
+ schema = ExternalDataSchema.objects.get(team_id=self.team.pk, name="events")
+ assert schema.enabled_columns == expected_persisted
+
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_refresh_schemas_renames_legacy_direct_query_rows(self, mock_get_source):
+ # Direct-query mode opts in to eager renaming: the live `DataWarehouseTable` is rebuilt
+ # from `schema_metadata` on every `refresh_schemas`, so renaming the row never orphans
+ # data. This is the long-standing behavior we MUST preserve for direct sources.
+ mock_get_source.return_value.parse_config.return_value = None
+ mock_get_source.return_value.get_schemas.return_value = [
+ SourceSchema(
+ name="public.auth_group",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="public",
+ source_table_name="auth_group",
+ ),
+ ]
+ source = 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="Postgres",
+ created_by=self.user,
+ prefix="direct",
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ job_inputs={"host": "localhost", "port": 5432, "schema": "public"},
+ )
+ legacy_table = DataWarehouseTable.objects.create(
+ name="auth_group",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team=self.team,
+ url_pattern=DIRECT_POSTGRES_URL_PATTERN,
+ external_data_source=source,
+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64"}},
+ )
+ legacy_schema = ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="auth_group",
+ should_sync=True,
+ table=legacy_table,
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ legacy_schema.refresh_from_db()
+ # Direct mode renames the row to the qualified discovered name.
+ assert legacy_schema.name == "public.auth_group"
+ assert legacy_schema.table_id == legacy_table.id
+
def test_create_direct_non_postgres_is_rejected(self):
response = self.client.post(
f"/api/environments/{self.team.pk}/external_data_sources/",
@@ -2398,27 +2524,6 @@ class TestExternalDataSource(APIBaseTest):
{"message": "Direct query mode is currently supported only for Postgres sources."},
)
- def test_create_postgres_warehouse_source_requires_schema(self):
- response = self.client.post(
- f"/api/environments/{self.team.pk}/external_data_sources/",
- data={
- "source_type": "Postgres",
- "created_via": "web",
- "access_method": "warehouse",
- "payload": {
- "host": "db.example.com",
- "port": 5432,
- "database": "postgres",
- "user": "postgres",
- "password": "secret",
- "schema": "",
- },
- },
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertEqual(response.json(), {"message": "Schema is required for warehouse imports."})
-
@patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
def test_database_schema_postgres_direct_allows_blank_schema(self, mock_get_source):
source = PostgresSource()
diff --git a/products/data_warehouse/backend/api/test/test_postgres_warehouse_migration.py b/products/data_warehouse/backend/api/test/test_postgres_warehouse_migration.py
new file mode 100644
index 000000000000..f3a513c5c589
--- /dev/null
+++ b/products/data_warehouse/backend/api/test/test_postgres_warehouse_migration.py
@@ -0,0 +1,462 @@
+"""Integration tests for Postgres warehouse-mode migration of legacy unqualified rows.
+
+Covers `consolidate_postgres_legacy_rows` (called from `refresh_schemas`) and
+`apply_on_schema_clear` (called from PATCH when `job_inputs.schema` is dropped). Both code paths
+sit in `products/data_warehouse/backend/postgres_warehouse_migration.py`; these tests exercise
+them end-to-end through the DRF viewset to confirm the migration is observable from the API.
+"""
+
+import uuid
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import Mock, patch
+
+from rest_framework import status
+
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+
+from products.data_warehouse.backend.models import ExternalDataSchema, ExternalDataSource
+from products.data_warehouse.backend.models.table import DataWarehouseTable
+
+
+class TestPostgresWarehouseMigration(APIBaseTest):
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_refresh_schemas_qualifies_legacy_warehouse_rows_in_place(self, mock_get_source):
+ # A pre-PR warehouse Postgres source had `schema=public` on the source config and
+ # `ExternalDataSchema.name="auth_group"` (no schema prefix). After this PR, discovery
+ # returns the qualified `public.auth_group`. `consolidate_postgres_legacy_rows` qualifies
+ # the legacy row in place and stores `dwh_storage_key="auth_group"` so the next sync
+ # writes to the original Delta path — no orphaned data, but the row picks up the new
+ # qualified naming so tables from other schemas can coexist without a name collision.
+ mock_get_source.return_value.parse_config.return_value = None
+ mock_get_source.return_value.get_schemas.return_value = [
+ SourceSchema(
+ name="public.auth_group",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="public",
+ source_table_name="auth_group",
+ ),
+ ]
+ source = 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="Postgres",
+ created_by=self.user,
+ prefix="legacy",
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ job_inputs={"host": "localhost", "port": 5432, "schema": "public"},
+ )
+ legacy_table = DataWarehouseTable.objects.create(
+ name="legacypostgres_auth_group",
+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ team=self.team,
+ url_pattern="https://bucket/team_X_postgres_auth_group/*",
+ external_data_source=source,
+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64"}},
+ )
+ legacy_schema = ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="auth_group",
+ should_sync=True,
+ table=legacy_table,
+ )
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ legacy_schema.refresh_from_db()
+ legacy_table.refresh_from_db()
+ # Row gets the qualified name so multi-schema discovery doesn't collide later.
+ assert legacy_schema.name == "public.auth_group"
+ # dwh_storage_key locks the Delta path to the legacy folder so existing data is preserved.
+ assert legacy_schema.sync_type_config.get("dwh_storage_key") == "auth_group"
+ # schema_metadata pinned so source_for_pipeline knows the canonical (schema, table) tuple.
+ metadata = legacy_schema.sync_type_config.get("schema_metadata") or {}
+ assert metadata.get("source_schema") == "public"
+ assert metadata.get("source_table_name") == "auth_group"
+ # DataWarehouseTable link + url_pattern untouched — no data orphaning.
+ assert legacy_schema.table_id == legacy_table.id
+ assert legacy_table.name == "legacypostgres_auth_group"
+ assert legacy_table.url_pattern == "https://bucket/team_X_postgres_auth_group/*"
+ # Discovery returned `public.auth_group` and we consolidated the legacy row into it —
+ # no duplicate qualified row, no soft-deleted unqualified row.
+ live_schemas = ExternalDataSchema.objects.filter(
+ team_id=self.team.pk, source_id=source.pk, deleted=False
+ ).values_list("name", flat=True)
+ assert list(live_schemas) == ["public.auth_group"]
+
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_refresh_schemas_idempotent_on_legacy_warehouse_rows(self, mock_get_source):
+ # Calling refresh_schemas twice on a legacy row should be a no-op on the second call —
+ # name stays put, schema_metadata stays put, no thrash of updated_at.
+ mock_get_source.return_value.parse_config.return_value = None
+ mock_get_source.return_value.get_schemas.return_value = [
+ SourceSchema(
+ name="public.auth_group",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="public",
+ source_table_name="auth_group",
+ ),
+ ]
+ source = 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="Postgres",
+ created_by=self.user,
+ prefix="legacy",
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ job_inputs={"host": "localhost", "port": 5432, "schema": "public"},
+ )
+ ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="auth_group",
+ should_sync=True,
+ )
+
+ for _ in range(2):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ names = list(
+ ExternalDataSchema.objects.filter(team_id=self.team.pk, source_id=source.pk, deleted=False).values_list(
+ "name", flat=True
+ )
+ )
+ # First refresh qualifies the legacy row in place; second refresh is a no-op (name already
+ # qualified, no duplicate to consolidate).
+ assert names == ["public.auth_group"]
+ schema = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="public.auth_group")
+ metadata = schema.sync_type_config.get("schema_metadata") or {}
+ assert metadata.get("source_schema") == "public"
+ assert metadata.get("source_table_name") == "auth_group"
+ assert schema.sync_type_config.get("dwh_storage_key") == "auth_group"
+
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_refresh_schemas_refreshes_legacy_warehouse_metadata_when_columns_change(self, mock_get_source):
+ # available_columns must keep up with upstream changes for legacy unqualified rows.
+ # Without resolving the row by source location, reconcile_postgres_schemas would only
+ # write metadata on the very first refresh and then leave the column-picker UI stale.
+ mock_get_source.return_value.parse_config.return_value = None
+ source = 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="Postgres",
+ created_by=self.user,
+ prefix="legacy",
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ job_inputs={"host": "localhost", "port": 5432, "schema": "public"},
+ )
+ ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="auth_group",
+ should_sync=True,
+ )
+
+ mock_get_source.return_value.get_schemas.return_value = [
+ SourceSchema(
+ name="public.auth_group",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="public",
+ source_table_name="auth_group",
+ ),
+ ]
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ mock_get_source.return_value.get_schemas.return_value = [
+ SourceSchema(
+ name="public.auth_group",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False), ("new_column", "text", True)],
+ foreign_keys=[],
+ source_schema="public",
+ source_table_name="auth_group",
+ ),
+ ]
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+ assert response.status_code == status.HTTP_200_OK
+
+ # First refresh qualifies the row in place; second refresh's metadata write should still
+ # land on the same row.
+ schema = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="public.auth_group")
+ metadata_columns = (schema.sync_type_config.get("schema_metadata") or {}).get("columns") or []
+ column_names = [c["name"] for c in metadata_columns]
+ assert column_names == ["id", "new_column"]
+
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_refresh_schemas_writes_metadata_for_new_other_schema_table_after_schema_cleared(self, mock_get_source):
+ # Scenario reported by users:
+ # 1. Source created on master with `job_inputs={schema: "public"}` — limits sync to the
+ # `public` namespace. Legacy `example_table` row has no schema_metadata.
+ # 2. After upgrading to this PR the user clears `job_inputs.schema`, expecting to enable
+ # tables from other Postgres schemas (e.g. `poblic`).
+ # 3. Refresh runs, discovery returns both `public.example_table` and `poblic.example_table`.
+ #
+ # The new `poblic.example_table` row MUST carry schema_metadata pointing at `poblic`/
+ # `example_table`, otherwise source_for_pipeline falls back to `config.schema or "public"`
+ # and emits `FROM "public"."poblic.example_table"` — a non-existent relation.
+ mock_get_source.return_value.parse_config.return_value = None
+ source = 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="Postgres",
+ created_by=self.user,
+ prefix="legacy",
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ job_inputs={"host": "localhost", "port": 5432, "schema": ""}, # cleared
+ )
+ ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="example_table",
+ should_sync=True,
+ )
+
+ mock_get_source.return_value.get_schemas.return_value = [
+ SourceSchema(
+ name="public.example_table",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="public",
+ source_table_name="example_table",
+ ),
+ SourceSchema(
+ name="poblic.example_table",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("id", "integer", False)],
+ foreign_keys=[],
+ source_schema="poblic",
+ source_table_name="example_table",
+ ),
+ ]
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ # `rename_postgres_schemas_to_match_source_schemas` matches the legacy unqualified
+ # row by location to the discovered `public.example_table` (legacy falls back to "public"
+ # when no default schema is set), then `consolidate_postgres_legacy_rows` qualifies the
+ # legacy row in place using the pinned `source_schema`. `dwh_storage_key="example_table"`
+ # keeps the Delta path anchored to the legacy folder so no data is orphaned.
+ legacy = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="public.example_table")
+ legacy_metadata = legacy.sync_type_config.get("schema_metadata") or {}
+ assert legacy_metadata.get("source_schema") == "public"
+ assert legacy_metadata.get("source_table_name") == "example_table"
+ assert legacy.sync_type_config.get("dwh_storage_key") == "example_table"
+ # The unqualified row is gone — it was renamed in place.
+ assert not ExternalDataSchema.objects.filter(
+ team_id=self.team.pk, source_id=source.pk, name="example_table", deleted=False
+ ).exists()
+
+ # The other discovered table from a different schema becomes its own brand-new row.
+ new_row = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="poblic.example_table")
+ new_metadata = new_row.sync_type_config.get("schema_metadata") or {}
+ assert new_metadata.get("source_schema") == "poblic", (
+ f"source_for_pipeline would emit SELECT FROM public.poblic.example_table "
+ f"(found source_schema={new_metadata.get('source_schema')!r})"
+ )
+ assert new_metadata.get("source_table_name") == "example_table"
+
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_clearing_postgres_schema_pins_legacy_rows_to_old_default_schema(self, mock_get_source):
+ # Repro for "lost data after clearing schema". Source had schema=poblic, legacy unqualified
+ # rows were synced from poblic.<name>. When user clears the schema field, the next refresh
+ # would otherwise reanchor those rows to "public" (the static fallback) and orphan their
+ # existing Delta data. Pin metadata to the OLD schema before saving the cleared config so
+ # the rename helper can match correctly.
+ from posthog.temporal.data_imports.sources.generated_configs import PostgresSourceConfig
+
+ source_mock = mock_get_source.return_value
+ parsed_config = Mock(spec=PostgresSourceConfig)
+ parsed_config.schema = ""
+ parsed_config.to_dict.return_value = {
+ "host": "db.example.com",
+ "port": 5432,
+ "database": "db",
+ "user": "u",
+ "password": "p",
+ "schema": "",
+ }
+ source_mock.parse_config.return_value = parsed_config
+ source_mock.validate_config.return_value = (True, [])
+ source_mock.validate_credentials_for_access_method.return_value = (True, None)
+ source_mock.validate_credentials.return_value = (True, None)
+
+ source = 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="Postgres",
+ created_by=self.user,
+ prefix="legacy",
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ job_inputs={
+ "host": "db.example.com",
+ "port": 5432,
+ "database": "db",
+ "user": "u",
+ "password": "p",
+ "schema": "poblic",
+ },
+ )
+ ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="example_table",
+ should_sync=True,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "host": "db.example.com",
+ "port": 5432,
+ "database": "db",
+ "user": "u",
+ "password": "p",
+ "schema": "",
+ },
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ # Row is renamed to the qualified form so it lives alongside newly-discovered tables from
+ # other schemas (e.g. public.example_table) without colliding on the unqualified name.
+ legacy = ExternalDataSchema.objects.get(team_id=self.team.pk, source_id=source.pk, name="poblic.example_table")
+ metadata = legacy.sync_type_config.get("schema_metadata") or {}
+ assert metadata.get("source_schema") == "poblic", (
+ f"legacy row pinned to wrong schema: {metadata.get('source_schema')!r}"
+ )
+ assert metadata.get("source_table_name") == "example_table"
+ # dwh_storage_key pins the Delta path to the legacy "example_table" key so existing data
+ # stays in place — no rewrite, no orphan.
+ assert legacy.sync_type_config.get("dwh_storage_key") == "example_table"
+ # The original unqualified row is gone (it was renamed in place).
+ assert not ExternalDataSchema.objects.filter(
+ team_id=self.team.pk, source_id=source.pk, name="example_table", deleted=False
+ ).exists()
+
+ @patch("products.data_warehouse.backend.api.external_data_source.SourceRegistry.get_source")
+ def test_clearing_postgres_schema_drops_duplicate_qualified_row(self, mock_get_source):
+ # A prior refresh (before this migration landed) might have created `poblic.example_table`
+ # as a separate row. When the user clears the schema, the legacy unqualified row gets
+ # renamed to that qualified form — the orphan duplicate must be soft-deleted so the legacy
+ # row (with the actual Delta data) is canonical.
+ from posthog.temporal.data_imports.sources.generated_configs import PostgresSourceConfig
+
+ source_mock = mock_get_source.return_value
+ parsed_config = Mock(spec=PostgresSourceConfig)
+ parsed_config.schema = ""
+ parsed_config.to_dict.return_value = {
+ "host": "h",
+ "port": 5432,
+ "database": "db",
+ "user": "u",
+ "password": "p",
+ "schema": "",
+ }
+ source_mock.parse_config.return_value = parsed_config
+ source_mock.validate_config.return_value = (True, [])
+ source_mock.validate_credentials_for_access_method.return_value = (True, None)
+ source_mock.validate_credentials.return_value = (True, None)
+
+ source = 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="Postgres",
+ created_by=self.user,
+ prefix="dup",
+ access_method=ExternalDataSource.AccessMethod.WAREHOUSE,
+ job_inputs={
+ "host": "h",
+ "port": 5432,
+ "database": "db",
+ "user": "u",
+ "password": "p",
+ "schema": "poblic",
+ },
+ )
+ live_table = DataWarehouseTable.objects.create(
+ name="duppostgres_example_table",
+ format=DataWarehouseTable.TableFormat.DeltaS3Wrapper,
+ team=self.team,
+ url_pattern="https://bucket/team_X_postgres_example_table/*",
+ external_data_source=source,
+ columns={"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64"}},
+ )
+ live = ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="example_table",
+ should_sync=True,
+ table=live_table,
+ )
+ orphan = ExternalDataSchema.objects.create(
+ team_id=self.team.pk,
+ source_id=source.pk,
+ name="poblic.example_table",
+ should_sync=False,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",
+ data={
+ "job_inputs": {
+ "host": "h",
+ "port": 5432,
+ "database": "db",
+ "user": "u",
+ "password": "p",
+ "schema": "",
+ },
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.content
+
+ # The legacy row absorbs the qualified name and keeps its DataWarehouseTable link.
+ live.refresh_from_db()
+ assert live.name == "poblic.example_table"
+ assert live.table_id == live_table.id
+ assert (live.sync_type_config or {}).get("dwh_storage_key") == "example_table"
+ # The orphan duplicate is soft-deleted.
+ orphan.refresh_from_db()
+ assert orphan.deleted is True
diff --git a/products/data_warehouse/backend/direct_postgres.py b/products/data_warehouse/backend/direct_postgres.py
index fc201cca763a..6ffc1d8bda1c 100644
--- a/products/data_warehouse/backend/direct_postgres.py
+++ b/products/data_warehouse/backend/direct_postgres.py
@@ -1,148 +1,23 @@
+"""Direct-query Postgres helpers — manages the live-query `DataWarehouseTable` that lets HogQL hit
+Postgres without going through Delta. Code shared with warehouse mode lives in `postgres_helpers.py`.
+"""
+
from __future__ import annotations
from typing import TYPE_CHECKING, Any
-from django.db.models import Q
-
-from posthog.temporal.data_imports.sources.common.schema import SourceSchema
-
from products.data_warehouse.backend.models.external_data_source import ExternalDataSource
-from products.data_warehouse.backend.models.util import postgres_column_to_dwh_column, postgres_columns_to_dwh_columns
if TYPE_CHECKING:
from products.data_warehouse.backend.models.table import DataWarehouseTable
+type DirectPostgresColumns = dict[str, dict[str, Any]]
+
DIRECT_POSTGRES_URL_PATTERN = "direct://postgres"
DIRECT_POSTGRES_CATALOG_OPTION = "direct_postgres_catalog"
DIRECT_POSTGRES_SCHEMA_OPTION = "direct_postgres_schema"
DIRECT_POSTGRES_TABLE_OPTION = "direct_postgres_table"
-type DirectPostgresColumns = dict[str, dict[str, Any]]
-type DirectPostgresLocation = 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 = default_schema.strip()
- return normalized_default_schema or None
-
-
-def postgres_schema_metadata_to_dwh_columns(schema_metadata: dict[str, Any] | None) -> DirectPostgresColumns:
- resolved_columns: DirectPostgresColumns = {}
- if not schema_metadata:
- return resolved_columns
-
- columns = schema_metadata.get("columns")
- if not isinstance(columns, list):
- return resolved_columns
-
- for column in columns:
- if not isinstance(column, dict):
- continue
-
- column_name = column.get("name")
- postgres_type = column.get("data_type")
- nullable = bool(column.get("is_nullable"))
-
- if not isinstance(column_name, str) or not isinstance(postgres_type, str):
- continue
-
- resolved_columns[column_name] = postgres_column_to_dwh_column(column_name, postgres_type, nullable)
-
- return resolved_columns
-
-
-def postgres_schema_metadata(
- columns: list[tuple[str, str, bool]],
- foreign_keys: list[tuple[str, str, str]] | None = None,
- source_catalog: str | None = None,
- source_schema: str | None = None,
- source_table_name: str | None = None,
-) -> dict[str, Any]:
- return {
- "columns": [
- {"name": column_name, "data_type": postgres_type, "is_nullable": nullable}
- for column_name, postgres_type, nullable in columns
- ],
- "foreign_keys": [
- {"column": column_name, "target_table": target_table, "target_column": target_column}
- for column_name, target_table, target_column in (foreign_keys or [])
- ],
- "source_catalog": source_catalog,
- "source_schema": source_schema,
- "source_table_name": source_table_name,
- }
-
-
-def get_direct_postgres_location(
- *,
- schema_name: str,
- schema_metadata: dict[str, Any] | None = None,
- default_schema: str | None = None,
-) -> tuple[str | None, str, str]:
- source_catalog = schema_metadata.get("source_catalog") if isinstance(schema_metadata, dict) else None
- source_schema = schema_metadata.get("source_schema") if isinstance(schema_metadata, dict) else None
- source_table_name = schema_metadata.get("source_table_name") if isinstance(schema_metadata, dict) else None
- normalized_default_schema = _normalize_default_schema(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_name
-
- if normalized_default_schema is None and "." in schema_name:
- inferred_schema, inferred_table_name = schema_name.split(".", 1)
- return None, inferred_schema, inferred_table_name
-
- return None, normalized_default_schema or "public", schema_name
-
-
-def get_direct_postgres_location_for_schema_model(
- *,
- schema_name: str,
- sync_type_config: dict[str, Any] | None = None,
- table_options: dict[str, Any] | None = None,
- default_schema: str | None = None,
-) -> DirectPostgresLocation:
- schema_metadata = (
- sync_type_config.get("schema_metadata")
- if isinstance(sync_type_config, dict) and isinstance(sync_type_config.get("schema_metadata"), dict)
- else None
- )
-
- if schema_metadata is not None:
- return get_direct_postgres_location(
- schema_name=schema_name,
- schema_metadata=schema_metadata,
- default_schema=default_schema,
- )
-
- table_source_schema = table_options.get(DIRECT_POSTGRES_SCHEMA_OPTION) if isinstance(table_options, dict) else None
- table_source_table_name = (
- table_options.get(DIRECT_POSTGRES_TABLE_OPTION) if isinstance(table_options, dict) else None
- )
- table_source_catalog = (
- table_options.get(DIRECT_POSTGRES_CATALOG_OPTION) if isinstance(table_options, dict) else None
- )
-
- if isinstance(table_source_schema, str) and isinstance(table_source_table_name, str):
- return (
- table_source_catalog if isinstance(table_source_catalog, str) else None,
- table_source_schema,
- table_source_table_name,
- )
-
- # Legacy direct-query rows may only have the schema encoded in the display name.
- if "." in schema_name:
- inferred_schema, inferred_table_name = schema_name.split(".", 1)
- return None, inferred_schema, inferred_table_name
-
- return get_direct_postgres_location(
- schema_name=schema_name,
- schema_metadata=None,
- default_schema=default_schema,
- )
-
def get_direct_postgres_table_options(
*, source_catalog: str | None = None, source_schema: str, source_table_name: str
@@ -218,137 +93,7 @@ def hide_direct_postgres_table(table: DataWarehouseTable | None) -> None:
def rename_direct_postgres_join_references(*, team_id: int, old_name: str, new_name: str) -> None:
if old_name == new_name:
return
-
from products.data_warehouse.backend.models.join import DataWarehouseJoin
DataWarehouseJoin.objects.filter(team_id=team_id, source_table_name=old_name).update(source_table_name=new_name)
DataWarehouseJoin.objects.filter(team_id=team_id, joining_table_name=old_name).update(joining_table_name=new_name)
-
-
-def reconcile_direct_postgres_schemas(
- *,
- source: ExternalDataSource,
- source_schemas: list[SourceSchema],
- team_id: int,
-) -> list[str]:
- from products.data_warehouse.backend.models.external_data_schema import ExternalDataSchema
-
- source_schema_names = [schema.name for schema in source_schemas]
- schema_models = {
- schema.name: schema
- for schema in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False)
- }
-
- for source_schema in source_schemas:
- schema_model = schema_models.get(source_schema.name)
- if schema_model is None:
- continue
-
- resolved_source_catalog, resolved_source_schema, resolved_source_table_name = get_direct_postgres_location(
- schema_name=source_schema.name,
- schema_metadata={
- "source_catalog": source_schema.source_catalog,
- "source_schema": source_schema.source_schema,
- "source_table_name": source_schema.source_table_name,
- },
- default_schema=(source.job_inputs or {}).get("schema"),
- )
- schema_metadata = postgres_schema_metadata(
- source_schema.columns,
- source_schema.foreign_keys,
- source_catalog=resolved_source_catalog,
- source_schema=resolved_source_schema,
- source_table_name=resolved_source_table_name,
- )
- schema_model.sync_type_config = {**(schema_model.sync_type_config or {}), "schema_metadata": schema_metadata}
- schema_model.save(update_fields=["sync_type_config", "updated_at"])
-
- if not schema_model.should_sync:
- hide_direct_postgres_table(schema_model.table)
- continue
-
- table_model = upsert_direct_postgres_table(
- schema_model.table,
- schema_name=source_schema.name,
- source=source,
- columns=postgres_columns_to_dwh_columns(source_schema.columns),
- source_catalog=resolved_source_catalog,
- source_schema=resolved_source_schema,
- source_table_name=resolved_source_table_name,
- )
- if schema_model.table_id != table_model.id:
- schema_model.table = table_model
- schema_model.save(update_fields=["table"])
-
- stale_schema_names: list[str] = []
- stale_schemas = ExternalDataSchema.objects.filter(
- Q(team_id=team_id, source_id=source.id),
- Q(deleted=False) | Q(table__deleted=False),
- ).exclude(name__in=source_schema_names)
-
- for stale_schema in stale_schemas:
- hide_direct_postgres_table(stale_schema.table)
- if not stale_schema.deleted:
- stale_schema.soft_delete()
- stale_schema_names.append(stale_schema.name)
-
- return stale_schema_names
-
-
-def rename_direct_postgres_schemas_to_match_source_schemas(
- *,
- source: ExternalDataSource,
- source_schemas: list[SourceSchema],
- team_id: int,
-) -> None:
- from products.data_warehouse.backend.models.external_data_schema import ExternalDataSchema
-
- default_schema = (source.job_inputs or {}).get("schema")
- schema_models = list(
- ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related("table")
- )
- schema_models_by_name = {schema.name: schema for schema in schema_models}
- schema_models_by_location: dict[DirectPostgresLocation, list[ExternalDataSchema]] = {}
-
- for schema_model in schema_models:
- location = get_direct_postgres_location_for_schema_model(
- schema_name=schema_model.name,
- sync_type_config=schema_model.sync_type_config,
- table_options=schema_model.table.options if schema_model.table is not None else None,
- default_schema=default_schema,
- )
- schema_models_by_location.setdefault(location, []).append(schema_model)
-
- renamed_schema_ids: set[str] = set()
-
- for source_schema in source_schemas:
- if source_schema.name in schema_models_by_name:
- continue
-
- location = get_direct_postgres_location(
- schema_name=source_schema.name,
- schema_metadata={
- "source_catalog": source_schema.source_catalog,
- "source_schema": source_schema.source_schema,
- "source_table_name": source_schema.source_table_name,
- },
- default_schema=default_schema,
- )
- rename_candidate = next(
- (
- schema_model
- for schema_model in schema_models_by_location.get(location, [])
- if str(schema_model.id) not in renamed_schema_ids and schema_model.name != source_schema.name
- ),
- None,
- )
- if rename_candidate is None:
- continue
-
- old_name = rename_candidate.name
- rename_candidate.name = source_schema.name
- rename_candidate.save(update_fields=["name", "updated_at"])
- rename_direct_postgres_join_references(team_id=team_id, old_name=old_name, new_name=source_schema.name)
- schema_models_by_name.pop(old_name, None)
- schema_models_by_name[source_schema.name] = rename_candidate
- renamed_schema_ids.add(str(rename_candidate.id))
diff --git a/products/data_warehouse/backend/migrations/0052_externaldataschema_enabled_columns.py b/products/data_warehouse/backend/migrations/0052_externaldataschema_enabled_columns.py
new file mode 100644
index 000000000000..1bbefc02d241
--- /dev/null
+++ b/products/data_warehouse/backend/migrations/0052_externaldataschema_enabled_columns.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_warehouse", "0051_alter_externaldatasource_source_type"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="externaldataschema",
+ name="enabled_columns",
+ field=models.JSONField(blank=True, default=None, null=True),
+ ),
+ ]
diff --git a/products/data_warehouse/backend/migrations/max_migration.txt b/products/data_warehouse/backend/migrations/max_migration.txt
index ab669125c49c..939c5e7005e9 100644
--- a/products/data_warehouse/backend/migrations/max_migration.txt
+++ b/products/data_warehouse/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0051_alter_externaldatasource_source_type
+0052_externaldataschema_enabled_columns
diff --git a/products/data_warehouse/backend/models/external_data_schema.py b/products/data_warehouse/backend/models/external_data_schema.py
index fcff42fb8bd7..039549fa596d 100644
--- a/products/data_warehouse/backend/models/external_data_schema.py
+++ b/products/data_warehouse/backend/models/external_data_schema.py
@@ -74,6 +74,9 @@ class ExternalDataSchema(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
sync_time_of_day = models.TimeField(null=True, blank=True, help_text="Time of day to run the sync (UTC)")
initial_sync_complete = models.BooleanField(default=False)
description = models.CharField(max_length=1000, null=True, blank=True)
+ # null = sync all columns (default). Non-empty list = exact column projection.
+ # PK + active incremental field are always retained server-side regardless of this list.
+ enabled_columns = models.JSONField(null=True, blank=True, default=None)
__repr__ = sane_repr("name")
diff --git a/products/data_warehouse/backend/postgres_helpers.py b/products/data_warehouse/backend/postgres_helpers.py
new file mode 100644
index 000000000000..c807ffb61008
--- /dev/null
+++ b/products/data_warehouse/backend/postgres_helpers.py
@@ -0,0 +1,410 @@
+"""Postgres source helpers shared between warehouse and direct-query modes.
+
+Direct-query-mode-only utilities (DataWarehouseTable upserts, the `direct://postgres` url_pattern,
+the option keys that encode source location on a direct table) live in `direct_postgres.py`. This
+module holds the parts both modes need: schema metadata builders, location resolution, column
+filtering, and the reconcile/rename helpers.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, Any, TypeVar
+
+from django.db.models import Q
+
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+
+from products.data_warehouse.backend.direct_postgres import (
+ DIRECT_POSTGRES_CATALOG_OPTION,
+ DIRECT_POSTGRES_SCHEMA_OPTION,
+ DIRECT_POSTGRES_TABLE_OPTION,
+ hide_direct_postgres_table,
+ rename_direct_postgres_join_references,
+ upsert_direct_postgres_table,
+)
+from products.data_warehouse.backend.models.external_data_source import ExternalDataSource
+from products.data_warehouse.backend.models.util import postgres_column_to_dwh_column, postgres_columns_to_dwh_columns
+
+if TYPE_CHECKING:
+ pass
+
+_TColumnValue = TypeVar("_TColumnValue")
+
+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,
+ source_catalog: str | None = None,
+ source_schema: str | None = None,
+ source_table_name: str | None = None,
+) -> dict[str, Any]:
+ return {
+ "columns": [
+ {"name": column_name, "data_type": postgres_type, "is_nullable": nullable}
+ for column_name, postgres_type, nullable in columns
+ ],
+ "foreign_keys": [
+ {"column": column_name, "target_table": target_table, "target_column": target_column}
+ for column_name, target_table, target_column in (foreign_keys or [])
+ ],
+ "source_catalog": source_catalog,
+ "source_schema": source_schema,
+ "source_table_name": source_table_name,
+ }
+
+
+def postgres_schema_metadata_to_dwh_columns(schema_metadata: dict[str, Any] | None) -> PostgresDwhColumns:
+ resolved: PostgresDwhColumns = {}
+ if not schema_metadata:
+ return resolved
+ columns = schema_metadata.get("columns")
+ if not isinstance(columns, list):
+ return resolved
+ for column in columns:
+ if not isinstance(column, dict):
+ continue
+ column_name = column.get("name")
+ postgres_type = column.get("data_type")
+ nullable = bool(column.get("is_nullable"))
+ if not isinstance(column_name, str) or not isinstance(postgres_type, str):
+ continue
+ resolved[column_name] = postgres_column_to_dwh_column(column_name, postgres_type, nullable)
+ return resolved
+
+
+def get_postgres_source_location(
+ *,
+ schema_name: str,
+ schema_metadata: dict[str, Any] | None = None,
+ default_schema: str | None = None,
+) -> PostgresSourceLocation:
+ """Resolve `(source_catalog, source_schema, source_table_name)` for a Postgres row.
+
+ Priority: explicit metadata → dot-split when no default schema → default schema fallback.
+ """
+ source_catalog = schema_metadata.get("source_catalog") if isinstance(schema_metadata, dict) else None
+ source_schema = schema_metadata.get("source_schema") if isinstance(schema_metadata, dict) else None
+ source_table_name = schema_metadata.get("source_table_name") if isinstance(schema_metadata, dict) else None
+ normalized_default = _normalize_default_schema(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_name
+
+ if normalized_default is None and "." in schema_name:
+ inferred_schema, inferred_table = schema_name.split(".", 1)
+ return None, inferred_schema, inferred_table
+
+ return None, normalized_default or "public", schema_name
+
+
+def get_postgres_source_location_for_schema_model(
+ *,
+ schema_name: str,
+ sync_type_config: dict[str, Any] | None = None,
+ table_options: dict[str, Any] | None = None,
+ default_schema: str | None = None,
+) -> PostgresSourceLocation:
+ schema_metadata = (
+ sync_type_config.get("schema_metadata")
+ if isinstance(sync_type_config, dict) and isinstance(sync_type_config.get("schema_metadata"), dict)
+ else None
+ )
+ if schema_metadata is not None:
+ return get_postgres_source_location(
+ schema_name=schema_name,
+ schema_metadata=schema_metadata,
+ default_schema=default_schema,
+ )
+
+ table_source_schema = table_options.get(DIRECT_POSTGRES_SCHEMA_OPTION) if isinstance(table_options, dict) else None
+ table_source_table_name = (
+ table_options.get(DIRECT_POSTGRES_TABLE_OPTION) if isinstance(table_options, dict) else None
+ )
+ table_source_catalog = (
+ table_options.get(DIRECT_POSTGRES_CATALOG_OPTION) if isinstance(table_options, dict) else None
+ )
+ if isinstance(table_source_schema, str) and isinstance(table_source_table_name, str):
+ return (
+ table_source_catalog if isinstance(table_source_catalog, str) else None,
+ table_source_schema,
+ table_source_table_name,
+ )
+
+ # Legacy direct-query rows may only have the schema encoded in the display name.
+ if "." in schema_name:
+ inferred_schema, inferred_table = schema_name.split(".", 1)
+ return None, inferred_schema, inferred_table
+
+ return get_postgres_source_location(
+ schema_name=schema_name,
+ schema_metadata=None,
+ default_schema=default_schema,
+ )
+
+
+def filter_dwh_columns_by_enabled_columns(
+ columns: dict[str, _TColumnValue],
+ enabled_columns: list[str] | None,
+ primary_keys: list[str] | None,
+ incremental_field: str | None = None,
+) -> dict[str, _TColumnValue]:
+ # `None` and `[]` are distinct: `None` syncs all, `[]` retains only PKs + incremental.
+ if enabled_columns is None:
+ return columns
+ retained: set[str] = set(enabled_columns)
+ for pk in primary_keys or []:
+ retained.add(pk)
+ if incremental_field:
+ retained.add(incremental_field)
+ return {name: column for name, column in columns.items() if name in retained}
+
+
+def filter_columns_by_enabled_columns(
+ columns: list[tuple[str, str, bool]],
+ enabled_columns: list[str] | None,
+ primary_keys: list[str] | None,
+ incremental_field: str | None = None,
+) -> list[tuple[str, str, bool]]:
+ if enabled_columns is None:
+ return columns
+ retained: set[str] = set(enabled_columns)
+ for pk in primary_keys or []:
+ retained.add(pk)
+ if incremental_field:
+ retained.add(incremental_field)
+ return [col for col in columns if col[0] in retained]
+
+
+def reconcile_postgres_schemas(
+ *,
+ source: ExternalDataSource,
+ source_schemas: list[SourceSchema],
+ team_id: int,
+) -> list[str]:
+ """Persist `schema_metadata` on every Postgres row + (direct mode only) upsert its live-query
+ `DataWarehouseTable`. Returns stale schema names that got soft-deleted (direct only)."""
+ from products.data_warehouse.backend.models.external_data_schema import ExternalDataSchema
+
+ is_direct = source.is_direct_query
+ source_schema_names = [s.name for s in source_schemas]
+ default_schema = (source.job_inputs or {}).get("schema")
+ schema_models = {
+ s.name: s for s in ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False)
+ }
+
+ # Location-indexed fallback so unqualified legacy rows still resolve to their qualified
+ # discovered counterparts on every refresh.
+ schema_models_by_location: dict[PostgresSourceLocation, ExternalDataSchema] = {}
+ for schema_model in schema_models.values():
+ location = get_postgres_source_location_for_schema_model(
+ schema_name=schema_model.name,
+ sync_type_config=schema_model.sync_type_config,
+ table_options=schema_model.table.options if schema_model.table is not None else None,
+ default_schema=default_schema,
+ )
+ schema_models_by_location.setdefault(location, schema_model)
+
+ for source_schema in source_schemas:
+ matched: ExternalDataSchema | None = schema_models.get(source_schema.name)
+ if matched is None:
+ location = get_postgres_source_location(
+ schema_name=source_schema.name,
+ schema_metadata={
+ "source_catalog": source_schema.source_catalog,
+ "source_schema": source_schema.source_schema,
+ "source_table_name": source_schema.source_table_name,
+ },
+ default_schema=default_schema,
+ )
+ matched = schema_models_by_location.get(location)
+ if matched is None:
+ continue
+
+ resolved_catalog, resolved_schema, resolved_table = get_postgres_source_location(
+ schema_name=source_schema.name,
+ schema_metadata={
+ "source_catalog": source_schema.source_catalog,
+ "source_schema": source_schema.source_schema,
+ "source_table_name": source_schema.source_table_name,
+ },
+ default_schema=default_schema,
+ )
+ # Metadata holds the full column list (column-picker UI); projection lives on `enabled_columns`.
+ schema_metadata = postgres_schema_metadata(
+ source_schema.columns,
+ source_schema.foreign_keys,
+ source_catalog=resolved_catalog,
+ source_schema=resolved_schema,
+ source_table_name=resolved_table,
+ )
+ matched.sync_type_config = {**(matched.sync_type_config or {}), "schema_metadata": schema_metadata}
+ matched.save(update_fields=["sync_type_config", "updated_at"])
+
+ if not is_direct:
+ # Warehouse mode: the ingestion workflow manages `DataWarehouseTable` itself.
+ continue
+
+ if not matched.should_sync:
+ hide_direct_postgres_table(matched.table)
+ continue
+
+ projected_columns = filter_columns_by_enabled_columns(
+ source_schema.columns,
+ matched.enabled_columns,
+ source_schema.detected_primary_keys,
+ matched.incremental_field,
+ )
+ table_model = upsert_direct_postgres_table(
+ matched.table,
+ schema_name=source_schema.name,
+ source=source,
+ columns=postgres_columns_to_dwh_columns(projected_columns),
+ source_catalog=resolved_catalog,
+ source_schema=resolved_schema,
+ source_table_name=resolved_table,
+ )
+ if matched.table_id != table_model.id:
+ matched.table = table_model
+ matched.save(update_fields=["table"])
+
+ if not is_direct:
+ # Warehouse mode delegates add/delete to `sync_old_schemas_with_new_schemas`.
+ return []
+
+ stale_names: list[str] = []
+ stale = ExternalDataSchema.objects.filter(
+ Q(team_id=team_id, source_id=source.id),
+ Q(deleted=False) | Q(table__deleted=False),
+ ).exclude(name__in=source_schema_names)
+ for s in stale:
+ hide_direct_postgres_table(s.table)
+ if not s.deleted:
+ s.soft_delete()
+ stale_names.append(s.name)
+ return stale_names
+
+
+def reproject_direct_postgres_table(
+ schema_row: Any,
+ *,
+ source: ExternalDataSource,
+ enabled_columns: list[str] | None,
+) -> Any:
+ """Rebuild the direct-query `DataWarehouseTable` with a fresh column projection — used on
+ column-picker save and on `should_sync` False → True. No re-sync needed in direct mode.
+ """
+ source_catalog, source_schema, source_table_name = get_postgres_source_location(
+ schema_name=schema_row.name,
+ schema_metadata=schema_row.schema_metadata,
+ default_schema=(source.job_inputs or {}).get("schema"),
+ )
+ return upsert_direct_postgres_table(
+ schema_row.table,
+ schema_name=schema_row.name,
+ source=source,
+ columns=filter_dwh_columns_by_enabled_columns(
+ postgres_schema_metadata_to_dwh_columns(schema_row.schema_metadata),
+ enabled_columns,
+ schema_row.primary_key_columns,
+ schema_row.incremental_field,
+ ),
+ source_catalog=source_catalog,
+ source_schema=source_schema,
+ source_table_name=source_table_name,
+ )
+
+
+def rename_postgres_schemas_to_match_source_schemas(
+ *,
+ source: ExternalDataSource,
+ source_schemas: list[SourceSchema],
+ team_id: int,
+ allow_rename: bool = True,
+) -> dict[str, str]:
+ """Match discovered schemas to existing rows by source location.
+ Direct mode (`allow_rename=True`) rewrites `name` in place; warehouse mode pins
+ `schema_metadata` only — the rename happens in `postgres_warehouse_migration`.
+ """
+ from products.data_warehouse.backend.models.external_data_schema import ExternalDataSchema
+
+ default_schema = (source.job_inputs or {}).get("schema")
+ schema_models = list(
+ ExternalDataSchema.objects.filter(team_id=team_id, source_id=source.id, deleted=False).select_related("table")
+ )
+ schema_models_by_name = {s.name: s for s in schema_models}
+ schema_models_by_location: dict[PostgresSourceLocation, list[ExternalDataSchema]] = {}
+ for s in schema_models:
+ location = get_postgres_source_location_for_schema_model(
+ schema_name=s.name,
+ sync_type_config=s.sync_type_config,
+ table_options=s.table.options if s.table is not None else None,
+ default_schema=default_schema,
+ )
+ schema_models_by_location.setdefault(location, []).append(s)
+
+ renamed_ids: set[str] = set()
+ name_substitutions: dict[str, str] = {}
+
+ for source_schema in source_schemas:
+ if source_schema.name in schema_models_by_name:
+ continue
+ location = get_postgres_source_location(
+ schema_name=source_schema.name,
+ schema_metadata={
+ "source_catalog": source_schema.source_catalog,
+ "source_schema": source_schema.source_schema,
+ "source_table_name": source_schema.source_table_name,
+ },
+ default_schema=default_schema,
+ )
+ candidate = next(
+ (
+ s
+ for s in schema_models_by_location.get(location, [])
+ if str(s.id) not in renamed_ids and s.name != source_schema.name
+ ),
+ None,
+ )
+ if candidate is None:
+ continue
+
+ if not allow_rename:
+ # Pin metadata so reconcile matches `candidate` to this discovered table by location.
+ sync_type_config = candidate.sync_type_config or {}
+ existing_metadata = sync_type_config.get("schema_metadata")
+ if not isinstance(existing_metadata, dict) or not existing_metadata.get("source_table_name"):
+ candidate.sync_type_config = {
+ **sync_type_config,
+ "schema_metadata": postgres_schema_metadata(
+ source_schema.columns,
+ source_schema.foreign_keys,
+ source_catalog=source_schema.source_catalog,
+ source_schema=source_schema.source_schema,
+ source_table_name=source_schema.source_table_name,
+ ),
+ }
+ candidate.save(update_fields=["sync_type_config", "updated_at"])
+ name_substitutions[source_schema.name] = candidate.name
+ schema_models_by_name[source_schema.name] = candidate
+ renamed_ids.add(str(candidate.id))
+ continue
+
+ old_name = candidate.name
+ candidate.name = source_schema.name
+ candidate.save(update_fields=["name", "updated_at"])
+ rename_direct_postgres_join_references(team_id=team_id, old_name=old_name, new_name=source_schema.name)
+ schema_models_by_name.pop(old_name, None)
+ schema_models_by_name[source_schema.name] = candidate
+ renamed_ids.add(str(candidate.id))
+
+ return name_substitutions
diff --git a/products/data_warehouse/backend/postgres_warehouse_migration.py b/products/data_warehouse/backend/postgres_warehouse_migration.py
new file mode 100644
index 000000000000..986b820c7cf6
--- /dev/null
+++ b/products/data_warehouse/backend/postgres_warehouse_migration.py
@@ -0,0 +1,221 @@
+"""Migrate pre-PR Postgres warehouse rows to qualified naming without re-syncing.
+
+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).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+
+from products.data_warehouse.backend.models.external_data_source import ExternalDataSource
+from products.data_warehouse.backend.postgres_helpers import (
+ _normalize_default_schema,
+ rename_postgres_schemas_to_match_source_schemas,
+)
+
+
+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.data_warehouse.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,
+ source_schemas: list[SourceSchema],
+ team_id: int,
+) -> dict[str, str]:
+ """Compute name substitutions for a Postgres refresh — combines the rename helper (direct mode
+ eager rename / warehouse metadata pin) with the consolidate helper (warehouse-mode qualify in
+ place) and chains them so the caller feeds a single dict to `sync_old_schemas_with_new_schemas`.
+ """
+ name_substitutions = rename_postgres_schemas_to_match_source_schemas(
+ source=source,
+ source_schemas=source_schemas,
+ team_id=team_id,
+ # Warehouse-mode rename would change the Delta path on the next sync; defer to consolidate
+ # below which preserves the path via `dwh_storage_key`.
+ allow_rename=source.is_direct_query,
+ )
+
+ if not source.is_direct_query:
+ consolidation_substitutions = apply_on_refresh(source=source, team_id=team_id)
+ # Chain {discovered: existing} → {discovered: renamed} when consolidate renamed `existing`.
+ for old_name, new_name in consolidation_substitutions.items():
+ for discovered, existing in list(name_substitutions.items()):
+ if existing == old_name:
+ name_substitutions[discovered] = new_name
+ name_substitutions = {**name_substitutions, **consolidation_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.data_warehouse.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_substitutions
diff --git a/products/data_warehouse/backend/test/test_direct_postgres.py b/products/data_warehouse/backend/test/test_direct_postgres.py
deleted file mode 100644
index 8a466f57c428..000000000000
--- a/products/data_warehouse/backend/test/test_direct_postgres.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from parameterized import parameterized
-
-from products.data_warehouse.backend.direct_postgres import get_direct_postgres_location
-
-
-class TestGetDirectPostgresLocation:
- @parameterized.expand(
- [
- ("whitespace_only_schema", "public.accounts", " ", (None, "public", "accounts")),
- ("trimmed_schema", "accounts", " public ", (None, "public", "accounts")),
- ]
- )
- def test_normalizes_default_schema_before_inference(
- self, _name: str, schema_name: str, default_schema: str, expected: tuple[str | None, str, str]
- ) -> None:
- assert get_direct_postgres_location(schema_name=schema_name, default_schema=default_schema) == expected
diff --git a/products/data_warehouse/backend/test/test_postgres_helpers.py b/products/data_warehouse/backend/test/test_postgres_helpers.py
new file mode 100644
index 000000000000..bf93caf5be2f
--- /dev/null
+++ b/products/data_warehouse/backend/test/test_postgres_helpers.py
@@ -0,0 +1,75 @@
+from parameterized import parameterized
+
+from products.data_warehouse.backend.postgres_helpers import (
+ filter_columns_by_enabled_columns,
+ filter_dwh_columns_by_enabled_columns,
+ get_postgres_source_location,
+)
+
+
+class TestGetPostgresSourceLocation:
+ @parameterized.expand(
+ [
+ ("whitespace_only_schema", "public.accounts", " ", (None, "public", "accounts")),
+ ("trimmed_schema", "accounts", " public ", (None, "public", "accounts")),
+ ]
+ )
+ def test_normalizes_default_schema_before_inference(
+ self, _name: str, schema_name: str, default_schema: str, expected: tuple[str | None, str, str]
+ ) -> None:
+ assert get_postgres_source_location(schema_name=schema_name, default_schema=default_schema) == expected
+
+
+class TestFilterColumnsByEnabledColumns:
+ columns = [("id", "integer", False), ("email", "text", True), ("name", "text", True), ("secret", "text", True)]
+
+ def test_none_returns_all(self) -> None:
+ assert filter_columns_by_enabled_columns(self.columns, None, ["id"]) == self.columns
+
+ def test_empty_keeps_only_pks(self) -> None:
+ result = filter_columns_by_enabled_columns(self.columns, [], ["id"])
+ names = [name for name, _type, _nullable in result]
+ assert names == ["id"]
+
+ def test_subset_excludes_unselected(self) -> None:
+ result = filter_columns_by_enabled_columns(self.columns, ["email"], ["id"])
+ names = [name for name, _type, _nullable in result]
+ # PK retained, secret excluded, source order preserved.
+ assert names == ["id", "email"]
+
+ def test_incremental_field_retained(self) -> None:
+ result = filter_columns_by_enabled_columns(self.columns, ["email"], ["id"], incremental_field="name")
+ names = [name for name, _type, _nullable in result]
+ assert "name" in names
+
+ def test_unknown_enabled_column_silently_dropped(self) -> None:
+ # Validation lives at the API boundary; helper just intersects with available columns.
+ result = filter_columns_by_enabled_columns(self.columns, ["email", "ghost"], ["id"])
+ names = [name for name, _type, _nullable in result]
+ assert names == ["id", "email"]
+
+
+class TestFilterDwhColumnsByEnabledColumns:
+ dwh_columns = {
+ "id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64"},
+ "email": {"hogql": "StringDatabaseField", "clickhouse": "String"},
+ "updated_at": {"hogql": "DateTimeDatabaseField", "clickhouse": "DateTime"},
+ "secret": {"hogql": "StringDatabaseField", "clickhouse": "String"},
+ }
+
+ def test_none_returns_all(self) -> None:
+ assert filter_dwh_columns_by_enabled_columns(self.dwh_columns, None, ["id"]) == self.dwh_columns
+
+ def test_subset_keeps_pks(self) -> None:
+ result = filter_dwh_columns_by_enabled_columns(self.dwh_columns, ["email"], ["id"])
+ assert set(result.keys()) == {"id", "email"}
+
+ def test_incremental_field_retained(self) -> None:
+ result = filter_dwh_columns_by_enabled_columns(
+ self.dwh_columns, ["email"], ["id"], incremental_field="updated_at"
+ )
+ assert set(result.keys()) == {"id", "email", "updated_at"}
+
+ def test_empty_keeps_only_pks_and_incremental(self) -> None:
+ result = filter_dwh_columns_by_enabled_columns(self.dwh_columns, [], ["id"], incremental_field="updated_at")
+ assert set(result.keys()) == {"id", "updated_at"}
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 22929d2b1300..e67cb60b902c 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -237,6 +237,12 @@ export const CdcTableModeEnumApi = {
*/
export type ExternalDataSchemaApiTable = { [key: string]: unknown } | null
+export type ExternalDataSchemaApiAvailableColumnsItem = {
+ name: string
+ data_type?: string
+ is_nullable?: boolean
+}
+
export interface ExternalDataSchemaApi {
readonly id: string
readonly name: string
@@ -309,6 +315,13 @@ export interface ExternalDataSchemaApi {
* `cdc_only` - cdc_only
* `both` - both */
cdc_table_mode?: CdcTableModeEnumApi | null
+ /**
+ * Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.
+ * @nullable
+ */
+ enabled_columns?: string[] | null
+ /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
+ readonly available_columns: readonly ExternalDataSchemaApiAvailableColumnsItem[]
}
export interface PaginatedExternalDataSchemaListApi {
@@ -325,6 +338,12 @@ export interface PaginatedExternalDataSchemaListApi {
*/
export type PatchedExternalDataSchemaApiTable = { [key: string]: unknown } | null
+export type PatchedExternalDataSchemaApiAvailableColumnsItem = {
+ name: string
+ data_type?: string
+ is_nullable?: boolean
+}
+
export interface PatchedExternalDataSchemaApi {
readonly id?: string
readonly name?: string
@@ -397,6 +416,13 @@ export interface PatchedExternalDataSchemaApi {
* `cdc_only` - cdc_only
* `both` - both */
cdc_table_mode?: CdcTableModeEnumApi | null
+ /**
+ * Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.
+ * @nullable
+ */
+ enabled_columns?: string[] | null
+ /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
+ readonly available_columns?: readonly PatchedExternalDataSchemaApiAvailableColumnsItem[]
}
/**
@@ -1068,6 +1094,11 @@ export interface ExternalDataSourceBulkUpdateSchemaApi {
* `cdc_only` - cdc_only
* `both` - both */
cdc_table_mode?: CdcTableModeEnumApi | null
+ /**
+ * Columns to sync. Null means sync all columns.
+ * @nullable
+ */
+ enabled_columns?: string[] | null
}
export interface PatchedExternalDataSourceBulkUpdateSchemasApi {
diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.ts
index 1e588eef08d2..fb3a4ab2e811 100644
--- a/products/data_warehouse/frontend/generated/api.zod.ts
+++ b/products/data_warehouse/frontend/generated/api.zod.ts
@@ -122,6 +122,12 @@ export const ExternalDataSchemasCreateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasUpdateBody = /* @__PURE__ */ zod.object({
@@ -191,6 +197,12 @@ export const ExternalDataSchemasUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({
@@ -260,6 +272,12 @@ export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
@@ -329,6 +347,12 @@ export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasIncrementalFieldsCreateBody = /* @__PURE__ */ zod.object({
@@ -398,6 +422,12 @@ export const ExternalDataSchemasIncrementalFieldsCreateBody = /* @__PURE__ */ zo
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasReloadCreateBody = /* @__PURE__ */ zod.object({
@@ -467,6 +497,12 @@ export const ExternalDataSchemasReloadCreateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasResyncCreateBody = /* @__PURE__ */ zod.object({
@@ -536,6 +572,12 @@ export const ExternalDataSchemasResyncCreateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
/**
@@ -818,6 +860,10 @@ export const ExternalDataSourcesBulkUpdateSchemasPartialUpdateBody = /* @__PURE_
.describe(
'How CDC-backed tables should be exposed.\n\n\* `consolidated` - consolidated\n\* `cdc_only` - cdc_only\n\* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe('Columns to sync. Null means sync all columns.'),
})
)
.optional()
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
index 169cecbeb68d..76e22b262132 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx
@@ -322,6 +322,10 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
schemas,
}),
toggleSchemaShouldSync: (schema: ExternalDataSourceSyncSchema, shouldSync: boolean) => ({ schema, shouldSync }),
+ setSchemaSyncedColumns: (schema: ExternalDataSourceSyncSchema, enabledColumns: string[] | null) => ({
+ schema,
+ enabledColumns,
+ }),
updateSchemaSyncType: (
schema: ExternalDataSourceSyncSchema,
syncType: ExternalDataSourceSyncSchema['sync_type'],
@@ -458,6 +462,12 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
should_sync: s.table === schema.table ? shouldSync : s.should_sync,
}))
},
+ setSchemaSyncedColumns: (state, { schema, enabledColumns }) => {
+ return state.map((s) => ({
+ ...s,
+ enabled_columns: s.table === schema.table ? enabledColumns : s.enabled_columns,
+ }))
+ },
updateSchemaSyncType: (
state,
{ schema, syncType, incrementalField, incrementalFieldType, primaryKeyColumns, cdcTableMode }
@@ -1176,6 +1186,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([
incremental_field_type: schema.incremental_field_type,
sync_time_of_day: schema.sync_time_of_day,
primary_key_columns: schema.primary_key_columns,
+ enabled_columns: schema.enabled_columns ?? null,
...(schema.sync_type === 'cdc' && schema.cdc_table_mode
? { cdc_table_mode: schema.cdc_table_mode }
: {}),
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
index d863dd0dd410..3266266cda16 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx
@@ -41,9 +41,19 @@ import {
} from 'products/data_warehouse/frontend/utils'
import { syncMethodModalLogic } from '../SourceScene/syncMethodModalLogic'
+import { ColumnSelectionPicker } from '../SourceScene/tabs/ColumnSelectionModal'
import { sourceSettingsLogic } from '../SourceScene/tabs/sourceSettingsLogic'
import { SchemaConfigurationSection } from './schemaSceneLogic'
+// null means "all columns" on either side, so switching to null after a partial list flags
+// every previously-excluded column as added.
+function getAddedColumns(prev: string[] | null, next: string[] | null, available: { name: string }[]): string[] {
+ const allColumns = available.map((c) => c.name)
+ const prevSet = new Set(prev ?? allColumns)
+ const nextSet = new Set(next ?? allColumns)
+ return allColumns.filter((c) => nextSet.has(c) && !prevSet.has(c))
+}
+
export interface ConfigurationTabProps {
sourceId: string
schema: ExternalDataSourceSchema
@@ -69,6 +79,15 @@ export function ConfigurationTab({ sourceId, schema, source, section }: Configur
)
case 'sync-method':
return <SyncMethodSection sourceId={sourceId} source={source} schema={schema} />
+ case 'columns':
+ return (
+ <ColumnsSection
+ source={source}
+ schema={schema}
+ updateSchema={updateSchema}
+ resyncSchema={resyncSchema}
+ />
+ )
case 'schedule':
return (
<ScheduleSection
@@ -391,6 +410,114 @@ function SyncMethodSection({
)
}
+function ColumnsSection({
+ source,
+ schema,
+ updateSchema,
+ resyncSchema,
+}: {
+ source: ExternalDataSource | null
+ schema: ExternalDataSourceSchema
+ updateSchema: (schema: ExternalDataSourceSchema) => void
+ resyncSchema: (schema: ExternalDataSourceSchema) => void
+}): JSX.Element {
+ const isPostgres = source?.source_type === 'Postgres'
+ const available = schema.available_columns ?? []
+ const synced = schema.enabled_columns
+
+ const alwaysRetained = new Set<string>([
+ ...(schema.primary_key_columns ?? []),
+ ...(schema.incremental_field ? [schema.incremental_field] : []),
+ ])
+ const syncedCount = synced ? new Set([...synced, ...alwaysRetained]).size : available.length
+ const summaryLine = !synced
+ ? `Syncing all ${available.length || 'discovered'} columns`
+ : `Syncing ${syncedCount} of ${available.length} columns`
+
+ const handleSave = (nextSyncedColumns: string[] | null): void => {
+ const syncType = schema.sync_type
+ const added = getAddedColumns(schema.enabled_columns ?? null, nextSyncedColumns, available)
+ const requiresPrompt =
+ !!schema.last_synced_at &&
+ (syncType === 'incremental' || syncType === 'append' || syncType === 'cdc') &&
+ added.length > 0
+
+ if (!requiresPrompt) {
+ updateSchema({ ...schema, enabled_columns: nextSyncedColumns })
+ lemonToast.success('Columns saved')
+ return
+ }
+
+ LemonDialog.open({
+ title: 'New columns added to a partial-sync table',
+ description: (
+ <div className="flex flex-col gap-2">
+ <span>
+ You added {added.length === 1 ? '1 column' : `${added.length} columns`} to a{' '}
+ <code>{syncType}</code> table. Existing rows will be backfilled with <code>NULL</code> for the
+ new column(s) unless you full-resync the table.
+ </span>
+ {added.length <= 6 && (
+ <span className="text-xs text-muted">Added: {added.map((c) => `"${c}"`).join(', ')}</span>
+ )}
+ </div>
+ ),
+ primaryButton: {
+ children: 'Full resync now',
+ onClick: () => {
+ // Bypass the bulk-update debounce so the Temporal workflow reads the new
+ // enabled_columns from the DB; firing resync against the queued (but unsent)
+ // PATCH would otherwise re-sync against the old column selection.
+ void api.externalDataSchemas
+ .update(schema.id, { enabled_columns: nextSyncedColumns })
+ .then(() => {
+ updateSchema({ ...schema, enabled_columns: nextSyncedColumns })
+ resyncSchema({ ...schema, enabled_columns: nextSyncedColumns })
+ lemonToast.success('Columns saved — full resync queued')
+ })
+ .catch((e: any) => {
+ lemonToast.error(e?.message || "Can't save columns at this time")
+ })
+ },
+ },
+ secondaryButton: {
+ children: 'Sync forward only',
+ onClick: () => {
+ updateSchema({ ...schema, enabled_columns: nextSyncedColumns })
+ lemonToast.success('Columns saved')
+ },
+ },
+ })
+ }
+
+ return (
+ <div>
+ <SectionHeader
+ title="Columns"
+ description="Choose which columns from this table get synced. Primary keys and the active incremental field are always synced."
+ />
+ <div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">
+ {!isPostgres ? (
+ <span className="text-muted">
+ Per-column selection is currently available for Postgres sources only.
+ </span>
+ ) : (
+ <>
+ <span className="text-sm text-secondary">{summaryLine}</span>
+ <SourceEditorAction source={source}>
+ {({ disabledReason }) => (
+ <fieldset disabled={!!disabledReason}>
+ <ColumnSelectionPicker schema={schema} onSave={handleSave} />
+ </fieldset>
+ )}
+ </SourceEditorAction>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
+
function ScheduleSection({
sourceId,
source,
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
index 94d882f15d89..2eca53859893 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx
@@ -38,6 +38,7 @@ export const scene: SceneExport<SchemaSceneProps> = {
const SECTION_LABELS: Record<SchemaConfigurationSection, string> = {
details: 'Details',
'sync-method': 'Sync method',
+ columns: 'Columns',
schedule: 'Schedule',
'danger-zone': 'Danger zone',
}
diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
index 9751d92b7d5f..4d7bc9d123d3 100644
--- a/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SchemaScene/schemaSceneLogic.ts
@@ -1,4 +1,4 @@
-import { actions, connect, kea, key, path, props, reducers, selectors } from 'kea'
+import { actions, afterMount, beforeUnmount, connect, kea, key, path, props, reducers, selectors } from 'kea'
import { actionToUrl, urlToAction } from 'kea-router'
import { Scene } from 'scenes/sceneTypes'
@@ -15,7 +15,7 @@ import type { schemaSceneLogicType } from './schemaSceneLogicType'
export const SCHEMA_SCENE_TABS = ['configuration', 'metrics'] as const
export type SchemaSceneTab = (typeof SCHEMA_SCENE_TABS)[number]
-export const SCHEMA_CONFIGURATION_SECTIONS = ['details', 'sync-method', 'schedule', 'danger-zone'] as const
+export const SCHEMA_CONFIGURATION_SECTIONS = ['details', 'sync-method', 'columns', 'schedule', 'danger-zone'] as const
export type SchemaConfigurationSection = (typeof SCHEMA_CONFIGURATION_SECTIONS)[number]
export const DEFAULT_SCHEMA_SCENE_TAB: SchemaSceneTab = 'configuration'
@@ -32,6 +32,10 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
path((key) => ['products', 'dataWarehouse', 'schemaSceneLogic', key]),
connect((props: SchemaSceneProps) => ({
values: [sourceSettingsLogic({ id: cleanSourceId(props.sourceId) }), ['source', 'sourceLoading']],
+ actions: [
+ sourceSettingsLogic({ id: cleanSourceId(props.sourceId) }),
+ ['pausePolling', 'resumePolling', 'loadSource'],
+ ],
})),
actions({
setCurrentTab: (tab: SchemaSceneTab) => ({ tab }),
@@ -121,7 +125,15 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
},
})),
urlToAction(({ actions, values }) => {
+ let initialNavigation = true
+
const applyTabAndSection = (tab: SchemaSceneTab, section?: SchemaConfigurationSection): void => {
+ if (!initialNavigation) {
+ // User navigated back to this scene — refresh data since polling is paused.
+ actions.loadSource()
+ }
+ initialNavigation = false
+
if (tab !== values.currentTab) {
actions._setCurrentTab(tab)
}
@@ -150,4 +162,10 @@ export const schemaSceneLogic = kea<schemaSceneLogicType>([
},
}
}),
+ afterMount(({ actions }) => {
+ actions.pausePolling()
+ }),
+ beforeUnmount(({ actions }) => {
+ actions.resumePolling()
+ }),
])
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/ColumnSelectionModal.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/ColumnSelectionModal.tsx
new file mode 100644
index 000000000000..3fa0e165dfdb
--- /dev/null
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/ColumnSelectionModal.tsx
@@ -0,0 +1,236 @@
+import { useEffect, useMemo, useState } from 'react'
+
+import { LemonButton, LemonCheckbox, LemonInput, LemonModal, Tooltip } from '@posthog/lemon-ui'
+
+import { ExternalDataSourceSchema } from '~/types'
+
+// Unifies the existing-source schema and the wizard's pre-creation sync schema so
+// both can drive the picker without coupling it to either concrete type.
+export interface ColumnSelectionTarget {
+ id: string
+ name?: string
+ enabled_columns?: string[] | null
+ primary_key_columns?: string[] | null
+ incremental_field?: string | null
+ available_columns?: { name: string; data_type?: string; is_nullable?: boolean }[]
+}
+
+interface ColumnSelectionPickerProps {
+ schema: ColumnSelectionTarget | null
+ onSave: (enabledColumns: string[] | null) => void
+ onCancel?: () => void
+ hideActions?: boolean
+}
+
+interface ColumnSelectionModalProps {
+ isOpen: boolean
+ schema: ExternalDataSourceSchema | null
+ onClose: () => void
+ onSave: (enabledColumns: string[] | null) => void
+}
+
+interface UseColumnSelectionResult {
+ selected: Set<string> | null
+ filter: string
+ setFilter: (value: string) => void
+ setSyncAll: () => void
+ toggleColumn: (name: string, checked: boolean) => void
+ isAlwaysRetained: (name: string) => boolean
+ isChecked: (name: string) => boolean
+ persistedSelection: () => string[] | null
+ available: { name: string; data_type?: string; is_nullable?: boolean }[]
+ primaryKeys: Set<string>
+ incrementalField: string | null | undefined
+ filteredColumns: { name: string; data_type?: string; is_nullable?: boolean }[]
+}
+
+function useColumnSelection(schema: ColumnSelectionTarget | null): UseColumnSelectionResult {
+ const available = schema?.available_columns ?? []
+ const primaryKeys = useMemo(() => new Set(schema?.primary_key_columns ?? []), [schema?.primary_key_columns])
+ const incrementalField = schema?.incremental_field
+
+ const [selected, setSelected] = useState<Set<string> | null>(null)
+ const [filter, setFilter] = useState('')
+
+ useEffect(() => {
+ const current = schema?.enabled_columns
+ setSelected(Array.isArray(current) ? new Set(current) : null)
+ setFilter('')
+ // Stable serialized key: the array ref changes on every poll even with identical contents,
+ // which would otherwise wipe out in-progress edits.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [schema?.id, schema?.enabled_columns?.join('\0') ?? null])
+
+ const isAlwaysRetained = (name: string): boolean => primaryKeys.has(name) || name === incrementalField
+
+ const isChecked = (name: string): boolean => {
+ if (isAlwaysRetained(name)) {
+ return true
+ }
+ if (selected === null) {
+ return true
+ }
+ return selected.has(name)
+ }
+
+ const toggleColumn = (name: string, checked: boolean): void => {
+ if (isAlwaysRetained(name)) {
+ return
+ }
+ setSelected((current) => {
+ const baseline = current ?? new Set(available.map((c) => c.name))
+ const next = new Set(baseline)
+ if (checked) {
+ next.add(name)
+ } else {
+ next.delete(name)
+ }
+ return next
+ })
+ }
+
+ const setSyncAll = (): void => setSelected(null)
+
+ const filteredColumns = useMemo(() => {
+ const term = filter.trim().toLowerCase()
+ if (!term) {
+ return available
+ }
+ return available.filter((column) => column.name.toLowerCase().includes(term))
+ }, [available, filter])
+
+ const persistedSelection = (): string[] | null => {
+ if (selected === null) {
+ return null
+ }
+ // PKs + incremental are always synced — including them explicitly keeps the persisted
+ // list legible (e.g. ["id"] reads as "PK only" rather than the ambiguous []).
+ const result = new Set(selected)
+ primaryKeys.forEach((pk) => result.add(pk))
+ if (incrementalField) {
+ result.add(incrementalField)
+ }
+ return Array.from(result)
+ }
+
+ return {
+ selected,
+ filter,
+ setFilter,
+ setSyncAll,
+ toggleColumn,
+ isAlwaysRetained,
+ isChecked,
+ persistedSelection,
+ available,
+ primaryKeys,
+ incrementalField,
+ filteredColumns,
+ }
+}
+
+export function ColumnSelectionPicker({
+ schema,
+ onSave,
+ onCancel,
+ hideActions,
+}: ColumnSelectionPickerProps): JSX.Element {
+ const {
+ filter,
+ setFilter,
+ setSyncAll,
+ toggleColumn,
+ isAlwaysRetained,
+ isChecked,
+ persistedSelection,
+ available,
+ primaryKeys,
+ filteredColumns,
+ } = useColumnSelection(schema)
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonInput type="search" placeholder="Filter columns" size="small" value={filter} onChange={setFilter} />
+ <div className="max-h-96 overflow-y-auto border rounded">
+ {available.length === 0 && (
+ <div className="text-center text-muted-alt py-6 text-sm">
+ No columns discovered yet. Run "Pull new schemas" on the source's Schemas tab first.
+ </div>
+ )}
+ {filteredColumns.map((column) => {
+ const retained = isAlwaysRetained(column.name)
+ const checkbox = (
+ <LemonCheckbox
+ checked={isChecked(column.name)}
+ disabled={retained}
+ onChange={(checked) => toggleColumn(column.name, checked)}
+ label={
+ <div className="flex items-center gap-2">
+ <code>{column.name}</code>
+ {column.data_type && (
+ <span className="text-xs text-muted-alt">{column.data_type}</span>
+ )}
+ {retained && (
+ <span className="text-xs text-muted">
+ {primaryKeys.has(column.name) ? 'primary key' : 'incremental field'}
+ </span>
+ )}
+ </div>
+ }
+ />
+ )
+ return (
+ <div key={column.name} className="px-3 py-1">
+ {retained ? (
+ <Tooltip title="Always synced — required for merges or incremental tracking.">
+ <div>{checkbox}</div>
+ </Tooltip>
+ ) : (
+ checkbox
+ )}
+ </div>
+ )
+ })}
+ {filteredColumns.length === 0 && available.length > 0 && (
+ <div className="text-center text-muted-alt py-6 text-sm">No columns match.</div>
+ )}
+ </div>
+ {!hideActions && (
+ <div className="flex items-center justify-between gap-2 mt-2">
+ <LemonButton type="tertiary" onClick={setSyncAll}>
+ Reset to sync all columns
+ </LemonButton>
+ <div className="flex gap-2">
+ {onCancel && (
+ <LemonButton type="secondary" onClick={onCancel}>
+ Cancel
+ </LemonButton>
+ )}
+ <LemonButton
+ type="primary"
+ onClick={() => onSave(persistedSelection())}
+ disabledReason={available.length === 0 ? 'No columns discovered' : undefined}
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
+
+export function ColumnSelectionModal({ isOpen, schema, onClose, onSave }: ColumnSelectionModalProps): JSX.Element {
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={onClose}
+ title={`Select columns to sync — ${schema?.name ?? ''}`}
+ description="Primary-key and incremental columns are always synced and cannot be unchecked."
+ >
+ <div className="min-w-[420px]">
+ <ColumnSelectionPicker schema={schema} onSave={onSave} onCancel={onClose} />
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx
index 17f1d1188c15..79804631237c 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/DirectQuerySchemasTab.tsx
@@ -21,6 +21,7 @@ import { ExternalDataSource, ExternalDataSourceSchema } from '~/types'
import { SourceEditorAction } from 'products/data_warehouse/frontend/shared/components/SourceEditorAction'
import { buildTableQueryUrl } from 'products/data_warehouse/frontend/utils'
+import { ColumnSelectionModal } from './ColumnSelectionModal'
import { sourceSettingsLogic } from './sourceSettingsLogic'
export function splitDirectQuerySchemaName(
@@ -81,6 +82,8 @@ export function DirectQuerySchemasTab({ id }: DirectQuerySchemasTabProps): JSX.E
useValues(logic)
const { setShowEnabledSchemasOnly, setSchemaNameFilter, refreshSchemas, updateSchema } = useActions(logic)
+ const [columnModalSchema, setColumnModalSchema] = useState<ExternalDataSourceSchema | null>(null)
+
const directQueryDefaultSchema = typeof source?.job_inputs?.schema === 'string' ? source.job_inputs.schema : null
const groupedSchemas = groupDirectQuerySourceSchemasBySchema(filteredSchemas, directQueryDefaultSchema)
@@ -120,6 +123,18 @@ export function DirectQuerySchemasTab({ id }: DirectQuerySchemasTabProps): JSX.E
groupedSchemas={groupedSchemas}
isLoading={sourceLoading}
updateSchema={updateSchema}
+ onConfigureColumns={setColumnModalSchema}
+ />
+ <ColumnSelectionModal
+ isOpen={columnModalSchema !== null}
+ schema={columnModalSchema}
+ onClose={() => setColumnModalSchema(null)}
+ onSave={(enabledColumns) => {
+ if (columnModalSchema) {
+ updateSchema({ ...columnModalSchema, enabled_columns: enabledColumns })
+ }
+ setColumnModalSchema(null)
+ }}
/>
</div>
)
@@ -130,11 +145,13 @@ function DirectQuerySchemaGroups({
groupedSchemas,
isLoading,
updateSchema,
+ onConfigureColumns,
}: {
source: ExternalDataSource | null
groupedSchemas: { schemaName: string; schemas: ExternalDataSourceSchema[] }[]
isLoading: boolean
updateSchema: (schema: ExternalDataSourceSchema) => void
+ onConfigureColumns?: (schema: ExternalDataSourceSchema) => void
}): JSX.Element {
const [initialLoad, setInitialLoad] = useState(true)
const groupedSchemaKeys = groupedSchemas.map((group) => group.schemaName)
@@ -241,7 +258,7 @@ function DirectQuerySchemaGroups({
return (
<div
key={schema.id}
- className="grid grid-cols-[auto_minmax(0,1fr)] gap-2 px-6 py-1 items-center"
+ className="grid grid-cols-[auto_minmax(0,1fr)_auto] gap-2 px-6 py-1 items-center"
>
<SourceEditorAction source={source}>
<LemonCheckbox
@@ -270,6 +287,17 @@ function DirectQuerySchemaGroups({
</Tooltip>
)}
</div>
+ {onConfigureColumns && (
+ <SourceEditorAction source={source}>
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ onClick={() => onConfigureColumns(schema)}
+ >
+ Columns
+ </LemonButton>
+ </SourceEditorAction>
+ )}
</div>
)
})}
diff --git a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
index 27fe218dcab5..18447a6eff71 100644
--- a/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
+++ b/products/data_warehouse/frontend/scenes/SourceScene/tabs/sourceSettingsLogic.ts
@@ -119,6 +119,7 @@ function buildSchemaUpdatePayload(
| 'sync_frequency'
| 'sync_time_of_day'
| 'cdc_table_mode'
+ | 'enabled_columns'
> {
return {
id: schema.id,
@@ -129,6 +130,7 @@ function buildSchemaUpdatePayload(
sync_frequency: schema.sync_frequency,
sync_time_of_day: schema.sync_time_of_day,
cdc_table_mode: schema.cdc_table_mode,
+ enabled_columns: schema.enabled_columns ?? null,
}
}
@@ -234,6 +236,8 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
payload,
}),
updateSchemaFailure: (error: string, errorObject?: any) => ({ error, errorObject }),
+ pausePolling: true,
+ resumePolling: true,
}),
loaders(({ actions, values, cache }) => ({
source: [
@@ -372,6 +376,13 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
refreshSchemas: () => true,
},
],
+ pollPauseCount: [
+ 0 as number,
+ {
+ pausePolling: (state) => state + 1,
+ resumePolling: (state) => Math.max(0, state - 1),
+ },
+ ],
sourceConfigLoading: [
false as boolean,
{
@@ -589,12 +600,14 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
? values.source?.prefix || values.source?.source_type || 'Source'
: values.source?.source_type || 'Source'
- cache.disposables.add(() => {
- const timerId = setTimeout(() => {
- actions.loadSource()
- }, REFRESH_INTERVAL)
- return () => clearTimeout(timerId)
- }, 'sourceRefreshTimeout')
+ if (values.pollPauseCount === 0) {
+ cache.disposables.add(() => {
+ const timerId = setTimeout(() => {
+ actions.loadSource()
+ }, REFRESH_INTERVAL)
+ return () => clearTimeout(timerId)
+ }, 'sourceRefreshTimeout')
+ }
const tabId = props.tabId ?? sceneLogic.findMounted()?.values.activeTabId ?? undefined
const sceneLogicInstance =
@@ -604,12 +617,22 @@ export const sourceSettingsLogic = kea<sourceSettingsLogicType>([
sceneLogicInstance?.actions.setBreadcrumbName(breadcrumbName)
},
loadSourceFailure: () => {
- cache.disposables.add(() => {
- const timerId = setTimeout(() => {
- actions.loadSource()
- }, REFRESH_INTERVAL)
- return () => clearTimeout(timerId)
- }, 'sourceRefreshTimeout')
+ if (values.pollPauseCount === 0) {
+ cache.disposables.add(() => {
+ const timerId = setTimeout(() => {
+ actions.loadSource()
+ }, REFRESH_INTERVAL)
+ return () => clearTimeout(timerId)
+ }, 'sourceRefreshTimeout')
+ }
+ },
+ resumePolling: () => {
+ // After the reducer runs we may have dropped to 0 — but no fresh load has been
+ // scheduled (the prior loadSourceSuccess fired while paused and skipped its
+ // reschedule). Kick a load now so the source page resumes auto-refreshing status.
+ if (values.pollPauseCount === 0) {
+ actions.loadSource()
+ }
},
refreshSchemas: async () => {
try {
diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
index 80611dc5df96..8ceaea192edf 100644
--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx
@@ -1,5 +1,5 @@
import { useActions, useValues } from 'kea'
-import { useEffect } from 'react'
+import { useEffect, useState } from 'react'
import { IconInfo, IconWarning } from '@posthog/icons'
import {
@@ -21,6 +21,7 @@ import { ExternalDataSourceSyncSchema } from '~/types'
import { SyncTypeLabelMap } from 'products/data_warehouse/frontend/utils'
import { sourceWizardLogic } from '../../../scenes/NewSourceScene/sourceWizardLogic'
+import { ColumnSelectionPicker } from '../../../scenes/SourceScene/tabs/ColumnSelectionModal'
import { splitDirectQueryTableName } from './directQuerySchemaUtils'
import { SyncMethodForm } from './SyncMethodForm'
@@ -53,11 +54,12 @@ export default function SchemaForm(): JSX.Element {
const {
toggleSchemaShouldSync,
openSyncMethodModal,
- toggleAllTables,
toggleDirectQuerySchemaGroup,
setExpandedDirectQuerySchemaKeys,
setSchemaNameFilter,
+ setSchemaSyncedColumns,
} = useActions(sourceWizardLogic)
+ const [columnSelectionSchema, setColumnSelectionSchema] = useState<ExternalDataSourceSyncSchema | null>(null)
const {
databaseSchema,
filteredDatabaseSchema,
@@ -67,7 +69,6 @@ export default function SchemaForm(): JSX.Element {
source,
groupedDirectQueryDatabaseSchema,
expandedDirectQuerySchemaKeys,
- tablesAllToggledOn,
} = useValues(sourceWizardLogic)
const onClickCheckbox = (schema: ExternalDataSourceSyncSchema, checked: boolean): void => {
@@ -225,251 +226,391 @@ export default function SchemaForm(): JSX.Element {
) : (
<div className="border rounded px-4 py-8 text-center text-muted-alt">No tables found</div>
)
- ) : (
- <LemonTable
- emptyState={schemaNameFilter ? `No tables match "${schemaNameFilter}"` : 'No schemas found'}
- dataSource={filteredDatabaseSchema}
- pagination={{ pageSize: 100, hideOnSinglePage: true }}
- columns={[
- {
- title: (
- <LemonCheckbox
- checked={tablesAllToggledOn}
- onChange={(checked) =>
- toggleAllTables(
- checked,
- schemaNameFilter
- ? filteredDatabaseSchema.map((s) => s.table)
- : undefined
- )
- }
- />
- ),
- width: 0,
- key: 'enabled',
- render: function RenderEnabled(_, schema) {
- return (
- <LemonCheckbox
- checked={schema.should_sync}
- onChange={(checked) => onClickCheckbox(schema, checked)}
- />
- )
- },
- },
- {
- title: 'Table',
- key: 'table',
- render: function RenderTable(_, schema) {
- const isSuggested = suggestedTablesMap[schema.table] !== undefined
- const tooltip =
- suggestedTablesMap[schema.table] ??
- 'This table is suggested to be enabled for this source'
-
- return (
- <div className="flex items-center gap-2">
- <span
- className="font-mono cursor-pointer"
- onClick={() => onClickCheckbox(schema, !schema.should_sync)}
- >
- {schema.label || schema.table}
+ ) : groupedDirectQueryDatabaseSchema.length > 0 ? (
+ <div className="border rounded bg-bg-light">
+ <LemonCollapse
+ multiple
+ embedded
+ activeKeys={expandedDirectQuerySchemaKeys}
+ onChange={setExpandedDirectQuerySchemaKeys}
+ panels={groupedDirectQueryDatabaseSchema.map(
+ ({
+ schemaName,
+ tables,
+ }: {
+ schemaName: string
+ tables: ExternalDataSourceSyncSchema[]
+ }) => ({
+ key: schemaName,
+ header: (
+ <div className="flex items-center justify-between gap-3 w-full">
+ <div className="flex items-center gap-2 min-w-0">
+ <LemonCheckbox
+ checked={getSchemaSelectionState(tables)}
+ stopPropagation
+ onChange={(checked) =>
+ toggleDirectQuerySchemaGroup(schemaName, checked)
+ }
+ />
+ <span className="font-semibold truncate">{schemaName}</span>
+ </div>
+ <span className="text-xs text-muted-alt whitespace-nowrap">
+ {tables.filter((t) => t.should_sync).length} of {tables.length}{' '}
+ tables
</span>
- {schema.description && (
- <Tooltip title={schema.description}>
- <IconInfo className="text-muted-alt text-base" />
- </Tooltip>
- )}
- {isSuggested && (
- <Tooltip title={tooltip} placement="top">
- <LemonTag type="primary" className="cursor-help">
- Suggested
- </LemonTag>
- </Tooltip>
- )}
</div>
- )
- },
- },
- {
- title: 'Rows',
- key: 'rows',
- isHidden: !databaseSchema.some((schema) => schema.rows),
- render: function RenderRows(_, schema) {
- if (schema.rows != null) {
- return schema.rows
- }
- return (
- <Tooltip title="Row count was skipped for this table because counting would require a full scan (e.g. plain views, Memory/Buffer/Log-engine tables, or Kafka/URL table functions). The table can still be synced — we just don't know its size up front.">
- <span className="text-muted-alt cursor-help">Skipped</span>
- </Tooltip>
- )
- },
- },
- {
- key: 'sync_field',
- title: 'Sync field',
- align: 'right',
- tooltip:
- 'Incremental and append-only refresh methods key on a unique field to determine the most up-to-date data.',
- isHidden:
- !shouldShowSyncColumns || !databaseSchema.some((schema) => schema.sync_type),
- render: function RenderSyncType(_, schema) {
- if (isDirectQueryMode) {
- return (
- <span className="text-xs text-muted-foreground">
- Only selected tables are queryable in direct mode
- </span>
- )
- }
- if (!schema.incremental_available && !schema.append_available) {
- return (
- <span className="text-xs text-muted-foreground">
- Incremental sync not supported
- </span>
- )
- }
+ ),
+ content: (
+ <LemonTable
+ embedded
+ showHeader={false}
+ dataSource={tables}
+ pagination={{ pageSize: 100, hideOnSinglePage: true }}
+ columns={[
+ {
+ width: 0,
+ key: 'enabled',
+ render: function RenderEnabled(_, schema) {
+ return (
+ <LemonCheckbox
+ checked={schema.should_sync}
+ onChange={(checked) =>
+ onClickCheckbox(schema, checked)
+ }
+ />
+ )
+ },
+ },
+ {
+ title: 'Table',
+ key: 'table',
+ render: function RenderTable(_, schema) {
+ const isSuggested =
+ suggestedTablesMap[schema.table] !== undefined
+ const tooltip =
+ suggestedTablesMap[schema.table] ??
+ 'This table is suggested to be enabled for this source'
- if (schema.sync_type === 'webhook') {
- return <LemonTag type="success">Webhook</LemonTag>
- }
+ return (
+ <div className="flex items-center gap-2">
+ <span
+ className="font-mono cursor-pointer"
+ onClick={() =>
+ onClickCheckbox(schema, !schema.should_sync)
+ }
+ >
+ {schema.label || schema.table}
+ </span>
+ {schema.description && (
+ <Tooltip title={schema.description}>
+ <IconInfo className="text-muted-alt text-base" />
+ </Tooltip>
+ )}
+ {isSuggested && (
+ <Tooltip title={tooltip} placement="top">
+ <LemonTag
+ type="primary"
+ className="cursor-help"
+ >
+ Suggested
+ </LemonTag>
+ </Tooltip>
+ )}
+ </div>
+ )
+ },
+ },
+ {
+ title: 'Rows',
+ key: 'rows',
+ isHidden: !databaseSchema.some((schema) => schema.rows),
+ render: function RenderRows(_, schema) {
+ if (schema.rows != null) {
+ return schema.rows
+ }
+ return (
+ <Tooltip title="Row count was skipped for this table because counting would require a full scan (e.g. plain views, Memory/Buffer/Log-engine tables, or Kafka/URL table functions). The table can still be synced — we just don't know its size up front.">
+ <span className="text-muted-alt cursor-help">
+ Skipped
+ </span>
+ </Tooltip>
+ )
+ },
+ },
+ {
+ key: 'sync_field',
+ title: 'Sync field',
+ align: 'right',
+ tooltip:
+ 'Incremental and append-only refresh methods key on a unique field to determine the most up-to-date data.',
+ isHidden:
+ !shouldShowSyncColumns ||
+ !databaseSchema.some((schema) => schema.sync_type),
+ render: function RenderSyncType(_, schema) {
+ if (isDirectQueryMode) {
+ return (
+ <span className="text-xs text-muted-foreground">
+ Only selected tables are queryable in direct
+ mode
+ </span>
+ )
+ }
+ if (
+ !schema.incremental_available &&
+ !schema.append_available
+ ) {
+ return (
+ <span className="text-xs text-muted-foreground">
+ Incremental sync not supported
+ </span>
+ )
+ }
- if (
- schema.sync_type !== 'full_refresh' &&
- schema.sync_type !== null &&
- schema.incremental_field
- ) {
- const field =
- schema.incremental_fields.find(
- (f) => f.field == schema.incremental_field
- ) ?? null
-
- if (field) {
- return (
- <div className="flex items-center justify-end">
- {field.nullable && (
- <Tooltip
- title={`This field is nullable. Any rows where ${field.label} is null will not be synced.`}
- >
- <IconWarning className="mr-1 text-warning text-xl" />
- </Tooltip>
- )}
- <span className="leading-5">{field.label}</span>
- <LemonTag className="ml-2" type="success">
- {field.type}
- </LemonTag>
- </div>
- )
- }
- }
+ if (schema.sync_type === 'webhook') {
+ return <LemonTag type="success">Webhook</LemonTag>
+ }
- return (
- <span className="text-xs text-muted-foreground">
- No sync field selected
- </span>
- )
- },
- },
- {
- key: 'primary_key',
- title: 'Primary key',
- align: 'right',
- tooltip:
- 'The column(s) used to uniquely identify rows for deduplication during incremental syncs. Auto-detected if not set.',
- isHidden:
- !shouldShowSyncColumns ||
- !databaseSchema.some((schema) => schema.sync_type === 'incremental'),
- render: function RenderPrimaryKey(_, schema) {
- if (schema.sync_type !== 'incremental') {
- return (
- <span className="text-xs text-muted-foreground">
- No primary key selected
- </span>
- )
- }
+ if (
+ schema.sync_type !== 'full_refresh' &&
+ schema.sync_type !== null &&
+ schema.incremental_field
+ ) {
+ const field =
+ schema.incremental_fields.find(
+ (f) => f.field == schema.incremental_field
+ ) ?? null
+
+ if (field) {
+ return (
+ <div className="flex items-center justify-end">
+ {field.nullable && (
+ <Tooltip
+ title={`This field is nullable. Any rows where ${field.label} is null will not be synced.`}
+ >
+ <IconWarning className="mr-1 text-warning text-xl" />
+ </Tooltip>
+ )}
+ <span className="leading-5">
+ {field.label}
+ </span>
+ <LemonTag className="ml-2" type="success">
+ {field.type}
+ </LemonTag>
+ </div>
+ )
+ }
+ }
- if (!schema.primary_key_columns || schema.primary_key_columns.length === 0) {
- const detected = schema.detected_primary_keys
- if (detected && detected.length > 0) {
- return (
- <div className="flex items-center justify-end gap-1 flex-wrap">
- {detected.map((col) => (
- <LemonTag key={col} type="muted">
- {col}
- </LemonTag>
- ))}
- </div>
- )
- }
+ return (
+ <span className="text-xs text-muted-foreground">
+ No sync field selected
+ </span>
+ )
+ },
+ },
+ {
+ key: 'primary_key',
+ title: 'Primary key',
+ align: 'right',
+ tooltip:
+ 'The column(s) used to uniquely identify rows for deduplication during incremental syncs. Auto-detected if not set.',
+ isHidden:
+ !shouldShowSyncColumns ||
+ !databaseSchema.some(
+ (schema) => schema.sync_type === 'incremental'
+ ),
+ render: function RenderPrimaryKey(_, schema) {
+ if (schema.sync_type !== 'incremental') {
+ return (
+ <span className="text-xs text-muted-foreground">
+ No primary key selected
+ </span>
+ )
+ }
- return <span className="text-xs text-muted-foreground">None detected</span>
- }
+ if (
+ !schema.primary_key_columns ||
+ schema.primary_key_columns.length === 0
+ ) {
+ const detected = schema.detected_primary_keys
+ if (detected && detected.length > 0) {
+ return (
+ <div className="flex items-center justify-end gap-1 flex-wrap">
+ {detected.map((col) => (
+ <LemonTag key={col} type="muted">
+ {col}
+ </LemonTag>
+ ))}
+ </div>
+ )
+ }
+
+ return (
+ <span className="text-xs text-muted-foreground">
+ None detected
+ </span>
+ )
+ }
- return (
- <div className="flex items-center justify-end gap-1 flex-wrap">
- {schema.primary_key_columns.map((col) => (
- <LemonTag key={col} type="default">
- {col}
- </LemonTag>
- ))}
- </div>
- )
- },
- },
- {
- key: 'sync_type',
- title: 'Sync method',
- align: 'right',
- isHidden: !shouldShowSyncColumns,
- tooltip:
- 'Full refresh will refresh the full table on every sync, whereas incremental will only sync new and updated rows since the last sync',
- render: function RenderSyncType(_, schema) {
- if (isDirectQueryMode) {
- return (
- <span className="text-xs text-muted-foreground">
- Only selected tables are queryable in direct mode
- </span>
- )
- }
- if (!schema.sync_type) {
- return (
- <div className="justify-end flex">
- <LemonButton
- className="my-1"
- type="primary"
- onClick={() => openSyncMethodModal(schema)}
- size="small"
- >
- Configure
- </LemonButton>
- </div>
- )
- }
- return (
- <div className="justify-end flex">
- <LemonButton
- className="my-1"
- size="small"
- type="secondary"
- onClick={() => openSyncMethodModal(schema)}
- disabledReason={
- !schema.incremental_available &&
- !schema.append_available &&
- !schema.supports_webhooks
- ? 'Full refresh is the only supported sync method for this table'
- : undefined
- }
- >
- {SyncTypeLabelMap[schema.sync_type]}
- </LemonButton>
- </div>
- )
- },
- },
- ]}
- />
+ return (
+ <div className="flex items-center justify-end gap-1 flex-wrap">
+ {schema.primary_key_columns.map((col) => (
+ <LemonTag key={col} type="default">
+ {col}
+ </LemonTag>
+ ))}
+ </div>
+ )
+ },
+ },
+ {
+ key: 'sync_type',
+ title: 'Sync method',
+ align: 'right',
+ isHidden: !shouldShowSyncColumns,
+ tooltip:
+ 'Full refresh will refresh the full table on every sync, whereas incremental will only sync new and updated rows since the last sync',
+ render: function RenderSyncType(_, schema) {
+ if (isDirectQueryMode) {
+ return (
+ <span className="text-xs text-muted-foreground">
+ Only selected tables are queryable in direct
+ mode
+ </span>
+ )
+ }
+ if (!schema.sync_type) {
+ return (
+ <div className="justify-end flex">
+ <LemonButton
+ className="my-1"
+ type="primary"
+ onClick={() => openSyncMethodModal(schema)}
+ size="small"
+ >
+ Configure
+ </LemonButton>
+ </div>
+ )
+ }
+ return (
+ <div className="justify-end flex">
+ <LemonButton
+ className="my-1"
+ size="small"
+ type="secondary"
+ onClick={() => openSyncMethodModal(schema)}
+ disabledReason={
+ !schema.incremental_available &&
+ !schema.append_available &&
+ !schema.supports_webhooks
+ ? 'Full refresh is the only supported sync method for this table'
+ : undefined
+ }
+ >
+ {SyncTypeLabelMap[schema.sync_type]}
+ </LemonButton>
+ </div>
+ )
+ },
+ },
+ {
+ key: 'columns',
+ title: 'Columns',
+ align: 'right',
+ isHidden: !shouldShowSyncColumns,
+ tooltip:
+ 'Pick a subset of columns to sync. Primary keys and the active incremental field are always retained.',
+ render: function RenderColumns(_, schema) {
+ if (schema.available_columns.length === 0) {
+ return (
+ <span className="text-xs text-muted-foreground">
+ —
+ </span>
+ )
+ }
+ const synced = schema.enabled_columns
+ const alwaysRetained = new Set<string>([
+ ...(schema.primary_key_columns ?? []),
+ ...(schema.incremental_field
+ ? [schema.incremental_field]
+ : []),
+ ])
+ const syncedCount = synced
+ ? new Set([...synced, ...alwaysRetained]).size
+ : schema.available_columns.length
+ const summary = !synced
+ ? `All ${schema.available_columns.length}`
+ : `${syncedCount} of ${schema.available_columns.length}`
+ return (
+ <div className="justify-end flex">
+ <LemonButton
+ className="my-1"
+ size="small"
+ type="secondary"
+ onClick={() => setColumnSelectionSchema(schema)}
+ >
+ {summary}
+ </LemonButton>
+ </div>
+ )
+ },
+ },
+ ]}
+ />
+ ),
+ })
+ )}
+ />
+ </div>
+ ) : (
+ <div className="border rounded px-4 py-8 text-center text-muted-alt">
+ {schemaNameFilter ? `No tables match "${schemaNameFilter}"` : 'No schemas found'}
+ </div>
)}
</div>
</div>
<SyncMethodModal />
+ <LemonModal
+ title={
+ columnSelectionSchema ? (
+ <>
+ Select columns for <span className="font-mono">{columnSelectionSchema.table}</span>
+ </>
+ ) : null
+ }
+ description="Primary-key and incremental columns are always synced and cannot be unchecked."
+ isOpen={columnSelectionSchema !== null}
+ onClose={() => setColumnSelectionSchema(null)}
+ >
+ <div className="min-w-[420px]">
+ <ColumnSelectionPicker
+ schema={
+ columnSelectionSchema
+ ? {
+ id: columnSelectionSchema.table,
+ name: columnSelectionSchema.table,
+ enabled_columns: columnSelectionSchema.enabled_columns,
+ primary_key_columns: columnSelectionSchema.primary_key_columns,
+ incremental_field: columnSelectionSchema.incremental_field,
+ available_columns: columnSelectionSchema.available_columns.map((c) => ({
+ name: c.field,
+ data_type: c.type,
+ is_nullable: c.nullable,
+ })),
+ }
+ : null
+ }
+ onSave={(enabledColumns) => {
+ if (columnSelectionSchema) {
+ setSchemaSyncedColumns(columnSelectionSchema, enabledColumns)
+ }
+ setColumnSelectionSchema(null)
+ }}
+ onCancel={() => setColumnSelectionSchema(null)}
+ />
+ </div>
+ </LemonModal>
</>
)
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 53a6b1feb7f7..f651ad7ebc46 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15741,6 +15741,12 @@ export namespace Schemas {
*/
export type ExternalDataSchemaTable = { [key: string]: unknown } | null;
+ export type ExternalDataSchemaAvailableColumnsItem = {
+ name: string;
+ data_type?: string;
+ is_nullable?: boolean;
+ };
+
/**
* * `full_refresh` - full_refresh
* `incremental` - incremental
@@ -15881,6 +15887,13 @@ export namespace Schemas {
* `cdc_only` - cdc_only
* `both` - both */
cdc_table_mode?: CdcTableModeEnum | null;
+ /**
+ * Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.
+ * @nullable
+ */
+ enabled_columns?: string[] | null;
+ /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
+ readonly available_columns: readonly ExternalDataSchemaAvailableColumnsItem[];
}
export interface ExternalDataSourceBulkUpdateSchema {
@@ -15922,6 +15935,11 @@ export namespace Schemas {
* `cdc_only` - cdc_only
* `both` - both */
cdc_table_mode?: CdcTableModeEnum | null;
+ /**
+ * Columns to sync. Null means sync all columns.
+ * @nullable
+ */
+ enabled_columns?: string[] | null;
}
export interface ExternalDataSourceConnectionOption {
@@ -26938,6 +26956,12 @@ export namespace Schemas {
*/
export type PatchedExternalDataSchemaTable = { [key: string]: unknown } | null;
+ export type PatchedExternalDataSchemaAvailableColumnsItem = {
+ name: string;
+ data_type?: string;
+ is_nullable?: boolean;
+ };
+
export interface PatchedExternalDataSchema {
readonly id?: string;
readonly name?: string;
@@ -27010,6 +27034,13 @@ export namespace Schemas {
* `cdc_only` - cdc_only
* `both` - both */
cdc_table_mode?: CdcTableModeEnum | null;
+ /**
+ * Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.
+ * @nullable
+ */
+ enabled_columns?: string[] | null;
+ /** Source-side column metadata (name, data type, nullable) discovered for this schema. Empty until the source has been refreshed via `refresh_schemas`. */
+ readonly available_columns?: readonly PatchedExternalDataSchemaAvailableColumnsItem[];
}
export interface PatchedExternalDataSourceBulkUpdateSchemas {
diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.ts
index 53e881abb3a1..5a5a6b26da13 100644
--- a/services/mcp/src/generated/data_warehouse/api.ts
+++ b/services/mcp/src/generated/data_warehouse/api.ts
@@ -119,6 +119,12 @@ export const ExternalDataSchemasPartialUpdateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasCancelCreateParams = /* @__PURE__ */ zod.object({
@@ -197,6 +203,12 @@ export const ExternalDataSchemasCancelCreateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasDeleteDataDestroyParams = /* @__PURE__ */ zod.object({
@@ -284,6 +296,12 @@ export const ExternalDataSchemasIncrementalFieldsCreateBody = /* @__PURE__ */ zo
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasReloadCreateParams = /* @__PURE__ */ zod.object({
@@ -362,6 +380,12 @@ export const ExternalDataSchemasReloadCreateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
export const ExternalDataSchemasResyncCreateParams = /* @__PURE__ */ zod.object({
@@ -440,6 +464,12 @@ export const ExternalDataSchemasResyncCreateBody = /* @__PURE__ */ zod.object({
.describe(
'For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both'
),
+ enabled_columns: zod
+ .array(zod.string())
+ .nullish()
+ .describe(
+ 'Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here.'
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.ts
index cb35f404e538..4d0fc9ab2593 100644
--- a/services/mcp/src/tools/generated/data_warehouse.ts
+++ b/services/mcp/src/tools/generated/data_warehouse.ts
@@ -108,6 +108,9 @@ const externalDataSchemasCancel = (): ToolBase<typeof ExternalDataSchemasCancelS
if (params.cdc_table_mode !== undefined) {
body['cdc_table_mode'] = params.cdc_table_mode
}
+ if (params.enabled_columns !== undefined) {
+ body['enabled_columns'] = params.enabled_columns
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/cancel/`,
@@ -169,6 +172,9 @@ const externalDataSchemasIncrementalFieldsCreate = (): ToolBase<
if (params.cdc_table_mode !== undefined) {
body['cdc_table_mode'] = params.cdc_table_mode
}
+ if (params.enabled_columns !== undefined) {
+ body['enabled_columns'] = params.enabled_columns
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/incremental_fields/`,
@@ -238,6 +244,9 @@ const externalDataSchemasPartialUpdate = (): ToolBase<
if (params.cdc_table_mode !== undefined) {
body['cdc_table_mode'] = params.cdc_table_mode
}
+ if (params.enabled_columns !== undefined) {
+ body['enabled_columns'] = params.enabled_columns
+ }
const result = await context.api.request<Schemas.ExternalDataSchema>({
method: 'PATCH',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/`,
@@ -281,6 +290,9 @@ const externalDataSchemasReload = (): ToolBase<typeof ExternalDataSchemasReloadS
if (params.cdc_table_mode !== undefined) {
body['cdc_table_mode'] = params.cdc_table_mode
}
+ if (params.enabled_columns !== undefined) {
+ body['enabled_columns'] = params.enabled_columns
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/reload/`,
@@ -324,6 +336,9 @@ const externalDataSchemasResync = (): ToolBase<typeof ExternalDataSchemasResyncS
if (params.cdc_table_mode !== undefined) {
body['cdc_table_mode'] = params.cdc_table_mode
}
+ if (params.enabled_columns !== undefined) {
+ body['enabled_columns'] = params.enabled_columns
+ }
const result = await context.api.request<unknown>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/external_data_schemas/${encodeURIComponent(String(params.id))}/resync/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-cancel.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-cancel.json
index 2dc4aa78322b..21fd6ed98783 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-cancel.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-cancel.json
@@ -14,6 +14,20 @@
],
"description": "For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both"
},
+ "enabled_columns": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here."
+ },
"id": {
"description": "A UUID string identifying this external data schema.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-incremental-fields-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-incremental-fields-create.json
index 2dc4aa78322b..21fd6ed98783 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-incremental-fields-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-incremental-fields-create.json
@@ -14,6 +14,20 @@
],
"description": "For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both"
},
+ "enabled_columns": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here."
+ },
"id": {
"description": "A UUID string identifying this external data schema.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-partial-update.json
index 2dc4aa78322b..21fd6ed98783 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-partial-update.json
@@ -14,6 +14,20 @@
],
"description": "For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both"
},
+ "enabled_columns": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here."
+ },
"id": {
"description": "A UUID string identifying this external data schema.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-reload.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-reload.json
index 2dc4aa78322b..21fd6ed98783 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-reload.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-reload.json
@@ -14,6 +14,20 @@
],
"description": "For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both"
},
+ "enabled_columns": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here."
+ },
"id": {
"description": "A UUID string identifying this external data schema.",
"type": "string"
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-resync.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-resync.json
index 2dc4aa78322b..21fd6ed98783 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-resync.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/external-data-schemas-resync.json
@@ -14,6 +14,20 @@
],
"description": "For CDC syncs: consolidated, cdc_only, or both.\n\n* `consolidated` - consolidated\n* `cdc_only` - cdc_only\n* `both` - both"
},
+ "enabled_columns": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Names of source columns to sync. `null` (default) syncs all columns. Primary-key columns and the active incremental field are always retained, even if not listed here."
+ },
"id": {
"description": "A UUID string identifying this external data schema.",
"type": "string"