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): resolve columns qualified by a nested table name (#109597)

Jovan Sakoviccbf0e55c67f9
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 87f5e84d4def..17f62b4e6e98 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -57,6 +57,7 @@ from posthog.hogql.resolver_utils import (
expand_hogqlx_query,
lookup_field_by_name,
lookup_table_by_name,
+ lookup_table_by_nested_name,
suggest_field_names,
suggested_field_fix,
)
@@ -2444,6 +2445,13 @@ class Resolver(CloningVisitor):
if not type:
type = lookup_field_by_name(self.scopes[-2], name, self.context)
+ # The number of leading chain segments that name the table or field found above.
+ qualifier_length = 1
+ if not type:
+ nested_match = lookup_table_by_nested_name(scope, node)
+ if nested_match:
+ type, qualifier_length = nested_match
+
if not type:
cte = self.ctes.get(name, None)
if cte:
@@ -2525,9 +2533,9 @@ class Resolver(CloningVisitor):
# Recursively resolve the rest of the chain until we can point to the deepest node.
field_name = str(node.chain[-1])
loop_type = type
- chain_to_parse = node.chain[1:]
+ chain_to_parse = node.chain[qualifier_length:]
previous_types = []
- resolved_chain: list[str] = [str(node.chain[0])]
+ resolved_chain: list[str] = [str(segment) for segment in node.chain[:qualifier_length]]
while True:
if isinstance(loop_type, FieldTraverserType):
chain_to_parse = loop_type.chain + chain_to_parse
diff --git a/posthog/hogql/resolver_utils.py b/posthog/hogql/resolver_utils.py
index 5b9f0a97a1b8..a871c34080c1 100644
--- a/posthog/hogql/resolver_utils.py
+++ b/posthog/hogql/resolver_utils.py
@@ -213,6 +213,34 @@ def lookup_table_by_name(
return None
+def lookup_table_by_nested_name(
+ scope: ast.SelectQueryType, node: ast.Field
+) -> Optional[tuple[ast.TableOrSelectType, int]]:
+ """Match a qualifier that spells a nested table's name, like `models.a` in `models.a.event`.
+
+ `FROM models.a` puts the table in scope as `models__a`, so the qualifier spans several chain
+ segments, or one backquoted segment holding dots. Returns the table and the number of chain
+ segments the qualifier used. The longest match wins, and at least one segment must remain.
+ """
+ if not scope.tables:
+ return None
+ # No qualifier can be deeper than the deepest nested name in scope, so a long chain stops early
+ # instead of rebuilding every prefix.
+ deepest_name = max(table_alias.count("__") + 1 for table_alias in scope.tables)
+ match: Optional[tuple[ast.TableOrSelectType, int]] = None
+ parts: list[str] = []
+ for consumed, segment in enumerate(node.chain[:-1], start=1):
+ parts.extend(str(segment).split("."))
+ if len(parts) > deepest_name:
+ break
+ if len(parts) < 2:
+ continue
+ table = scope.tables.get("__".join(parts))
+ if table is not None:
+ match = table, consumed
+ return match
+
+
def _folds_identifier_case(table_type: ast.TableOrSelectType) -> bool:
if isinstance(table_type, ast.TableType):
return getattr(table_type.table, "case_insensitive_identifiers", False)
diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.py
index 43b19d8a9149..9d7300b18e7d 100644
--- a/posthog/hogql/test/test_resolver.py
+++ b/posthog/hogql/test/test_resolver.py
@@ -1710,6 +1710,24 @@ class TestResolver(BaseTest):
query = "SELECT * FROM events.copy"
resolve_types(self._select(query), self.context, dialect="hogql")
+ @parameterized.expand(
+ [
+ ("dotted_qualifier", ["models", "a"], "SELECT models.a.event FROM models.a"),
+ ("backquoted_qualifier", ["models", "a"], "SELECT `models.a`.event FROM models.a"),
+ ("three_segment_qualifier", ["models", "marts", "a"], "SELECT models.marts.a.event FROM models.marts.a"),
+ ("explicit_alias_still_wins", ["models", "a"], "SELECT a.event FROM models.a AS a"),
+ ]
+ )
+ def test_column_qualified_by_nested_table_name(self, _name: str, chain: list[str], query: str) -> None:
+ self.database.tables.add_child(TableNode.create_nested_for_chain(chain, EventsTable()))
+
+ resolved = cast(ast.SelectQuery, resolve_types(self._select(query), self.context, dialect="hogql"))
+
+ expr = resolved.select[0]
+ field_type = expr.type.type if isinstance(expr.type, ast.FieldAliasType) else expr.type
+ assert isinstance(field_type, ast.FieldType)
+ assert field_type.name == "event"
+
def test_lambda_scope(self):
query = "SELECT arrayMap(a -> e.timestamp, [1]) as a FROM events e"
resolve_types(self._select(query), self.context, dialect="hogql")