diff --git a/posthog/hogql_queries/persons_query_runner.py b/posthog/hogql_queries/persons_query_runner.py index d597f4bab1c2a..34c86ee13300b 100644 --- a/posthog/hogql_queries/persons_query_runner.py +++ b/posthog/hogql_queries/persons_query_runner.py @@ -192,11 +192,11 @@ def to_query(self) -> ast.SelectQuery: elif "count()" in self.input_columns(): order_by = [ast.OrderExpr(expr=parse_expr("count()"), order="DESC")] elif len(aggregations) > 0: - order_by = [ast.OrderExpr(expr=aggregations[0], order="DESC")] + order_by = [ast.OrderExpr(expr=self._remove_aliases(aggregations[0]), order="DESC")] elif "created_at" in self.input_columns(): order_by = [ast.OrderExpr(expr=ast.Field(chain=["created_at"]), order="DESC")] elif len(columns) > 0: - order_by = [ast.OrderExpr(expr=columns[0], order="ASC")] + order_by = [ast.OrderExpr(expr=self._remove_aliases(columns[0]), order="ASC")] else: order_by = [] @@ -227,3 +227,8 @@ def _is_stale(self, cached_result_package): def _refresh_frequency(self): return timedelta(minutes=1) + + def _remove_aliases(self, node: ast.Expr) -> ast.Expr: + if isinstance(node, ast.Alias): + return self._remove_aliases(node.expr) + return node diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py index c81106f9a7a61..8f0656e7922bc 100644 --- a/posthog/hogql_queries/query_runner.py +++ b/posthog/hogql_queries/query_runner.py @@ -91,7 +91,7 @@ def get_query_runner( if isinstance(query, dict): kind = query.get("kind", None) elif hasattr(query, "kind"): - kind = cast(RunnableQueryNode, query).kind + kind = query.kind # type: ignore else: raise ValueError(f"Can't get a runner for an unknown query type: {query}") diff --git a/posthog/hogql_queries/test/test_persons_query_runner.py b/posthog/hogql_queries/test/test_persons_query_runner.py index 77ac274cb44e0..a5f09e3c6619f 100644 --- a/posthog/hogql_queries/test/test_persons_query_runner.py +++ b/posthog/hogql_queries/test/test_persons_query_runner.py @@ -153,6 +153,13 @@ def test_persons_query_order_by(self): results = runner.calculate().results self.assertEqual(results[0], [f"jacob9@{self.random_uuid}.posthog.com"]) + def test_persons_query_order_by_with_aliases(self): + # We use the first column by default as an order key. It used to cause "error redefining alias" errors. + self.random_uuid = self._create_random_persons() + runner = self._create_runner(PersonsQuery(select=["properties.email as email"])) + results = runner.calculate().results + self.assertEqual(results[0], [f"jacob0@{self.random_uuid}.posthog.com"]) + def test_persons_query_limit(self): self.random_uuid = self._create_random_persons() runner = self._create_runner(