: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(data-warehouse): only allow expressions on tables, not views (#96729)
Jovan Sakovic195592aec5e5
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsxindex ebc82ec7f047..86e82c31af51 100644--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx@@ -1004,27 +1004,6 @@ export const QueryDatabase = ({</ButtonPrimitive></DropdownMenuItem>) : null}- {addJoinSourceTableName ? (- <DropdownMenuItem- asChild- onClick={(e) => {- e.stopPropagation()- if (addJoinAccessDisabledReason) {- return- }- openNewExpressionModal(addJoinSourceTableName)- }}- >- <ButtonPrimitive- menuItem- disabledReasons={- addJoinAccessDisabledReason ? { [addJoinAccessDisabledReason]: true } : {}- }- >- Add expression- </ButtonPrimitive>- </DropdownMenuItem>- ) : null}{item.record.type === 'view' ? (<DropdownMenuItemasChilddiff --git a/products/data_warehouse/backend/presentation/views/expression.py b/products/data_warehouse/backend/presentation/views/expression.pyindex deb96a373438..b3b75665b6d0 100644--- a/products/data_warehouse/backend/presentation/views/expression.py+++ b/products/data_warehouse/backend/presentation/views/expression.py@@ -21,6 +21,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.models.user import Userfrom products.access_control.backend.presentation.access_control import AccessControlViewSetMixin+from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_tools.backend.facade.models import DataWarehouseExpression# Same simple-identifier shape as `escape_hogql_identifier`. A whitelist rather than a@@ -113,6 +114,24 @@ class DataWarehouseExpressionSerializer(serializers.ModelSerializer):except Exception:raise serializers.ValidationError({"table_name": [f"Invalid table: {table_name}"]})+ # A field that belongs on a view belongs in the view's query, where it is versioned with the+ # view and materialized with it. Matched by saved-query name rather than by HogQL table+ # class: a materialized view resolves to its backing S3 table, so a class check would let+ # materialized views through. A warehouse table sharing the name wins in the catalog, so a+ # name the catalog resolved to a table still takes expressions. Runs after the lookup above,+ # so a view the requester can't read stays indistinguishable from a name that doesn't exist.+ if (+ table_name not in set(database.get_warehouse_table_names())+ and DataWarehouseSavedQuery.objects.filter(team_id=team_id, name=table_name).exclude(deleted=True).exists()+ ):+ raise serializers.ValidationError(+ {+ "table_name": [+ f'"{table_name}" is a view. Expressions can only be added to tables. To add a field to a view, edit its query.'+ ]+ }+ )+# The field this instance already contributes to the built database is the one name it may keep.is_own_field = (instance is not Nonediff --git a/products/data_warehouse/backend/tests/api/test_expression.py b/products/data_warehouse/backend/tests/api/test_expression.pyindex 74037f0d3c53..44aa56a3193b 100644--- a/products/data_warehouse/backend/tests/api/test_expression.py+++ b/products/data_warehouse/backend/tests/api/test_expression.py@@ -17,6 +17,7 @@ from posthog.hogql.printer import prepare_and_print_astfrom posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.scoping import team_scope+from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_tools.backend.models.expression import DataWarehouseExpressionfrom products.data_warehouse.backend.presentation.views.expression import (MAX_EXPRESSION_LENGTH,@@ -72,6 +73,60 @@ class TestExpressionApi(APIBaseTest):self.assertEqual(response.status_code, 400, response.content)self.assertEqual(DataWarehouseExpression.objects.for_team(self.team.pk).count(), 0)+ def _view(self, name: str, *, materialized: bool = False, deleted: bool = False) -> DataWarehouseSavedQuery:+ columns = {"one": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True}}+ view = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name=name,+ query={"kind": "HogQLQuery", "query": "SELECT 1 AS one"},+ columns=columns,+ created_by=self.user,+ is_materialized=materialized,+ deleted=deleted,+ )+ if materialized:+ view.table = DataWarehouseTable.objects.create(+ team=self.team,+ name=name,+ format="Delta",+ # The catalog hides a view's own backing table by matching the view's folder path,+ # so the name resolves through the view rather than through this row.+ url_pattern=f"https://bucket.s3.amazonaws.com/{view.folder_path}/{name}",+ columns=columns,+ )+ view.save()+ return view++ def _table(self, name: str) -> DataWarehouseTable:+ return DataWarehouseTable.objects.create(+ team=self.team,+ name=name,+ format="Parquet",+ url_pattern=f"https://bucket.s3.amazonaws.com/{name}/*.parquet",+ columns={"one": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True}},+ )++ @parameterized.expand([("virtual", False), ("materialized", True)])+ def test_expression_on_a_view_rejected(self, _name: str, materialized: bool) -> None:+ self._view("orders", materialized=materialized)++ response = self._create(table_name="orders", field_name="derived", expression="one + 1")++ self.assertEqual(response.status_code, 400, response.content)+ self.assertIn("is a view", response.json()["detail"])+ self.assertEqual(DataWarehouseExpression.objects.for_team(self.team.pk).count(), 0)++ @parameterized.expand([("view_is_deleted", True), ("table_shadows_the_view_name", False)])+ def test_expression_on_a_table_sharing_a_views_name_allowed(self, _name: str, deleted: bool) -> None:+ # A saved query may share its name with a warehouse table, and the catalog resolves that+ # name to the table. The expression lands on the table, so the view rule must not block it.+ self._table("orders")+ self._view("orders", deleted=deleted)++ response = self._create(table_name="orders", field_name="derived", expression="one + 1")++ self.assertEqual(response.status_code, 201, response.content)+def test_per_team_count_cap(self):with patch("products.data_warehouse.backend.presentation.views.expression.MAX_EXPRESSIONS_PER_TEAM",