:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): column selection on MySQL, MSSQL, BigQuery, Snowflake, Redshift (#60155)
Daniel RC3db2d7ab2c97
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 56ac0e340ec6..7bf8df129699 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -38466,6 +38466,11 @@},"type": "array"},+ "supportsColumnSelection": {+ "default": false,+ "description": "Whether the source-creation wizard should expose the per-column projection picker. Mirrors `SQLSource.supports_column_selection` so the wizard doesn't show a picker for drivers that ignore `enabled_columns` at sync time.",+ "type": "boolean"+ },"unreleasedSource": {"type": "boolean"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 156956208901..a6214a981bad 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -5904,6 +5904,14 @@ export interface SourceConfig {* @default false*/featured?: boolean++ /**+ * Whether the source-creation wizard should expose the per-column projection picker.+ * Mirrors `SQLSource.supports_column_selection` so the wizard doesn't show a picker+ * for drivers that ignore `enabled_columns` at sync time.+ * @default false+ */+ supportsColumnSelection?: boolean}export const externalDataSources = [diff --git a/posthog/schema.py b/posthog/schema.pyindex fffea5bef79e..cf8e05015726 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -27213,6 +27213,15 @@ class SourceConfig(BaseModel):default=[],description="Tables to suggest enabling, with optional tooltip explaining why",)+ supportsColumnSelection: bool | None = Field(+ default=False,+ description=(+ "Whether the source-creation wizard should expose the per-column projection"+ " picker. Mirrors `SQLSource.supports_column_selection` so the wizard"+ " doesn't show a picker for drivers that ignore `enabled_columns` at sync"+ " time."+ ),+ )unreleasedSource: bool | None = NonewebhookFields: (list[diff --git a/posthog/temporal/data_imports/sources/bigquery/bigquery.py b/posthog/temporal/data_imports/sources/bigquery/bigquery.pyindex cae749a0088c..fe0891c2bc75 100644--- a/posthog/temporal/data_imports/sources/bigquery/bigquery.py+++ b/posthog/temporal/data_imports/sources/bigquery/bigquery.py@@ -39,8 +39,11 @@ from posthog.temporal.data_imports.pipelines.pipeline.consts import DEFAULT_TABLfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponsefrom posthog.temporal.data_imports.pipelines.pipeline.utils import DEFAULT_PARTITION_TARGET_SIZE_IN_BYTESfrom posthog.temporal.data_imports.sources.common.http import DEFAULT_RETRY, TrackedHTTPAdapter+from posthog.temporal.data_imports.sources.common.sql import compute_projected_columns+from posthog.temporal.data_imports.sources.common.sql.identifiers import BacktickIdentifierQuoterfrom posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementationfrom posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter+from posthog.temporal.data_imports.sources.common.sql.projection import format_projected_select_clausefrom posthog.temporal.data_imports.sources.generated_configs import BigQuerySourceConfigfrom products.data_warehouse.backend.types import IncrementalFieldType, PartitionSettings@@ -369,13 +372,30 @@ def _get_rows_to_sync(return 0+_BQ_QUOTER = BacktickIdentifierQuoter()+++def _bq_select_clause(+ enabled_columns: list[str] | None,+ primary_keys: list[str] | None,+ incremental_field: str | None,+) -> str:+ """BigQuery SELECT-list with backtick quoting and identifier allowlist."""+ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ return format_projected_select_clause(projected, _BQ_QUOTER)++def _get_query(should_use_incremental_field: bool,db_incremental_field_last_value: typing.Any,bq_table: bigquery.Table,incremental_field: str | None = None,incremental_field_type: IncrementalFieldType | None = None,+ enabled_columns: list[str] | None = None,+ primary_keys: list[str] | None = None,) -> str:+ select_clause = _bq_select_clause(enabled_columns, primary_keys, incremental_field)+if should_use_incremental_field:if incremental_field is None or incremental_field_type is None:raise ValueError("incremental_field and incremental_field_type can't be None")@@ -390,12 +410,12 @@ def _get_query(operator = incremental_type_to_operator(incremental_field_type)return f"""- SELECT * FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`+ SELECT {select_clause} FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`WHERE `{incremental_field}` {operator} {last_value}ORDER BY `{incremental_field}` ASC"""- return f"SELECT * FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`"+ return f"SELECT {select_clause} FROM `{bq_table.dataset_id}`.`{bq_table.table_id}`"class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigquery.Client, Any]):@@ -659,6 +679,7 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqudb_incremental_field_last_value = (inputs.db_incremental_field_last_value if should_use_incremental_field else None)+ enabled_columns = inputs.enabled_columnslogger = inputs.loggerproject_id = config.key_file.project_id@@ -705,6 +726,11 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqu) as bq_client:bq_table = bq_client.get_table(fully_qualified_table_name)+ # Query path projects into the temp table; direct-storage path projects via+ # `selected_fields` on the read session.+ projected_columns = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ storage_selected_fields: list[str] | None = None+if should_use_incremental_field:# This is only done because incremental syncs require progress tracking.# This requirement means we need to enforce an order, as otherwise@@ -720,6 +746,8 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqubq_table,incremental_field,incremental_field_type,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)destination_table = bigquery.Table(bq_destination_table_id)@@ -741,6 +769,8 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqubq_table,incremental_field,incremental_field_type,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)destination_table = bigquery.Table(bq_destination_table_id)@@ -750,16 +780,21 @@ class BigQueryImplementation(SQLSourceImplementation[BigQuerySourceConfig, bigqubq_table = bq_client.get_table(destination_table)+ else:+ if projected_columns is not None:+ storage_selected_fields = projected_columns+requested_session = bigquery_storage.ReadSession(table=bq_table.to_bqstorage(),data_format=bigquery_storage.DataFormat.ARROW,read_options=bigquery_storage.ReadSession.TableReadOptions(+ selected_fields=storage_selected_fields or [],arrow_serialization_options=bigquery_storage.ArrowSerializationOptions(# LZ4 offers a good trade-off of low resource usage for compression, so# as an initial value without further testing it should do fine. That being said,# TODO: Evaluate if ZSTD is a better alternative for our use case.buffer_compression=bigquery_storage.ArrowSerializationOptions.CompressionCodec.LZ4_FRAME- )+ ),),)with bigquery_storage_read_client(diff --git a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.pyindex f23d4ec8c592..fa58dc9ae895 100644--- a/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py+++ b/posthog/temporal/data_imports/sources/bigquery/tests/test_source.py@@ -5,8 +5,13 @@ from unittest import mockfrom dateutil import parserfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs-from posthog.temporal.data_imports.sources.bigquery.bigquery import BigQueryImplementation+from posthog.temporal.data_imports.sources.bigquery.bigquery import (+ BigQueryImplementation,+ _bq_select_clause,+ _get_query,+)from posthog.temporal.data_imports.sources.bigquery.source import BigQuerySource+from posthog.temporal.data_imports.sources.common.sql.identifiers import InvalidIdentifierErrorfrom posthog.temporal.data_imports.sources.generated_configs import (BigQueryDatasetProjectConfig,BigQueryKeyFileConfig,@@ -14,6 +19,8 @@ from posthog.temporal.data_imports.sources.generated_configs import (BigQueryTemporaryDatasetConfig,)+from products.data_warehouse.backend.types import IncrementalFieldType+def _make_inputs(**overrides) -> SourceInputs:defaults: dict = {@@ -125,3 +132,60 @@ def test_bigquery_build_pipeline_resolves_dataset_routing(assert mock_build.call_args.kwargs["bq_destination_table_id"] == expected_table_idassert mock_delete.call_args.kwargs["table_id"] == expected_table_id+++ "enabled_columns,primary_keys,incremental_field,expected",+ [+ (None, ["id"], None, "*"),+ (["email"], ["id"], None, "`email`, `id`"),+ (["email"], ["id"], "created_at", "`email`, `id`, `created_at`"),+ ([], None, None, "*"),+ ([], ["id"], None, "`id`"),+ ],+)+def test_bigquery_select_clause(enabled_columns, primary_keys, incremental_field, expected):+ assert _bq_select_clause(enabled_columns, primary_keys, incremental_field) == expected+++def test_bigquery_get_query_projects_enabled_columns():+ bq_table = mock.MagicMock(dataset_id="ds", table_id="t")+ query = _get_query(+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ bq_table=bq_table,+ enabled_columns=["email"],+ primary_keys=["id"],+ )+ assert "SELECT `email`, `id` FROM" in query+++def test_bigquery_get_query_keeps_incremental_field_in_projection():+ bq_table = mock.MagicMock(dataset_id="ds", table_id="t")+ query = _get_query(+ should_use_incremental_field=True,+ db_incremental_field_last_value=42,+ bq_table=bq_table,+ incremental_field="updated_at",+ incremental_field_type=IncrementalFieldType.Integer,+ enabled_columns=["email"],+ primary_keys=["id"],+ )+ assert "SELECT `email`, `id`, `updated_at` FROM" in query+ assert "WHERE `updated_at` > 42" in query+++ "malicious_column",+ [+ "x` FROM `other.private` --",+ "id; DROP TABLE customers",+ "email`, `secret",+ "name with space",+ "col\x00null",+ ],+)+def test_bigquery_select_clause_rejects_injection_attempts(malicious_column):+ """`enabled_columns` flows from user config — must be allowlisted before backtick quoting."""+ with pytest.raises(InvalidIdentifierError):+ _bq_select_clause([malicious_column], primary_keys=None, incremental_field=None)diff --git a/posthog/temporal/data_imports/sources/common/base.py b/posthog/temporal/data_imports/sources/common/base.pyindex 27ad85d3cb3c..d714aea50188 100644--- a/posthog/temporal/data_imports/sources/common/base.py+++ b/posthog/temporal/data_imports/sources/common/base.py@@ -51,6 +51,10 @@ class _BaseSource(ABC, Generic[ConfigType]):source_for_pipeline - use SimpleSource or ResumableSource instead."""+ # Default `False` for every source; `SQLSource` flips to `True` (subclasses opt out+ # via their own override if a driver genuinely can't project columns).+ supports_column_selection: bool = False+@property@abstractmethoddef source_type(self) -> ExternalDataSourceType:diff --git a/posthog/temporal/data_imports/sources/common/sql/base.py b/posthog/temporal/data_imports/sources/common/sql/base.pyindex 1a3b1bb8cf66..1033504a8db4 100644--- a/posthog/temporal/data_imports/sources/common/sql/base.py+++ b/posthog/temporal/data_imports/sources/common/sql/base.py@@ -53,7 +53,7 @@ class SQLSource(SimpleSource[ConfigType], Generic[ConfigType]):wiring around it."""- supports_column_selection: bool = False+ supports_column_selection: bool = True@property@abstractmethoddiff --git a/posthog/temporal/data_imports/sources/mssql/mssql.py b/posthog/temporal/data_imports/sources/mssql/mssql.pyindex 3fea30f2f316..8c96e3427bd3 100644--- a/posthog/temporal/data_imports/sources/mssql/mssql.py+++ b/posthog/temporal/data_imports/sources/mssql/mssql.py@@ -33,7 +33,14 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (table_from_iterator,)from posthog.temporal.data_imports.sources.common.mixins import open_ssh_tunnel-from posthog.temporal.data_imports.sources.common.sql import BracketIdentifierQuoter, Column, Table+from posthog.temporal.data_imports.sources.common.sql import (+ BracketIdentifierQuoter,+ Column,+ Table,+ compute_projected_columns,+ format_projected_select_clause,+ project_arrow_columns,+)from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation, TableStatsfrom posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilterfrom posthog.temporal.data_imports.sources.generated_configs import MSSQLSourceConfig@@ -73,13 +80,17 @@ def _build_query(incremental_field_type: IncrementalFieldType | None,db_incremental_field_last_value: Any | None,add_limit: bool = False,+ enabled_columns: list[str] | None = None,+ primary_keys: list[str] | None = None,) -> tuple[str, dict[str, Any]]:# Every identifier interpolated below is validated by the bracket# quoter — bad input (`;`, `]`, whitespace, etc.) raises before any# SQL is built. Parameter values still flow through pymssql binding.qualified_table = _IDENTIFIER_QUOTER.quote_qualified(schema, table_name)top = "TOP 100 " if add_limit else ""- base_query = f"SELECT {top}* FROM {qualified_table}"+ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ select_clause = format_projected_select_clause(projected, _IDENTIFIER_QUOTER)+ base_query = f"SELECT {top}{select_clause} FROM {qualified_table}"if not should_use_incremental_field:return base_query, {}@@ -561,9 +572,22 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conincremental_field = inputs.incremental_fieldincremental_field_type = inputs.incremental_field_typedb_incremental_field_last_value = inputs.db_incremental_field_last_value+ enabled_columns = inputs.enabled_columnswith self.connect(config) as connection:with connection.cursor() as cursor:+ primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)+ full_table = self.get_table_metadata(cursor, schema, table_name)++ # Resolve PKs before projection so SELECT and Arrow schema agree.+ if primary_keys is None and "id" in full_table:+ primary_keys = ["id"]++ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ table = project_arrow_columns(full_table, projected)+ arrow_schema = table.to_arrow_schema()+ logger.debug(f"Source schema: {arrow_schema}")+inner_query, inner_query_args = _build_query(schema,table_name,@@ -571,12 +595,10 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conincremental_field,incremental_field_type,db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)- primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)- table = self.get_table_metadata(cursor, schema, table_name)- arrow_schema = table.to_arrow_schema()- logger.debug(f"Source schema: {arrow_schema}")rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)chunk_size = self.get_chunk_size(cursor, schema, table_name, inner_query, inner_query_args, logger)partition_settings = (@@ -585,10 +607,6 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conelse None)- # Fallback on checking for an `id` field on the table- if primary_keys is None and "id" in table:- primary_keys = ["id"]-def get_rows() -> Iterator[Any]:with self.connect(config) as streaming_connection:with streaming_connection.cursor() as cursor:@@ -599,6 +617,8 @@ class MSSQLImplementation(SQLSourceImplementation[MSSQLSourceConfig, pymssql.Conincremental_field,incremental_field_type,db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)if incremental_field:query = f"{query} ORDER BY {_IDENTIFIER_QUOTER.quote(incremental_field)} ASC"diff --git a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.pyindex f68322bd1df1..745539b206f9 100644--- a/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py+++ b/posthog/temporal/data_imports/sources/mssql/tests/test_mssql.py@@ -165,6 +165,45 @@ class TestBuildQuery:)+class TestBuildQueryEnabledColumns:+ @pytest.mark.parametrize(+ "enabled_columns,primary_keys,expected_select",+ [+ (None, ["id"], "SELECT * FROM"),+ (["email"], ["id"], "SELECT [email], [id] FROM"),+ ([], None, "SELECT * FROM"),+ ([], ["id"], "SELECT [id] FROM"),+ ],+ )+ def test_full_refresh_projection(self, enabled_columns, primary_keys, expected_select):+ query, _ = _build_query(+ schema="dbo",+ table_name="users",+ should_use_incremental_field=False,+ incremental_field=None,+ incremental_field_type=None,+ db_incremental_field_last_value=None,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,+ )+ assert query.startswith(expected_select)++ def test_incremental_projection_retains_incremental_field(self):+ query, args = _build_query(+ schema="dbo",+ table_name="users",+ should_use_incremental_field=True,+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.DateTime,+ db_incremental_field_last_value="2025-01-01",+ enabled_columns=["email"],+ primary_keys=["id"],+ )+ assert query.startswith("SELECT [email], [id], [created_at] FROM")+ assert "WHERE [created_at] > %(incremental_value)s" in query+ assert args == {"incremental_value": "2025-01-01"}++# ---------------------------------------------------------------------------# Per-cursor metadata queries# ---------------------------------------------------------------------------diff --git a/posthog/temporal/data_imports/sources/mysql/mysql.py b/posthog/temporal/data_imports/sources/mysql/mysql.pyindex 62b2043e9c91..32dacf6eb4f2 100644--- a/posthog/temporal/data_imports/sources/mysql/mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/mysql.py@@ -48,6 +48,8 @@ from posthog.temporal.data_imports.sources.common.sql import (InvalidIdentifierError,SelectQueryBuilder,Table,+ compute_projected_columns,+ project_arrow_columns,)from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation, TableStatsfrom posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilter@@ -158,6 +160,8 @@ def _build_query(incremental_field_type: IncrementalFieldType | None,db_incremental_field_last_value: Any | None,force_index_name: str | None = None,+ enabled_columns: list[str] | None = None,+ primary_keys: list[str] | None = None,) -> tuple[str, dict[str, Any]]:hint: str | None = Noneif force_index_name is not None:@@ -169,6 +173,8 @@ def _build_query(schema=schema,table_name=table_name,extra_table_hint=hint,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)params = result.params if isinstance(result.params, dict) else {}return result.sql, params@@ -183,6 +189,8 @@ def _build_query(incremental_field_type=incremental_field_type,incremental_last_value=db_incremental_field_last_value,extra_table_hint=hint,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)params = result.params if isinstance(result.params, dict) else {}return result.sql, params@@ -722,9 +730,22 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conincremental_field = inputs.incremental_fieldincremental_field_type = inputs.incremental_field_typedb_incremental_field_last_value = inputs.db_incremental_field_last_value+ enabled_columns = inputs.enabled_columnswith self.connect(config) as connection:with connection.cursor() as cursor:+ primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)+ full_table = self.get_table_metadata(cursor, schema, table_name)++ # Resolve PKs before the projection so probe/sample queries match the streaming SELECT.+ if primary_keys is None and "id" in full_table:+ primary_keys = ["id"]++ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ table = project_arrow_columns(full_table, projected)+ arrow_schema = table.to_arrow_schema()+ logger.debug(f"Source schema: {arrow_schema}")+inner_query, inner_query_args = _build_query(schema,table_name,@@ -732,12 +753,10 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conincremental_field,incremental_field_type,db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)- primary_keys = self.get_primary_keys_for_table(cursor, schema, table_name)- table = self.get_table_metadata(cursor, schema, table_name)- arrow_schema = table.to_arrow_schema()- logger.debug(f"Source schema: {arrow_schema}")rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_args, logger)chunk_size = self.get_chunk_size(cursor, schema, table_name, inner_query, inner_query_args, logger)partition_settings = (@@ -746,10 +765,6 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conelse None)- # Fallback on checking for an `id` field on the table- if primary_keys is None and "id" in table:- primary_keys = ["id"]-def _stream_with_optional_force_index(force_index_name: str | None) -> Iterator[Any]:"""Open a fresh connection and stream rows.@@ -780,6 +795,8 @@ class MySQLImplementation(SQLSourceImplementation[MySQLSourceConfig, pymysql.Conincremental_field_type,db_incremental_field_last_value,force_index_name=force_index_name,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)logger.debug(f"MySQL query: {query.format(args)}")diff --git a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex 14bfcabecd66..6e9ba1f36e63 100644--- a/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/posthog/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -656,6 +656,49 @@ class TestBuildQueryForceIndex:)+class TestBuildQueryEnabledColumns:+ @pytest.mark.parametrize(+ "enabled_columns,primary_keys,expected_prefix",+ [+ (None, ["id"], "SELECT * FROM"),+ (["email"], ["id"], "SELECT `email`, `id` FROM"),+ ([], None, "SELECT * FROM"),+ ([], ["id"], "SELECT `id` FROM"),+ ],+ )+ def test_full_refresh_projection(+ self,+ enabled_columns: list[str] | None,+ primary_keys: list[str] | None,+ expected_prefix: str,+ ):+ query, _ = _build_query(+ schema="mydb",+ table_name="message",+ should_use_incremental_field=False,+ incremental_field=None,+ incremental_field_type=None,+ db_incremental_field_last_value=None,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,+ )+ assert query.startswith(expected_prefix)++ def test_incremental_projection_retains_incremental_field(self):+ query, _ = _build_query(+ schema="mydb",+ table_name="message",+ should_use_incremental_field=True,+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.DateTime,+ db_incremental_field_last_value="2025-01-01",+ enabled_columns=["email"],+ primary_keys=["id"],+ )+ assert query.startswith("SELECT `email`, `id`, `created_at` FROM")+ assert "WHERE `created_at` > %(incremental_value)s" in query++class TestMySQLSourceNonRetryableErrors:@pytest.fixturedef source(self):diff --git a/posthog/temporal/data_imports/sources/postgres/source.py b/posthog/temporal/data_imports/sources/postgres/source.pyindex 8c1a33ff2c80..1d2b414cea30 100644--- a/posthog/temporal/data_imports/sources/postgres/source.py+++ b/posthog/temporal/data_imports/sources/postgres/source.py@@ -63,8 +63,6 @@ _POSTGRES_IMPLEMENTATION = PostgresImplementation()@SourceRegistry.registerclass PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDatabaseHostMixin):- supports_column_selection: bool = True-def __init__(self, source_name: str = "Postgres"):super().__init__()self.source_name = source_namediff --git a/posthog/temporal/data_imports/sources/redshift/redshift.py b/posthog/temporal/data_imports/sources/redshift/redshift.pyindex 53a0ae01bd58..165328d94a17 100644--- a/posthog/temporal/data_imports/sources/redshift/redshift.py+++ b/posthog/temporal/data_imports/sources/redshift/redshift.py@@ -38,7 +38,12 @@ from posthog.temporal.data_imports.pipelines.pipeline.utils import (table_from_iterator,)from posthog.temporal.data_imports.sources.common.mixins import open_ssh_tunnel-from posthog.temporal.data_imports.sources.common.sql import Column, Table+from posthog.temporal.data_imports.sources.common.sql import (+ Column,+ Table,+ compute_projected_columns,+ project_arrow_columns,+)from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementation, TableStatsfrom posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilterfrom posthog.temporal.data_imports.sources.generated_configs import RedshiftSourceConfig@@ -91,6 +96,18 @@ class JsonAsStringLoader(Loader):return bytes(data).decode("utf-8")+def _redshift_select_clause(+ enabled_columns: Optional[list[str]],+ primary_keys: Optional[list[str]],+ incremental_field: Optional[str],+) -> sql.Composable:+ """Build the SELECT-list fragment as a `psycopg.sql.Composable`."""+ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ if projected is None:+ return sql.SQL("*")+ return sql.SQL(", ").join(sql.Identifier(column) for column in projected)++def _build_query(schema: str,table_name: str,@@ -100,13 +117,21 @@ def _build_query(incremental_field_type: Optional[IncrementalFieldType],db_incremental_field_last_value: Optional[Any],add_sampling: Optional[bool] = False,+ enabled_columns: Optional[list[str]] = None,+ primary_keys: Optional[list[str]] = None,) -> sql.Composed:+ select_clause = _redshift_select_clause(enabled_columns, primary_keys, incremental_field)+if not should_use_incremental_field:if add_sampling:# Redshift doesn't support TABLESAMPLE SYSTEM, use random() instead- 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 {}").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")@@ -125,8 +150,9 @@ def _build_query(if add_sampling:# Redshift doesn't support TABLESAMPLE SYSTEMquery = 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),@@ -134,7 +160,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),@@ -748,33 +775,13 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoincremental_field = inputs.incremental_fieldincremental_field_type = inputs.incremental_field_typedb_incremental_field_last_value = inputs.db_incremental_field_last_value+ enabled_columns = inputs.enabled_columnswith self.connect(config) as connection:with connection.cursor() as cursor:logger.debug("Getting table types...")- table = self.get_table_metadata(cursor, schema, table_name, logger)- 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,- )+ full_table = self.get_table_metadata(cursor, schema, table_name, logger)- inner_query_without_limit = _build_query(- schema,- table_name,- should_use_incremental_field,- table.type,- incremental_field,- incremental_field_type,- db_incremental_field_last_value,- )cursor.execute(sql.SQL("SET statement_timeout = {timeout}").format(timeout=sql.Literal(1000 * 60 * 10)) # 10 mins)@@ -783,6 +790,40 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoprimary_keys = self.get_primary_keys_for_table(cursor, schema, table_name, logger)if primary_keys:logger.debug(f"Found primary keys: {primary_keys}")++ # Resolve PKs before projection so SELECT and Arrow schema agree.+ if primary_keys is None and "id" in full_table:+ logger.debug("Falling back to ['id'] for primary keys...")+ primary_keys = ["id"]++ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ table = project_arrow_columns(full_table, projected)+ 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,+ )++ inner_query_without_limit = _build_query(+ schema,+ table_name,+ should_use_incremental_field,+ table.type,+ incremental_field,+ incremental_field_type,+ db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,+ )logger.debug("Getting table chunk size...")if chunk_size_override is not None:chunk_size = chunk_size_override@@ -808,11 +849,8 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoelse None)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 primary_keys == ["id"] and "id" in full_table:+ # Only check dupes when we fell back to the `id` PK above.logger.debug("Checking duplicate primary keys...")duplicate_primary_keys = self.has_duplicate_primary_keys(cursor, schema, table_name, primary_keys, logger@@ -837,6 +875,8 @@ class RedshiftImplementation(SQLSourceImplementation[RedshiftSourceConfig, psycoincremental_field,incremental_field_type,db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)logger.debug(f"Redshift query: {query.as_string()}")diff --git a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.pyindex ada9346471df..2c52fc901428 100644--- a/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py+++ b/posthog/temporal/data_imports/sources/redshift/tests/test_redshift.py@@ -10,6 +10,7 @@ from posthog.temporal.data_imports.sources.generated_configs import RedshiftSourfrom posthog.temporal.data_imports.sources.redshift.redshift import (RedshiftColumn,RedshiftImplementation,+ _build_query,filter_redshift_incremental_fields,)from posthog.temporal.data_imports.sources.redshift.source import _REDSHIFT_IMPLEMENTATION, RedshiftSource@@ -83,6 +84,48 @@ class TestFilterIncrementalFields:assert result == []+class TestBuildQueryEnabledColumns:+ @pytest.mark.parametrize(+ "enabled_columns,primary_keys,expected_select",+ [+ (None, ["id"], "SELECT * FROM"),+ (["email"], ["id"], 'SELECT "email", "id" FROM'),+ ([], None, "SELECT * FROM"),+ ([], ["id"], 'SELECT "id" FROM'),+ ],+ )+ def test_full_refresh_projection(self, enabled_columns, primary_keys, expected_select):+ composed = _build_query(+ schema="public",+ table_name="users",+ should_use_incremental_field=False,+ table_type=None,+ incremental_field=None,+ incremental_field_type=None,+ db_incremental_field_last_value=None,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,+ )+ rendered = composed.as_string()+ assert rendered.startswith(expected_select)++ def test_incremental_projection_retains_incremental_field(self):+ composed = _build_query(+ schema="public",+ table_name="users",+ should_use_incremental_field=True,+ table_type=None,+ incremental_field="created_at",+ incremental_field_type=IncrementalFieldType.DateTime,+ db_incremental_field_last_value="2025-01-01",+ enabled_columns=["email"],+ primary_keys=["id"],+ )+ rendered = composed.as_string()+ assert rendered.startswith('SELECT "email", "id", "created_at" FROM')+ assert 'WHERE "created_at"' in rendered++class TestRedshiftColumnToArrowField:def test_decimal_requires_precision(self):col = RedshiftColumn(name="x", data_type="decimal", nullable=True)diff --git a/posthog/temporal/data_imports/sources/snowflake/snowflake.py b/posthog/temporal/data_imports/sources/snowflake/snowflake.pyindex df53df75ea6e..67f7e3ce1c46 100644--- a/posthog/temporal/data_imports/sources/snowflake/snowflake.py+++ b/posthog/temporal/data_imports/sources/snowflake/snowflake.py@@ -28,6 +28,11 @@ from posthog.temporal.data_imports.pipelines.helpers import (incremental_type_to_operator,)from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.sql import (+ AnsiIdentifierQuoter,+ compute_projected_columns,+ format_projected_select_clause,+)from posthog.temporal.data_imports.sources.common.sql.implementation import SQLSourceImplementationfrom posthog.temporal.data_imports.sources.common.sql.incremental import IncrementalFieldFilterfrom posthog.temporal.data_imports.sources.generated_configs import SnowflakeSourceConfig@@ -58,6 +63,9 @@ def filter_snowflake_incremental_fields(return results+_SNOWFLAKE_IDENTIFIER_QUOTER = AnsiIdentifierQuoter()++def _build_query(database: str,schema: str,@@ -66,9 +74,14 @@ def _build_query(incremental_field: Optional[str],incremental_field_type: Optional[IncrementalFieldType],db_incremental_field_last_value: Optional[Any],+ enabled_columns: list[str] | None = None,+ primary_keys: list[str] | None = None,) -> tuple[str, tuple[Any, ...]]:+ projected = compute_projected_columns(enabled_columns, primary_keys, incremental_field)+ select_clause = format_projected_select_clause(projected, _SNOWFLAKE_IDENTIFIER_QUOTER)+if not should_use_incremental_field:- return "SELECT * FROM IDENTIFIER(%s)", (f"{database}.{schema}.{table_name}",)+ return f"SELECT {select_clause} FROM IDENTIFIER(%s)", (f"{database}.{schema}.{table_name}",)if incremental_field is None or incremental_field_type is None:raise ValueError("incremental_field and incremental_field_type can't be None")@@ -77,11 +90,14 @@ def _build_query(db_incremental_field_last_value = incremental_type_to_initial_value(incremental_field_type)operator = incremental_type_to_operator(incremental_field_type)- return f"SELECT * FROM IDENTIFIER(%s) WHERE IDENTIFIER(%s) {operator} %s ORDER BY IDENTIFIER(%s) ASC", (- f"{database}.{schema}.{table_name}",- incremental_field,- db_incremental_field_last_value,- incremental_field,+ return (+ f"SELECT {select_clause} FROM IDENTIFIER(%s) WHERE IDENTIFIER(%s) {operator} %s ORDER BY IDENTIFIER(%s) ASC",+ (+ f"{database}.{schema}.{table_name}",+ incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ ),)@@ -390,11 +406,13 @@ class SnowflakeImplementation(incremental_field = inputs.incremental_fieldincremental_field_type = inputs.incremental_field_typedb_incremental_field_last_value = inputs.db_incremental_field_last_value+ enabled_columns = inputs.enabled_columnswith self.connect(config) as connection:with connection.cursor() as cursor:if cursor is None:raise Exception("Can't create cursor to Snowflake")+ primary_keys = self.get_primary_keys_for_table(cursor, database, schema, table_name)inner_query, inner_query_params = _build_query(database,schema,@@ -403,8 +421,9 @@ class SnowflakeImplementation(incremental_field,incremental_field_type,db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)- primary_keys = self.get_primary_keys_for_table(cursor, database, schema, table_name)rows_to_sync = self.get_rows_to_sync(cursor, inner_query, inner_query_params, logger)def get_rows() -> Iterator[Any]:@@ -420,6 +439,8 @@ class SnowflakeImplementation(incremental_field,incremental_field_type,db_incremental_field_last_value,+ enabled_columns=enabled_columns,+ primary_keys=primary_keys,)logger.debug(f"Snowflake query: {query.format(params)}")streaming_cursor.execute(query, params)diff --git a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.pyindex 996b057d9af8..a2ae94aed639 100644--- a/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py+++ b/posthog/temporal/data_imports/sources/snowflake/tests/test_snowflake.py@@ -146,6 +146,49 @@ class TestBuildQuery:assert params[2] is not None+class TestBuildQueryEnabledColumns:+ def test_full_refresh_none_uses_select_star(self):+ sql, _ = _build_query("DB", "PUBLIC", "t", False, None, None, None, enabled_columns=None, primary_keys=["id"])+ assert sql.startswith("SELECT * FROM IDENTIFIER(%s)")++ def test_full_refresh_subset_projects_pk_retained(self):+ sql, _ = _build_query(+ "DB", "PUBLIC", "t", False, None, None, None, enabled_columns=["EMAIL"], primary_keys=["ID"]+ )+ assert sql.startswith('SELECT "EMAIL", "ID" FROM IDENTIFIER(%s)')++ def test_full_refresh_subset_keeps_incremental_field(self):+ sql, _ = _build_query(+ "DB",+ "PUBLIC",+ "t",+ False,+ None,+ None,+ None,+ enabled_columns=["EMAIL"],+ primary_keys=["ID"],+ )+ assert '"EMAIL"' in sql+ assert '"ID"' in sql++ def test_incremental_subset_retains_incremental_field(self):+ sql, params = _build_query(+ "DB",+ "PUBLIC",+ "t",+ True,+ "CREATED_AT",+ IncrementalFieldType.DateTime,+ "2025-01-01",+ enabled_columns=["EMAIL"],+ primary_keys=["ID"],+ )+ assert sql.startswith('SELECT "EMAIL", "ID", "CREATED_AT" FROM IDENTIFIER(%s)')+ assert "WHERE IDENTIFIER(%s)" in sql+ assert params == ("DB.PUBLIC.t", "CREATED_AT", "2025-01-01", "CREATED_AT")++# ---------------------------------------------------------------------------# Implementation fixtures# ---------------------------------------------------------------------------diff --git a/products/data_warehouse/backend/api/external_data_source.py b/products/data_warehouse/backend/api/external_data_source.pyindex 626e0f79bc86..e211dd701f1c 100644--- a/products/data_warehouse/backend/api/external_data_source.py+++ b/products/data_warehouse/backend/api/external_data_source.py@@ -48,6 +48,7 @@ from posthog.temporal.data_imports.sources.common.base import AnySource, Externafrom posthog.temporal.data_imports.sources.common.config import Configfrom posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.common.sql import filter_dwh_columns_by_enabled_columns, sql_schema_metadata+from posthog.temporal.data_imports.sources.common.sql.base import SQLSourcefrom posthog.temporal.data_imports.sources.postgres.cdc.config import PostgresCDCConfigfrom posthog.temporal.data_imports.sources.postgres.source import PostgresSource@@ -607,8 +608,8 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializerexcept Exception as e:capture_exception(e)return False- # Explicit cast: Mock attribute access returns a Mock that orjson can't serialize.- return bool(getattr(source, "supports_column_selection", False))+ # `bool()` guards against test mocks whose attribute access returns a Mock — orjson can't serialize.+ return bool(source.supports_column_selection)def get_status(self, instance: ExternalDataSource) -> str:active_schemas: list[ExternalDataSchema] = list(instance.active_schemas) # type: ignore@@ -1252,34 +1253,32 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixischema_name = schema.get("name")source_schema = source_schemas_by_name.get(schema_name)- resolved_source_catalog, resolved_source_schema, resolved_source_table_name = (- get_postgres_source_table_location(- schema_name=schema_name,- source_schema=source_schema,- default_schema=default_source_schema,++ metadata_source_catalog: str | None+ metadata_source_schema: str | None+ metadata_source_table_name: str | None+ if source_type_model == ExternalDataSourceType.POSTGRES:+ metadata_source_catalog, metadata_source_schema, metadata_source_table_name = (+ get_postgres_source_table_location(+ schema_name=schema_name,+ source_schema=source_schema,+ default_schema=default_source_schema,+ ))- )- 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,- "source_schema": source_schema.source_schema if source_schema else None,- "source_table_name": source_schema.source_table_name if source_schema else None,- },- default_schema=default_source_schema,- )- # Postgres writes here so direct-mode `DataWarehouseTable` and the column picker have- # data immediately. Non-Postgres sources populate via `reconcile_schema_metadata` on- # the next `refresh_schemas` run.+ else:+ metadata_source_catalog = source_schema.source_catalog if source_schema else None+ metadata_source_schema = source_schema.source_schema if source_schema else None+ metadata_source_table_name = source_schema.source_table_name if source_schema else None+schema_metadata = (sql_schema_metadata(source_schema.columns if source_schema else [],source_schema.foreign_keys if source_schema else [],- source_catalog=resolved_source_catalog,- source_schema=resolved_source_schema,- source_table_name=resolved_source_table_name,+ source_catalog=metadata_source_catalog,+ source_schema=metadata_source_schema,+ source_table_name=metadata_source_table_name,)- if source_type_model == ExternalDataSourceType.POSTGRES+ if source.supports_column_selectionelse {})@@ -1330,15 +1329,17 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixienabled_columns=enabled_columns,)- # For CDC schemas with PostHog-managed mode, add table to publication+ # CDC + direct-postgres paths are Postgres-only — `get_postgres_source_table_location`+ # guarantees non-None schema/table in that branch above. `cast` narrows for mypy+ # without a runtime check.if is_cdc_schema and should_sync and cdc_enabled:cdc_config = PostgresCDCConfig.from_source(new_source_model)if cdc_config.management_mode == "posthog" and cdc_config.publication_name:self._add_table_to_cdc_publication(new_source_model,cdc_config.publication_name,- resolved_source_schema,- resolved_source_table_name,+ cast(str, metadata_source_schema),+ cast(str, metadata_source_table_name),)if new_source_model.is_direct_postgres and should_sync:@@ -1355,9 +1356,9 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixisource_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,+ source_catalog=metadata_source_catalog,+ source_schema=cast(str, metadata_source_schema),+ source_table_name=cast(str, metadata_source_table_name),)schema_model.save(update_fields=["table"])@@ -1770,7 +1771,6 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixidescriptions=descriptions,)- # Direct call (not via hook): tests that mock `SourceRegistry` need the real reconcile.if instance.source_type == ExternalDataSourceType.POSTGRES:reconciled_deleted_schemas = reconcile_postgres_schemas(source=instance,@@ -1779,6 +1779,8 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi)if reconciled_deleted_schemas:schemas_deleted = list({*schemas_deleted, *reconciled_deleted_schemas})+ elif isinstance(source, SQLSource) and source.supports_column_selection:+ source.reconcile_schema_metadata(source=instance, source_schemas=schemas, team_id=self.team_id)logger.debug("refresh_schemas completed",source_id=str(instance.id),@@ -2067,12 +2069,13 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi@action(methods=["GET"], detail=False)def wizard(self, request: Request, *arg: Any, **kwargs: Any):sources = SourceRegistry.get_all_sources()- configs = {name: source.get_source_config for name, source in sources.items()}+ results = {}+ for source_type, source in sources.items():+ config = source.get_source_config.model_dump()+ config["supportsColumnSelection"] = bool(source.supports_column_selection)+ results[str(source_type)] = config- return Response(- status=status.HTTP_200_OK,- data={str(key): value.model_dump() for key, value in configs.items()},- )+ return Response(status=status.HTTP_200_OK, data=results)@extend_schema(responses=ExternalDataSourceConnectionOptionSerializer(many=True))@action(methods=["GET"], detail=False)diff --git a/products/data_warehouse/backend/api/public_source_configs.py b/products/data_warehouse/backend/api/public_source_configs.pyindex a93807891bff..d113ddd6ffe4 100644--- a/products/data_warehouse/backend/api/public_source_configs.py+++ b/products/data_warehouse/backend/api/public_source_configs.py@@ -27,6 +27,10 @@ class PublicSourceConfigViewSet(viewsets.ViewSet):def list(self, request: Request) -> Response:sources = SourceRegistry.get_all_sources()- results = {str(source_type): source.get_source_config.model_dump() for source_type, source in sources.items()}+ results = {}+ for source_type, source in sources.items():+ config = source.get_source_config.model_dump()+ config["supportsColumnSelection"] = bool(source.supports_column_selection)+ results[str(source_type)] = configreturn Response(status=status.HTTP_200_OK, data=results)diff --git a/products/data_warehouse/backend/api/test/test_external_data_schema.py b/products/data_warehouse/backend/api/test/test_external_data_schema.pyindex 2b3570bfb639..9c340e273fa7 100644--- a/products/data_warehouse/backend/api/test/test_external_data_schema.py+++ b/products/data_warehouse/backend/api/test/test_external_data_schema.py@@ -1667,3 +1667,96 @@ class TestExternalDataSchemaSerializerValidation(APIBaseTest):assert response.status_code == 200self.schema.refresh_from_db()assert self.schema.sync_type == ExternalDataSchema.SyncType.INCREMENTAL+++class TestAvailableColumnsAcrossSqlSources(APIBaseTest):+ """`available_columns` is source-type-agnostic — it reads `schema_metadata.columns`.+ Parameterized across every SQL source to lock in that the serializer doesn't regress+ to Postgres-only behavior."""++ @parameterized.expand(+ [+ (ExternalDataSourceType.POSTGRES,),+ (ExternalDataSourceType.MYSQL,),+ (ExternalDataSourceType.MSSQL,),+ (ExternalDataSourceType.BIGQUERY,),+ (ExternalDataSourceType.SNOWFLAKE,),+ (ExternalDataSourceType.REDSHIFT,),+ ]+ )+ def test_available_columns_populated_from_schema_metadata(self, source_type: ExternalDataSourceType):+ source = ExternalDataSource.objects.create(team=self.team, source_type=source_type)+ schema = ExternalDataSchema.objects.create(+ name="customers",+ team=self.team,+ source=source,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ sync_type_config={+ "schema_metadata": {+ "columns": [+ {"name": "id", "data_type": "integer", "is_nullable": False},+ {"name": "email", "data_type": "text", "is_nullable": True},+ ],+ "foreign_keys": [],+ },+ },+ )++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/",+ )+ assert response.status_code == 200, response.json()+ payload = response.json()+ assert payload["available_columns"] == [+ {"name": "id", "data_type": "integer", "is_nullable": False},+ {"name": "email", "data_type": "text", "is_nullable": True},+ ]++ @parameterized.expand(+ [+ (ExternalDataSourceType.POSTGRES,),+ (ExternalDataSourceType.MYSQL,),+ (ExternalDataSourceType.MSSQL,),+ (ExternalDataSourceType.BIGQUERY,),+ (ExternalDataSourceType.SNOWFLAKE,),+ (ExternalDataSourceType.REDSHIFT,),+ ]+ )+ def test_available_columns_empty_when_schema_metadata_missing(self, source_type: ExternalDataSourceType):+ source = ExternalDataSource.objects.create(team=self.team, source_type=source_type)+ schema = ExternalDataSchema.objects.create(+ name="customers",+ team=self.team,+ source=source,+ should_sync=True,+ status=ExternalDataSchema.Status.COMPLETED,+ )++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.id}/",+ )+ assert response.status_code == 200, response.json()+ assert response.json()["available_columns"] == []++ @parameterized.expand(+ [+ # source_type, supports_column_selection_expected+ (ExternalDataSourceType.POSTGRES, True),+ (ExternalDataSourceType.MYSQL, True),+ (ExternalDataSourceType.MSSQL, True),+ (ExternalDataSourceType.BIGQUERY, True),+ (ExternalDataSourceType.SNOWFLAKE, True),+ (ExternalDataSourceType.REDSHIFT, True),+ # Non-SQL sources stay False+ (ExternalDataSourceType.STRIPE, False),+ ]+ )+ def test_source_supports_column_selection_flag(self, source_type: ExternalDataSourceType, expected: bool):+ source = ExternalDataSource.objects.create(team=self.team, source_type=source_type)++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ )+ assert response.status_code == 200, response.json()+ assert response.json()["supports_column_selection"] is expecteddiff --git a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsxindex 398037fa59d9..da528a9907ad 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx+++ b/products/data_warehouse/frontend/scenes/SchemaScene/ConfigurationTab.tsx@@ -63,8 +63,9 @@ export interface ConfigurationTabProps {export function ConfigurationTab({ sourceId, schema, source, section }: ConfigurationTabProps): JSX.Element {const logic = sourceSettingsLogic({ id: sourceId })- const { isProjectTime } = useValues(logic)- const { setIsProjectTime, updateSchema, reloadSchema, resyncSchema, cancelSchema, deleteTable } = useActions(logic)+ const { isProjectTime, refreshingSchemas } = useValues(logic)+ const { setIsProjectTime, updateSchema, reloadSchema, resyncSchema, cancelSchema, deleteTable, refreshSchemas } =+ useActions(logic)switch (section) {case 'details':@@ -86,6 +87,8 @@ export function ConfigurationTab({ sourceId, schema, source, section }: Configurschema={schema}updateSchema={updateSchema}resyncSchema={resyncSchema}+ refreshSchemas={refreshSchemas}+ refreshingSchemas={refreshingSchemas}/>)case 'schedule':@@ -415,11 +418,15 @@ function ColumnsSection({schema,updateSchema,resyncSchema,+ refreshSchemas,+ refreshingSchemas,}: {source: ExternalDataSource | nullschema: ExternalDataSourceSchemaupdateSchema: (schema: ExternalDataSourceSchema) => voidresyncSchema: (schema: ExternalDataSourceSchema) => void+ refreshSchemas: () => void+ refreshingSchemas: boolean}): JSX.Element {const available = schema.available_columns ?? []const hasAvailableColumns = available.length > 0@@ -498,7 +505,19 @@ function ColumnsSection({/><div className="border rounded p-4 bg-surface-primary flex flex-col gap-3">{!hasAvailableColumns ? (- <span className="text-muted">Per-column selection isn't available for this source yet.</span>+ <div className="flex flex-col items-center gap-2 text-center text-muted-alt py-6">+ <span className="text-sm">No columns discovered yet for this schema.</span>+ <SourceEditorAction source={source}>+ <LemonButton+ type="secondary"+ size="small"+ loading={refreshingSchemas}+ onClick={() => refreshSchemas()}+ >+ Pull new schemas+ </LemonButton>+ </SourceEditorAction>+ </div>) : (<><span className="text-sm text-secondary">{summaryLine}</span>diff --git a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsxindex 50797f8e02a6..c10c8fe0c990 100644--- a/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx+++ b/products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene.tsx@@ -67,7 +67,7 @@ function SchemaSceneContent({ sourceId, schemaId }: SchemaSceneProps): JSX.Elemeconst cleanedSourceId = cleanSourceId(sourceId)const showMetrics = !!featureFlags[FEATURE_FLAGS.DWH_SOURCE_METRICS]- const showColumnsSection = (schema?.available_columns?.length ?? 0) > 0+ const showColumnsSection = source?.supports_column_selection === trueconst visibleSections = SCHEMA_CONFIGURATION_SECTIONS.filter((key) => key !== 'columns' || showColumnsSection)useEffect(() => {diff --git a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsxindex 466d2d8e9e98..0c73e0784797 100644--- a/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SchemaForm.tsx@@ -69,6 +69,7 @@ export default function SchemaForm(): JSX.Element {isDirectQueryMode,tablesAllToggledOn,source,+ selectedConnector,groupedDirectQueryDatabaseSchema,expandedDirectQuerySchemaKeys,} = useValues(sourceWizardLogic)@@ -84,7 +85,7 @@ export default function SchemaForm(): JSX.Element {toggleSchemaShouldSync(schema, checked)}- const shouldShowSyncColumns = !isDirectQueryMode+ const shouldShowSyncColumns = !isDirectQueryMode && !!selectedConnector?.supportsColumnSelection// scroll to top of containeruseEffect(() => {