: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
fix(hogql): desugar JOIN USING into an ON constraint (#73084)
Thomas Obermüllered9f1b722abc
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 5089a765212f..03660d121eb3 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -2201,6 +2201,57 @@ class TestPrinter(BaseTest):self.assertNotIn("enable_analyzer=1", result)+ @parameterized.expand(+ [+ (+ "bare_column_table_join",+ "SELECT q1.event FROM events AS q1 INNER JOIN events AS q2 USING event",+ "ON equals(q1.event, q2.event)",+ ),+ (+ "cte_join",+ "WITH exposed AS (SELECT event, distinct_id FROM events), "+ "first_event AS (SELECT event, distinct_id FROM events) "+ "SELECT e.distinct_id FROM exposed AS e JOIN first_event AS f USING (distinct_id)",+ "ON equals(e.distinct_id, f.distinct_id)",+ ),+ (+ "multiple_columns_subquery_join",+ "SELECT a.event FROM (SELECT event, distinct_id FROM events) AS a "+ "JOIN (SELECT event, distinct_id FROM events) AS b USING (event, distinct_id)",+ "ON and(equals(a.event, b.event), equals(a.distinct_id, b.distinct_id))",+ ),+ (+ "aliasless_subquery_right_join",+ "SELECT a.event FROM events AS a JOIN (SELECT event FROM events) USING event",+ "AS __using_join_1 ON equals(a.event, __using_join_1.event)",+ ),+ (+ "aliasless_subquery_left_join",+ "SELECT 1 FROM (SELECT event FROM events) JOIN events AS e USING event",+ "ON equals(__using_join_1.event, e.event)",+ ),+ (+ "aliasless_subqueries_both_sides",+ "SELECT 1 FROM (SELECT event FROM events) JOIN (SELECT event FROM events) USING event",+ "AS __using_join_2 ON equals(__using_join_1.event, __using_join_2.event)",+ ),+ ],+ )+ def test_join_using_desugars_to_on_constraint(self, _name: str, query: str, expected_constraint: str):+ printed = self._select(query)+ self.assertIn(expected_constraint, printed)+ self.assertNotIn("USING", printed)++ def test_join_using_unknown_right_column_raises(self):+ with self.assertRaisesMessage(+ QueryError, "Unable to resolve USING column 'event' on the right-hand table \"b\" of the join"+ ):+ self._select(+ "SELECT a.event FROM (SELECT event FROM events) AS a "+ "JOIN (SELECT distinct_id FROM events) AS b USING event"+ )+def test_select_array_join(self):self.assertEqual(self._select("select 1, a from events array join [1,2,3] as a"),diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.pyindex 54f25eea5f1d..a978496815f9 100644--- a/posthog/hogql/resolver.py+++ b/posthog/hogql/resolver.py@@ -298,6 +298,7 @@ class Resolver(CloningVisitor):self.cte_counter = 0self._scope_table_names: dict[int, dict[str, str]] = {}self._scope_table_column_aliases: dict[int, dict[str, list[str]]] = {}+ 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@@ -1140,6 +1141,14 @@ class Resolver(CloningVisitor):if isinstance(node.table, ast.HogQLXTag):node.table = expand_hogqlx_query(node.table, self.context.team_id)+ # Capture the bare column names of a USING constraint before resolution qualifies its+ # fields, so the constraint can be desugared into an ON constraint once the joined+ # table is in scope. SQL dialects require unqualified, both-sided column names inside+ # USING, but we resolve and print fields fully qualified.+ using_column_names: Optional[list[str]] = None+ if node.constraint and node.constraint.constraint_type == "USING":+ using_column_names = self._using_constraint_column_names(node.constraint)+if isinstance(node.table, ast.Field):table_name_chain = [str(n) for n in node.table.chain]table_name_alias = "__".join(table_name_chain)@@ -1176,8 +1185,7 @@ class Resolver(CloningVisitor):node.next_join = self.visit(node.next_join)node.alias = table_alias- if node.constraint and node.constraint.constraint_type == "ON":- node.constraint = self.visit_join_constraint(node.constraint)+ node.constraint = self._resolve_join_constraint(node, using_column_names)node.sample = self.visit(node.sample)return node@@ -1310,8 +1318,7 @@ class Resolver(CloningVisitor):next_join.join_type = f"GLOBAL {next_join.join_type}"next_join = next_join.next_join- if node.constraint and node.constraint.constraint_type == "ON":- node.constraint = self.visit_join_constraint(node.constraint)+ node.constraint = self._resolve_join_constraint(node, using_column_names)node.sample = self.visit(node.sample)# In case we had a function call table, and had to add an alias where none was present, mark it here@@ -1325,6 +1332,8 @@ class Resolver(CloningVisitor):if node.constraint and node.constraint.constraint_type == "USING":# visit USING constraint before adding the table to avoid ambiguous namesnode.constraint = self.visit_join_constraint(node.constraint)+ if node.alias is None and self._join_chain_has_using(node):+ node.alias = self._synthesize_using_join_alias(scope)node.table = cast("ast.SelectQuery | ast.SelectSetQuery", super().visit(node.table))@@ -1405,14 +1414,16 @@ class Resolver(CloningVisitor):# :TRICKY: Make sure to clone and visit _all_ JoinExpr fields/nodes.node.next_join = self.visit(node.next_join)- if node.constraint and node.constraint.constraint_type == "ON":- node.constraint = self.visit_join_constraint(node.constraint)+ node.constraint = self._resolve_join_constraint(node, using_column_names)node.sample = self.visit(node.sample)return nodeelif isinstance(node.table, ast.ValuesQuery):node = cast(ast.JoinExpr, clone_expr(node))+ if node.constraint and node.constraint.constraint_type == "USING":+ # visit USING constraint before adding the table to avoid ambiguous names+ node.constraint = self.visit_join_constraint(node.constraint)node.table = cast(ast.ValuesQuery, self.visit(node.table))# Auto-generate alias and column_aliases when omitted so the@@ -1449,8 +1460,7 @@ class Resolver(CloningVisitor):scope.anonymous_tables.append(cast(ast.SelectQueryType, node.type))node.next_join = self.visit(node.next_join)- if node.constraint and node.constraint.constraint_type == "ON":- node.constraint = self.visit_join_constraint(node.constraint)+ node.constraint = self._resolve_join_constraint(node, using_column_names)node.sample = self.visit(node.sample)return node@@ -1459,6 +1469,8 @@ class Resolver(CloningVisitor):node = cast(ast.JoinExpr, clone_expr(node))if node.constraint and node.constraint.constraint_type == "USING":node.constraint = self.visit_join_constraint(node.constraint)+ if node.alias is None and self._join_chain_has_using(node):+ node.alias = self._synthesize_using_join_alias(scope)node.table = cast(ast.UnpivotExpr, self.visit(node.table))@@ -1476,8 +1488,7 @@ class Resolver(CloningVisitor):scope.anonymous_tables.append(cast(ast.SelectQueryType, node.type))node.next_join = self.visit(node.next_join)- if node.constraint and node.constraint.constraint_type == "ON":- node.constraint = self.visit_join_constraint(node.constraint)+ node.constraint = self._resolve_join_constraint(node, using_column_names)node.sample = self.visit(node.sample)return node@@ -1485,6 +1496,8 @@ class Resolver(CloningVisitor):node = cast(ast.JoinExpr, clone_expr(node))if node.constraint and node.constraint.constraint_type == "USING":node.constraint = self.visit_join_constraint(node.constraint)+ if node.alias is None and self._join_chain_has_using(node):+ node.alias = self._synthesize_using_join_alias(scope)node.table = cast(ast.PivotExpr, self.visit(node.table))@@ -1502,14 +1515,103 @@ class Resolver(CloningVisitor):scope.anonymous_tables.append(cast(ast.SelectQueryType, node.type))node.next_join = self.visit(node.next_join)- if node.constraint and node.constraint.constraint_type == "ON":- node.constraint = self.visit_join_constraint(node.constraint)+ node.constraint = self._resolve_join_constraint(node, using_column_names)node.sample = self.visit(node.sample)return nodeelse:raise QueryError(f"A {type(node.table).__name__} cannot be used as a SELECT source")+ def _join_chain_has_using(self, node: ast.JoinExpr) -> bool:+ current: Optional[ast.JoinExpr] = node+ while current is not None:+ if current.constraint and current.constraint.constraint_type == "USING":+ return True+ current = current.next_join+ return False++ def _synthesize_using_join_alias(self, scope: ast.SelectQueryType) -> str:+ """Alias an aliasless sub-select that takes part in a USING join.++ Fields of an anonymous sub-select print unqualified, which inside the ON constraint a+ USING join desugars to is ambiguous next to the other join side — or a tautological+ self-comparison when both sides are anonymous. A synthetic alias lets the constraint+ qualify the sub-select's columns.+ """+ index = 1+ while f"__using_join_{index}" in scope.tables:+ index += 1+ alias = f"__using_join_{index}"+ self._synthetic_using_join_aliases.add(alias)+ return alias++ def _using_constraint_column_names(self, constraint: ast.JoinConstraint) -> list[str]:+ exprs = constraint.expr.exprs if isinstance(constraint.expr, ast.Tuple) else [constraint.expr]+ column_names: list[str] = []+ for expr in exprs:+ if not isinstance(expr, ast.Field) or len(expr.chain) == 0 or not isinstance(expr.chain[-1], str):+ raise QueryError("JOIN ... USING expects a column name or a list of column names")+ column_names.append(expr.chain[-1])+ return column_names++ def _resolve_join_constraint(+ self, node: ast.JoinExpr, using_column_names: Optional[list[str]]+ ) -> Optional[ast.JoinConstraint]:+ if node.constraint is None:+ return None+ if node.constraint.constraint_type == "USING":+ return self._desugar_using_constraint(node, using_column_names)+ return self.visit_join_constraint(node.constraint)++ def _desugar_using_constraint(+ self, node: ast.JoinExpr, using_column_names: Optional[list[str]]+ ) -> ast.JoinConstraint:+ """Rewrite `JOIN t USING (col)` into `JOIN t ON left.col = t.col`.++ The USING expression was resolved before the joined table entered the scope, so it+ points at the left-hand column and prints fully qualified — which SQL dialects reject+ inside USING. Resolve the same column names against the joined table alone and emit+ an equivalent ON constraint instead.+ """+ constraint = node.constraint+ assert constraint is not None+ left_exprs = constraint.expr.exprs if isinstance(constraint.expr, ast.Tuple) else [constraint.expr]+ if using_column_names is None or len(using_column_names) != len(left_exprs):+ raise ImpossibleASTError("USING constraint columns are out of sync with its resolved expressions")+ compare_exprs: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=left_expr,+ right=self._resolve_using_column_on_joined_table(node, column_name),+ type=ast.BooleanType(nullable=False),+ )+ for left_expr, column_name in zip(left_exprs, using_column_names)+ ]+ expr: ast.Expr = (+ compare_exprs[0]+ if len(compare_exprs) == 1+ else ast.And(exprs=compare_exprs, type=ast.BooleanType(nullable=False))+ )+ return ast.JoinConstraint(expr=expr, constraint_type="ON")++ def _resolve_using_column_on_joined_table(self, node: ast.JoinExpr, column_name: str) -> ast.Expr:+ assert node.type is not None+ # An isolated scope containing only the joined table, so the column can't resolve+ # ambiguously against the left-hand tables. The scope key never reaches the printed+ # SQL - fields print via their resolved type.+ scope_name = node.alias or "__using_join_table"+ self.scopes.append(ast.SelectQueryType(tables={scope_name: node.type}))+ try:+ return self.visit(ast.Field(chain=[scope_name, column_name]))+ except (QueryError, ResolutionError) as err:+ has_user_alias = node.alias is not None and node.alias not in self._synthetic_using_join_aliases+ table_name = f' "{node.alias}"' if has_user_alias else ""+ raise QueryError(+ f"Unable to resolve USING column '{column_name}' on the right-hand table{table_name} of the join"+ ) from err+ finally:+ self.scopes.pop()+def visit_hogqlx_tag(self, node: ast.HogQLXTag):if node.kind in HOGQLX_TAGS or node.kind in HOGQLX_COMPONENTS:return self.visit(convert_to_hx(node))diff --git a/posthog/hogql/test/test_resolver.py b/posthog/hogql/test/test_resolver.pyindex 0bc453a22c47..a3722e9c689c 100644--- a/posthog/hogql/test/test_resolver.py+++ b/posthog/hogql/test/test_resolver.py@@ -1029,26 +1029,26 @@ class TestResolver(BaseTest):assert "events__override" in sqlassert "LEFT" in sql.upper()- def test_join_using(self):- node = self._select(- "WITH my_table AS (SELECT 1 AS a) SELECT q1.a FROM my_table AS q1 INNER JOIN my_table AS q2 USING a"- )+ @parameterized.expand(+ [+ (+ "cte",+ "WITH my_table AS (SELECT 1 AS a) SELECT q1.a FROM my_table AS q1 INNER JOIN my_table AS q2 USING a",+ ),+ ("table", "SELECT q1.event FROM events AS q1 INNER JOIN events AS q2 USING event"),+ ],+ )+ def test_join_using_desugars_to_on(self, _name: str, query: str):+ node = self._select(query)node = resolve_types(node, self.context, dialect="clickhouse")assert isinstance(node, ast.SelectQuery)assert isinstance(node.select_from, ast.JoinExpr)assert isinstance(node.select_from.next_join, ast.JoinExpr)- assert isinstance(node.select_from.next_join.constraint, ast.JoinConstraint)constraint = node.select_from.next_join.constraint- assert constraint.constraint_type == "USING"- assert cast(ast.Alias, constraint.expr).alias == "a"-- node = self._select("SELECT q1.event FROM events AS q1 INNER JOIN events AS q2 USING event")- node = resolve_types(node, self.context, dialect="clickhouse")- assert isinstance(node, ast.SelectQuery)- assert isinstance(node.select_from, ast.JoinExpr)- assert isinstance(node.select_from.next_join, ast.JoinExpr)- assert isinstance(node.select_from.next_join.constraint, ast.JoinConstraint)- assert node.select_from.next_join.constraint.constraint_type == "USING"+ assert isinstance(constraint, ast.JoinConstraint)+ assert constraint.constraint_type == "ON"+ assert isinstance(constraint.expr, ast.CompareOperation)+ assert constraint.expr.op == ast.CompareOperationOp.Eq@override_settings(PERSON_ON_EVENTS_OVERRIDE=False, PERSON_ON_EVENTS_V2_OVERRIDE=False)@pytest.mark.usefixtures("unittest_snapshot")diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.tsindex e5c401a4bb3d..c72697283508 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -1757,6 +1757,15 @@ export interface ActivityLogEntryApi {readonly item_id: stringdetail?: DetailApireadonly created_at: string+ /** Whether the activity was performed by the system rather than a user. */+ readonly is_system: boolean+ /** Whether the acting user was being impersonated by PostHog staff. */+ readonly was_impersonated: boolean+ /**+ * API client that triggered the activity, from the x-posthog-client request header (e.g. 'mcp'). Null for requests that did not send the header.+ * @nullable+ */+ readonly client: string | null}/**