: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): preserve table filters with column aliases (#60859)
Marius Andraa6619898ff07
diff --git a/posthog/hogql/printer/clickhouse.py b/posthog/hogql/printer/clickhouse.pyindex 2ce1dd2fdad3..0dfa596db29e 100644--- a/posthog/hogql/printer/clickhouse.py+++ b/posthog/hogql/printer/clickhouse.py@@ -29,14 +29,21 @@ from posthog.models.team.team import WeekStartDayfrom posthog.models.utils import UUIDT+def _table_filter_type(table_type: ast.TableOrSelectType) -> ast.TableOrSelectType:+ if isinstance(table_type, ast.ColumnAliasedTableType):+ return ast.TableAliasType(alias=table_type.alias, table_type=table_type.table_type)+ return table_type++def team_id_guard_for_table(table_type: ast.TableOrSelectType, context: HogQLContext) -> ast.Expr:"""Add a mandatory "and(team_id, ...)" filter around the expression."""if not context.team_id:raise InternalHogQLError("context.team_id not found")+ field_table_type = _table_filter_type(table_type)return ast.CompareOperation(op=ast.CompareOperationOp.Eq,- left=ast.Field(chain=["team_id"], type=ast.FieldType(name="team_id", table_type=table_type)),+ left=ast.Field(chain=["team_id"], type=ast.FieldType(name="team_id", table_type=field_table_type)),right=ast.Constant(value=context.team_id),type=ast.BooleanType(),)diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.pyindex 3c8073fbec48..d944c1d7a607 100644--- a/posthog/hogql/printer/test/test_printer.py+++ b/posthog/hogql/printer/test/test_printer.py@@ -199,6 +199,11 @@ class TestPrinter(BaseTest):self.assertNotIn("e.a", printed)self.assertNotIn("e.c", printed)+ def test_column_aliases_keep_table_filter_column(self):+ printed = self._select("select b from events as e (a, b, c, d, f, g, h, i, j, team_id)")+ self.assertIn("WHERE equals(e.team_id,", printed)+ self.assertNotIn("WHERE equals(e.person_mode,", printed)+def test_column_aliases_unqualified_refs(self):printed = self._select("select a, b from events as e (a, b, c)")self.assertIn("e.uuid", printed)