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.

fix(data-warehouse): pass SELECT * through to direct clickhouse connections (#74700)

Tom Owers8fbb38ea9769
diff --git a/posthog/hogql/database/direct_sql_table.py b/posthog/hogql/database/direct_sql_table.py
index f3987dea1868..94c12ecdf9ae 100644
--- a/posthog/hogql/database/direct_sql_table.py
+++ b/posthog/hogql/database/direct_sql_table.py
@@ -10,6 +10,11 @@ class DirectSQLTable(FunctionCallTable):
requires_args: bool = False
external_data_source_id: str
connection_metadata: dict[str, object] | None = None
+ # True only when these fields are the table's complete physical schema (no column-picker
+ # restriction). Gates the direct `SELECT *` literal-star passthrough: when a restriction is in
+ # effect the fields are a subset, so the star must expand from them rather than let the external
+ # server expand against the unrestricted physical table (which would leak the hidden columns).
+ has_complete_columns: bool = False
def to_printed_hogql(self) -> str:
return escape_hogql_identifier(self.name)
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index e860b0f16ecf..f0e002075151 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -468,7 +468,12 @@ class HogQLQueryExecutor:
self.results = result.results
self.types = result.types
self.error = result.error
- if result.print_columns and not self.print_columns:
+ # A literal `SELECT *` on a direct connection is expanded by the external server, so the
+ # driver response is the only source of truth for the columns. Detect that by the count
+ # disagreeing with HogQL's own column list (and cover the empty case) — then take the
+ # driver's names, keeping them consistent with `self.types`, which is always driver-derived
+ # above. When counts match (ordinary explicit-column queries) HogQL's names are left as-is.
+ if result.print_columns and (not self.print_columns or len(result.print_columns) != len(self.print_columns)):
self.print_columns = result.print_columns
@tracer.start_as_current_span("HogQLQueryExecutor._generate_clickhouse_sql")
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 766ca9f5f416..5bf2f2036e29 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -12,6 +12,7 @@ from posthog.hogql.base import _T_AST
from posthog.hogql.constants import SQL_TARGET_DIALECTS, HogQLDialect
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.database.direct_clickhouse_table import DirectClickHouseTable
from posthog.hogql.database.models import FunctionCallTable, LazyTable, SavedQuery, StringJSONDatabaseField
from posthog.hogql.database.s3_table import (
DataWarehouseTable as HogQLDataWarehouseTable,
@@ -358,6 +359,10 @@ class Resolver(CloningVisitor):
self._synthetic_using_join_aliases: set[str] = set()
# Re-entrancy guard for argument-duplicating bot-lookup macros (see _expand_duplicating_macro).
self._inside_posthog_macro_expansion: bool = False
+ # Marks whether the outermost SELECT has been entered. Used to keep a top-level `SELECT *`
+ # on a direct-connection table literal (so the external server expands the star); nested and
+ # CTE-body stars still expand to explicit columns so enclosing queries can read them.
+ self._entered_root_select: bool = False
def _get_scope_table_names(self, scope: ast.SelectQueryType) -> dict[str, str]:
return self._scope_table_names.setdefault(id(scope), {})
@@ -843,6 +848,11 @@ class Resolver(CloningVisitor):
def visit_select_query(self, node: ast.SelectQuery):
"""Visit each SELECT query or subquery."""
+ # Capture before visiting CTEs/subqueries (which re-enter here), so only the outermost query
+ # counts as root — a top-level `SELECT *` on a direct table is kept literal below.
+ is_root_select = not self._entered_root_select
+ self._entered_root_select = True
+
# This "SelectQueryType" is also a new scope for variables in the SELECT query.
# We will add fields to it when we encounter them. This is used to resolve fields later.
node_type = ast.SelectQueryType()
@@ -925,6 +935,27 @@ class Resolver(CloningVisitor):
if self.dialect == "snowflake" and _select_from_is_pivot(new_node.select_from):
select_nodes.append(new_expr)
continue
+ # Direct-connect: keep a top-level `SELECT *` on a direct table literal so the
+ # external server expands the star natively, matching its live schema and skipping
+ # materialized/alias columns that a HogQL-expanded list would break on (CH error 47).
+ # Restricted to the root select (is_direct_query is only set in the direct render
+ # pass) so nested/CTE stars still expand and remain readable by enclosing queries.
+ # Gated on has_complete_columns: a column-picker restriction makes the table's fields
+ # a subset, so the star must expand from them — letting the server expand against the
+ # unrestricted physical table would leak the columns the restriction hides.
+ asterisk_direct_table = (
+ new_expr.type.table_type.resolve_database_table(self.context)
+ if isinstance(new_expr.type.table_type, ast.BaseTableType)
+ else None
+ )
+ if (
+ self.context.is_direct_query
+ and is_root_select
+ and isinstance(asterisk_direct_table, DirectClickHouseTable)
+ and asterisk_direct_table.has_complete_columns
+ ):
+ select_nodes.append(new_expr)
+ continue
columns = self._asterisk_columns(new_expr.type, chain_prefix=new_expr.chain[:-1])
for col in columns:
visited_col = self.visit(col)
diff --git a/posthog/hogql/test/test_direct_clickhouse_query.py b/posthog/hogql/test/test_direct_clickhouse_query.py
index 41a2bfc240a5..19043f2c79d1 100644
--- a/posthog/hogql/test/test_direct_clickhouse_query.py
+++ b/posthog/hogql/test/test_direct_clickhouse_query.py
@@ -4,7 +4,7 @@ from posthog.test.base import APIBaseTest
from posthog.hogql.query import HogQLQueryExecutor
-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource
# Storage keys / URL pattern for direct-ClickHouse tables, duplicated as literals to respect the
# products.data_warehouse module boundary (the canonical constants live in
@@ -33,8 +33,14 @@ class TestDirectClickHouseQuery(APIBaseTest):
},
)
- def _create_table(self, source: ExternalDataSource, *, options: dict | None = None) -> DataWarehouseTable:
- return DataWarehouseTable.objects.create(
+ def _create_table(
+ self,
+ source: ExternalDataSource,
+ *,
+ options: dict | None = None,
+ enabled_columns: list[str] | None = None,
+ ) -> DataWarehouseTable:
+ table = DataWarehouseTable.objects.create(
name="events",
format="Parquet",
team=self.team,
@@ -48,6 +54,12 @@ class TestDirectClickHouseQuery(APIBaseTest):
},
options=options or {},
)
+ # The schema carries the column-picker restriction (enabled_columns); None means "all
+ # columns", which is what gates the literal-star passthrough.
+ ExternalDataSchema.objects.create(
+ name="events", team=self.team, source=source, table=table, enabled_columns=enabled_columns
+ )
+ return table
def _from_database(self, source: ExternalDataSource) -> str:
executor = HogQLQueryExecutor(query="SELECT * FROM events", team=self.team, connection_id=str(source.id))
@@ -62,6 +74,43 @@ class TestDirectClickHouseQuery(APIBaseTest):
sql = self._from_database(source)
self.assertIn("posthog.events", sql)
+ def test_select_star_stays_literal_for_direct_connection(self):
+ # A top-level SELECT * on a direct ClickHouse table must print as a literal `*` so the
+ # external server expands the star against its own live schema — not a HogQL-expanded column
+ # list, which can include stale / materialized / alias columns that break the whole query
+ # (ClickHouse error 47, UNKNOWN_IDENTIFIER).
+ source = self._create_source(database="posthog")
+ self._create_table(source)
+
+ sql = self._from_database(source)
+ # The pretty-printer puts the star on its own line (`SELECT\n *\n`), so match on
+ # "SELECT" followed only by whitespace before the `*` rather than the literal substring
+ # "SELECT *" — a check that would otherwise never match either shape.
+ self.assertRegex(sql, r"SELECT\s*\*\s")
+ self.assertNotIn("events.id AS id", sql)
+ self.assertNotIn("events.team_id AS team_id", sql)
+
+ def test_select_star_expands_when_columns_are_restricted(self):
+ # Security: with a column-picker restriction (enabled_columns) the table's fields are a
+ # subset, so SELECT * must expand from them — a literal star would let the server expand
+ # against the unrestricted physical table and leak the hidden columns.
+ source = self._create_source(database="posthog")
+ self._create_table(source, enabled_columns=["id"])
+
+ sql = self._from_database(source)
+ self.assertNotRegex(sql, r"SELECT\s*\*\s")
+ self.assertIn("events.id AS id", sql)
+
+ def test_explicit_columns_still_expand_for_direct_connection(self):
+ # Only the star is kept literal — explicit column selection is unaffected.
+ source = self._create_source(database="posthog")
+ self._create_table(source)
+
+ executor = HogQLQueryExecutor(query="SELECT id FROM events", team=self.team, connection_id=str(source.id))
+ sql, _context = executor.generate_clickhouse_sql()
+ self.assertIn("events.id AS id", sql.replace("`", ""))
+ self.assertNotRegex(sql, r"SELECT\s*\*\s")
+
def test_configured_database_overrides_a_stale_default_option(self):
# Regression: a table synced before the source's database was set stored "default" in its
# per-table options. The live config ("posthog") must win, else the query targets
diff --git a/products/data_warehouse/backend/direct_virtual_tables.py b/products/data_warehouse/backend/direct_virtual_tables.py
index 737bdc598c27..d9008daa044a 100644
--- a/products/data_warehouse/backend/direct_virtual_tables.py
+++ b/products/data_warehouse/backend/direct_virtual_tables.py
@@ -227,6 +227,9 @@ def build_direct_table_for_schema(schema: "ExternalDataSchema", source: "Externa
clickhouse_table_name=table_name,
external_data_source_id=str(source.id),
connection_metadata=source.connection_metadata,
+ # No column-picker restriction → these fields are the complete physical schema, so a
+ # `SELECT *` can pass through to the server literally.
+ has_complete_columns=schema.enabled_columns is None,
)
return None
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index 38d7f0051c52..16e2359117bc 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -613,6 +613,19 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
raise
return s3_table_func, placeholder_context
+ def _direct_columns_are_complete(self) -> bool:
+ """Whether this direct table's stored columns are the complete physical schema — i.e. no
+ column-picker restriction (`ExternalDataSchema.enabled_columns`) is in effect. Only then may
+ a direct `SELECT *` pass through literally; otherwise the fields are a subset and the star
+ must expand from them. Reads the schema rows preloaded onto this instance by
+ `_preload_active_external_data_schemas` (every direct-query DB build path calls it before
+ `hogql_definition`); if they aren't preloaded, returns False (safe: expand) rather than issue
+ a query on this hot table-build path."""
+ schema_rows = self.__dict__.get("_active_external_data_schemas")
+ if schema_rows is None:
+ return False
+ return len(schema_rows) > 0 and all(row.enabled_columns is None for row in schema_rows)
+
def hogql_definition(
self, modifiers: Optional["HogQLQueryModifiers"] = None
) -> (
@@ -783,6 +796,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
clickhouse_table_name=clickhouse_table_name,
external_data_source_id=str(self.external_data_source_id),
connection_metadata=self.external_data_source.connection_metadata,
+ has_complete_columns=self._direct_columns_are_complete(),
)
# Replace fields with any redefined fields if they exist