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(hogql): serve system.information_schema via external tables (#65757)

Tom Owersa65ef3db6b50
diff --git a/posthog/clickhouse/client/execute.py b/posthog/clickhouse/client/execute.py
index 4cccc2d3badc..8727fb6b3954 100644
--- a/posthog/clickhouse/client/execute.py
+++ b/posthog/clickhouse/client/execute.py
@@ -9,7 +9,7 @@ from contextlib import contextmanager
from enum import StrEnum
from functools import lru_cache
from time import perf_counter
-from typing import Any, Optional, Union
+from typing import Any, Optional, TypedDict, Union
from django.conf import settings as app_settings
@@ -245,6 +245,16 @@ logger = structlog.get_logger(__name__)
logger.setLevel(logging.INFO)
+class ClickHouseExternalTable(TypedDict):
+ """A query-scoped external data table sent to ClickHouse alongside the query (the
+ clickhouse_driver `external_tables` format). `structure` is `(column, ClickHouse type)` pairs and
+ `data` is row dicts keyed by column name."""
+
+ name: str
+ structure: list[tuple[str, str]]
+ data: list[dict[str, Any]]
+
+
@patchable
@trace_clickhouse_query_decorator
def sync_execute(
@@ -259,6 +269,7 @@ def sync_execute(
readonly=False,
sync_client: Optional[SyncClient] = None,
ch_user: ClickHouseUser = ClickHouseUser.DEFAULT,
+ external_tables: Optional[list[ClickHouseExternalTable]] = None,
):
"""
Executes a synchronous query on the ClickHouse database based on predefined workloads and tags.
@@ -294,6 +305,8 @@ def sync_execute(
sync_client (Optional[SyncClient]): A specific ClickHouse client to use for the query.
ch_user (ClickHouseUser): The user context for the query execution. Defaults to
ClickHouseUser.DEFAULT.
+ external_tables (Optional[list[ClickHouseExternalTable]]): Query-scoped external data tables
+ sent alongside the query instead of inlined.
Returns:
Union[List[Tuple], int, None]: The result of the query. For select queries, it returns a list of
@@ -455,6 +468,7 @@ def sync_execute(
settings=settings,
with_column_types=with_column_types,
query_id=query_id,
+ external_tables=external_tables,
)
if (
"INSERT INTO" in prepared_sql
diff --git a/posthog/hogql/context.py b/posthog/hogql/context.py
index f535ede12282..8a92c44968ac 100644
--- a/posthog/hogql/context.py
+++ b/posthog/hogql/context.py
@@ -14,6 +14,7 @@ if TYPE_CHECKING:
from posthog.hogql.observability import HogQLTypeObservability
from posthog.hogql.transforms.property_types import PropertySwapper
+ from posthog.clickhouse.client.execute import ClickHouseExternalTable
from posthog.models import Team, User
from posthog.rbac.user_access_control import UserAccessControl
@@ -60,6 +61,10 @@ class HogQLContext:
direct_postgres_connection_metadata: dict[str, Any] | None = None
# If set, will save string constants to this dict. Inlines strings into the query if None.
values: dict = field(default_factory=dict)
+ # Query-scoped ClickHouse external data tables accumulated during printing (keyed by table name).
+ # Lets `system.information_schema` ship its rows out-of-band instead of inlining them; read by the
+ # executor and passed to `sync_execute`.
+ external_tables: dict[str, "ClickHouseExternalTable"] = field(default_factory=dict, compare=False, repr=False)
# Are we small part of a non-HogQL query? If so, use custom syntax for accessed person properties.
within_non_hogql_query: bool = False
# Temporary (June 2026 MaxMind incident): the geoip dict fallback decision, evaluated exactly once per query in
@@ -110,9 +115,9 @@ class HogQLContext:
# Workload detected during AST resolution (set by prepare_ast_for_printing)
workload: Optional[Workload] = None
# Per-query cache of the `system.information_schema` introspection result (populated lazily in
- # posthog/hogql/database/schema/information_schema.py). Shared across the information_schema
- # tables so a single query touching several of them walks the database (and fires the warehouse
- # metadata ORM queries) only once.
+ # posthog/hogql/database/schema/information_schema.py). A dict keyed by the pushed-down table
+ # filter, so information_schema tables resolving to the same bound within one query walk the
+ # database (and fire the warehouse metadata ORM queries) only once.
information_schema_introspection: Optional[Any] = field(default=None, compare=False, repr=False)
# Property-level access control: set of (property_name, PropertyDefinition.Type) tuples
# that the current user is denied access to. Populated before type resolution so that
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index 87393fef300d..168c0a61645e 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -12,6 +12,7 @@ uniformly from `FieldOrTable.description`; for data warehouse tables they are me
`WarehouseColumnAnnotation` semantic layer, fetched lazily only when these tables are queried.
"""
+import hashlib
from typing import TYPE_CHECKING, Any, Optional
import structlog
@@ -19,6 +20,7 @@ import structlog
from posthog.hogql import ast
from posthog.hogql.database.models import (
BooleanDatabaseField,
+ DANGEROUS_NoTeamIdCheckTable,
DatabaseField,
DateDatabaseField,
DateTimeDatabaseField,
@@ -160,22 +162,29 @@ def _visible_table_names(database: "Database") -> list[str]:
return [n for n in database.tables.resolve_visible_table_names() if not n.startswith("posthog.")]
-def _warehouse_metadata(team_id: Optional[int]) -> tuple[dict[tuple[str, str], str], dict[str, Optional[int]]]:
+def _warehouse_metadata(
+ team_id: Optional[int],
+) -> tuple[dict[tuple[str, str], str], dict[str, Optional[int]], dict[str, Optional[int]]]:
"""Lazily load warehouse semantic descriptions and row counts for the team.
- Returns `(descriptions, row_counts)` where descriptions is keyed by `(table_name, column_name)`
- with `""` denoting the table-level description. Only runs when an information_schema table is
- actually queried, so it never touches the hot `create_hogql_database` path.
+ Returns `(descriptions, row_counts, view_row_counts)`. Descriptions are keyed by
+ `(table_name, column_name)` with `""` denoting the table-level description. `row_counts` is keyed
+ by warehouse table name, `view_row_counts` by saved-query (view) name. Only runs when an
+ information_schema table is actually queried, so it never touches the hot
+ `create_hogql_database` path. Mirrors how `serialize_database` sources counts so the catalog and
+ the SQL-editor schema agree.
"""
descriptions: dict[tuple[str, str], str] = {}
row_counts: dict[str, Optional[int]] = {}
+ view_row_counts: dict[str, Optional[int]] = {}
if team_id is None:
- return descriptions, row_counts
+ return descriptions, row_counts, view_row_counts
# Inline imports: keeps the products dependency off the hogql import path (avoids an import
# cycle, since products import hogql) and off every non-information_schema query.
from posthog.models.scoping import team_scope # noqa: PLC0415
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery # noqa: PLC0415
from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation # noqa: PLC0415
from products.warehouse_sources.backend.models.table import DataWarehouseTable # noqa: PLC0415
@@ -185,25 +194,223 @@ def _warehouse_metadata(team_id: Optional[int]) -> tuple[dict[tuple[str, str], s
"table__name", "column_name", "description"
):
descriptions[(table_name, column_name)] = description
- for table_name, row_count in DataWarehouseTable.objects.values_list("name", "row_count"):
+ # `DataWarehouseTable` is on the IDOR baseline (not team-scoped), so `team_scope` is a
+ # no-op for it — filter by team_id explicitly or it reads every team's tables. `.queryable()`
+ # (not `.objects`) drops soft-deleted tables and orphans of a soft-deleted source —
+ # otherwise a re-synced table's dead duplicate clobbers the live row_count with a stale/null
+ # value. Oldest first so the newest row wins a name collision, matching the last-write-wins
+ # order `serialize_database` uses.
+ for table_name, row_count in (
+ DataWarehouseTable.objects.queryable()
+ .filter(team_id=team_id)
+ .order_by("created_at")
+ .values_list("name", "row_count")
+ ):
row_counts[table_name] = row_count
+ # Views carry their row count on the materialized backing table (`saved_query.table`).
+ for view_name, row_count in (
+ DataWarehouseSavedQuery.objects.exclude(deleted=True)
+ .filter(team_id=team_id, table__isnull=False)
+ .values_list("name", "table__row_count")
+ ):
+ view_row_counts[view_name] = row_count
except Exception:
# Schema discovery must never fail a query because the warehouse metadata could not be read,
# but log so a transient DB error can be told apart from a real bug in the fetch loop.
logger.exception("information_schema: failed to load warehouse metadata", team_id=team_id)
- return {}, {}
+ return {}, {}, {}
+
+ return descriptions, row_counts, view_row_counts
+
+
+def _unwrap(expr: ast.Expr) -> ast.Expr:
+ """Peel resolver-inserted `Alias` wrappers — a resolved WHERE turns `table_name` into
+ `Alias(alias='table_name', expr=Field(...))`, so predicate matching has to see through them."""
+ while isinstance(expr, ast.Alias):
+ expr = expr.expr
+ return expr
+
+
+def _constant_str(expr: ast.Expr) -> Optional[str]:
+ """The string form of a non-null, non-bool constant expr, or None if it isn't one."""
+ expr = _unwrap(expr)
+ if isinstance(expr, ast.Constant) and expr.value is not None and not isinstance(expr.value, bool):
+ return str(expr.value)
+ return None
+
+
+def _is_target_field(expr: ast.Expr, column: str) -> bool:
+ expr = _unwrap(expr)
+ return isinstance(expr, ast.Field) and bool(expr.chain) and expr.chain[-1] == column
+
+
+def _bound_table_names(expr: Optional[ast.Expr], column: str) -> Optional[set[str]]:
+ """Best-effort *superset* of the `column` values a WHERE expr can match.
+
+ Returns None when no safe bound can be derived — the caller then emits every row and relies on
+ ClickHouse to apply the real predicate. The invariant is one-directional: the returned set must
+ never exclude a value the predicate could accept (that would drop valid rows), so anything not
+ understood widens to None rather than guessing.
+ """
+ if expr is None:
+ return None
+ expr = _unwrap(expr)
+ if isinstance(expr, ast.And):
+ # An AND result satisfies every conjunct, so it lies within any bounded conjunct; intersect
+ # the bounded ones for the tightest still-correct superset, ignoring conjuncts we can't bound.
+ bound: Optional[set[str]] = None
+ for child in expr.exprs:
+ child_bound = _bound_table_names(child, column)
+ if child_bound is None:
+ continue
+ bound = child_bound if bound is None else (bound & child_bound)
+ return bound
+ if isinstance(expr, ast.Or):
+ # An OR result satisfies at least one branch, so every branch must be bounded to bound the
+ # union — a single unbounded branch makes the whole disjunction unbounded.
+ union: set[str] = set()
+ for child in expr.exprs:
+ child_bound = _bound_table_names(child, column)
+ if child_bound is None:
+ return None
+ union |= child_bound
+ return union
+ if isinstance(expr, ast.CompareOperation):
+ if expr.op == ast.CompareOperationOp.Eq:
+ for field_side, value_side in ((expr.left, expr.right), (expr.right, expr.left)):
+ if _is_target_field(field_side, column):
+ value = _constant_str(value_side)
+ return {value} if value is not None else None
+ return None
+ if expr.op in (ast.CompareOperationOp.In, ast.CompareOperationOp.GlobalIn):
+ if _is_target_field(expr.left, column) and isinstance(expr.right, ast.Tuple | ast.Array):
+ values = [_constant_str(e) for e in expr.right.exprs]
+ return None if any(v is None for v in values) else {v for v in values if v is not None}
+ return None
+ return None
+
+
+def _pushdown_table_filter(node: Any, column: str) -> Optional[frozenset[str]]:
+ """Derive a table-name bound from a *simple* single-table information_schema query.
+
+ Only attempted when the query selects from exactly one table with no joins: with a join a bare
+ `table_name` reference is ambiguous between relations, and a wrong bound could silently drop rows,
+ so we skip pushdown (return None → emit everything) rather than risk it.
+ """
+ if not isinstance(node, ast.SelectQuery) or node.select_from is None or node.select_from.next_join is not None:
+ return None
+ bound = _bound_table_names(node.where, column)
+ return frozenset(bound) if bound is not None else None
- return descriptions, row_counts
+
+# ClickHouse column types for the external data table, keyed by the same kinds as `_constant_rows_select`.
+_KIND_TO_CLICKHOUSE: dict[str, str] = {
+ _STRING: "String",
+ _NULLABLE_STRING: "Nullable(String)",
+ _INTEGER: "Int64",
+ _NULLABLE_INTEGER: "Nullable(Int64)",
+ # HogQL's BooleanDatabaseField maps to ClickHouse UInt8; Python bool serializes to it directly.
+ _BOOLEAN: "UInt8",
+}
+
+
+def _column_field(name: str, kind: str) -> DatabaseField:
+ if kind == _STRING:
+ return StringDatabaseField(name=name, nullable=False)
+ if kind == _NULLABLE_STRING:
+ return StringDatabaseField(name=name, nullable=True)
+ if kind == _INTEGER:
+ return IntegerDatabaseField(name=name, nullable=False)
+ if kind == _NULLABLE_INTEGER:
+ return IntegerDatabaseField(name=name, nullable=True)
+ if kind == _BOOLEAN:
+ return BooleanDatabaseField(name=name, nullable=False)
+ raise ValueError(f"Unknown information_schema column kind: {kind}")
+
+
+class _ExternalDataTable(DANGEROUS_NoTeamIdCheckTable):
+ """A query-scoped ClickHouse external data table, referenced by a bare name.
+
+ Its rows travel out-of-band via `sync_execute(external_tables=...)`, so the printed query text
+ stays small no matter how large the catalog is. `to_printed_clickhouse` emits the registered name
+ verbatim; ClickHouse resolves it against the external data sent alongside the request. The
+ no-team-id base is correct: the data is the caller's own catalog metadata, not cross-team rows.
+ """
+
+ def to_printed_clickhouse(self, context: "HogQLContext") -> str:
+ return self.name or ""
+
+ def to_printed_hogql(self) -> str:
+ return self.name or ""
+
+
+def _external_table_name(table_label: str, allowed: Optional[frozenset[str]]) -> str:
+ # Deterministic per (table, pushdown filter) so re-registration within a query is idempotent and
+ # the printed name always matches the data attached to the request.
+ if allowed is None:
+ suffix = "all"
+ else:
+ # Non-cryptographic: just a stable, collision-resistant suffix for the table name.
+ suffix = "f" + hashlib.sha256("\x01".join(sorted(allowed)).encode()).hexdigest()[:12]
+ return f"__ph_information_schema_{table_label}_{suffix}"
+
+
+def _rows_select(
+ context: "HogQLContext",
+ table_label: str,
+ columns: list[tuple[str, str]],
+ rows: list[list[Any]],
+ allowed: Optional[frozenset[str]],
+) -> ast.SelectQuery:
+ """Register `rows` as a query-scoped external data table and return a SELECT over it.
+
+ Falls back to inlining the rows as constants when there's no live database to register against
+ (in that case introspection returned no rows anyway).
+ """
+ database = context.database
+ if database is None:
+ return _constant_rows_select(columns, rows)
+
+ column_names = [name for name, _ in columns]
+ ext_name = _external_table_name(table_label, allowed)
+ if ext_name not in context.external_tables:
+ context.external_tables[ext_name] = {
+ "name": ext_name,
+ "structure": [(name, _KIND_TO_CLICKHOUSE[kind]) for name, kind in columns],
+ "data": [dict(zip(column_names, row)) for row in rows],
+ }
+ fields: dict[str, FieldOrTable] = {name: _column_field(name, kind) for name, kind in columns}
+ database.tables.add_child(
+ TableNode(name=ext_name, table=_ExternalDataTable(name=ext_name, fields=fields), hidden=True),
+ table_conflict_mode="override",
+ children_conflict_mode="override",
+ )
+
+ return ast.SelectQuery(
+ select=[ast.Alias(alias=name, expr=ast.Field(chain=[name])) for name in column_names],
+ select_from=ast.JoinExpr(table=ast.Field(chain=[ext_name])),
+ )
class _Introspection:
"""Walks the live database once and produces the rows for every information_schema table."""
- def __init__(self, database: "Database", context: "HogQLContext") -> None:
+ def __init__(
+ self, database: "Database", context: "HogQLContext", allowed_tables: Optional[frozenset[str]] = None
+ ) -> None:
self.database = database
+ self.allowed_tables = allowed_tables
self.warehouse = set(database.get_warehouse_table_names())
self.views = set(database.get_view_names())
- self.descriptions, self.row_counts = _warehouse_metadata(context.team_id)
+ self.descriptions, self.row_counts, self.view_row_counts = _warehouse_metadata(context.team_id)
+
+ def _row_count(self, name: str, table: Table, table_type: str) -> Optional[int]:
+ if table_type == "data_warehouse" and table.name:
+ return self.row_counts.get(table.name)
+ if table_type == "view":
+ # Views are keyed by their catalog name (the saved-query name), which is `name` here.
+ return self.view_row_counts.get(name)
+ return None
def _table_description(self, table: Table, table_type: str) -> Optional[str]:
if table.description:
@@ -226,7 +433,11 @@ class _Introspection:
column_rows: list[list[Any]] = []
relationship_rows: list[list[Any]] = []
- for name in _visible_table_names(self.database):
+ names = _visible_table_names(self.database)
+ if self.allowed_tables is not None:
+ names = [name for name in names if name in self.allowed_tables]
+
+ for name in names:
try:
table = self.database.get_table(name)
except Exception:
@@ -234,7 +445,7 @@ class _Introspection:
continue
table_type, table_schema = _classify_table(name, table, self.warehouse, self.views)
- row_count = self.row_counts.get(table.name) if table_type == "data_warehouse" and table.name else None
+ row_count = self._row_count(name, table, table_type)
table_rows.append(
[name, table_schema, name, table_type, self._table_description(table, table_type), row_count]
)
@@ -323,18 +534,25 @@ class _Introspection:
return ordinal
-def _introspect(context: "HogQLContext") -> tuple[list[list[Any]], list[list[Any]], list[list[Any]]]:
- """Introspect the database once per query, reusing the result across information_schema tables.
+def _introspect(
+ context: "HogQLContext", allowed_tables: Optional[frozenset[str]] = None
+) -> tuple[list[list[Any]], list[list[Any]], list[list[Any]]]:
+ """Introspect the database once per (query, pushdown filter), reusing the result across tables.
A query that joins several information_schema tables would otherwise rebuild the full
- introspection — including the warehouse-metadata ORM queries — once per referenced table.
+ introspection — including the warehouse-metadata ORM queries — once per referenced table. The
+ cache is keyed by the pushed-down `allowed_tables` set so a filtered scan walks only the tables
+ it needs while still sharing work between references that resolve to the same bound.
"""
- if context.information_schema_introspection is None:
+ cache = context.information_schema_introspection
+ if cache is None:
+ cache = context.information_schema_introspection = {}
+ if allowed_tables not in cache:
database = context.database
- if database is None:
- return [], [], []
- context.information_schema_introspection = _Introspection(database, context).collect()
- return context.information_schema_introspection
+ cache[allowed_tables] = (
+ _Introspection(database, context, allowed_tables).collect() if database is not None else ([], [], [])
+ )
+ return cache[allowed_tables]
# --- the virtual tables ----------------------------------------------------------------------- #
@@ -402,8 +620,9 @@ class InformationSchemaTablesTable(LazyTable):
}
def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:
- table_rows, _, _ = _introspect(context)
- return _constant_rows_select(_TABLES_COLUMNS, table_rows)
+ allowed = _pushdown_table_filter(node, "table_name")
+ table_rows, _, _ = _introspect(context, allowed)
+ return _rows_select(context, "tables", _TABLES_COLUMNS, table_rows, allowed)
def to_printed_clickhouse(self, context: "HogQLContext") -> str:
return "information_schema.tables"
@@ -426,8 +645,9 @@ class InformationSchemaColumnsTable(LazyTable):
}
def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:
- _, column_rows, _ = _introspect(context)
- return _constant_rows_select(_COLUMNS_COLUMNS, column_rows)
+ allowed = _pushdown_table_filter(node, "table_name")
+ _, column_rows, _ = _introspect(context, allowed)
+ return _rows_select(context, "columns", _COLUMNS_COLUMNS, column_rows, allowed)
def to_printed_clickhouse(self, context: "HogQLContext") -> str:
return "information_schema.columns"
@@ -447,8 +667,9 @@ class InformationSchemaRelationshipsTable(LazyTable):
}
def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:
- _, _, relationship_rows = _introspect(context)
- return _constant_rows_select(_RELATIONSHIPS_COLUMNS, relationship_rows)
+ allowed = _pushdown_table_filter(node, "source_table")
+ _, _, relationship_rows = _introspect(context, allowed)
+ return _rows_select(context, "relationships", _RELATIONSHIPS_COLUMNS, relationship_rows, allowed)
def to_printed_clickhouse(self, context: "HogQLContext") -> str:
return "information_schema.relationships"
diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.py
index 533b5dcc2804..69ee6263049e 100644
--- a/posthog/hogql/database/schema/test/test_information_schema.py
+++ b/posthog/hogql/database/schema/test/test_information_schema.py
@@ -1,18 +1,157 @@
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+from parameterized import parameterized
+
+from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
+from posthog.hogql.database.schema.information_schema import (
+ _bound_table_names,
+ _pushdown_table_filter,
+ _warehouse_metadata,
+)
from posthog.hogql.parser import parse_select
from posthog.hogql.printer import prepare_and_print_ast
from posthog.hogql.query import execute_hogql_query
+from posthog.models import Team
from posthog.models.scoping import team_scope
+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
from products.warehouse_sources.backend.models.column_annotation import WarehouseColumnAnnotation
from products.warehouse_sources.backend.models.credential import DataWarehouseCredential
from products.warehouse_sources.backend.models.table import DataWarehouseTable
+def _field(name: str) -> ast.Field:
+ return ast.Field(chain=[name])
+
+
+def _eq(field: str, value: str) -> ast.CompareOperation:
+ return ast.CompareOperation(op=ast.CompareOperationOp.Eq, left=_field(field), right=ast.Constant(value=value))
+
+
+def _in(field: str, values: list[str]) -> ast.CompareOperation:
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=_field(field),
+ right=ast.Tuple(exprs=[ast.Constant(value=v) for v in values]),
+ )
+
+
+class TestInformationSchemaPushdown(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("eq", _eq("table_name", "events"), {"events"}),
+ # The resolver wraps the column in an Alias; matching must see through it.
+ (
+ "aliased_field",
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Alias(alias="table_name", expr=_field("table_name")),
+ right=ast.Constant(value="events"),
+ ),
+ {"events"},
+ ),
+ (
+ "flipped_eq",
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq, left=ast.Constant(value="events"), right=_field("table_name")
+ ),
+ {"events"},
+ ),
+ ("in_list", _in("table_name", ["a", "b"]), {"a", "b"}),
+ # AND with an unrelated/unbounded conjunct keeps the bound from the conjunct we understand.
+ ("and_with_unrelated", ast.And(exprs=[_eq("table_name", "events"), _eq("data_type", "JSON")]), {"events"}),
+ # AND of two bounds intersects (here to an unsatisfiable empty set).
+ ("and_intersects", ast.And(exprs=[_eq("table_name", "a"), _eq("table_name", "b")]), set()),
+ # OR where every branch is bounded unions them.
+ ("or_all_bounded", ast.Or(exprs=[_eq("table_name", "a"), _in("table_name", ["b", "c"])]), {"a", "b", "c"}),
+ # OR with an unbounded branch can match any table → must widen to None (never drop rows).
+ ("or_one_unbounded", ast.Or(exprs=[_eq("table_name", "a"), _eq("data_type", "JSON")]), None),
+ # Negation and other ops we can't safely bound → None.
+ (
+ "not_eq",
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.NotEq, left=_field("table_name"), right=ast.Constant(value="x")
+ ),
+ None,
+ ),
+ ("unrelated_column", _eq("data_type", "JSON"), None),
+ (
+ "no_constant",
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq, left=_field("table_name"), right=_field("table_schema")
+ ),
+ None,
+ ),
+ ]
+ )
+ def test_bound_table_names(self, _name: str, where: ast.Expr, expected: set[str] | None) -> None:
+ assert _bound_table_names(where, "table_name") == expected
+
+ def test_pushdown_skipped_when_query_has_a_join(self) -> None:
+ # With a join, a bare `table_name` could resolve to either relation, so a wrong bound might
+ # drop rows — pushdown must bail out (None) and emit everything instead.
+ joined = ast.SelectQuery(
+ select=[_field("table_name")],
+ select_from=ast.JoinExpr(table=_field("columns"), next_join=ast.JoinExpr(table=_field("tables"))),
+ where=_eq("table_name", "events"),
+ )
+ assert _pushdown_table_filter(joined, "table_name") is None
+
+ def test_pushdown_returns_frozenset_for_simple_query(self) -> None:
+ simple = ast.SelectQuery(
+ select=[_field("table_name")],
+ select_from=ast.JoinExpr(table=_field("columns")),
+ where=_eq("table_name", "events"),
+ )
+ assert _pushdown_table_filter(simple, "table_name") == frozenset({"events"})
+
+
+class TestWarehouseMetadata(APIBaseTest):
+ def _table(
+ self, name: str, row_count: int | None, *, deleted: bool = False, team: Team | None = None
+ ) -> DataWarehouseTable:
+ team = team or self.team
+ credential = DataWarehouseCredential.objects.create(access_key="x", access_secret="x", team=team)
+ return DataWarehouseTable.objects.create(
+ name=name,
+ format="Parquet",
+ team=team,
+ credential=credential,
+ url_pattern="https://bucket.s3/data/*",
+ row_count=row_count,
+ deleted=deleted,
+ columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},
+ )
+
+ def test_soft_deleted_duplicate_does_not_clobber_live_row_count(self):
+ # Re-synced tables leave soft-deleted duplicates sharing the name; the live row_count must win
+ # rather than being clobbered by a dead row's stale value (which is what `.objects` returned).
+ self._table("orders", 100)
+ self._table("orders", 5, deleted=True)
+ _descriptions, row_counts, _view_row_counts = _warehouse_metadata(self.team.id)
+ assert row_counts["orders"] == 100
+
+ def test_view_row_count_comes_from_the_backing_table(self):
+ backing = self._table("orders_view_backing", 42)
+ DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="orders_view", query={"query": "SELECT 1"}, columns={}, table=backing
+ )
+ _descriptions, _row_counts, view_row_counts = _warehouse_metadata(self.team.id)
+ assert view_row_counts["orders_view"] == 42
+
+ def test_metadata_does_not_leak_other_teams_row_counts(self):
+ # `DataWarehouseTable` is not team-scoped, so the query must filter team_id explicitly — a
+ # same-named table in another team must not surface (or clobber) this team's count.
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ self._table("shared", 999, team=other_team)
+ self._table("shared", 7)
+ _descriptions, row_counts, _view_row_counts = _warehouse_metadata(self.team.id)
+ assert row_counts["shared"] == 7
+
+
class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
def _context(self, db: Database) -> HogQLContext:
return HogQLContext(team_id=self.team.pk, enable_select_queries=True, database=db)
@@ -23,11 +162,21 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
for table in ["tables", "columns", "relationships", "data_types"]:
assert f"system.information_schema.{table}" in names
- def test_select_from_information_schema_tables_compiles(self):
+ def test_select_compiles_to_an_external_table_reference(self):
+ # Rows are sent out-of-band as a ClickHouse external data table, so the printed SQL references
+ # the external table by name and never inlines the catalog as constants.
db = Database.create_for(team=self.team)
+ context = self._context(db)
sql = "SELECT table_name, table_type, table_schema, description FROM system.information_schema.tables"
- query, _ = prepare_and_print_ast(parse_select(sql), self._context(db), dialect="clickhouse")
- assert "arrayJoin" in query
+ query, _ = prepare_and_print_ast(parse_select(sql), context, dialect="clickhouse")
+ assert "arrayJoin" not in query
+ assert "__ph_information_schema_tables_" in query
+ # The matching external data was registered on the context for the executor to send.
+ registered = list(context.external_tables.values())
+ assert len(registered) == 1
+ assert registered[0]["name"] in query
+ assert any(name == "table_name" for name, _ in registered[0]["structure"])
+ assert any(row["table_name"] == "events" for row in registered[0]["data"])
def test_tables_lists_builtin_and_system_tables(self):
response = execute_hogql_query(
@@ -101,16 +250,16 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
type_names = {row[0] for row in response.results or []}
assert {"String", "DateTime", "JSON", "Integer", "Boolean"}.issubset(type_names)
- def _create_warehouse_table(self) -> DataWarehouseTable:
+ def _create_warehouse_table(self, name: str = "stripe_charges", column: str = "id") -> DataWarehouseTable:
credentials = DataWarehouseCredential.objects.create(access_key="x", access_secret="x", team=self.team)
return DataWarehouseTable.objects.create(
- name="stripe_charges",
+ name=name,
format="Parquet",
team=self.team,
credential=credentials,
url_pattern="https://bucket.s3/data/*",
row_count=42,
- columns={"id": {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},
+ columns={column: {"hogql": "StringDatabaseField", "clickhouse": "Nullable(String)", "schema_valid": True}},
)
def test_warehouse_tables_appear_with_row_count(self):
@@ -182,6 +331,53 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
# Sanity check that at least one nested virtual-table column was surfaced.
assert any("." in row[0] for row in results)
+ def test_pushdown_sends_only_the_filtered_table(self):
+ # A `WHERE table_name = '…'` query must only ship that table's rows in the external data,
+ # never the whole catalog — that's what keeps the out-of-band payload (and the work) small.
+ self._create_warehouse_table(name="stripe_charges", column="charge_id")
+ self._create_warehouse_table(name="stripe_refunds", column="refund_id")
+ db = Database.create_for(team=self.team)
+ context = self._context(db)
+ prepare_and_print_ast(
+ parse_select(
+ "SELECT column_name FROM system.information_schema.columns WHERE table_name = 'stripe_charges'"
+ ),
+ context,
+ dialect="clickhouse",
+ )
+ rows = next(iter(context.external_tables.values()))["data"]
+ shipped_tables = {row["table_name"] for row in rows}
+ assert shipped_tables == {"stripe_charges"}
+
+ def test_columns_in_filter_returns_only_listed_tables(self):
+ for name, column in (("orders", "order_id"), ("refunds", "refund_id"), ("customers", "customer_id")):
+ self._create_warehouse_table(name=name, column=column)
+ response = execute_hogql_query(
+ """
+ SELECT DISTINCT table_name FROM system.information_schema.columns
+ WHERE table_name IN ('orders', 'refunds')
+ """,
+ team=self.team,
+ )
+ names = {row[0] for row in response.results or []}
+ assert names == {"orders", "refunds"}
+
+ def test_disjunction_with_unbounded_branch_does_not_drop_rows(self):
+ # An OR where one branch isn't a table_name bound (here a data_type predicate) can match rows
+ # from tables not named in the query, so pushdown must widen to "emit everything" rather than
+ # bound to the named table — otherwise we'd silently drop matching rows.
+ response = execute_hogql_query(
+ """
+ SELECT DISTINCT table_name FROM system.information_schema.columns
+ WHERE table_name = 'events' OR data_type = 'JSON'
+ """,
+ team=self.team,
+ )
+ names = {row[0] for row in response.results or []}
+ # `persons` has JSON columns but isn't named in the WHERE — it must still come through.
+ assert "events" in names
+ assert "persons" in names
+
def test_columns_filter_and_join_against_tables(self):
# Proves the virtual tables behave like real relations: WHERE + JOIN both work.
response = execute_hogql_query(
diff --git a/posthog/hogql/database/schema/test/test_table_query_log.py b/posthog/hogql/database/schema/test/test_table_query_log.py
index 49884525a633..dc1e4b3bf5ca 100644
--- a/posthog/hogql/database/schema/test/test_table_query_log.py
+++ b/posthog/hogql/database/schema/test/test_table_query_log.py
@@ -44,5 +44,6 @@ LIMIT 10 SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_t
workload=ANY,
team_id=self.team.pk,
readonly=True,
+ external_tables=None,
)
assert response.results is not None
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index 8df6928ea5fd..f4d5993c3db9 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -236,10 +236,13 @@ class HogQLQueryExecutor:
bypass_warehouse_access_control=self.context.bypass_warehouse_access_control,
)
- # Reset between executions: the resolver appends per query, and dataclasses.replace below
- # shares this dict by reference. Without reset, callers reusing a HogQLContext across
- # executors would see warnings from prior runs.
+ # Reset between executions: the resolver/printer append per query, and dataclasses.replace
+ # below shares these by reference. Without reset, callers reusing a HogQLContext across
+ # executors would see warnings from prior runs — and a stale external_tables entry would skip
+ # re-registering the hidden table against the rebuilt database, leaving a dangling reference.
self.context.data_warehouse_sync_warnings.clear()
+ self.context.external_tables.clear()
+ self.context.information_schema_introspection = None
self.hogql_context = dataclasses.replace(
self.context,
@@ -632,6 +635,7 @@ class HogQLQueryExecutor:
workload=workload,
team_id=self.team.pk,
readonly=True,
+ external_tables=list(clickhouse_context.external_tables.values()) or None,
)
except Exception as e:
if self.debug:
@@ -653,6 +657,7 @@ class HogQLQueryExecutor:
workload=workload,
team_id=self.team.pk,
readonly=True,
+ external_tables=list(clickhouse_context.external_tables.values()) or None,
)
self.explain = [str(r[0]) for r in explain_results[0]]
with self.timings.measure("metadata"):