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.

feat(hogql): count views shadowed by a same-named warehouse table (#113194)

Jovan Sakovic5feb645a0bf0
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 94a1736e33f5..5150898473af 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -8,7 +8,7 @@ import threading
import dataclasses
import pickletools
from collections import defaultdict
-from collections.abc import Callable, Collection, Mapping, Sequence
+from collections.abc import Callable, Collection, Iterator, Mapping, Sequence
from datetime import UTC, datetime
from functools import cache
from types import MappingProxyType
@@ -19,6 +19,7 @@ from django.conf import settings
from django.db.models import Q, prefetch_related_objects
import structlog
+import posthoganalytics
from opentelemetry import trace
from pydantic import BaseModel, ConfigDict
@@ -799,6 +800,7 @@ class Database(BaseModel):
_warehouse_table_names: list[str] = []
_warehouse_self_managed_table_names: list[str] = []
_view_table_names: list[str] = []
+ _table_slot_origins: dict[tuple[str, ...], str] = {}
_denied_tables: set[str] = set() # Tables user doesn't have permission to access
_connection_id: str | None = None
_direct_connection_metadata: dict[str, Any] | None = None
@@ -856,6 +858,7 @@ class Database(BaseModel):
self._warehouse_table_names = []
self._warehouse_self_managed_table_names = []
self._view_table_names = []
+ self._table_slot_origins = {}
self._denied_tables = set()
self._connection_id = None
self._direct_connection_metadata = None
@@ -1138,16 +1141,64 @@ class Database(BaseModel):
def _add_warehouse_tables(self, node: TableNode):
self.tables.merge_with(node, table_conflict_mode="override" if self._is_direct_query() else "ignore")
+ self._record_table_slot_origins(node, "warehouse_table")
for name in sorted(node.resolve_all_table_names()):
self._warehouse_table_names.append(name)
def _add_warehouse_self_managed_tables(self, node: TableNode):
self.tables.merge_with(node)
+ self._record_table_slot_origins(node, "self_managed_table")
for name in sorted(node.resolve_all_table_names()):
self._warehouse_self_managed_table_names.append(name)
+ @staticmethod
+ def _walk_table_slots(
+ node: TableNode, path: tuple[str, ...] = ()
+ ) -> Iterator[tuple[tuple[str, ...], FieldOrTable]]:
+ if path and node.table is not None:
+ yield path, node.table
+ for child in node.children.values():
+ yield from Database._walk_table_slots(child, (*path, child.name))
+
+ def _node_at_slot(self, path: tuple[str, ...]) -> TableNode | None:
+ node = self.tables
+ for name in path:
+ child = node.children.get(name)
+ if child is None:
+ return None
+ node = child
+ return node
+
+ def _record_table_slot_origins(self, node: TableNode, origin: str) -> None:
+ for path, table in self._walk_table_slots(node):
+ installed = self._node_at_slot(path)
+ if installed is not None and installed.table is table:
+ self._table_slot_origins[path] = origin
+
+ def _count_views_shadowed_by_tables(self, node: TableNode) -> None:
+ shadowed: dict[str, int] = {}
+ for path, _ in self._walk_table_slots(node):
+ occupant = self._node_at_slot(path)
+ if occupant is None or occupant.table is None:
+ continue
+ shadowed_by = self._table_slot_origins.get(path, "posthog_table")
+ if shadowed_by == "view":
+ continue
+ shadowed[shadowed_by] = shadowed.get(shadowed_by, 0) + 1
+
+ client = posthoganalytics.default_client
+ if not shadowed or client is None:
+ return
+ try:
+ for shadowed_by, count in shadowed.items():
+ client.metrics.count("hogql.database.views_shadowed", count, attributes={"shadowed_by": shadowed_by})
+ except Exception:
+ logger.warning("hogql_views_shadowed_metric_failed", exc_info=True)
+
def _add_views(self, node: TableNode):
- self.tables.merge_with(node)
+ self._count_views_shadowed_by_tables(node)
+ self.tables.merge_with(node, table_conflict_mode="ignore")
+ self._record_table_slot_origins(node, "view")
for name in sorted(node.resolve_all_table_names()):
self._view_table_names.append(name)
diff --git a/posthog/hogql/database/test/test_view.py b/posthog/hogql/database/test/test_view.py
index 3f04bf3567a1..e2cb65cdd3f4 100644
--- a/posthog/hogql/database/test/test_view.py
+++ b/posthog/hogql/database/test/test_view.py
@@ -1,12 +1,15 @@
from typing import Literal
from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
from django.test import override_settings
+from parameterized import parameterized
+
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
-from posthog.hogql.database.models import TableNode
+from posthog.hogql.database.models import SavedQuery, TableNode
from posthog.hogql.database.test.tables import (
create_aapl_stock_s3_table,
create_aapl_stock_table_self_referencing,
@@ -61,6 +64,84 @@ class TestView(BaseTest):
modifiers=create_default_modifiers_for_team(self.team),
)
+ @parameterized.expand(
+ [
+ ("warehouse_table", "aapl_stock_view", "warehouse_table"),
+ ("self_managed_table", "aapl_stock_view", "self_managed_table"),
+ ("self_managed_table", "events", "posthog_table"),
+ ]
+ )
+ def test_a_view_shadowed_by_a_table_keeps_the_table_and_is_counted(
+ self, added_as: str, name: str, shadowed_by: str
+ ):
+ database = Database.create_for(team=self.team)
+ tables = TableNode(children={name: TableNode(name=name, table=create_aapl_stock_s3_table(name))})
+ if added_as == "warehouse_table":
+ database._add_warehouse_tables(tables)
+ else:
+ database._add_warehouse_self_managed_tables(tables)
+
+ client = MagicMock()
+ with patch("posthoganalytics.default_client", client):
+ database._add_views(
+ TableNode(
+ children={
+ name: TableNode(name=name, table=create_aapl_stock_table_view()),
+ "aapl_stock_nested_view": TableNode(
+ name="aapl_stock_nested_view", table=create_nested_aapl_stock_view()
+ ),
+ }
+ )
+ )
+
+ assert not isinstance(database.get_table([name]), SavedQuery)
+ client.metrics.count.assert_called_once_with(
+ "hogql.database.views_shadowed", 1, attributes={"shadowed_by": shadowed_by}
+ )
+
+ def test_a_nested_view_is_not_shadowed_by_a_flat_table_with_the_same_dotted_name(self):
+ database = Database.create_for(team=self.team)
+ database._add_warehouse_self_managed_tables(
+ TableNode(
+ children={
+ "schema.stock": TableNode(name="schema.stock", table=create_aapl_stock_s3_table("schema.stock"))
+ }
+ )
+ )
+
+ client = MagicMock()
+ with patch("posthoganalytics.default_client", client):
+ database._add_views(
+ TableNode(
+ children={
+ "schema": TableNode.create_nested_for_chain(["schema", "stock"], create_aapl_stock_table_view())
+ }
+ )
+ )
+
+ assert isinstance(database.get_table("schema.stock"), SavedQuery)
+ client.metrics.count.assert_not_called()
+
+ def test_a_view_shadowed_by_another_view_is_not_counted(self):
+ database = Database.create_for(team=self.team)
+ database._add_views(
+ TableNode(
+ children={"aapl_stock_view": TableNode(name="aapl_stock_view", table=create_aapl_stock_table_view())}
+ )
+ )
+
+ client = MagicMock()
+ with patch("posthoganalytics.default_client", client):
+ database._add_views(
+ TableNode(
+ children={
+ "aapl_stock_view": TableNode(name="aapl_stock_view", table=create_nested_aapl_stock_view())
+ }
+ )
+ )
+
+ client.metrics.count.assert_not_called()
+
def _select(self, query: str, dialect: Literal["clickhouse", "hogql"] = "clickhouse") -> str:
return prepare_and_print_ast(parse_select(query), self.context, dialect=dialect)[0]