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(data-warehouse): save raw hosted Trino queries as views (#126362)

Jovan Sakovicf254437ec335
diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
index 114693ef24aa..ed7e0984c1a7 100644
--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx
@@ -37,7 +37,7 @@ import { QueryPane } from './QueryPane'
import { QueryPlaceholdersMenu } from './QueryPlaceholdersMenu'
import { QueryVariablesMenu } from './QueryVariablesMenu'
import { RunButton } from './RunButton'
-import { sqlEditorLogic, tabModelPath } from './sqlEditorLogic'
+import { isRawTrinoView, sqlEditorLogic, tabModelPath } from './sqlEditorLogic'
const EMBEDDED_MAX_TOOL_CONTEXT_DEBOUNCE_MS = 150
@@ -325,6 +325,11 @@ export function QueryWindow({
size="small"
icon={<IconDatabase />}
onClick={() => openMaterializationModal(editingView)}
+ disabledReason={
+ isRawTrinoView(editingView)
+ ? 'Views that run raw Trino SQL cannot be materialized yet.'
+ : undefined
+ }
data-attr="sql-editor-materialization-button"
>
Materialization
diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx
index f43ca246b76d..eb439fafa46e 100644
--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/QueryInfo.tsx
@@ -23,7 +23,7 @@ import { lineageNodeUrl } from 'products/data_modeling/frontend/lineage/lineageN
import { NODE_TYPE_TAG_SETTINGS } from 'products/data_modeling/frontend/lineage/nodeStyles'
import { syncIntervalToShorthand } from 'products/data_warehouse/frontend/utils'
-import { sqlEditorLogic } from '../sqlEditorLogic'
+import { isRawTrinoView, sqlEditorLogic } from '../sqlEditorLogic'
import { infoTabLogic } from './infoTabLogic'
import { ViewDataQualityChecks } from './ViewDataQualityChecks'
@@ -43,7 +43,11 @@ export function QueryInfo({ tabId, view, tabbed = false }: QueryInfoProps): JSX.
} = useValues(sqlEditorLogic)
const targetView = view ?? editingView
// Mounting it loads the lineage for the view being edited.
- const infoLogic = infoTabLogic({ tabId, viewId: targetView?.id })
+ const infoLogic = infoTabLogic({
+ tabId,
+ viewId: targetView?.id,
+ skipLineage: !!targetView && isRawTrinoView(targetView),
+ })
useMountedLogic(infoLogic)
const { activeSection, lineageVisited, lineageNodePositions } = useValues(infoLogic)
const { setActiveSection, lineageNodeDragStopped, resetLineageNodePositions } = useActions(infoLogic)
diff --git a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/infoTabLogic.ts b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/infoTabLogic.ts
index d764c4b72214..62542e6bb78a 100644
--- a/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/infoTabLogic.ts
+++ b/frontend/src/scenes/data-warehouse/editor/output-pane-tabs/infoTabLogic.ts
@@ -15,6 +15,7 @@ import { sqlEditorLogic } from '../sqlEditorLogic'
export interface InfoTabLogicProps {
tabId: string
viewId?: string
+ skipLineage?: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -93,7 +94,7 @@ export const infoTabLogic = kea<infoTabLogicType>([
],
}),
afterMount(({ actions, props }) => {
- if (props.viewId) {
+ if (props.viewId && !props.skipLineage) {
actions.loadUpstream(props.viewId)
}
}),
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index bca065198d85..6193c61cdfe0 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -381,6 +381,31 @@ describe('sqlEditorLogic', () => {
logic.mount()
}
+ it('opens a raw Trino view without unsaved changes', async () => {
+ const trinoQuery = {
+ ...MOCK_VIEW.query,
+ query: 'SELECT * FROM "catalog".schema.events',
+ filters: {},
+ executionTarget: 'managed_trino',
+ sendRawQuery: true,
+ }
+ useMocks({
+ get: {
+ '/api/:scope/:team_id/warehouse_saved_queries/:id/': [200, { ...MOCK_VIEW, query: trinoQuery }],
+ },
+ })
+ mountEditor()
+ await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }))
+ .toDispatchActions(['createTab', 'setQueryInput'])
+ .toFinishAllListeners()
+
+ expect(logic.values.sourceQuery.source).toMatchObject({
+ executionTarget: 'managed_trino',
+ sendRawQuery: true,
+ })
+ expect(logic.values.hasEditorChanges).toBe(false)
+ })
+
it.each(
[
{ searchParams: { open_view: MOCK_VIEW.id }, savedQuery: MOCK_VIEW.query.query },
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index fbe429ef8766..d97ad0570465 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -418,6 +418,11 @@ export function normalizeRawQuerySource(source: HogQLQuery): HogQLQuery {
}
}
+// Raw Trino views run only on hosted Trino, so they have no lineage node and cannot be materialized.
+export function isRawTrinoView(view: DataWarehouseSavedQuery): boolean {
+ return view.query?.executionTarget === 'managed_trino' && !!view.query?.sendRawQuery
+}
+
function hogQLEditorSourceQuery(source: Partial<HogQLQuery> = {}): DataVisualizationNode {
return {
kind: NodeKind.DataVisualizationNode,
@@ -2553,6 +2558,9 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
current: candidates.queries[candidates.initialIndex],
}
const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)
+ const isRawTrinoSave =
+ values.sourceQuery.source.executionTarget === 'managed_trino' &&
+ !!values.sourceQuery.source.sendRawQuery
const folderOptions: { value: string | null; label: string }[] = [
{ value: null, label: 'No folder' },
@@ -2595,7 +2603,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
viewName: values.activeTab?.name || '',
folderId: null,
isTest: false,
- materializeAfterSave,
+ materializeAfterSave: isRawTrinoSave ? false : materializeAfterSave,
incrementalEnabled: false,
incrementalKey: null,
incrementalUniqueKey: [],
@@ -2683,6 +2691,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
checked={value}
onChange={onChange}
data-attr="sql-editor-input-save-view-materialize"
+ disabledReason={
+ isRawTrinoSave
+ ? 'Views that run raw Trino SQL cannot be materialized yet.'
+ : undefined
+ }
label="Materialize this view"
/>
<Tooltip title="Pre-compute the results into a table for faster queries. Syncs daily by default — you can adjust the frequency later in the view's materialization settings.">
@@ -3596,7 +3609,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
},
editingView: (editingView) => {
- if (editingView) {
+ if (editingView && !isRawTrinoView(editingView)) {
actions.loadUpstream(editingView.id)
}
},
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 1e25c830ec67..8044d7dbc3e5 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -2152,11 +2152,12 @@ class Database(BaseModel):
.select_related("table", "managed_viewset")
)
all_saved_queries = list(queryset)
- saved_queries = (
- all_saved_queries
- if is_managed_viewset_enabled
- else [sq for sq in all_saved_queries if sq.managed_viewset_id is None]
- )
+ # Raw Trino views hold Trino SQL, which HogQL cannot expand.
+ saved_queries = [
+ sq
+ for sq in all_saved_queries
+ if (is_managed_viewset_enabled or sq.managed_viewset_id is None) and not sq.is_raw_managed_trino
+ ]
with timings.measure("endpoint_saved_query", emit_span=True):
# Endpoint-origin rows are a subset of the non-deleted saved queries fetched above,
diff --git a/products/data_modeling/backend/facade/models.py b/products/data_modeling/backend/facade/models.py
index e600aba1a997..1504786fa8a8 100644
--- a/products/data_modeling/backend/facade/models.py
+++ b/products/data_modeling/backend/facade/models.py
@@ -23,6 +23,7 @@ from products.data_modeling.backend.models.datawarehouse_saved_query import (
aget_saved_query_by_id,
aget_table_by_saved_query_id,
asave_saved_query,
+ is_raw_managed_trino_query,
validate_saved_query_name,
)
from products.data_modeling.backend.models.datawarehouse_saved_query_column_annotation import (
@@ -54,5 +55,6 @@ __all__ = [
"aget_saved_query_by_id",
"aget_table_by_saved_query_id",
"asave_saved_query",
+ "is_raw_managed_trino_query",
"validate_saved_query_name",
]
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index 4af6661826ed..cc4ef4b3b3ec 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -120,6 +120,13 @@ class SchedulingUnavailableError(Exception):
The caller decides what to keep, because the saved query itself is not at fault."""
+def is_raw_managed_trino_query(query: object) -> bool:
+ """A raw Trino view stores Trino SQL that only hosted Trino can run, so ClickHouse and lineage skip it."""
+ return (
+ isinstance(query, dict) and query.get("executionTarget") == "managed_trino" and bool(query.get("sendRawQuery"))
+ )
+
+
class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields, DeletedMetaFields):
class Status(models.TextChoices):
"""Possible states of this SavedQuery."""
@@ -299,6 +306,10 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
def name_chain(self) -> list[str]:
return self.name.split(".")
+ @property
+ def is_raw_managed_trino(self) -> bool:
+ return is_raw_managed_trino_query(self.query)
+
def schedule_materialization(
self, reconcile: bool = True, trigger_immediate_run: bool = False, triggered_by_id: int | None = None
):
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/editing.py b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
index 962d8a5efabd..1f2c5b16fbb9 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/editing.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
@@ -13,12 +13,15 @@ import structlog
from drf_spectacular.utils import extend_schema_field
from rest_framework import exceptions, serializers
+from posthog.schema import ExecutionTarget, HogQLQuery
+
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import (
MODELS_NAMESPACE_QUERY_ERROR,
is_reserved_models_name,
models_namespace_chain,
)
+from posthog.hogql.direct_sql.trino_adapter import ensure_read_only_raw_trino_statement
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.parser import parse_select
from posthog.hogql.placeholders import FindPlaceholders
@@ -41,10 +44,12 @@ from products.data_modeling.backend.facade.modeling import ResolutionCycleError,
from products.data_modeling.backend.facade.models import (
DataWarehouseSavedQuery,
DataWarehouseSavedQueryColumnAnnotation,
+ is_raw_managed_trino_query,
validate_saved_query_name,
)
from products.data_tools.backend.facade.models import DataWarehouseSavedQueryFolder
from products.data_warehouse.backend.presentation.views.column_annotation_base import upsert_annotation
+from products.managed_warehouse.backend.facade.query_execution import validate_managed_trino_query
from products.warehouse_sources.backend.facade.hogql import (
get_view_or_table_by_name,
hogql_type_name_for_clickhouse_type,
@@ -68,6 +73,17 @@ def _lineage_sync_error_detail(error: Exception) -> str:
return str(error) if isinstance(error, ExposedHogQLError) else GENERIC_LINEAGE_SYNC_ERROR
+def _columns_from_client_types(client_types: list[list[str]]) -> dict[str, dict[str, Any]]:
+ return {
+ str(item[0]): {
+ "hogql": hogql_type_name_for_clickhouse_type(str(item[1])),
+ "clickhouse": item[1],
+ "valid": True,
+ }
+ for item in client_types
+ }
+
+
def _capture_unless_user_error(error: Exception) -> None:
# Errors in the user's own SQL are not defects. Classify by error code, not by class, because
# some user-safe ClickHouse codes, for example UNKNOWN_IDENTIFIER, are not ExposedCHQueryError.
@@ -347,6 +363,22 @@ class DataWarehouseSavedQuerySerializer(
capture_exception(e)
logger.exception("Failed to report view action", analytics_event=event)
+ def _raw_trino_columns(self, sync_frequency: str | None) -> dict[str, dict[str, Any]]:
+ if sync_frequency not in (None, "never"):
+ raise serializers.ValidationError("Views that run raw Trino SQL cannot be materialized yet.")
+ client_types = self.context["request"].data.get("types", [])
+ if not isinstance(client_types, list) or any(
+ not isinstance(item, list | tuple)
+ or len(item) != 2
+ or not isinstance(item[0], str)
+ or not isinstance(item[1], str)
+ for item in client_types
+ ):
+ raise serializers.ValidationError('"types" must be a list of [column name, column type] string pairs.')
+ if len(client_types) == 0:
+ raise serializers.ValidationError("Run the query in the SQL editor before saving it as a view.")
+ return _columns_from_client_types(client_types)
+
def _validate_view_dependencies(self, team: Team, name: str, query: str) -> None:
try:
get_parents_from_model_query(team, name, query, database=self.context["database"])
@@ -367,24 +399,20 @@ class DataWarehouseSavedQuerySerializer(
validated_data.pop("edited_history_id", None)
view = DataWarehouseSavedQuery(**validated_data)
- self._validate_view_dependencies(self.context["get_team"](), view.name, validated_data["query"]["query"])
+ if view.is_raw_managed_trino:
+ # ClickHouse cannot run Trino SQL, so the view gets no lineage, no inferred types and no DAG node.
+ view.set_columns(self._raw_trino_columns(sync_frequency))
+ else:
+ self._validate_view_dependencies(self.context["get_team"](), view.name, validated_data["query"]["query"])
- if not soft_update:
+ if not soft_update and not view.is_raw_managed_trino:
try:
# The columns will be inferred from the query
client_types = self.context["request"].data.get("types", [])
if len(client_types) == 0:
view.set_columns(view.get_columns(user=self.context["request"].user))
else:
- columns = {
- str(item[0]): {
- "hogql": hogql_type_name_for_clickhouse_type(str(item[1])),
- "clickhouse": item[1],
- "valid": True,
- }
- for item in client_types
- }
- view.set_columns(columns)
+ view.set_columns(_columns_from_client_types(client_types))
view.external_tables = view.get_s3_tables(database=self.context["database"])
except Exception as e:
@@ -419,14 +447,15 @@ class DataWarehouseSavedQuerySerializer(
],
),
)
- try:
- with transaction.atomic():
- modeling_api.sync_saved_query_to_dag(view)
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
- modeling_api.adopt_saved_query_without_edges(view.team_id, view.id, _lineage_sync_error_detail(e))
- if sync_frequency is not None:
+ if not view.is_raw_managed_trino:
+ try:
+ with transaction.atomic():
+ modeling_api.sync_saved_query_to_dag(view)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ modeling_api.adopt_saved_query_without_edges(view.team_id, view.id, _lineage_sync_error_detail(e))
+ if sync_frequency is not None and not view.is_raw_managed_trino:
if sync_frequency != "never":
assert_user_can_read_query(
view.query,
@@ -453,6 +482,10 @@ class DataWarehouseSavedQuerySerializer(
frequency_given = "sync_frequency" in validated_data
sync_frequency = validated_data.pop("sync_frequency", None)
+ raw_trino = is_raw_managed_trino_query(validated_data.get("query", instance.query))
+
+ if raw_trino and sync_frequency not in (None, "never"):
+ raise serializers.ValidationError("Views that run raw Trino SQL cannot be materialized yet.")
if sync_frequency and sync_frequency != "never":
# Scheduling a view is the same grant as materializing it directly.
@@ -463,8 +496,8 @@ class DataWarehouseSavedQuerySerializer(
database=self.context.get("database"),
)
- # The frequency writes through to the DAG node's freshness target.
- frequency_changed = frequency_given
+ # The frequency writes through to the DAG node's freshness target. Raw Trino views have no node.
+ frequency_changed = frequency_given and not raw_trino
soft_update = validated_data.pop("soft_update", False)
edited_history_id = self.context["request"].data.get("edited_history_id", None)
@@ -482,13 +515,21 @@ class DataWarehouseSavedQuerySerializer(
inferred_columns: dict[str, dict[str, Any]] | None = None
inferred_external_tables: list[str] | None = None
- if "query" in validated_data or "name" in validated_data:
+ if raw_trino != instance.is_raw_managed_trino:
+ raise serializers.ValidationError(
+ "A view cannot switch between Trino and ClickHouse. Save it as a new view."
+ )
+ if raw_trino:
+ if "query" in validated_data and not soft_update:
+ inferred_columns = self._raw_trino_columns(None)
+ inferred_external_tables = []
+ elif "query" in validated_data or "name" in validated_data:
self._validate_view_dependencies(
instance.team,
validated_data.get("name", instance.name),
validated_data.get("query", instance.query)["query"],
)
- if "query" in validated_data and not soft_update:
+ if "query" in validated_data and not soft_update and not raw_trino:
# Inference runs the query on ClickHouse, so it happens before the row lock, on a probe
# carrying the pending query and name rather than the stored ones, as create() does.
probe = DataWarehouseSavedQuery(
@@ -501,14 +542,7 @@ class DataWarehouseSavedQuerySerializer(
if len(client_types) == 0:
inferred_columns = probe.get_columns(user=self.context["request"].user)
else:
- inferred_columns = {
- str(item[0]): {
- "hogql": hogql_type_name_for_clickhouse_type(str(item[1])),
- "clickhouse": item[1],
- "valid": True,
- }
- for item in client_types
- }
+ inferred_columns = _columns_from_client_types(client_types)
inferred_external_tables = probe.get_s3_tables(database=self.context["database"])
except (RecursionError, ResolutionCycleError):
raise serializers.ValidationError("Model contains a cycle")
@@ -616,7 +650,7 @@ class DataWarehouseSavedQuerySerializer(
# Best effort sync to the data modeling DAG representation. The savepoint keeps a
# failed sync best effort without poisoning the update's own transaction.
- if "query" in validated_data or name_changed:
+ if ("query" in validated_data or name_changed) and not view.is_raw_managed_trino:
try:
with transaction.atomic():
modeling_api.sync_saved_query_to_dag(view)
@@ -656,6 +690,18 @@ class DataWarehouseSavedQuerySerializer(
team_id = self.context["team_id"]
user = self.context["request"].user
+ if is_raw_managed_trino_query(query):
+ try:
+ validate_managed_trino_query(
+ HogQLQuery(query=query["query"], executionTarget=ExecutionTarget.MANAGED_TRINO, sendRawQuery=True),
+ self.context["get_team"](),
+ user,
+ )
+ ensure_read_only_raw_trino_statement(query["query"])
+ except ExposedHogQLError as err:
+ raise exceptions.ValidationError(detail=f"Invalid query: {err}")
+ return query
+
context = HogQLContext(team_id=team_id, user=user, enable_select_queries=True)
try:
select_ast = parse_select(query["query"])
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
index 3c68f4c34de8..8914118b13f5 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
@@ -329,6 +329,8 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
body.is_valid(raise_exception=True)
saved_query = self.get_object()
+ if saved_query.is_raw_managed_trino:
+ raise exceptions.ValidationError(detail="Views that run raw Trino SQL cannot be materialized yet.")
on_trino = body.validated_data["engine"] == MaterializationEngine.TRINO
if body.validated_data["full_refresh"] and not on_trino:
@@ -506,6 +508,8 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
Enable materialization for this saved query, at the requested sync frequency or daily.
"""
saved_query: DataWarehouseSavedQuery = self.get_object()
+ if saved_query.is_raw_managed_trino:
+ raise serializers.ValidationError("Views that run raw Trino SQL cannot be materialized yet.")
params = SavedQueryMaterializeSerializer(data=request.data)
params.is_valid(raise_exception=True)
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index aaeadc5ecd92..6708dd72b96f 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -180,6 +180,96 @@ class TestSavedQuery(APIBaseTest):
)
self.assertIsNotNone(saved_query["latest_history_id"])
+ def test_create_raw_managed_trino_view(self) -> None:
+ trino_sql = 'SELECT * FROM "warehouse_catalog".production.hub_occupancy'
+ with patch("posthoganalytics.feature_enabled", return_value=True):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",
+ {
+ "name": "hub_occupancy",
+ "query": {
+ "kind": "HogQLQuery",
+ "query": trino_sql,
+ "executionTarget": "managed_trino",
+ "sendRawQuery": True,
+ },
+ "types": [["hub_id", "Int64"], ["occupied_at", "DateTime64(6)"]],
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, 201, response.content)
+ view = DataWarehouseSavedQuery.objects.get(id=response.json()["id"])
+ assert view.query is not None and view.columns is not None
+ self.assertEqual(view.query["query"], trino_sql)
+ self.assertEqual(view.query["executionTarget"], "managed_trino")
+ self.assertEqual(set(view.columns), {"hub_id", "occupied_at"})
+ self.assertFalse(Node.objects.filter(saved_query=view).exists())
+
+ # HogQL on ClickHouse cannot expand Trino SQL, so the view stays out of the HogQL database.
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/query/",
+ {"query": {"kind": "HogQLQuery", "query": "select * from hub_occupancy"}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ # Expanding the view would fail on its inner Trino table instead, so the view name pins the filter.
+ self.assertIn("Unknown table `hub_occupancy`", response.json()["detail"])
+
+ @parameterized.expand(
+ [
+ ("not_select", "SHOW SCHEMAS", True, [["x", "Int64"]], "read-only SELECT"),
+ ("flag_off", "SELECT 1 AS x", False, [["x", "Int64"]], "not enabled"),
+ ("no_types", "SELECT 1 AS x", True, [], "Run the query"),
+ ("null_types", "SELECT 1 AS x", True, None, "must be a list"),
+ ("short_pair", "SELECT 1 AS x", True, [["x"]], "must be a list"),
+ ]
+ )
+ def test_create_raw_managed_trino_view_refused(
+ self, _case: str, sql: str, flag_enabled: bool, types: list[list[str]] | None, expected_detail: str
+ ) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=flag_enabled):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",
+ {
+ "name": "trino_view",
+ "query": {
+ "kind": "HogQLQuery",
+ "query": sql,
+ "executionTarget": "managed_trino",
+ "sendRawQuery": True,
+ },
+ "types": types,
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertIn(expected_detail, response.json()["detail"])
+ self.assertFalse(DataWarehouseSavedQuery.objects.filter(team=self.team, name="trino_view").exists())
+
+ @parameterized.expand(
+ [
+ ("run", "post", "run/", {}),
+ ("schedule", "patch", "", {"sync_frequency": "24hour"}),
+ ]
+ )
+ def test_raw_managed_trino_view_never_reaches_the_dag(self, _case: str, method: str, path: str, body: dict) -> None:
+ view = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="trino_view",
+ query={
+ "kind": "HogQLQuery",
+ "query": 'SELECT * FROM "warehouse_catalog".production.hub_occupancy',
+ "executionTarget": "managed_trino",
+ "sendRawQuery": True,
+ },
+ )
+ response = getattr(self.client, method)(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{view.id}/{path}", body, format="json"
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertIn("raw Trino SQL cannot be materialized", response.json()["detail"])
+ self.assertFalse(Node.objects.filter(saved_query=view).exists())
+
@parameterized.expand(
[("ui", {}), ("mcp", {"HTTP_X_POSTHOG_CLIENT": "mcp"}), ("api", {"HTTP_USER_AGENT": "test-api-client"})]
)