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(hogql): match schema-split filters in information_schema (#107338)

posthog[bot]98e3772221ae
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index 27777316b24f..4d5871c27d3e 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -360,6 +360,51 @@ def _pushdown_table_filter(node: Any, column: str) -> Optional[frozenset[str]]:
return frozenset(bound) if bound is not None else None
+def _schema_split_aliases(
+ node: Any, allowed: Optional[frozenset[str]], database: Optional["Database"]
+) -> dict[str, str]:
+ """Map a qualified table name to its bare name for a SQL-standard `table_schema = … AND table_name = …` query.
+
+ The catalog names each table by its fully-qualified name (`system.insights`), so the split form
+ matches no row and silently returns nothing. When a bare name is not itself a visible table, the
+ caller reports the visible table with that last name segment in the filtered schema under the
+ bare name. The schema is the classified bucket (`posthog.ai_events` is in `public`), not the name
+ prefix. A bare name that matches more than one table in a schema stays unmatched.
+ """
+ if allowed is None or database is None:
+ return {}
+ schemas = _pushdown_table_filter(node, "table_schema")
+ if not schemas:
+ return {}
+ visible = _visible_table_names(database)
+ bare_names = allowed.difference(visible)
+ candidates = [name for name in visible if "." in name and name.rsplit(".", 1)[1] in bare_names]
+ if not candidates:
+ return {}
+ warehouse = set(database.get_warehouse_table_names())
+ views = set(database.get_view_names())
+ matches: defaultdict[tuple[str, str], list[str]] = defaultdict(list)
+ for name in candidates:
+ try:
+ table = database.get_table(name)
+ except Exception:
+ continue
+ _, table_schema = _classify_table(name, table, warehouse, views)
+ if table_schema in schemas:
+ matches[(table_schema, name.rsplit(".", 1)[1])].append(name)
+ return {names[0]: bare for (_, bare), names in matches.items() if len(names) == 1}
+
+
+def _relabel_table_names(rows: list[list[Any]], aliases: dict[str, str], indexes: tuple[int, ...]) -> list[list[Any]]:
+ relabeled = []
+ for row in rows:
+ row = list(row)
+ for index in indexes:
+ row[index] = aliases.get(row[index], row[index])
+ relabeled.append(row)
+ return relabeled
+
+
# 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",
@@ -1611,6 +1656,9 @@ class InformationSchemaTablesTable(InformationSchemaTable):
def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:
allowed = _pushdown_table_filter(node, "table_name")
+ aliases = _schema_split_aliases(node, allowed, context.database)
+ if aliases and allowed is not None:
+ allowed = allowed.union(aliases)
introspection = _introspection(context, allowed)
data_catalog_enrichment_requested = "certification" in self.fields and _accesses_any_field(
table_to_add, _DATA_CATALOG_TABLE_FIELDS
@@ -1623,6 +1671,10 @@ class InformationSchemaTablesTable(InformationSchemaTable):
table_rows = introspection.table_rows()
columns = _DATA_CATALOG_ENRICHED_TABLES_COLUMNS if data_catalog_enrichment_requested else _TABLES_COLUMNS
table_label = "data_catalog_enriched_tables" if data_catalog_enrichment_requested else "tables"
+ if aliases:
+ # table_catalog and table_name both carry the table's name.
+ table_rows = _relabel_table_names(table_rows, aliases, (0, 2))
+ table_label = f"{table_label}_schema_split"
return _rows_select(context, table_label, columns, table_rows, allowed)
def to_printed_clickhouse(self, context: "HogQLContext") -> str:
@@ -1701,8 +1753,19 @@ class InformationSchemaColumnsTable(InformationSchemaTable):
def lazy_select(self, table_to_add: LazyTableToAdd, context: "HogQLContext", node: Any) -> ast.SelectQuery:
allowed = _pushdown_table_filter(node, "table_name")
+ aliases = _schema_split_aliases(node, allowed, context.database)
+ if aliases and allowed is not None:
+ allowed = allowed.union(aliases)
introspection = _introspection(context, allowed)
column_rows = introspection.column_rows() if introspection is not None else []
+ if aliases:
+ return _rows_select(
+ context,
+ "columns_schema_split",
+ _COLUMNS_COLUMNS,
+ _relabel_table_names(column_rows, aliases, (1,)),
+ allowed,
+ )
return _rows_select(context, "columns", _COLUMNS_COLUMNS, column_rows, allowed)
def to_printed_clickhouse(self, context: "HogQLContext") -> str:
diff --git a/posthog/hogql/database/schema/test/test_information_schema.py b/posthog/hogql/database/schema/test/test_information_schema.py
index ac1f8d63eb7a..8d449cf1da08 100644
--- a/posthog/hogql/database/schema/test/test_information_schema.py
+++ b/posthog/hogql/database/schema/test/test_information_schema.py
@@ -344,6 +344,48 @@ class TestInformationSchema(ClickhouseTestMixin, APIBaseTest):
assert "system.cohorts" in names
assert "system.feature_flags" not in names
+ @parameterized.expand(
+ [
+ (
+ "columns",
+ "SELECT table_schema, table_name, column_name FROM system.information_schema.columns "
+ "WHERE table_schema = 'system' AND table_name = 'insights'",
+ ("system", "insights"),
+ ),
+ (
+ "tables",
+ "SELECT table_schema, table_name, table_catalog FROM system.information_schema.tables "
+ "WHERE table_schema = 'system' AND table_name IN ('insights', 'events')",
+ ("system", "insights"),
+ ),
+ (
+ "classified_schema_differs_from_prefix",
+ "SELECT table_schema, table_name, column_name FROM system.information_schema.columns "
+ "WHERE table_schema = 'public' AND table_name = 'ai_events'",
+ ("public", "ai_events"),
+ ),
+ (
+ "information_schema_bucket",
+ "SELECT table_schema, table_name, column_name FROM system.information_schema.columns "
+ "WHERE table_schema = 'information_schema' AND table_name = 'columns'",
+ ("information_schema", "columns"),
+ ),
+ ]
+ )
+ def test_schema_split_filter_finds_qualified_tables(self, _name: str, query: str, expected: tuple[str, str]):
+ response = execute_hogql_query(query, team=self.team, user=self.user)
+ rows = response.results or []
+ assert rows
+ assert {(row[0], row[1]) for row in rows} == {expected}
+
+ def test_bare_system_table_name_without_schema_matches_nothing(self):
+ response = execute_hogql_query(
+ "SELECT column_name FROM system.information_schema.columns WHERE table_name = 'insights'",
+ team=self.team,
+ user=self.user,
+ )
+ assert response.results == []
+
@parameterized.expand(
[
("person_id", "UUID"),
diff --git a/services/mcp/src/templates/execute-sql-prompt.md b/services/mcp/src/templates/execute-sql-prompt.md
index e57500f253d7..bdce5bfa2153 100644
--- a/services/mcp/src/templates/execute-sql-prompt.md
+++ b/services/mcp/src/templates/execute-sql-prompt.md
@@ -22,7 +22,7 @@ Both typed queries and SQL can support saved visualizations. A chart or table al
### Common pitfalls
-- **For `system.*` entities, filter `information_schema` by the fully-qualified `table_name`:** use `'system.insights'`, not `'insights'`; the bare name (or a `table_schema = 'system'` split) silently returns zero rows.
+- **For `system.*` entities, `information_schema` stores the fully-qualified `table_name`:** `table_name = 'system.insights'` works alone. The bare name works only with a schema filter: `table_schema = 'system' AND table_name = 'insights'`. A bare `table_name = 'insights'` alone returns zero rows.
- **HogQL rejects the ClickHouse `SETTINGS` clause outright** — appending `SETTINGS ...` (e.g. to tune `max_execution_time` or `join_algorithm`) always fails with `Unsupported: SelectStmt.settingsClause()`. Don't include it.
- **`toDate()` takes exactly one argument** — it does not accept ClickHouse's `toDate(value, timezone)` form. Convert timezone first with `toTimeZone()`, then wrap in `toDate()`: `toDate(toTimeZone(timestamp, 'US/Pacific'))`, not `toDate(timestamp, 'US/Pacific')`.
- **Width-suffixed conversion functions aren't supported** — `toInt64`, `toInt32`, `toFloat64`, `toUInt8`, etc. (and their `OrNull`/`OrZero` variants) always fail. Use the unsuffixed form instead: `toInt()`, `toFloat()`, `toUInt()`, `toIntOrNull()`, `toFloatOrZero()`, and so on.