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): isolate hidden-backed expression fields on postgres tables (#109582)

posthog[bot]ef02c0e0f933
diff --git a/posthog/hogql/database/postgres_table.py b/posthog/hogql/database/postgres_table.py
index f22971873b48..fb3361097963 100644
--- a/posthog/hogql/database/postgres_table.py
+++ b/posthog/hogql/database/postgres_table.py
@@ -5,11 +5,14 @@ from typing import TYPE_CHECKING, Optional, cast
from django.conf import settings
from psycopg.conninfo import conninfo_to_dict
+from pydantic import model_validator
+from posthog.hogql import ast
from posthog.hogql.base import Expr
from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.models import FunctionCallTable
+from posthog.hogql.database.models import DatabaseField, ExpressionField, FunctionCallTable
from posthog.hogql.escape_sql import escape_hogql_identifier
+from posthog.hogql.visitor import TraversingVisitor
from posthog.person_db_router import PERSONS_DB_MODELS
from posthog.persons_db import persons_db_url
@@ -87,6 +90,15 @@ def build_function_call(postgres_table_name: str, context: Optional[HogQLContext
return f"postgresql({address}, {db}, {table}, {user}, {password})"
+class _FieldNameCollector(TraversingVisitor):
+ def __init__(self) -> None:
+ super().__init__()
+ self.names: set[str] = set()
+
+ def visit_field(self, node: ast.Field) -> None:
+ self.names.add(str(node.chain[0]))
+
+
class PostgresTable(FunctionCallTable):
requires_args: bool = False
postgres_table_name: str
@@ -119,6 +131,21 @@ class PostgresTable(FunctionCallTable):
postgres_pushdown_values: dict[str, str | int | bool] = {}
predicates: list[Expr] = []
+ @model_validator(mode="after")
+ def _isolate_hidden_backed_expression_fields(self) -> "PostgresTable":
+ # A query can't qualify a hidden column, so an expression over one must resolve against
+ # this table. Otherwise a join with another table that has the same hidden column is ambiguous.
+ hidden_names = {
+ name for name, field in self.fields.items() if isinstance(field, DatabaseField) and field.hidden
+ }
+ for field in self.fields.values():
+ if isinstance(field, ExpressionField) and field.isolate_scope is None:
+ collector = _FieldNameCollector()
+ collector.visit(field.expr)
+ if collector.names & hidden_names:
+ field.isolate_scope = True
+ return self
+
def get_predicates(self, context: Optional[HogQLContext] = None) -> list[Expr]:
return self.predicates
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 61e51f93da0e..d399dfb7afb4 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -1201,6 +1201,26 @@ class TestSystemTablesCanvasDeletedExclusion(BaseTest):
assert f"equals(system__canvases.team_id, {self.team.pk})" in query
+class TestSystemTablesJoinOnHiddenBackedFields(NonAtomicBaseTest):
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def test_joined_tables_filtered_on_deleted_are_not_ambiguous(self):
+ tile = _create_dashboard_tile(self.team, "join")
+
+ response = execute_hogql_query(
+ "SELECT i.id, d.id FROM system.insights i "
+ "JOIN system.dashboard_tiles dt ON dt.insight_id = i.id "
+ "JOIN system.dashboards d ON d.id = dt.dashboard_id "
+ "WHERE i.deleted = 0 AND dt.deleted = 0 AND d.deleted = 0",
+ team=self.team,
+ user=self.user,
+ )
+
+ assert [(str(row[0]), str(row[1])) for row in response.results] == [
+ (str(tile.insight_id), str(tile.dashboard_id))
+ ]
+
+
class TestSystemTablesCanvasDeletedExclusionIsolation(NonAtomicBaseTest):
"""End-to-end check that soft-deleted canvases are never returned via HogQL."""