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.

chore(data-warehouse): split the saved-query view module by concern (#99027)

posthog[bot]6bcc6c0e9c2e
diff --git a/posthog/temporal/data_modeling/AGENTS.md b/posthog/temporal/data_modeling/AGENTS.md
index 79b2c2dd83b6..ce271f939bd3 100644
--- a/posthog/temporal/data_modeling/AGENTS.md
+++ b/posthog/temporal/data_modeling/AGENTS.md
@@ -25,7 +25,7 @@ record of what ran before the cutover.
## Scoping
- `products/data_warehouse/` is owned by another team, but the saved-query surface in it
- (`presentation/views/saved_query.py`) is data modeling's to change. Anything else under that
+ (`presentation/views/saved_query/`) is data modeling's to change. Anything else under that
tree needs their review.
- `DataModelingJob` lives in `products/data_modeling/backend/models/`. Only its viewset is
still under `products/data_warehouse/`.
diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.py
deleted file mode 100644
index b8e26aaabb37..000000000000
--- a/products/data_warehouse/backend/presentation/views/saved_query.py
+++ /dev/null
@@ -1,2157 +0,0 @@
-import uuid
-from dataclasses import dataclass
-from datetime import datetime, timedelta
-from typing import Any, cast
-
-from django.conf import settings
-from django.db import models, transaction
-from django.db.models import Count, IntegerField, Model, OuterRef, Prefetch, Q, Subquery, TextField
-from django.db.models.functions import Cast, Coalesce
-
-import structlog
-import posthoganalytics
-from asgiref.sync import async_to_sync
-from drf_spectacular.utils import extend_schema, extend_schema_field
-from rest_framework import exceptions, filters, request, response, serializers, status, viewsets
-from rest_framework.decorators import action
-from rest_framework.pagination import PageNumberPagination
-from rest_framework.response import Response
-
-from posthog.schema import DataWarehouseManagedViewsetKind
-
-from posthog.hogql.context import HogQLContext
-from posthog.hogql.database.database import Database, SerializedField, serialize_fields
-from posthog.hogql.errors import ExposedHogQLError
-from posthog.hogql.parser import parse_select
-from posthog.hogql.placeholders import FindPlaceholders
-from posthog.hogql.printer import prepare_and_print_ast
-
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
-from posthog.api.shared import UserBasicSerializer
-from posthog.errors import ExposedCHQueryError
-from posthog.exceptions_capture import capture_exception
-from posthog.helpers.impersonation import is_impersonated
-from posthog.models import Team, User
-from posthog.models.activity_logging.activity_log import (
- ActivityLog,
- Change,
- Detail,
- changes_between,
- load_activity,
- log_activity,
-)
-from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
-from posthog.rate_limit import MaterializationRateThrottle, PersonalApiKeyOrUserRateThrottle, RunSavedQueryRateThrottle
-from posthog.rbac.query_access import assert_user_can_read_query
-from posthog.temporal.common.client import sync_connect
-
-from products.access_control.backend.facade.user_access_control import UserAccessControl
-from products.access_control.backend.presentation.access_control import (
- AccessControlViewSetMixin,
- UserAccessControlSerializerMixin,
-)
-from products.data_modeling.backend.facade.api import MAX_LOOKBACK_SECONDS, get_incremental_config
-from products.data_modeling.backend.facade.models import (
- DataModelingJob,
- DataModelingJobEngine,
- DataWarehouseSavedQuery,
- DataWarehouseSavedQueryColumnAnnotation,
- Edge,
- Node,
-)
-from products.data_tools.backend.facade.models import DataWarehouseJoin, DataWarehouseSavedQueryFolder
-from products.data_warehouse.backend.presentation.views.column_annotation_base import (
- DESCRIPTION_HELP_TEXT,
- upsert_annotation,
-)
-from products.warehouse_sources.backend.facade.hogql import (
- get_view_or_table_by_name,
- hogql_type_name_for_clickhouse_type,
-)
-from products.warehouse_sources.backend.facade.models import (
- DataWarehouseTable,
- sync_frequency_interval_to_sync_frequency,
- sync_frequency_to_sync_frequency_interval,
-)
-
-logger = structlog.get_logger(__name__)
-
-
-def _view_types_validation_error(e: Exception) -> serializers.ValidationError:
- # Column inference runs the HogQL-to-ClickHouse path, so a raw exception can carry stack
- # traces, internal table or column names, and S3 URIs. Surface only the errors already marked
- # user-safe; reduce everything else to its class name. Mirrors validate_query below, which
- # keeps the full cause in error tracking and logs instead of the response.
- if isinstance(e, ExposedHogQLError | ExposedCHQueryError):
- return serializers.ValidationError(f"Failed to retrieve types for view: {e}")
- return serializers.ValidationError(f"Failed to retrieve types for view: unexpected {type(e).__name__}")
-
-
-@dataclass(frozen=True, kw_only=True)
-class _CancelTarget:
- workflow_id: str
- workflow_run_id: str | None
-
-
-# A DataWarehouseSavedQuery's activity log also records materialization syncs and status
-# transitions (activity="sync_triggered", status changes) that advance the log without the query
-# being edited. Optimistic-concurrency ("modified by someone else") must key off the latest activity
-# that actually changed the query — otherwise every background sync of a materialized view looks
-# like a foreign edit and blocks the next save. This filter scopes activity lookups to query edits.
-QUERY_CHANGE_ACTIVITY_FILTER = {"detail__changes__contains": [{"field": "query"}]}
-
-# Cadences offered for view materialization. 15min is the fastest — sub-15min intervals
-# (1min, 5min) are source-only and not meaningful for materialized views, matching the
-# frontend `DataModelingSyncInterval` type. All values are accepted by
-# `sync_frequency_to_sync_frequency_interval`.
-SYNC_FREQUENCY_CHOICES = [
- ("never", "never"),
- ("15min", "15min"),
- ("30min", "30min"),
- ("1hour", "1hour"),
- ("6hour", "6hour"),
- ("12hour", "12hour"),
- ("24hour", "24hour"),
- ("7day", "7day"),
- ("30day", "30day"),
-]
-
-# Deprecated sub-15min cadences clamped up to the 15min floor for backwards compatibility
-# with any legacy caller still sending them.
-DEPRECATED_FAST_SYNC_FREQUENCIES = {"1min", "5min"}
-
-# What `materialize` enables at when the caller expresses no preference, preserving the
-# behavior from when the action had no request body at all.
-DEFAULT_MATERIALIZE_SYNC_FREQUENCY = "24hour"
-
-# `never` is missing on purpose: materializing is what starts the refreshes, so asking for none
-# has no meaning here. Callers stop them afterwards by setting the cadence to `never`.
-MATERIALIZE_SYNC_FREQUENCY_CHOICES = [choice for choice in SYNC_FREQUENCY_CHOICES if choice[0] != "never"]
-
-
-class SyncFrequencyBlockerSerializer(serializers.Serializer):
- """The node holding a cadence back, named so a refusal points at something a person can open."""
-
- id = serializers.CharField(help_text="Data modeling node ID of the source or view.")
- name = serializers.CharField(help_text="Node name, as it appears in the data modeling graph.")
-
-
-class SyncFrequencyBoundSerializer(serializers.Serializer):
- label = serializers.CharField( # type: ignore[assignment] # field name intentionally shadows Field.label
- help_text="The bounding cadence in plain English, for example '6 hours'. Matches the wording "
- "used in the error raised when an out-of-bounds cadence is written. Prose rather than a "
- "`sync_frequency` value because a source can deliver on a cadence no `sync_frequency` names."
- )
- blocker = SyncFrequencyBlockerSerializer(
- allow_null=True,
- help_text="Node that set this bound. Null when nothing identifiable set it, and also when it "
- "sits outside the caller's access grants: the bound still applies, it just goes unnamed.",
- )
-
-
-class SyncFrequencyBlockedBy(models.TextChoices):
- SOURCE = "source", "source"
- CONSUMER = "consumer", "consumer"
-
-
-class SyncFrequencyOptionSerializer(serializers.Serializer):
- cadence = serializers.ChoiceField(choices=MATERIALIZE_SYNC_FREQUENCY_CHOICES, help_text="A `sync_frequency` value.")
- allowed = serializers.BooleanField(help_text="False when writing this cadence would be rejected.")
- blocked_by = serializers.ChoiceField(
- choices=SyncFrequencyBlockedBy.choices,
- allow_null=True,
- help_text="Which side withholds this cadence: 'source' when no upstream source syncs that "
- "often, 'consumer' when a downstream view or endpoint refreshes more often than this. "
- "Null when the cadence is allowed.",
- )
- blocker = SyncFrequencyBlockerSerializer(
- allow_null=True,
- help_text="The source or consumer named in `blocked_by`. Null when allowed, and also when the "
- "blocker sits outside the caller's access grants, where `blocked_by` still gives the direction.",
- )
-
-
-class SyncFrequencyBoundsSerializer(serializers.Serializer):
- frequency_mode = serializers.ChoiceField(
- choices=[
- ("tiered", "tiered"),
- ("managed_viewset", "managed_viewset"),
- ("legacy", "legacy"),
- ("no_node", "no_node"),
- ],
- help_text="What governs this view's cadence. 'tiered' is the only mode where `options` is "
- "meaningful and `sync_frequency` is writable per view. 'managed_viewset' means PostHog owns "
- "the view, 'legacy' means the v1 backend, where any cadence is accepted and no bounds apply, "
- "and 'no_node' means the view has no data modeling node to store a cadence on.",
- )
- options = SyncFrequencyOptionSerializer(
- many=True,
- help_text="Every cadence a picker may show, coarsest-last, each marked allowed or blocked with "
- "its cause. Empty outside 'tiered' mode.",
- )
- floor = SyncFrequencyBoundSerializer(
- allow_null=True,
- help_text="The fastest bound: no cadence finer than this is allowed, because the source named "
- "here does not sync more often. Null when no source withholds a cadence.",
- )
- ceiling = SyncFrequencyBoundSerializer(
- allow_null=True,
- help_text="The slowest bound: no cadence coarser than this is allowed, because the consumer "
- "named here refreshes that often. Null when no consumer withholds a cadence.",
- )
- best_effort_sources = SyncFrequencyBlockerSerializer(
- many=True,
- help_text="Upstream sources with no sync schedule, so the floor is a guess: these arrive when "
- "someone runs them, and refreshing more often than they really sync will serve stale data. "
- "Only sources the caller may read are listed.",
- )
- best_effort_sources_withheld = serializers.BooleanField(
- help_text="True when at least one such source sits outside the caller's access grants, so the "
- "list above is incomplete and the caveat still applies."
- )
-
-
-SYNC_FREQUENCY_BOUNDS_HELP_TEXT = (
- "Which cadences this view can actually be set to, and what withholds the rest. Computed from the "
- "view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences "
- "set a ceiling. Read-only, and present on retrieve, create and update responses only."
-)
-
-
-def _unbounded_frequency_payload(mode: str) -> dict[str, Any]:
- """The payload for a view whose cadence no lineage governs, so there is nothing to withhold."""
- return {
- "frequency_mode": mode,
- "options": [],
- "floor": None,
- "ceiling": None,
- "best_effort_sources": [],
- "best_effort_sources_withheld": False,
- }
-
-
-def _blocker_node_ids(resolved: Any) -> set[str]:
- """Every node the bounds would name, across the two bounds, the options and the best-effort list."""
- node_ids: set[str] = set(resolved.best_effort_source_ids)
- for bound in (resolved.bounds.floor, resolved.bounds.ceiling):
- if bound is not None and bound.blocker is not None:
- node_ids.add(bound.blocker)
- node_ids.update(option.blocker for option in resolved.bounds.options if option.blocker is not None)
- return node_ids
-
-
-def visible_blocker_names(
- resolved: Any, user_access_control: UserAccessControl | None, *, team_id: int
-) -> dict[str, str]:
- """The blocker names this caller may read, keyed by node id.
-
- Fails closed, and withholds the node id along with the name: an id on its own still answers
- "something upstream of this view exists", which is what the grant is there to withhold. A node
- with no resolvable resource (predating the origin stamp) is withheld for the same reason.
- """
- node_ids = _blocker_node_ids(resolved)
- if not node_ids or user_access_control is None:
- return {}
-
- visible: dict[str, str] = {}
- # Lists, not single ids: one saved query or table can hold a node in several DAGs, and a grant
- # covers the resource, so every node of it becomes visible together.
- node_ids_by_saved_query: dict[str, list[str]] = {}
- node_ids_by_table: dict[str, list[str]] = {}
- for node_id in node_ids:
- identity = resolved.identities.get(node_id)
- name = resolved.names.get(node_id)
- if identity is None or name is None:
- continue
- if identity.is_posthog_table:
- visible[node_id] = name # events, persons and friends: readable by anyone on the project
- elif identity.saved_query_id is not None:
- node_ids_by_saved_query.setdefault(identity.saved_query_id, []).append(node_id)
- elif identity.warehouse_table_id is not None:
- node_ids_by_table.setdefault(identity.warehouse_table_id, []).append(node_id)
-
- def reveal(resource_node_ids: list[str]) -> None:
- visible.update({node_id: resolved.names[node_id] for node_id in resource_node_ids})
-
- if node_ids_by_saved_query:
- creators = DataWarehouseSavedQuery.objects.filter(id__in=node_ids_by_saved_query, team_id=team_id).values_list(
- "id", "created_by_id"
- )
- levels = user_access_control.bulk_object_access_levels(
- "warehouse_view", [(str(pk), created_by) for pk, created_by in creators]
- )
- for saved_query_id, level in levels.items():
- if level is not None and level != "none":
- reveal(node_ids_by_saved_query[saved_query_id])
-
- if node_ids_by_table:
- # One at a time rather than in bulk: `warehouse_table` falls back to `external_data_source`,
- # and the bulk call refuses any resource with a fallback parent. Per object is also what
- # honours a deny on one table, or on the source it came from. A table that no longer
- # resolves keeps its name withheld.
- tables = list(
- DataWarehouseTable.objects.filter(id__in=node_ids_by_table, team_id=team_id).exclude(deleted=True)
- )
- user_access_control.preload_object_access_controls(cast(list[Model], tables))
- for table in tables:
- if user_access_control.check_access_level_for_object(table, "viewer"):
- reveal(node_ids_by_table[str(table.id)])
- return visible
-
-
-def _frequency_bounds_payload(resolved: Any, visible_names: dict[str, str]) -> dict[str, Any]:
- from products.data_modeling.backend.facade.api import humanize_cadence
-
- def blocker(node_id: str | None) -> dict[str, str] | None:
- if node_id is None or node_id not in visible_names:
- return None
- return {"id": node_id, "name": visible_names[node_id]}
-
- def bound(value: Any) -> dict[str, Any] | None:
- if value is None:
- return None
- return {"label": humanize_cadence(value.value), "blocker": blocker(value.blocker)}
-
- best_effort = sorted(resolved.best_effort_source_ids)
- return {
- "frequency_mode": "tiered",
- "options": [
- {
- "cadence": sync_frequency_interval_to_sync_frequency(option.value),
- "allowed": option.allowed,
- "blocked_by": option.blocked_by,
- "blocker": blocker(option.blocker),
- }
- for option in resolved.bounds.options
- ],
- "floor": bound(resolved.bounds.floor),
- "ceiling": bound(resolved.bounds.ceiling),
- "best_effort_sources": [blocker(node_id) for node_id in best_effort if node_id in visible_names],
- "best_effort_sources_withheld": any(node_id not in visible_names for node_id in best_effort),
- }
-
-
-def _node_frequency_targets(root: serializers.BaseSerializer, view: DataWarehouseSavedQuery) -> dict[str, timedelta]:
- """Declared node targets for every view the root serializer renders, fetched once.
-
- Resolved from the root's instance rather than the viewset context, because the context is
- built without knowing which page of views is being serialized. Memoized on the root so a
- `list` response costs one query instead of one per view.
- """
- cached = getattr(root, "_node_frequency_targets_cache", None)
- if cached is not None:
- return cached
-
- from products.data_modeling.backend.facade.api import declared_targets_by_saved_query
-
- instance = root.instance
- if isinstance(instance, DataWarehouseSavedQuery):
- views = [instance]
- elif instance is None:
- views = [view]
- else:
- views = list(instance)
-
- targets = declared_targets_by_saved_query(view.team_id, [rendered.pk for rendered in views])
- root._node_frequency_targets_cache = targets # type: ignore[attr-defined]
- return targets
-
-
-def resolve_sync_frequency(root: serializers.BaseSerializer, view: DataWarehouseSavedQuery) -> str | None:
- """Cadence string for a view, preferring its DAG node's declared freshness target.
-
- On tiered v2 teams the node target is the only store of cadence — reconcile deliberately NULLs
- `sync_frequency_interval` so a stale v1 schedule can't be revived from it — so reading the
- column alone reports "never" for every scheduled view. The column still covers v1 and
- single-schedule v2 teams, which have no node target.
- """
- target = _node_frequency_targets(root, view).get(str(view.pk))
- if target is not None:
- return sync_frequency_interval_to_sync_frequency(target)
- return sync_frequency_interval_to_sync_frequency(view.sync_frequency_interval)
-
-
-class SyncFrequencyField(serializers.ChoiceField):
- """Writable sync-cadence field for saved queries.
-
- Reads resolve the cadence via `resolve_sync_frequency` (node target first, then the model's
- `sync_frequency_interval`); writes are validated against the choices and consumed by the
- serializer's `update()`. Declaring it as a real (non read-only) field is what lets the
- cadence flow into the generated PATCH body and MCP tool schema.
- """
-
- def __init__(self, **kwargs: Any) -> None:
- kwargs.setdefault("choices", SYNC_FREQUENCY_CHOICES)
- kwargs.setdefault("required", False)
- kwargs.setdefault("allow_null", True)
- super().__init__(**kwargs)
-
- def to_internal_value(self, data: Any) -> str:
- # Clamp deprecated sub-15min cadences up to the floor before validating against choices.
- if data in DEPRECATED_FAST_SYNC_FREQUENCIES:
- data = "15min"
- return super().to_internal_value(data)
-
- def get_attribute(self, instance: DataWarehouseSavedQuery) -> str | None:
- return resolve_sync_frequency(self.root, instance)
-
-
-def delete_saved_query(saved_query: DataWarehouseSavedQuery) -> None:
- from products.data_modeling.backend.facade.api import HasDependentsError, delete_node_from_dag
-
- if saved_query.managed_viewset is not None:
- raise serializers.ValidationError(
- "Cannot delete a query from a managed viewset directly. Disable the managed viewset instead."
- )
-
- try:
- delete_node_from_dag(saved_query)
- except HasDependentsError:
- raise
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to delete node for saved query", saved_query_name=saved_query.name)
-
- for join in DataWarehouseJoin.objects.filter(
- Q(team_id=saved_query.team_id)
- & (Q(source_table_name=saved_query.name) | Q(joining_table_name=saved_query.name))
- ).exclude(deleted=True):
- join.soft_delete()
-
- saved_query.revert_materialization()
- saved_query.soft_delete()
-
-
-VIEW_DESCRIPTION_HELP_TEXT = (
- "Semantic description of what this view represents, surfaced to AI agents. Set it to describe the "
- "view; send an empty string to clear it. Per-column descriptions are read back in `columns` and set "
- "via the saved-query column annotation endpoints. " + DESCRIPTION_HELP_TEXT
-)
-
-
-def view_annotation_map(view: DataWarehouseSavedQuery) -> dict[str, str]:
- """`{column_name: description}` from a view's column annotations (``""`` = view-level)."""
- return {a.column_name: a.description for a in view.column_annotations.all()}
-
-
-class ViewDescriptionField(serializers.CharField):
- """View-level description, stored as a column annotation with an empty `column_name`.
-
- Reads the annotation for display; on write the serializer's create/update upserts or clears it. The
- view model has no `description` column, so the value is resolved here rather than bound to the model.
- """
-
- def get_attribute(self, instance: DataWarehouseSavedQuery) -> str | None:
- return view_annotation_map(instance).get("")
-
-
-# Only these two are still written to the column: MODIFIED on edit, CANCELLED by the cancel action.
-# Every other value was last written by the v1 materialization workflow, which no longer exists, so it
-# describes a run no current code path could have produced.
-STATUSES_STILL_WRITTEN = frozenset({DataWarehouseSavedQuery.Status.MODIFIED, DataWarehouseSavedQuery.Status.CANCELLED})
-
-
-class DataWarehouseSavedQuerySerializerMixin:
- """Shared methods for DataWarehouseSavedQuery serializers.
-
- This mixin is intended to be used with serializers.ModelSerializer subclasses.
- """
-
- def _serving_run(self, view: DataWarehouseSavedQuery) -> DataModelingJob | None:
- """The newest materialization run that serves this view, or None if it has never run.
-
- Prefers the prefetched job so a list of views costs one query. Falls back to a lookup for
- the detail route, which has no prefetch.
- """
- try:
- jobs = view.jobs # type: ignore[attr-defined]
- return jobs[0] if jobs else None
- except AttributeError:
- return (
- DataModelingJob.objects.filter(saved_query_id=view.id, engine=DataModelingJobEngine.CLICKHOUSE)
- .order_by("-last_run_at")
- .first()
- )
-
- @extend_schema_field(serializers.DateTimeField(allow_null=True))
- def get_last_run_at(self, view: DataWarehouseSavedQuery) -> datetime | None:
- run = self._serving_run(view)
- return run.last_run_at if run is not None else None
-
- @extend_schema_field(serializers.ChoiceField(choices=DataWarehouseSavedQuery.Status.choices, allow_null=True))
- def get_status(self, view: DataWarehouseSavedQuery) -> str | None:
- run = self._serving_run(view)
- if run is None:
- return view.status if view.status in STATUSES_STILL_WRITTEN else None
- # Modified means "edited and not materialized since", which no run can express. A run that
- # happened after the edit answers it, so the column only wins while the edit is the newer fact.
- edited_since_the_run = (
- view.status == DataWarehouseSavedQuery.Status.MODIFIED
- and view.updated_at is not None
- and view.updated_at > run.last_run_at
- )
- return view.status if edited_since_the_run else run.status
-
- @extend_schema_field(serializers.CharField(allow_null=True))
- def get_latest_error(self, view: DataWarehouseSavedQuery) -> str | None:
- run = self._serving_run(view)
- return run.error if run is not None else None
-
- @extend_schema_field(serializers.CharField(allow_null=True))
- def get_sync_frequency(self, schema: DataWarehouseSavedQuery):
- return resolve_sync_frequency(self.root, schema) # type: ignore[attr-defined]
-
- @extend_schema_field(serializers.BooleanField())
- def get_is_incremental(self, view: DataWarehouseSavedQuery) -> bool:
- return get_incremental_config(view) is not None
-
- @extend_schema_field(SyncFrequencyBoundsSerializer())
- def get_sync_frequency_bounds(self, view: DataWarehouseSavedQuery) -> dict[str, Any]:
- from products.data_modeling.backend.facade.api import saved_query_target_bounds
-
- if view.managed_viewset is not None:
- return _unbounded_frequency_payload("managed_viewset")
-
- resolved = saved_query_target_bounds(view.team_id, view.pk)
- if resolved is None:
- return _unbounded_frequency_payload("no_node")
- visible = visible_blocker_names(resolved, self.user_access_control, team_id=view.team_id) # type: ignore[attr-defined]
- return _frequency_bounds_payload(resolved, visible)
-
- @extend_schema_field(serializers.CharField(allow_null=True))
- def get_managed_viewset_kind(self, view: DataWarehouseSavedQuery) -> DataWarehouseManagedViewsetKind | None:
- return cast(DataWarehouseManagedViewsetKind, view.managed_viewset.kind) if view.managed_viewset else None
-
- @extend_schema_field(serializers.ListField(child=serializers.DictField()))
- def get_columns(self, view: DataWarehouseSavedQuery) -> list[SerializedField]:
- # `hogql_fields` rather than `hogql_definition`, which would read the SQL body the list
- # page defers.
- hogql_fields = view.hogql_fields()
- if not hogql_fields:
- return []
-
- # `hogql_fields` holds concrete `DatabaseField` subclasses only, and `serialize_fields`
- # reads the context database for none of those, so this needs no HogQL database build.
- context = HogQLContext(team_id=self.context["team_id"]) # type: ignore[attr-defined]
-
- descriptions = view_annotation_map(view)
- fields = serialize_fields(hogql_fields, context, view.name_chain, table_type="external")
- return [
- SerializedField(
- key=field.name,
- name=field.name,
- type=field.type,
- schema_valid=field.schema_valid,
- fields=field.fields,
- table=field.table,
- chain=field.chain,
- description=descriptions.get(field.name),
- )
- for field in fields
- ]
-
-
-class DataWarehouseSavedQueryMinimalSerializer(
- DataWarehouseSavedQuerySerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer
-):
- """Lightweight serializer for list views - excludes large query field to reduce memory usage."""
-
- created_by = UserBasicSerializer(read_only=True)
- columns = serializers.SerializerMethodField(read_only=True)
- description = ViewDescriptionField(read_only=True, help_text=VIEW_DESCRIPTION_HELP_TEXT)
- sync_frequency = serializers.SerializerMethodField()
- last_run_at = serializers.SerializerMethodField(read_only=True)
- status = serializers.SerializerMethodField(read_only=True)
- latest_error = serializers.SerializerMethodField(read_only=True)
- managed_viewset_kind = serializers.SerializerMethodField(read_only=True)
- folder_id = serializers.UUIDField(source="folder.id", read_only=True, allow_null=True)
- folder_name = serializers.CharField(source="folder.name", read_only=True, allow_null=True)
- is_incremental = serializers.SerializerMethodField(
- read_only=True,
- help_text="Whether this view is set up to update incrementally. A run can still rebuild the "
- "whole table, for example on the first run or after the query changes.",
- )
-
- class Meta:
- model = DataWarehouseSavedQuery
- fields = [
- "id",
- "deleted",
- "name",
- "created_by",
- "created_at",
- "description",
- "sync_frequency",
- "columns",
- "status",
- "last_run_at",
- "managed_viewset_kind",
- "folder_id",
- "folder_name",
- "latest_error",
- "is_materialized",
- "is_incremental",
- "origin",
- "is_test",
- "expires_at",
- "user_access_level",
- ]
- read_only_fields = fields
-
-
-def _clickhouse_types(columns: Any) -> dict[str, str] | None:
- """Pull the ClickHouse type out of each entry in a saved query's stored `columns` blob.
-
- Only used to spot a nullable unique key, which would silently duplicate rows on every run.
- """
- if not isinstance(columns, dict):
- return None
- types: dict[str, str] = {}
- for name, meta in columns.items():
- if isinstance(meta, dict) and isinstance(meta.get("clickhouse"), str):
- types[name] = meta["clickhouse"]
- return types or None
-
-
-class SavedQuerySuspensionSerializer(serializers.Serializer):
- at = serializers.DateTimeField(help_text="When materialization was suspended.")
- reason = serializers.CharField(help_text="Error from the materialization run that tripped suspension.")
- job_id = serializers.CharField(help_text="Materialization job that tripped suspension.")
-
-
-class IncrementalConfigSerializer(serializers.Serializer):
- """How a view updates its materialized table in place rather than rebuilding it."""
-
- enabled = serializers.BooleanField(
- default=False, help_text="Whether runs update the table incrementally instead of rebuilding it."
- )
- incremental_key = serializers.CharField(
- help_text="Output column whose advancing value marks rows as new. Each run reads only rows at "
- "or after the last run's highest value for it. When the query groups, this must be one of the "
- "grouped columns, so every group a run touches is recomputed in full.",
- )
- unique_key = serializers.ListField(
- child=serializers.CharField(),
- allow_empty=False,
- help_text="Output columns that identify a row, used to match recomputed rows against stored "
- "ones. Must include every GROUP BY column. These columns can never be null.",
- )
- lookback_seconds = serializers.IntegerField(
- required=False,
- default=0,
- min_value=0,
- max_value=MAX_LOOKBACK_SECONDS,
- help_text="How far back before the last run's high point to re-read, so late-arriving data is "
- "picked up. Only applies when the incremental key is a date or time.",
- )
-
-
-class IncrementalStateSerializer(serializers.Serializer):
- """Read-only progress written by the materialization run."""
-
- watermark = serializers.CharField(
- allow_null=True,
- required=False,
- help_text="Highest incremental key value written so far. The next run starts here.",
- )
- definition_fingerprint = serializers.CharField(
- allow_null=True,
- required=False,
- help_text="Fingerprint of the query, incremental key, and unique key the stored rows were "
- "built from. When it stops matching, the next run rebuilds the whole table. Lookback is "
- "not part of it: changing lookback never forces a rebuild.",
- )
- last_full_refresh_at = serializers.CharField(
- allow_null=True, required=False, help_text="When the table was last rebuilt from scratch."
- )
- last_run_mode = serializers.ChoiceField(
- choices=[("incremental", "incremental"), ("full_refresh", "full_refresh")],
- allow_null=True,
- required=False,
- help_text="Whether the last run updated the table or rebuilt it.",
- )
-
-
-class DataWarehouseSavedQuerySerializer(
- DataWarehouseSavedQuerySerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer
-):
- @extend_schema_field(
- {
- "type": "object",
- "properties": {
- "kind": {"type": "string", "enum": ["HogQLQuery"], "default": "HogQLQuery"},
- "query": {"type": "string"},
- },
- "required": ["query"],
- }
- )
- class QueryDefinitionField(serializers.JSONField):
- pass
-
- created_by = UserBasicSerializer(read_only=True)
- columns = serializers.SerializerMethodField(read_only=True)
- query = QueryDefinitionField(
- help_text='HogQL query definition as a JSON object with a "query" key containing the SQL string and a "kind" key (always "HogQLQuery"). Format the SQL string multi-line with indentation and inline `--` comments for non-obvious logic — the SQL editor renders it verbatim, so avoid minified single-line SQL. Example: {"kind": "HogQLQuery", "query": "SELECT\\n event,\\n count() AS cnt\\nFROM events\\nGROUP BY event\\nLIMIT 100"}',
- )
- sync_frequency = SyncFrequencyField(
- help_text=(
- "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', "
- "'24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest "
- "cadence available. Null means no scheduled materialization. Read back after a write, this "
- "reflects the cadence stored on the view's DAG node."
- ),
- )
- sync_frequency_bounds = serializers.SerializerMethodField(read_only=True, help_text=SYNC_FREQUENCY_BOUNDS_HELP_TEXT)
- latest_history_id = serializers.SerializerMethodField(read_only=True)
- last_run_at = serializers.SerializerMethodField(read_only=True)
- status = serializers.SerializerMethodField(read_only=True)
- latest_error = serializers.SerializerMethodField(read_only=True)
- managed_viewset_kind = serializers.SerializerMethodField(read_only=True)
- suspended = serializers.SerializerMethodField(read_only=True)
- folder_id = TeamScopedPrimaryKeyRelatedField(
- source="folder",
- queryset=DataWarehouseSavedQueryFolder.objects.all(),
- required=False,
- allow_null=True,
- help_text="Optional folder ID used to organize this view in the SQL editor sidebar.",
- )
- folder_name = serializers.CharField(
- source="folder.name",
- read_only=True,
- allow_null=True,
- help_text="Folder name used to organize this view in the SQL editor sidebar.",
- )
- edited_history_id = serializers.CharField(
- write_only=True,
- required=False,
- allow_null=True,
- help_text="Activity log ID from the last known edit. Used for conflict detection.",
- )
- soft_update = serializers.BooleanField(
- write_only=True,
- required=False,
- allow_null=True,
- help_text="If true, skip column inference and validation. For saving drafts.",
- )
- dag_id = serializers.UUIDField(
- write_only=True, required=False, allow_null=True, help_text="Optional DAG to place this view into"
- )
- description = ViewDescriptionField(
- required=False, allow_blank=True, allow_null=True, help_text=VIEW_DESCRIPTION_HELP_TEXT
- )
- incremental = IncrementalConfigSerializer(
- source="incremental_config",
- required=False,
- allow_null=True,
- help_text="Update the materialized table in place instead of rebuilding it. Null or absent "
- "means every run rebuilds the whole table.",
- )
- incremental_state = IncrementalStateSerializer(
- read_only=True,
- allow_null=True,
- help_text="How far incremental materialization has progressed. Null until the first run "
- "records any. Written by the materialization run, not by this API.",
- )
-
- class Meta:
- model = DataWarehouseSavedQuery
- fields = [
- "id",
- "deleted",
- "name",
- "query",
- "incremental",
- "incremental_state",
- "created_by",
- "created_at",
- "updated_at",
- "description",
- "sync_frequency",
- "sync_frequency_bounds",
- "columns",
- "status",
- "last_run_at",
- "managed_viewset_kind",
- "folder_id",
- "folder_name",
- "latest_error",
- "edited_history_id",
- "latest_history_id",
- "soft_update",
- "dag_id",
- "is_materialized",
- "origin",
- "is_test",
- "expires_at",
- "user_access_level",
- "suspended",
- ]
- read_only_fields = [
- "id",
- "created_by",
- "created_at",
- "updated_at",
- "columns",
- "incremental_state",
- "status",
- "last_run_at",
- "managed_viewset_kind",
- "sync_frequency_bounds",
- "folder_name",
- "latest_error",
- "latest_history_id",
- "user_access_level",
- "is_materialized",
- "origin",
- "expires_at",
- "suspended",
- ]
- extra_kwargs = {
- "soft_update": {"write_only": True},
- "name": {
- "help_text": "Unique name for the view. Used as the table name in HogQL queries and the node name in the data modeling Node.",
- },
- }
-
- def _write_view_description(self, view: DataWarehouseSavedQuery, description: str | None) -> None:
- team_id = self.context["team_id"]
- if description:
- upsert_annotation(
- DataWarehouseSavedQueryColumnAnnotation,
- team_id,
- parent_field="saved_query",
- parent=view,
- column_name="",
- description=description,
- )
- else:
- DataWarehouseSavedQueryColumnAnnotation.objects.for_team(team_id).filter(
- saved_query=view, column_name=""
- ).delete()
-
- @extend_schema_field(serializers.IntegerField(allow_null=True))
- def get_latest_history_id(self, view: DataWarehouseSavedQuery):
- # First check if we have an activity log from a recent creation/update
- if (
- "activity_log" in self.context
- and self.context["activity_log"]
- and self.context["activity_log"].item_id == str(view.id)
- ):
- return self.context["activity_log"].id
-
- # Otherwise check for annotated field from queryset
- if hasattr(view, "latest_activity_id"):
- return view.latest_activity_id
-
- return None
-
- @extend_schema_field(
- serializers.DictField(
- child=SavedQuerySuspensionSerializer(),
- help_text="Engines this query's materialization is suspended for after repeated failures. "
- "Suspended engines are skipped by scheduled runs until the query is resumed.",
- )
- )
- def get_suspended(self, view: DataWarehouseSavedQuery) -> dict[str, Any]:
- from products.data_modeling.backend.facade.api import suspension_state_for_saved_query
-
- return {
- engine: SavedQuerySuspensionSerializer(entry).data
- for engine, entry in suspension_state_for_saved_query(view).items()
- }
-
- def create(self, validated_data):
- validated_data["team_id"] = self.context["team_id"]
- validated_data["created_by"] = self.context["request"].user
- validated_data["origin"] = DataWarehouseSavedQuery.Origin.DATA_WAREHOUSE
- soft_update = validated_data.pop("soft_update", False)
- dag_id = validated_data.pop("dag_id", None)
- has_description = "description" in validated_data
- description = validated_data.pop("description", None)
- # Sync cadence is configured via materialization, not on creation — drop it so it
- # isn't passed to the model constructor.
- validated_data.pop("sync_frequency", None)
- view = DataWarehouseSavedQuery(**validated_data)
-
- if not soft_update:
- 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.external_tables = view.get_s3_tables(database=self.context["database"])
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to retrieve types for view %s", view.name)
- raise _view_types_validation_error(e)
-
- with transaction.atomic():
- view.save()
- if has_description:
- self._write_view_description(view, description)
- try:
- view.setup_model_paths()
- except Exception:
- # For now, do not fail saved query creation if we cannot model-ize it.
- # Later, after bugs and errors have been ironed out, we may tie these two
- # closer together.
- logger.exception("Failed to create model path when creating view %s", view.name)
-
- team = Team.objects.get(id=view.team_id)
-
- activity_log = log_activity(
- organization_id=team.organization_id,
- team_id=team.id,
- user=view.created_by,
- was_impersonated=is_impersonated(self.context["request"]),
- item_id=view.id,
- scope="DataWarehouseSavedQuery",
- activity="created",
- detail=Detail(
- name=view.name,
- changes=[
- Change(
- field="query",
- action="created",
- type="DataWarehouseSavedQuery",
- before=None,
- after=view.query,
- )
- ],
- ),
- )
-
- # Store the activity log in the serializer context
- if activity_log:
- self.context["activity_log"] = activity_log
- # best effort sync to new data modeling DAG representation
- try:
- from products.data_modeling.backend.facade.api import sync_saved_query_to_dag
- from products.data_modeling.backend.facade.models import DAG
-
- dag_obj = None
- if dag_id:
- try:
- dag_obj = DAG.objects.get(id=dag_id, team_id=view.team_id)
- except DAG.DoesNotExist:
- raise serializers.ValidationError({"dag_id": "Invalid DAG ID or DAG does not belong to this team"})
- sync_saved_query_to_dag(view, dag=dag_obj)
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
- return view
-
- def update(self, instance: Any, validated_data: Any) -> Any:
- dag_id = validated_data.pop("dag_id", None)
- has_description = "description" in validated_data
- description = validated_data.pop("description", None)
-
- if instance.managed_viewset is not None:
- raise serializers.ValidationError("Cannot update a query from a managed viewset")
-
- try:
- before_update = DataWarehouseSavedQuery.objects.get(pk=instance.id)
- except DataWarehouseSavedQuery.DoesNotExist:
- before_update = None
-
- sync_frequency = validated_data.pop("sync_frequency", None)
-
- if sync_frequency and sync_frequency != "never":
- # Scheduling a view is the same grant as materializing it directly.
- assert_user_can_read_query(
- instance.query,
- self.context["team_id"],
- cast(User, self.context["request"].user),
- database=self.context.get("database"),
- )
-
- # The frequency writes through to the DAG node's freshness target.
- frequency_changed = bool(sync_frequency)
-
- soft_update = validated_data.pop("soft_update", False)
-
- with transaction.atomic():
- locked_instance = DataWarehouseSavedQuery.objects.select_for_update().get(pk=instance.pk)
-
- # Get latest activity log for this model
-
- if validated_data.get("query", None) and not soft_update:
- edited_history_id = self.context["request"].data.get("edited_history_id", None)
- latest_activity_id = (
- ActivityLog.objects.filter(
- team_id=locked_instance.team_id,
- item_id=locked_instance.id,
- scope="DataWarehouseSavedQuery",
- **QUERY_CHANGE_ACTIVITY_FILTER,
- )
- .order_by("-created_at")
- .values_list("id", flat=True)
- .first()
- )
-
- if str(edited_history_id) != str(latest_activity_id):
- raise serializers.ValidationError("The query was modified by someone else.")
-
- if frequency_changed:
- # The node target is the only store of frequency intent. The interval column
- # stays NULL so a stale v1 schedule can never be revived from it.
- locked_instance.sync_frequency_interval = None
- validated_data["sync_frequency_interval"] = None
-
- view: DataWarehouseSavedQuery = super().update(locked_instance, validated_data)
-
- if frequency_changed:
- from products.data_modeling.backend.facade.api import (
- UnsatisfiableFrequencyError,
- UnsupportedFrequencyTargetError,
- apply_saved_query_frequency_target,
- declared_targets_by_saved_query,
- saved_query_target_bounds,
- )
-
- target = (
- None if sync_frequency == "never" else sync_frequency_to_sync_frequency_interval(sync_frequency)
- )
- previous_target = declared_targets_by_saved_query(view.team_id, [view.pk]).get(str(view.pk))
- # A refusal names what blocks the cadence, so it obeys the same grants the read
- # payload does — otherwise one rejected PATCH reads back a name the caller was
- # never shown. Withheld nodes fall back to generic prose inside the refusal.
- bounds = saved_query_target_bounds(view.team_id, view.pk)
- visible = (
- visible_blocker_names(bounds, self.user_access_control, team_id=view.team_id)
- if bounds is not None
- else {}
- )
- try:
- # Validates inside the transaction (a rejected frequency rolls the whole
- # update back) and queues the schedule reconcile for after commit.
- nodes_written = apply_saved_query_frequency_target(view, target, visible_names=visible)
- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:
- raise serializers.ValidationError(str(e))
- if target is not None and nodes_written == 0:
- raise serializers.ValidationError(
- "Cannot set a materialization frequency: this view is not wired into the data "
- "modeling DAG yet. Re-save the view to create its node, then set the frequency."
- )
-
- if has_description:
- self._write_view_description(view, description)
-
- # Only update columns and status if the query has changed
- if "query" in validated_data:
- 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.external_tables = view.get_s3_tables(database=self.context["database"])
- except RecursionError:
- raise serializers.ValidationError("Model contains a cycle")
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to retrieve types for view %s", view.name)
- raise _view_types_validation_error(e)
-
- view.status = DataWarehouseSavedQuery.Status.MODIFIED
- view.save()
-
- try:
- view.setup_model_paths()
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to update model path when updating view %s", view.name)
-
- team = Team.objects.get(id=view.team_id)
-
- changes = changes_between("DataWarehouseSavedQuery", previous=before_update, current=view)
- changes = [
- Change(
- type=change.type,
- action=change.action,
- field=change.field,
- before=getattr(change.before, "name", change.before) if change.field == "folder" else change.before,
- after=getattr(change.after, "name", change.after) if change.field == "folder" else change.after,
- )
- for change in changes
- ]
- if frequency_changed and previous_target != target:
- # The cadence lives on the DAG node, so changes_between() sees nothing and
- # log_activity would discard the whole updated entry as a no-op.
- changes.append(
- Change(
- type="DataWarehouseSavedQuery",
- action="changed",
- field="sync_frequency_interval",
- before=str(previous_target) if previous_target is not None else None,
- after=str(target) if target is not None else None,
- )
- )
- activity_log = log_activity(
- organization_id=team.organization_id,
- team_id=team.id,
- user=self.context["request"].user,
- was_impersonated=is_impersonated(self.context["request"]),
- item_id=view.id,
- scope="DataWarehouseSavedQuery",
- activity="updated",
- detail=Detail(name=view.name, changes=changes),
- )
-
- # Store the activity log in the serializer context
- if activity_log:
- self.context["activity_log"] = activity_log
- else:
- # get latest query-changing activity log for this model (see QUERY_CHANGE_ACTIVITY_FILTER)
- latest_activity_log = (
- ActivityLog.objects.filter(
- team_id=locked_instance.team_id,
- item_id=locked_instance.id,
- scope="DataWarehouseSavedQuery",
- **QUERY_CHANGE_ACTIVITY_FILTER,
- )
- .order_by("-created_at")
- .first()
- )
- self.context["activity_log"] = latest_activity_log
- # best effort sync to new data modeling DAG representation
- if "query" in validated_data:
- try:
- from products.data_modeling.backend.facade.api import sync_saved_query_to_dag
- from products.data_modeling.backend.facade.models import DAG
-
- dag_obj = None
- if dag_id:
- dag_obj = DAG.objects.filter(id=dag_id, team_id=view.team_id).first()
- sync_saved_query_to_dag(view, dag=dag_obj)
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
- return view
-
- def validate_query(self, query):
- if not isinstance(query, dict):
- raise exceptions.ValidationError(
- detail=(
- 'Query must be a JSON object with a "query" key, '
- f"got {type(query).__name__}. "
- 'Example: {"kind": "HogQLQuery", "query": "SELECT * FROM events WHERE timestamp >= now() - INTERVAL 7 DAY LIMIT 100"}'
- )
- )
- if not isinstance(query.get("query"), str) or not query["query"].strip():
- raise exceptions.ValidationError(
- detail='Query object must contain a non-empty "query" key with the SQL string.'
- )
-
- team_id = self.context["team_id"]
- user = self.context["request"].user
-
- context = HogQLContext(team_id=team_id, user=user, enable_select_queries=True)
- try:
- select_ast = parse_select(query["query"])
-
- find_placeholders = FindPlaceholders()
- find_placeholders.visit(select_ast)
- except ExposedHogQLError as err:
- raise exceptions.ValidationError(detail=f"Invalid query: {err}")
- if len(find_placeholders.placeholder_fields) > 0:
- placeholder = find_placeholders.placeholder_fields.pop()
- placeholder_string = ".".join(str(field) for field in placeholder if field is not None)
- raise exceptions.ValidationError(
- detail=f"Variables like {'{'}{placeholder_string}{'}'} are not allowed in views"
- )
- elif find_placeholders.placeholder_expressions or find_placeholders.has_filters:
- raise exceptions.ValidationError(detail="Filters and placeholder expressions are not allowed in views")
-
- try:
- prepare_and_print_ast(
- node=select_ast,
- context=context,
- dialect="clickhouse",
- stack=None,
- settings=None,
- )
- except Exception as err:
- if isinstance(err, ExposedHogQLError):
- error = str(err)
- raise exceptions.ValidationError(detail=f"Invalid query: {error}")
- elif not settings.DEBUG:
- # We don't want to accidentally expose too much data via errors
- raise exceptions.ValidationError(detail=f"Unexpected {err.__class__.__name__}")
-
- return query
-
- def validate(self, attrs):
- attrs = super().validate(attrs)
-
- # Falls back to the stored config so editing the query of an already-incremental view is
- # checked too. Otherwise a query that incremental cannot serve would save while the view
- # stays incremental, and only fail at the next run.
- config = attrs.get("incremental_config")
- if config is None and self.instance is not None:
- config = self.instance.incremental_config
- if not isinstance(config, dict) or not config.get("enabled"):
- return attrs
- if not config.get("incremental_key") or not config.get("unique_key"):
- return attrs
-
- query_changed = "query" in attrs
- query = attrs.get("query") or (self.instance.query if self.instance is not None else None)
- sql = (query or {}).get("query")
- if not isinstance(sql, str):
- raise serializers.ValidationError({"incremental": "This view has no query to make incremental."})
-
- from products.data_modeling.backend.facade.api import IncrementalConfig, check_incremental_eligibility
-
- # The stored column types describe the stored query, so they say nothing about a query being
- # replaced. The runtime guard still catches a nullable key on the first incremental run.
- column_types = None if query_changed or self.instance is None else self.instance.columns
- # The context only carries a database when the request touches the query or name; a
- # config-only PATCH still has to check `SELECT *` against real columns, so build one then.
- database = self.context.get("database") or Database.create_for(
- team_id=self.context["team_id"], user=cast(User, self.context["request"].user)
- )
- result = check_incremental_eligibility(
- sql,
- IncrementalConfig(
- incremental_key=config["incremental_key"],
- unique_key=tuple(config["unique_key"]),
- lookback_seconds=config.get("lookback_seconds", 0),
- ),
- column_types=_clickhouse_types(column_types),
- database=database,
- )
- if not result.eligible:
- raise serializers.ValidationError({"incremental": result.blockers})
- return attrs
-
- def validate_is_test(self, is_test):
- if is_test and not self.context["request"].user.is_staff:
- raise serializers.ValidationError("Only staff users can create test views.")
- return is_test
-
- def validate_folder(self, folder):
- if folder is not None and folder.team_id != self.context["team_id"]:
- raise serializers.ValidationError("Folder not found.")
- return folder
-
- def validate_name(self, name):
- # if it's an upsert, we don't want to validate the name
- if self.instance is not None and isinstance(self.instance, DataWarehouseSavedQuery):
- if self.instance.name == name:
- return name
-
- # has_table covers system/posthog tables and warehouse objects the requesting user can see; it's
- # user-filtered, so also resolve the name team-wide using get_view_or_table_by_name.
- # Otherwise a user with denied table could create another one with colliding name.
- if self.context["database"].has_table(name) or get_view_or_table_by_name(self.context["team_id"], name):
- raise serializers.ValidationError("A table or view with this name already exists. Choose a different name.")
-
- return name
-
-
-class DataWarehouseSavedQueryPagination(PageNumberPagination):
- page_size = 1000
-
-
-class DataWarehouseSavedQueryFolderSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
- created_by = UserBasicSerializer(read_only=True)
- view_count = serializers.IntegerField(read_only=True)
-
- class Meta:
- model = DataWarehouseSavedQueryFolder
- fields = ["id", "name", "created_at", "created_by", "view_count", "user_access_level"]
- read_only_fields = ["id", "created_at", "created_by", "view_count", "user_access_level"]
- extra_kwargs = {
- "name": {
- "help_text": "Display name for the folder used to organize saved queries in the SQL editor sidebar."
- }
- }
-
- def validate_name(self, name: str) -> str:
- normalized_name = name.strip()
- if not normalized_name:
- raise serializers.ValidationError("Folder name cannot be empty.")
-
- team_id = self.context["team_id"]
- queryset = DataWarehouseSavedQueryFolder.objects.filter(team_id=team_id, name=normalized_name)
- if self.instance is not None:
- queryset = queryset.exclude(pk=self.instance.pk)
-
- if queryset.exists():
- raise serializers.ValidationError("A folder with this name already exists.")
-
- return normalized_name
-
-
-class DataWarehouseSavedQueryFolderViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
- scope_object = "warehouse_view"
- queryset = DataWarehouseSavedQueryFolder.objects.all()
- serializer_class = DataWarehouseSavedQueryFolderSerializer
- pagination_class = None
- http_method_names = ["get", "post", "patch", "delete"]
- ordering = "name"
-
- def safely_get_queryset(self, queryset):
- return (
- queryset.filter(team_id=self.team_id)
- .select_related("created_by")
- .annotate(
- view_count=Coalesce(
- Subquery(
- DataWarehouseSavedQuery.objects.filter(folder=OuterRef("pk"), deleted=False)
- .order_by()
- .values("folder")
- .annotate(c=Count("id"))
- .values("c"),
- output_field=IntegerField(),
- ),
- 0,
- )
- )
- .order_by(self.ordering)
- )
-
- def perform_create(self, serializer):
- serializer.save(team_id=self.team_id, created_by=self.request.user)
-
- def destroy(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
- from products.data_modeling.backend.facade.api import HasDependentsError
-
- folder: DataWarehouseSavedQueryFolder = self.get_object()
- remaining_queries = {
- saved_query.id: saved_query
- for saved_query in DataWarehouseSavedQuery.objects.filter(folder=folder, deleted=False).select_related(
- "managed_viewset", "folder"
- )
- }
-
- while remaining_queries:
- deleted_ids: list[uuid.UUID] = []
-
- for saved_query_id, saved_query in remaining_queries.items():
- try:
- delete_saved_query(saved_query)
- deleted_ids.append(saved_query_id)
- except HasDependentsError:
- continue
-
- if not deleted_ids:
- blocked_names = ", ".join(sorted(saved_query.name for saved_query in remaining_queries.values()))
- raise serializers.ValidationError(
- f"Cannot delete this folder because these views still have dependencies outside the folder: {blocked_names}"
- )
-
- for saved_query_id in deleted_ids:
- remaining_queries.pop(saved_query_id, None)
-
- folder.delete()
- return response.Response(status=status.HTTP_204_NO_CONTENT)
-
-
-class SavedQueryResumeSerializer(serializers.Serializer):
- resumed = serializers.BooleanField(help_text="False when the query's materialization was not suspended.")
-
-
-class SavedQueryResumeSchedulesRequestSerializer(serializers.Serializer):
- """Body of the `resume_schedules` action."""
-
- view_ids = serializers.ListField(
- child=serializers.UUIDField(),
- allow_empty=False,
- help_text=(
- "Ids of the saved queries to resume. An id is ignored when it is not in this project, "
- "has been deleted, or you cannot edit it."
- ),
- )
-
-
-class SavedQueryLineageRequestSerializer(serializers.Serializer):
- """Body of the `ancestors` and `descendants` actions."""
-
- level = serializers.IntegerField(
- required=False,
- allow_null=True,
- min_value=1,
- help_text="How many hops to walk, so 1 gives the immediate neighbours. Omit to walk the whole cone.",
- )
-
-
-class SavedQueryAncestorsSerializer(serializers.Serializer):
- ancestors = serializers.ListField(
- child=serializers.CharField(),
- help_text="Ids of the saved queries and warehouse tables this query reads from, directly or "
- "through other queries, and the names of the PostHog tables among them.",
- )
-
-
-class SavedQueryDescendantsSerializer(serializers.Serializer):
- descendants = serializers.ListField(
- child=serializers.CharField(),
- help_text="Ids of the saved queries that read from this query, directly or through other queries.",
- )
-
-
-class SavedQueryDependenciesSerializer(serializers.Serializer):
- upstream_count = serializers.IntegerField(help_text="How many tables and queries this query reads from directly.")
- downstream_count = serializers.IntegerField(help_text="How many queries read from this query directly.")
-
-
-class IncrementalEligibilitySerializer(serializers.Serializer):
- """Whether a query can be materialized incrementally, and what stands in the way."""
-
- eligible = serializers.BooleanField(help_text="True when nothing blocks incremental materialization.")
- key_candidates = serializers.ListField(
- child=serializers.CharField(),
- help_text="Output columns that could be used as the incremental key. Excludes aggregates, "
- "columns whose type cannot serve as an advancing watermark (strings, booleans, arrays), "
- "and for a union only includes columns every branch produces.",
- )
- unique_key_candidates = serializers.ListField(
- child=serializers.CharField(),
- help_text="Output columns the unique key may be built from. A superset of key_candidates: "
- "identifying a row only needs equality, so strings qualify here even though they cannot "
- "be the incremental key.",
- )
- key_candidate_types = serializers.DictField(
- child=serializers.CharField(),
- help_text="Coarse type per candidate, keyed by column name: datetime, date, integer, "
- "decimal, float, string, or uuid. A candidate with no entry has a type the check could "
- "not determine.",
- )
- blockers = serializers.ListField(
- child=serializers.CharField(),
- help_text="Reasons this query cannot be incremental. Each names the construct responsible.",
- )
- warnings = serializers.ListField(
- child=serializers.CharField(),
- help_text="Things that still work but are worth knowing, such as a filter that cannot be "
- "pushed down so each run reads as much data as a full refresh.",
- )
-
-
-class CheckIncrementalThrottle(PersonalApiKeyOrUserRateThrottle):
- """check_incremental parses caller-supplied SQL synchronously on a read scope. The editor calls
- it on a debounce, so a per-caller budget far above typing speed only stops scripted floods of
- large bodies from tying up API workers."""
-
- scope = "check_incremental"
- rate = "120/minute"
-
-
-# The check parses synchronously on an API worker. The bound keeps a scripted flood of large bodies
-# from tying up workers while sitting well above any view the editor produces.
-CHECK_INCREMENTAL_MAX_QUERY_LENGTH = 256 * 1024
-
-
-class CheckIncrementalSerializer(serializers.Serializer):
- """Body of the `check_incremental` action: a query and an optional config to check it against."""
-
- query = serializers.CharField(max_length=CHECK_INCREMENTAL_MAX_QUERY_LENGTH, help_text="The HogQL query to check.")
- incremental_key = serializers.CharField(
- required=False,
- allow_null=True,
- help_text="Output column whose advancing value marks rows as new. Omit to only list candidates.",
- )
- unique_key = serializers.ListField(
- child=serializers.CharField(),
- required=False,
- allow_null=True,
- help_text="Output columns that identify a row. Must include every GROUP BY column.",
- )
- lookback_seconds = serializers.IntegerField(
- required=False,
- min_value=0,
- max_value=MAX_LOOKBACK_SECONDS,
- help_text="How far back before the watermark to re-read each run, to pick up late-arriving data.",
- )
-
-
-class SavedQueryRunSerializer(serializers.Serializer):
- """Body of the `run` action."""
-
- full_refresh = serializers.BooleanField(
- required=False,
- default=False,
- help_text="Rebuild the whole table instead of updating it incrementally. Has no effect on a "
- "view that is not incremental. This is how you reprocess history after changing what the "
- "query means without changing its text, or after upstream data was corrected.",
- )
-
-
-class SavedQueryMaterializeSerializer(serializers.Serializer):
- """Body of the `materialize` action: which cadence to enable materialization at."""
-
- sync_frequency = SyncFrequencyField(
- choices=MATERIALIZE_SYNC_FREQUENCY_CHOICES,
- allow_null=False,
- default=DEFAULT_MATERIALIZE_SYNC_FREQUENCY,
- help_text=(
- "How often to refresh the materialized table, defaulting to daily. Rejected with a 400 when it falls "
- "outside what the query's lineage allows: no more often than its sources deliver new data, and no less "
- "often than a downstream view or endpoint needs."
- ),
- )
-
-
-class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
- """
- Create, Read, Update and Delete Warehouse Tables.
- """
-
- scope_object = "warehouse_view"
- queryset = DataWarehouseSavedQuery.objects.all()
- serializer_class = DataWarehouseSavedQuerySerializer
- pagination_class = DataWarehouseSavedQueryPagination
- filter_backends = [filters.SearchFilter]
- search_fields = ["name"]
- ordering = "-created_at"
-
- def get_serializer_context(self) -> dict[str, Any]:
- context = super().get_serializer_context()
- request_data = getattr(self.request, "data", {})
- # Read actions stay out: building a database selects every view in the team, SQL body
- # included, and neither serializer reads it. Only the write paths below do, to check a
- # name collision and to resolve a query's source tables.
- should_include_database = self.action == "create" or (
- self.action in {"update", "partial_update"} and ("name" in request_data or "query" in request_data)
- )
-
- if should_include_database:
- context["database"] = Database.create_for(team_id=self.team_id, user=cast(User, self.request.user))
- return context
-
- def get_serializer_class(self):
- if self.action == "list":
- return DataWarehouseSavedQueryMinimalSerializer
- return DataWarehouseSavedQuerySerializer
-
- def safely_get_queryset(self, queryset):
- base_queryset = (
- queryset.prefetch_related(
- "created_by",
- "managed_viewset",
- "column_annotations",
- Prefetch(
- "datamodelingjob_set",
- queryset=DataModelingJob.objects.filter(engine=DataModelingJobEngine.CLICKHOUSE).order_by(
- "-last_run_at"
- )[:1],
- to_attr="jobs",
- ),
- )
- # Both serializers read `folder.id` and `folder.name`, so without the join Django
- # fetches the folder once per foldered view.
- .select_related("folder")
- .exclude(deleted=True)
- .order_by(self.ordering)
- )
-
- # Hide endpoint-origin saved queries from the list view — they belong to the endpoints UI.
- # Allow retrieve so the Node detail page can fetch them by ID.
- if self.action == "list":
- # The list serializer reads none of these large JSONB columns. Left in the SELECT,
- # Postgres detoasts each one per view, and a page holds up to a thousand views.
- base_queryset = base_queryset.exclude(origin=DataWarehouseSavedQuery.Origin.ENDPOINT).defer(
- "query", "external_tables", "incremental_state"
- )
-
- # Detect whether we should include managed views in the queryset
- is_managed_viewset_enabled = posthoganalytics.feature_enabled(
- "managed-viewsets",
- str(self.team.uuid),
- groups={
- "organization": str(self.team.organization_id),
- "project": str(self.team.id),
- },
- group_properties={
- "organization": {
- "id": str(self.team.organization_id),
- },
- "project": {
- "id": str(self.team.id),
- },
- },
- send_feature_flag_events=False,
- )
-
- if not is_managed_viewset_enabled:
- base_queryset = base_queryset.filter(managed_viewset__isnull=True)
-
- # Only the detail serializer returns `latest_history_id`, and the subquery costs a jsonb
- # key-path filter the GIN index on `detail` cannot serve, so keep it off the list page.
- if getattr(self, "action", None) == "retrieve":
- # Scoped to query edits (see QUERY_CHANGE_ACTIVITY_FILTER) so materialization syncs
- # don't advance the head.
- latest_activity = (
- ActivityLog.objects.filter(
- scope="DataWarehouseSavedQuery",
- item_id=Cast(OuterRef("id"), output_field=TextField()),
- team_id=self.team_id,
- **QUERY_CHANGE_ACTIVITY_FILTER,
- )
- .order_by("-created_at")
- .values("id")[:1]
- )
-
- return base_queryset.annotate(latest_activity_id=Subquery(latest_activity))
-
- return base_queryset
-
- def create(self, request, *args, **kwargs):
- # Check for UPSERT logic
- saved_query = DataWarehouseSavedQuery.objects.filter(
- team_id=self.team_id, name=request.data.get("name")
- ).first()
- if saved_query:
- # The UPSERT branch updates an existing row without going through get_object(),
- # so run object-level permission checks explicitly to honor per-object access controls.
- self.check_object_permissions(request, saved_query)
- serializer = self.get_serializer(saved_query, data=request.data, partial=True)
- serializer.is_valid(raise_exception=True)
- self.perform_update(serializer)
- return Response(serializer.data, status=status.HTTP_200_OK)
- else:
- serializer = self.get_serializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- # Create logic
- self.perform_create(serializer)
- return Response(serializer.data, status=status.HTTP_201_CREATED)
-
- def destroy(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
- from products.data_modeling.backend.facade.api import HasDependentsError
-
- instance: DataWarehouseSavedQuery = self.get_object()
- name = instance.name
- try:
- delete_saved_query(instance)
- except HasDependentsError:
- raise serializers.ValidationError(
- "Cannot delete this view because other views depend on it. Delete or update those views first."
- )
-
- log_activity(
- organization_id=self.team.organization_id,
- team_id=self.team_id,
- user=cast(User, request.user),
- was_impersonated=is_impersonated(request),
- item_id=instance.id,
- scope="DataWarehouseSavedQuery",
- activity="deleted",
- detail=Detail(name=name),
- )
-
- return response.Response(status=status.HTTP_204_NO_CONTENT)
-
- @extend_schema(request=SavedQueryRunSerializer, responses={200: None})
- @action(
- methods=["POST"],
- detail=True,
- required_scopes=["warehouse_view:write"],
- throttle_classes=[RunSavedQueryRateThrottle],
- )
- def run(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Run this saved query."""
- from products.data_modeling.backend.facade.api import (
- MissingDagNodeError,
- clear_incremental_state,
- materialize_saved_query,
- )
-
- body = SavedQueryRunSerializer(data=request.data)
- body.is_valid(raise_exception=True)
-
- saved_query = self.get_object()
-
- if body.validated_data["full_refresh"]:
- # Dropping the watermark is the whole mechanism: the next run finds no progress to
- # build on and rebuilds. Commit it before dispatch, and outside any transaction the
- # dispatch could roll back, or the worker reads the old watermark and runs
- # incrementally instead.
- clear_incremental_state(saved_query)
-
- try:
- materialize_saved_query(saved_query, triggered_by_id=request.user.pk)
- except MissingDagNodeError:
- raise exceptions.ValidationError(
- detail="This view isn't fully set up to materialize. Save the query again, then try syncing."
- )
-
- log_activity(
- organization_id=self.team.organization_id,
- team_id=self.team_id,
- user=cast(User, request.user),
- was_impersonated=is_impersonated(request),
- item_id=saved_query.id,
- scope="DataWarehouseSavedQuery",
- activity="sync_triggered",
- detail=Detail(name=saved_query.name),
- )
-
- return response.Response(status=status.HTTP_200_OK)
-
- @extend_schema(request=CheckIncrementalSerializer, responses={200: IncrementalEligibilitySerializer})
- @action(
- methods=["POST"],
- detail=False,
- required_scopes=["warehouse_view:read"],
- throttle_classes=[CheckIncrementalThrottle],
- )
- def check_incremental(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Report whether a query can be materialized incrementally, without running it.
-
- Parses the SQL only, so it is cheap enough to call from the editor as the user types. Lets
- the editor explain why the incremental option is unavailable before anything is saved.
- """
- from products.data_modeling.backend.facade.api import IncrementalConfig, check_incremental_eligibility
-
- body = CheckIncrementalSerializer(data=request.data)
- body.is_valid(raise_exception=True)
- data = body.validated_data
-
- config = None
- if data.get("incremental_key") and data.get("unique_key"):
- config = IncrementalConfig(
- incremental_key=data["incremental_key"],
- unique_key=tuple(data["unique_key"]),
- lookback_seconds=data.get("lookback_seconds", 0),
- )
-
- result = check_incremental_eligibility(
- data["query"],
- config,
- database=Database.create_for(team_id=self.team_id, user=cast(User, request.user)),
- )
- return response.Response(
- IncrementalEligibilitySerializer(
- {
- "eligible": result.eligible,
- "key_candidates": result.key_candidates,
- "unique_key_candidates": result.unique_key_candidates,
- "key_candidate_types": result.key_candidate_types,
- "blockers": result.blockers,
- "warnings": result.warnings,
- }
- ).data,
- status=status.HTTP_200_OK,
- )
-
- @extend_schema(request=None, responses={200: SavedQueryResumeSerializer})
- @action(methods=["POST"], detail=True, required_scopes=["warehouse_view:write"])
- def resume(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Resume materialization suspended after repeated failures.
-
- Scheduled runs skip a suspended model and everything downstream of it, so it cannot succeed
- its way back on its own.
- """
- from products.data_modeling.backend.facade.api import unsuspend_saved_query
-
- resumed = unsuspend_saved_query(self.get_object())
-
- return response.Response({"resumed": bool(resumed)}, status=status.HTTP_200_OK)
-
- @action(
- methods=["POST"],
- detail=True,
- required_scopes=["warehouse_view:write"],
- throttle_classes=[MaterializationRateThrottle],
- )
- def revert_materialization(self, request: request.Request, *args, **kwargs) -> response.Response:
- """
- Undo materialization, revert back to the original view.
- (i.e. delete the materialized table and the schedule)
- """
- saved_query: DataWarehouseSavedQuery = self.get_object()
-
- if saved_query.managed_viewset is not None:
- raise serializers.ValidationError("Cannot revert materialization of a query from a managed viewset.")
-
- saved_query.revert_materialization()
-
- # set data modeling node type to view
- try:
- from products.data_modeling.backend.facade.api import update_node_type
- from products.data_modeling.backend.facade.models import NodeType
-
- update_node_type(saved_query, NodeType.VIEW)
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to update node type to view", saved_query_name=saved_query.name)
-
- log_activity(
- organization_id=self.team.organization_id,
- team_id=self.team_id,
- user=cast(User, request.user),
- was_impersonated=is_impersonated(request),
- item_id=saved_query.id,
- scope="DataWarehouseSavedQuery",
- activity="materialization_disabled",
- detail=Detail(name=saved_query.name),
- )
-
- return response.Response(status=status.HTTP_200_OK)
-
- @extend_schema(request=SavedQueryMaterializeSerializer, responses={200: None})
- @action(
- methods=["POST"],
- detail=True,
- required_scopes=["warehouse_view:write"],
- throttle_classes=[MaterializationRateThrottle],
- )
- def materialize(self, request: request.Request, *args, **kwargs) -> response.Response:
- """
- Enable materialization for this saved query, at the requested sync frequency or daily.
- """
- saved_query: DataWarehouseSavedQuery = self.get_object()
-
- if saved_query.managed_viewset is not None:
- raise serializers.ValidationError("Cannot materialize a query from a managed viewset.")
-
- assert_user_can_read_query(saved_query.query, self.team_id, cast(User, request.user))
-
- params = SavedQueryMaterializeSerializer(data=request.data)
- params.is_valid(raise_exception=True)
- sync_frequency_interval = sync_frequency_to_sync_frequency_interval(params.validated_data["sync_frequency"])
-
- from products.data_modeling.backend.facade.api import (
- UnsatisfiableFrequencyError,
- UnsupportedFrequencyTargetError,
- check_saved_query_frequency_target,
- saved_query_target_bounds,
- )
-
- if sync_frequency_interval is not None:
- # Ask before writing, so the ordinary refusal never has to be undone below. Names only
- # what this caller may read, matching the bounds payload — otherwise one rejected
- # materialize reads back a node they were never shown.
- bounds = saved_query_target_bounds(self.team_id, saved_query.pk)
- try:
- check_saved_query_frequency_target(
- saved_query,
- sync_frequency_interval,
- visible_names=(
- visible_blocker_names(bounds, self.user_access_control, team_id=self.team_id) if bounds else {}
- ),
- )
- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:
- raise serializers.ValidationError(str(e))
-
- previous_interval = saved_query.sync_frequency_interval
- previously_materialized = saved_query.is_materialized
-
- saved_query.sync_frequency_interval = sync_frequency_interval
- saved_query.is_materialized = True
- saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])
-
- # Enable materialization - this handles model path setup and schedule creation
- # If this fails, it will set is_materialized = False
- try:
- saved_query.schedule_materialization(trigger_immediate_run=True, triggered_by_id=request.user.pk)
- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError):
- # The check above already refused every cadence the lineage forbids, so reaching here
- # means the lineage moved mid-request. Say so plainly rather than forwarding a message
- # built from unredacted names. `schedule_materialization` re-raises these without
- # applying its disable-on-failure contract, and this action is not inside an atomic
- # block, so undo the enable by hand: otherwise the 400 leaves is_materialized=True
- # behind and the UI reads the rejection as a success.
- saved_query.sync_frequency_interval = previous_interval
- saved_query.is_materialized = previously_materialized
- saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])
- raise serializers.ValidationError(
- "This view's lineage changed while we were setting it up. Reopen it and pick a cadence again."
- )
-
- # Refresh from DB to check if schedule_materialization set is_materialized = False on failure
- saved_query.refresh_from_db()
- if saved_query.is_materialized is False:
- return response.Response(
- {"error": "Materialization failed. Please try again or contact support."},
- status=status.HTTP_500_INTERNAL_SERVER_ERROR,
- )
-
- # set data modeling node type to matview
- try:
- from products.data_modeling.backend.facade.api import update_node_type
- from products.data_modeling.backend.facade.models import NodeType
-
- update_node_type(saved_query, NodeType.MAT_VIEW)
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to update node type to matview", saved_query_name=saved_query.name)
-
- log_activity(
- organization_id=self.team.organization_id,
- team_id=self.team_id,
- user=cast(User, request.user),
- was_impersonated=is_impersonated(request),
- item_id=saved_query.id,
- scope="DataWarehouseSavedQuery",
- activity="materialization_enabled",
- detail=Detail(
- name=saved_query.name,
- changes=[
- Change(
- field="sync_frequency_interval",
- action="changed",
- type="DataWarehouseSavedQuery",
- before=str(previous_interval) if previous_interval else None,
- after=str(sync_frequency_interval),
- ),
- ],
- ),
- )
-
- return response.Response(status=status.HTTP_200_OK)
-
- @extend_schema(request=SavedQueryResumeSchedulesRequestSerializer, responses={202: None})
- @action(methods=["POST"], detail=False, required_scopes=["warehouse_view:write"])
- def resume_schedules(self, request: request.Request, *args, **kwargs) -> response.Response:
- """
- Resume materialization for several models that were suspended after repeated failures.
-
- Accepts a list of view IDs in the request body: {"view_ids": ["id1", "id2", ...]}
- This endpoint is idempotent - calling it on models that are already running is safe.
- """
- from products.data_modeling.backend.facade.api import unsuspend_saved_query
-
- serializer = SavedQueryResumeSchedulesRequestSerializer(data=request.data)
- serializer.is_valid(raise_exception=True)
-
- # Skip rather than refuse, so one id the caller cannot edit does not cost them the rest of
- # the batch. Every skipped id looks the same from outside, whether it is absent, in another
- # project, deleted, or denied - the response would otherwise confirm that a model exists.
- candidates = list(
- DataWarehouseSavedQuery.objects.filter(
- id__in=serializer.validated_data["view_ids"], team_id=self.team_id
- ).exclude(deleted=True)
- )
- self.user_access_control.preload_object_access_controls(cast(list[Model], candidates))
- for saved_query in candidates:
- if self.user_access_control.check_access_level_for_object(saved_query, "editor"):
- unsuspend_saved_query(saved_query)
- return response.Response(status=status.HTTP_202_ACCEPTED)
-
- @extend_schema(request=SavedQueryLineageRequestSerializer, responses={200: SavedQueryAncestorsSerializer})
- @action(methods=["POST"], detail=True)
- def ancestors(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Return the ancestors of this saved query.
-
- By default, we return every ancestor. The `level` parameter bounds how many hops back
- to walk, so 1 gives the immediate parents.
- """
- saved_query = self.get_object()
- ancestors = _related_saved_queries(saved_query, upstream=True, max_depth=_parse_level(request))
- return response.Response({"ancestors": ancestors})
-
- @extend_schema(request=SavedQueryLineageRequestSerializer, responses={200: SavedQueryDescendantsSerializer})
- @action(methods=["POST"], detail=True)
- def descendants(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Return the descendants of this saved query.
-
- By default, we return every descendant. The `level` parameter bounds how many hops
- forward to walk, so 1 gives the immediate children.
- """
- saved_query = self.get_object()
- descendants = _related_saved_queries(saved_query, upstream=False, max_depth=_parse_level(request))
- return response.Response({"descendants": descendants})
-
- @action(methods=["GET"], detail=True, required_scopes=["activity_log:read"])
- def activity(self, request: request.Request, **kwargs):
- page_params = parse_activity_page_params(request)
-
- item_id = kwargs["pk"]
- if not DataWarehouseSavedQuery.objects.filter(id=item_id, team_id=self.team_id).exists():
- return Response(status=status.HTTP_404_NOT_FOUND)
-
- activity_page = load_activity(
- scope="DataWarehouseSavedQuery",
- team_id=self.team_id,
- item_ids=[str(item_id)],
- limit=page_params.limit,
- page=page_params.page,
- )
- return activity_page_response(activity_page, page_params.limit, page_params.page, request)
-
- @action(methods=["POST"], detail=True)
- def cancel(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Cancel a running saved query workflow."""
- saved_query = self.get_object()
-
- targets = {
- _CancelTarget(workflow_id=job.workflow_id, workflow_run_id=job.workflow_run_id)
- for job in DataModelingJob.objects.filter(
- team_id=self.team_id,
- saved_query=saved_query,
- status=DataModelingJob.Status.RUNNING,
- )
- if job.workflow_id
- }
-
- if not targets:
- return response.Response(
- {"error": "Cannot cancel a query that is not running"}, status=status.HTTP_400_BAD_REQUEST
- )
-
- temporal = sync_connect()
- failed = False
-
- for target in sorted(targets, key=lambda target: target.workflow_id):
- try:
- workflow_handle = temporal.get_workflow_handle(target.workflow_id, run_id=target.workflow_run_id)
- async_to_sync(workflow_handle.cancel)()
- except Exception as e:
- failed = True
- logger.exception(
- "Failed to cancel workflow",
- saved_query_id=str(saved_query.id),
- workflow_id=target.workflow_id,
- error=str(e),
- )
-
- if failed:
- return response.Response(
- {"error": "Failed to cancel workflow"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
- )
-
- saved_query.status = DataWarehouseSavedQuery.Status.CANCELLED
- saved_query.save()
-
- log_activity(
- organization_id=self.team.organization_id,
- team_id=self.team_id,
- user=cast(User, request.user),
- was_impersonated=is_impersonated(request),
- item_id=saved_query.id,
- scope="DataWarehouseSavedQuery",
- activity="sync_cancelled",
- detail=Detail(name=saved_query.name),
- )
-
- return response.Response(status=status.HTTP_200_OK)
-
- @extend_schema(request=None, responses={200: SavedQueryDependenciesSerializer})
- @action(methods=["GET"], detail=True)
- def dependencies(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Return the count of immediate upstream and downstream dependencies for this saved query."""
- saved_query = self.get_object()
- return response.Response(
- {
- "upstream_count": len(_related_saved_queries(saved_query, upstream=True, max_depth=1)),
- "downstream_count": len(_related_saved_queries(saved_query, upstream=False, max_depth=1)),
- }
- )
-
- @action(methods=["GET"], detail=True, required_scopes=["warehouse_view:read"])
- def run_history(self, request: request.Request, *args, **kwargs) -> response.Response:
- """Return the recent run history (up to 5 most recent) for this materialized view."""
- saved_query = self.get_object()
-
- # Get the 5 most recent runs
- jobs = (
- DataModelingJob.objects.filter(saved_query=saved_query)
- .order_by("-last_run_at")[:5]
- .values("status", "last_run_at")
- )
-
- run_history = [{"status": job["status"], "timestamp": job["last_run_at"]} for job in jobs]
-
- return response.Response({"run_history": run_history})
-
-
-def _parse_level(request: request.Request) -> int | None:
- """Read the `level` bound off a lineage request.
-
- No level means walk the whole cone. Zero or less would walk nothing and return an empty
- answer, so it is refused, as is anything that is not a whole number.
- """
- serializer = SavedQueryLineageRequestSerializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- return serializer.validated_data.get("level")
-
-
-def _related_saved_queries(saved_query: DataWarehouseSavedQuery, *, upstream: bool, max_depth: int | None) -> set[str]:
- """Walk the data modeling graph from a saved query and identify what it reaches.
-
- The walk starts from every node that stands for the query and unions what they reach: a
- saved query can hold a node in more than one DAG, and a query in a managed DAG is also
- represented by a proxy table node in each DAG that reads from it. Without the proxies a
- consumer would report the managed query upstream while the managed query reported no
- consumer downstream.
-
- Each reached node is identified the way the lineage endpoints have always identified it: a
- query by its saved-query id, an imported warehouse table by its `DataWarehouseTable` id, a
- cross-DAG proxy by the id of the saved query it stands in for, and a PostHog system table by
- its name. A table node carries the id in its properties
- (`saved_query_dag_sync.resolve_dependency_to_node`) rather than the `saved_query` FK.
- """
- start_node_ids = {
- str(node_id)
- for node_id in Node.objects.filter(team=saved_query.team)
- .filter(Q(saved_query=saved_query) | Q(properties__saved_query_id=str(saved_query.id)))
- .values_list("id", flat=True)
- }
- if not start_node_ids:
- return set()
-
- reached = _reachable_node_ids(saved_query.team_id, start_node_ids, upstream=upstream, max_depth=max_depth)
-
- identifiers: set[str] = set()
- for saved_query_id, name, properties in Node.objects.filter(team=saved_query.team, id__in=reached).values_list(
- "saved_query_id", "name", "properties"
- ):
- properties = properties or {}
- if saved_query_id is not None:
- identifiers.add(str(saved_query_id))
- elif properties.get("saved_query_id"):
- identifiers.add(str(properties["saved_query_id"]))
- elif properties.get("warehouse_table_id"):
- identifiers.add(str(properties["warehouse_table_id"]))
- else:
- identifiers.add(name)
- return identifiers
-
-
-def _reachable_node_ids(team_id: int, start_node_ids: set[str], *, upstream: bool, max_depth: int | None) -> set[str]:
- """Node ids reachable from `start_node_ids` within `max_depth` hops, the start nodes excluded.
-
- One query per hop, each reading the frontier's edges off the `Edge` foreign-key indexes, so
- the work is bounded by the cone that is reached rather than by every edge the team owns.
- Upstream follows edges into the frontier back to their sources; downstream follows edges
- out of it to their targets.
- """
- edges = Edge.objects.filter(team_id=team_id)
-
- reached: set[str] = set()
- frontier = set(start_node_ids)
- depth = 0
- while frontier and (max_depth is None or depth < max_depth):
- if upstream:
- neighbor_ids = edges.filter(target_id__in=frontier).values_list("source_id", flat=True)
- else:
- neighbor_ids = edges.filter(source_id__in=frontier).values_list("target_id", flat=True)
- frontier = {str(neighbor_id) for neighbor_id in neighbor_ids} - reached - start_node_ids
- reached |= frontier
- depth += 1
- return reached
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/__init__.py b/products/data_warehouse/backend/presentation/views/saved_query/__init__.py
new file mode 100644
index 000000000000..81d7cbbde3ca
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/__init__.py
@@ -0,0 +1 @@
+"""Saved-query API. One module per concern; import the module you need, not this package."""
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/editing.py b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
new file mode 100644
index 000000000000..1cae1231c480
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
@@ -0,0 +1,662 @@
+"""The writable saved-query serializer: validation, create, and update."""
+
+from typing import Any, cast
+
+from django.conf import settings
+from django.db import transaction
+
+import structlog
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import exceptions, serializers
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import Database
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.placeholders import FindPlaceholders
+from posthog.hogql.printer import prepare_and_print_ast
+
+from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
+from posthog.api.shared import UserBasicSerializer
+from posthog.errors import ExposedCHQueryError
+from posthog.exceptions_capture import capture_exception
+from posthog.helpers.impersonation import is_impersonated
+from posthog.models import Team, User
+from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, changes_between, log_activity
+from posthog.rbac.query_access import assert_user_can_read_query
+
+from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+from products.data_modeling.backend.facade.models import (
+ DataWarehouseSavedQuery,
+ DataWarehouseSavedQueryColumnAnnotation,
+)
+from products.data_tools.backend.facade.models import DataWarehouseSavedQueryFolder
+from products.data_warehouse.backend.presentation.views.column_annotation_base import upsert_annotation
+from products.warehouse_sources.backend.facade.hogql import (
+ get_view_or_table_by_name,
+ hogql_type_name_for_clickhouse_type,
+)
+from products.warehouse_sources.backend.facade.models import sync_frequency_to_sync_frequency_interval
+
+from . import incremental_config, sync_cadence, view_description, view_state
+
+logger = structlog.get_logger(__name__)
+
+
+def _view_types_validation_error(e: Exception) -> serializers.ValidationError:
+ # Column inference runs the HogQL-to-ClickHouse path, so a raw exception can carry stack
+ # traces, internal table or column names, and S3 URIs. Surface only the errors already marked
+ # user-safe; reduce everything else to its class name. Mirrors validate_query below, which
+ # keeps the full cause in error tracking and logs instead of the response.
+ if isinstance(e, ExposedHogQLError | ExposedCHQueryError):
+ return serializers.ValidationError(f"Failed to retrieve types for view: {e}")
+ return serializers.ValidationError(f"Failed to retrieve types for view: unexpected {type(e).__name__}")
+
+
+# A DataWarehouseSavedQuery's activity log also records materialization syncs and status
+# transitions (activity="sync_triggered", status changes) that advance the log without the query
+# being edited. Optimistic-concurrency ("modified by someone else") must key off the latest activity
+# that actually changed the query — otherwise every background sync of a materialized view looks
+# like a foreign edit and blocks the next save. This filter scopes activity lookups to query edits.
+QUERY_CHANGE_ACTIVITY_FILTER = {"detail__changes__contains": [{"field": "query"}]}
+
+
+class DataWarehouseSavedQuerySerializer(
+ view_state.DataWarehouseSavedQuerySerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer
+):
+ @extend_schema_field(
+ {
+ "type": "object",
+ "properties": {
+ "kind": {"type": "string", "enum": ["HogQLQuery"], "default": "HogQLQuery"},
+ "query": {"type": "string"},
+ },
+ "required": ["query"],
+ }
+ )
+ class QueryDefinitionField(serializers.JSONField):
+ pass
+
+ created_by = UserBasicSerializer(read_only=True)
+ columns = serializers.SerializerMethodField(read_only=True)
+ query = QueryDefinitionField(
+ help_text='HogQL query definition as a JSON object with a "query" key containing the SQL string and a "kind" key (always "HogQLQuery"). Format the SQL string multi-line with indentation and inline `--` comments for non-obvious logic — the SQL editor renders it verbatim, so avoid minified single-line SQL. Example: {"kind": "HogQLQuery", "query": "SELECT\\n event,\\n count() AS cnt\\nFROM events\\nGROUP BY event\\nLIMIT 100"}',
+ )
+ sync_frequency = sync_cadence.SyncFrequencyField(
+ help_text=(
+ "How often to materialize this view. One of '15min', '30min', '1hour', '6hour', '12hour', "
+ "'24hour', '7day', '30day', or 'never' to pause scheduled materialization. 15min is the fastest "
+ "cadence available. Null means no scheduled materialization. Read back after a write, this "
+ "reflects the cadence stored on the view's DAG node."
+ ),
+ )
+ sync_frequency_bounds = serializers.SerializerMethodField(
+ read_only=True, help_text=sync_cadence.SYNC_FREQUENCY_BOUNDS_HELP_TEXT
+ )
+ latest_history_id = serializers.SerializerMethodField(read_only=True)
+ last_run_at = serializers.SerializerMethodField(read_only=True)
+ status = serializers.SerializerMethodField(read_only=True)
+ latest_error = serializers.SerializerMethodField(read_only=True)
+ managed_viewset_kind = serializers.SerializerMethodField(read_only=True)
+ suspended = serializers.SerializerMethodField(read_only=True)
+ folder_id = TeamScopedPrimaryKeyRelatedField(
+ source="folder",
+ queryset=DataWarehouseSavedQueryFolder.objects.all(),
+ required=False,
+ allow_null=True,
+ help_text="Optional folder ID used to organize this view in the SQL editor sidebar.",
+ )
+ folder_name = serializers.CharField(
+ source="folder.name",
+ read_only=True,
+ allow_null=True,
+ help_text="Folder name used to organize this view in the SQL editor sidebar.",
+ )
+ edited_history_id = serializers.CharField(
+ write_only=True,
+ required=False,
+ allow_null=True,
+ help_text="Activity log ID from the last known edit. Used for conflict detection.",
+ )
+ soft_update = serializers.BooleanField(
+ write_only=True,
+ required=False,
+ allow_null=True,
+ help_text="If true, skip column inference and validation. For saving drafts.",
+ )
+ dag_id = serializers.UUIDField(
+ write_only=True, required=False, allow_null=True, help_text="Optional DAG to place this view into"
+ )
+ description = view_description.ViewDescriptionField(
+ required=False, allow_blank=True, allow_null=True, help_text=view_description.VIEW_DESCRIPTION_HELP_TEXT
+ )
+ incremental = incremental_config.IncrementalConfigSerializer(
+ source="incremental_config",
+ required=False,
+ allow_null=True,
+ help_text="Update the materialized table in place instead of rebuilding it. Null or absent "
+ "means every run rebuilds the whole table.",
+ )
+ incremental_state = incremental_config.IncrementalStateSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="How far incremental materialization has progressed. Null until the first run "
+ "records any. Written by the materialization run, not by this API.",
+ )
+
+ class Meta:
+ model = DataWarehouseSavedQuery
+ fields = [
+ "id",
+ "deleted",
+ "name",
+ "query",
+ "incremental",
+ "incremental_state",
+ "created_by",
+ "created_at",
+ "updated_at",
+ "description",
+ "sync_frequency",
+ "sync_frequency_bounds",
+ "columns",
+ "status",
+ "last_run_at",
+ "managed_viewset_kind",
+ "folder_id",
+ "folder_name",
+ "latest_error",
+ "edited_history_id",
+ "latest_history_id",
+ "soft_update",
+ "dag_id",
+ "is_materialized",
+ "origin",
+ "is_test",
+ "expires_at",
+ "user_access_level",
+ "suspended",
+ ]
+ read_only_fields = [
+ "id",
+ "created_by",
+ "created_at",
+ "updated_at",
+ "columns",
+ "incremental_state",
+ "status",
+ "last_run_at",
+ "managed_viewset_kind",
+ "sync_frequency_bounds",
+ "folder_name",
+ "latest_error",
+ "latest_history_id",
+ "user_access_level",
+ "is_materialized",
+ "origin",
+ "expires_at",
+ "suspended",
+ ]
+ extra_kwargs = {
+ "soft_update": {"write_only": True},
+ "name": {
+ "help_text": "Unique name for the view. Used as the table name in HogQL queries and the node name in the data modeling Node.",
+ },
+ }
+
+ def _write_view_description(self, view: DataWarehouseSavedQuery, description: str | None) -> None:
+ team_id = self.context["team_id"]
+ if description:
+ upsert_annotation(
+ DataWarehouseSavedQueryColumnAnnotation,
+ team_id,
+ parent_field="saved_query",
+ parent=view,
+ column_name="",
+ description=description,
+ )
+ else:
+ DataWarehouseSavedQueryColumnAnnotation.objects.for_team(team_id).filter(
+ saved_query=view, column_name=""
+ ).delete()
+
+ @extend_schema_field(serializers.IntegerField(allow_null=True))
+ def get_latest_history_id(self, view: DataWarehouseSavedQuery):
+ # First check if we have an activity log from a recent creation/update
+ if (
+ "activity_log" in self.context
+ and self.context["activity_log"]
+ and self.context["activity_log"].item_id == str(view.id)
+ ):
+ return self.context["activity_log"].id
+
+ # Otherwise check for annotated field from queryset
+ if hasattr(view, "latest_activity_id"):
+ return view.latest_activity_id
+
+ return None
+
+ @extend_schema_field(
+ serializers.DictField(
+ child=view_state.SavedQuerySuspensionSerializer(),
+ help_text="Engines this query's materialization is suspended for after repeated failures. "
+ "Suspended engines are skipped by scheduled runs until the query is resumed.",
+ )
+ )
+ def get_suspended(self, view: DataWarehouseSavedQuery) -> dict[str, Any]:
+ from products.data_modeling.backend.facade.api import suspension_state_for_saved_query
+
+ return {
+ engine: view_state.SavedQuerySuspensionSerializer(entry).data
+ for engine, entry in suspension_state_for_saved_query(view).items()
+ }
+
+ def create(self, validated_data):
+ validated_data["team_id"] = self.context["team_id"]
+ validated_data["created_by"] = self.context["request"].user
+ validated_data["origin"] = DataWarehouseSavedQuery.Origin.DATA_WAREHOUSE
+ soft_update = validated_data.pop("soft_update", False)
+ dag_id = validated_data.pop("dag_id", None)
+ has_description = "description" in validated_data
+ description = validated_data.pop("description", None)
+ # Sync cadence is configured via materialization, not on creation — drop it so it
+ # isn't passed to the model constructor.
+ validated_data.pop("sync_frequency", None)
+ view = DataWarehouseSavedQuery(**validated_data)
+
+ if not soft_update:
+ 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.external_tables = view.get_s3_tables(database=self.context["database"])
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to retrieve types for view %s", view.name)
+ raise _view_types_validation_error(e)
+
+ with transaction.atomic():
+ view.save()
+ if has_description:
+ self._write_view_description(view, description)
+ try:
+ view.setup_model_paths()
+ except Exception:
+ # For now, do not fail saved query creation if we cannot model-ize it.
+ # Later, after bugs and errors have been ironed out, we may tie these two
+ # closer together.
+ logger.exception("Failed to create model path when creating view %s", view.name)
+
+ team = Team.objects.get(id=view.team_id)
+
+ activity_log = log_activity(
+ organization_id=team.organization_id,
+ team_id=team.id,
+ user=view.created_by,
+ was_impersonated=is_impersonated(self.context["request"]),
+ item_id=view.id,
+ scope="DataWarehouseSavedQuery",
+ activity="created",
+ detail=Detail(
+ name=view.name,
+ changes=[
+ Change(
+ field="query",
+ action="created",
+ type="DataWarehouseSavedQuery",
+ before=None,
+ after=view.query,
+ )
+ ],
+ ),
+ )
+
+ # Store the activity log in the serializer context
+ if activity_log:
+ self.context["activity_log"] = activity_log
+ # best effort sync to new data modeling DAG representation
+ try:
+ from products.data_modeling.backend.facade.api import sync_saved_query_to_dag
+ from products.data_modeling.backend.facade.models import DAG
+
+ dag_obj = None
+ if dag_id:
+ try:
+ dag_obj = DAG.objects.get(id=dag_id, team_id=view.team_id)
+ except DAG.DoesNotExist:
+ raise serializers.ValidationError({"dag_id": "Invalid DAG ID or DAG does not belong to this team"})
+ sync_saved_query_to_dag(view, dag=dag_obj)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ return view
+
+ def update(self, instance: Any, validated_data: Any) -> Any:
+ dag_id = validated_data.pop("dag_id", None)
+ has_description = "description" in validated_data
+ description = validated_data.pop("description", None)
+
+ if instance.managed_viewset is not None:
+ raise serializers.ValidationError("Cannot update a query from a managed viewset")
+
+ try:
+ before_update = DataWarehouseSavedQuery.objects.get(pk=instance.id)
+ except DataWarehouseSavedQuery.DoesNotExist:
+ before_update = None
+
+ sync_frequency = validated_data.pop("sync_frequency", None)
+
+ if sync_frequency and sync_frequency != "never":
+ # Scheduling a view is the same grant as materializing it directly.
+ assert_user_can_read_query(
+ instance.query,
+ self.context["team_id"],
+ cast(User, self.context["request"].user),
+ database=self.context.get("database"),
+ )
+
+ # The frequency writes through to the DAG node's freshness target.
+ frequency_changed = bool(sync_frequency)
+
+ soft_update = validated_data.pop("soft_update", False)
+
+ with transaction.atomic():
+ locked_instance = DataWarehouseSavedQuery.objects.select_for_update().get(pk=instance.pk)
+
+ # Get latest activity log for this model
+
+ if validated_data.get("query", None) and not soft_update:
+ edited_history_id = self.context["request"].data.get("edited_history_id", None)
+ latest_activity_id = (
+ ActivityLog.objects.filter(
+ team_id=locked_instance.team_id,
+ item_id=locked_instance.id,
+ scope="DataWarehouseSavedQuery",
+ **QUERY_CHANGE_ACTIVITY_FILTER,
+ )
+ .order_by("-created_at")
+ .values_list("id", flat=True)
+ .first()
+ )
+
+ if str(edited_history_id) != str(latest_activity_id):
+ raise serializers.ValidationError("The query was modified by someone else.")
+
+ if frequency_changed:
+ # The node target is the only store of frequency intent. The interval column
+ # stays NULL so a stale v1 schedule can never be revived from it.
+ locked_instance.sync_frequency_interval = None
+ validated_data["sync_frequency_interval"] = None
+
+ view: DataWarehouseSavedQuery = super().update(locked_instance, validated_data)
+
+ if frequency_changed:
+ from products.data_modeling.backend.facade.api import (
+ UnsatisfiableFrequencyError,
+ UnsupportedFrequencyTargetError,
+ apply_saved_query_frequency_target,
+ declared_targets_by_saved_query,
+ saved_query_target_bounds,
+ )
+
+ target = (
+ None if sync_frequency == "never" else sync_frequency_to_sync_frequency_interval(sync_frequency)
+ )
+ previous_target = declared_targets_by_saved_query(view.team_id, [view.pk]).get(str(view.pk))
+ # A refusal names what blocks the cadence, so it obeys the same grants the read
+ # payload does — otherwise one rejected PATCH reads back a name the caller was
+ # never shown. Withheld nodes fall back to generic prose inside the refusal.
+ bounds = saved_query_target_bounds(view.team_id, view.pk)
+ visible = (
+ sync_cadence.visible_blocker_names(bounds, self.user_access_control, team_id=view.team_id)
+ if bounds is not None
+ else {}
+ )
+ try:
+ # Validates inside the transaction (a rejected frequency rolls the whole
+ # update back) and queues the schedule reconcile for after commit.
+ nodes_written = apply_saved_query_frequency_target(view, target, visible_names=visible)
+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:
+ raise serializers.ValidationError(str(e))
+ if target is not None and nodes_written == 0:
+ raise serializers.ValidationError(
+ "Cannot set a materialization frequency: this view is not wired into the data "
+ "modeling DAG yet. Re-save the view to create its node, then set the frequency."
+ )
+
+ if has_description:
+ self._write_view_description(view, description)
+
+ # Only update columns and status if the query has changed
+ if "query" in validated_data:
+ 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.external_tables = view.get_s3_tables(database=self.context["database"])
+ except RecursionError:
+ raise serializers.ValidationError("Model contains a cycle")
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to retrieve types for view %s", view.name)
+ raise _view_types_validation_error(e)
+
+ view.status = DataWarehouseSavedQuery.Status.MODIFIED
+ view.save()
+
+ try:
+ view.setup_model_paths()
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to update model path when updating view %s", view.name)
+
+ team = Team.objects.get(id=view.team_id)
+
+ changes = changes_between("DataWarehouseSavedQuery", previous=before_update, current=view)
+ changes = [
+ Change(
+ type=change.type,
+ action=change.action,
+ field=change.field,
+ before=getattr(change.before, "name", change.before) if change.field == "folder" else change.before,
+ after=getattr(change.after, "name", change.after) if change.field == "folder" else change.after,
+ )
+ for change in changes
+ ]
+ if frequency_changed and previous_target != target:
+ # The cadence lives on the DAG node, so changes_between() sees nothing and
+ # log_activity would discard the whole updated entry as a no-op.
+ changes.append(
+ Change(
+ type="DataWarehouseSavedQuery",
+ action="changed",
+ field="sync_frequency_interval",
+ before=str(previous_target) if previous_target is not None else None,
+ after=str(target) if target is not None else None,
+ )
+ )
+ activity_log = log_activity(
+ organization_id=team.organization_id,
+ team_id=team.id,
+ user=self.context["request"].user,
+ was_impersonated=is_impersonated(self.context["request"]),
+ item_id=view.id,
+ scope="DataWarehouseSavedQuery",
+ activity="updated",
+ detail=Detail(name=view.name, changes=changes),
+ )
+
+ # Store the activity log in the serializer context
+ if activity_log:
+ self.context["activity_log"] = activity_log
+ else:
+ # get latest query-changing activity log for this model (see QUERY_CHANGE_ACTIVITY_FILTER)
+ latest_activity_log = (
+ ActivityLog.objects.filter(
+ team_id=locked_instance.team_id,
+ item_id=locked_instance.id,
+ scope="DataWarehouseSavedQuery",
+ **QUERY_CHANGE_ACTIVITY_FILTER,
+ )
+ .order_by("-created_at")
+ .first()
+ )
+ self.context["activity_log"] = latest_activity_log
+ # best effort sync to new data modeling DAG representation
+ if "query" in validated_data:
+ try:
+ from products.data_modeling.backend.facade.api import sync_saved_query_to_dag
+ from products.data_modeling.backend.facade.models import DAG
+
+ dag_obj = None
+ if dag_id:
+ dag_obj = DAG.objects.filter(id=dag_id, team_id=view.team_id).first()
+ sync_saved_query_to_dag(view, dag=dag_obj)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ return view
+
+ def validate_query(self, query):
+ if not isinstance(query, dict):
+ raise exceptions.ValidationError(
+ detail=(
+ 'Query must be a JSON object with a "query" key, '
+ f"got {type(query).__name__}. "
+ 'Example: {"kind": "HogQLQuery", "query": "SELECT * FROM events WHERE timestamp >= now() - INTERVAL 7 DAY LIMIT 100"}'
+ )
+ )
+ if not isinstance(query.get("query"), str) or not query["query"].strip():
+ raise exceptions.ValidationError(
+ detail='Query object must contain a non-empty "query" key with the SQL string.'
+ )
+
+ team_id = self.context["team_id"]
+ user = self.context["request"].user
+
+ context = HogQLContext(team_id=team_id, user=user, enable_select_queries=True)
+ try:
+ select_ast = parse_select(query["query"])
+
+ find_placeholders = FindPlaceholders()
+ find_placeholders.visit(select_ast)
+ except ExposedHogQLError as err:
+ raise exceptions.ValidationError(detail=f"Invalid query: {err}")
+ if len(find_placeholders.placeholder_fields) > 0:
+ placeholder = find_placeholders.placeholder_fields.pop()
+ placeholder_string = ".".join(str(field) for field in placeholder if field is not None)
+ raise exceptions.ValidationError(
+ detail=f"Variables like {'{'}{placeholder_string}{'}'} are not allowed in views"
+ )
+ elif find_placeholders.placeholder_expressions or find_placeholders.has_filters:
+ raise exceptions.ValidationError(detail="Filters and placeholder expressions are not allowed in views")
+
+ try:
+ prepare_and_print_ast(
+ node=select_ast,
+ context=context,
+ dialect="clickhouse",
+ stack=None,
+ settings=None,
+ )
+ except Exception as err:
+ if isinstance(err, ExposedHogQLError):
+ error = str(err)
+ raise exceptions.ValidationError(detail=f"Invalid query: {error}")
+ elif not settings.DEBUG:
+ # We don't want to accidentally expose too much data via errors
+ raise exceptions.ValidationError(detail=f"Unexpected {err.__class__.__name__}")
+
+ return query
+
+ def validate(self, attrs):
+ attrs = super().validate(attrs)
+
+ # Falls back to the stored config so editing the query of an already-incremental view is
+ # checked too. Otherwise a query that incremental cannot serve would save while the view
+ # stays incremental, and only fail at the next run.
+ config = attrs.get("incremental_config")
+ if config is None and self.instance is not None:
+ config = self.instance.incremental_config
+ if not isinstance(config, dict) or not config.get("enabled"):
+ return attrs
+ if not config.get("incremental_key") or not config.get("unique_key"):
+ return attrs
+
+ query_changed = "query" in attrs
+ query = attrs.get("query") or (self.instance.query if self.instance is not None else None)
+ sql = (query or {}).get("query")
+ if not isinstance(sql, str):
+ raise serializers.ValidationError({"incremental": "This view has no query to make incremental."})
+
+ from products.data_modeling.backend.facade.api import IncrementalConfig, check_incremental_eligibility
+
+ # The stored column types describe the stored query, so they say nothing about a query being
+ # replaced. The runtime guard still catches a nullable key on the first incremental run.
+ column_types = None if query_changed or self.instance is None else self.instance.columns
+ # The context only carries a database when the request touches the query or name; a
+ # config-only PATCH still has to check `SELECT *` against real columns, so build one then.
+ database = self.context.get("database") or Database.create_for(
+ team_id=self.context["team_id"], user=cast(User, self.context["request"].user)
+ )
+ result = check_incremental_eligibility(
+ sql,
+ IncrementalConfig(
+ incremental_key=config["incremental_key"],
+ unique_key=tuple(config["unique_key"]),
+ lookback_seconds=config.get("lookback_seconds", 0),
+ ),
+ column_types=incremental_config._clickhouse_types(column_types),
+ database=database,
+ )
+ if not result.eligible:
+ raise serializers.ValidationError({"incremental": result.blockers})
+ return attrs
+
+ def validate_is_test(self, is_test):
+ if is_test and not self.context["request"].user.is_staff:
+ raise serializers.ValidationError("Only staff users can create test views.")
+ return is_test
+
+ def validate_folder(self, folder):
+ if folder is not None and folder.team_id != self.context["team_id"]:
+ raise serializers.ValidationError("Folder not found.")
+ return folder
+
+ def validate_name(self, name):
+ # if it's an upsert, we don't want to validate the name
+ if self.instance is not None and isinstance(self.instance, DataWarehouseSavedQuery):
+ if self.instance.name == name:
+ return name
+
+ # has_table covers system/posthog tables and warehouse objects the requesting user can see; it's
+ # user-filtered, so also resolve the name team-wide using get_view_or_table_by_name.
+ # Otherwise a user with denied table could create another one with colliding name.
+ if self.context["database"].has_table(name) or get_view_or_table_by_name(self.context["team_id"], name):
+ raise serializers.ValidationError("A table or view with this name already exists. Choose a different name.")
+
+ return name
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/folders.py b/products/data_warehouse/backend/presentation/views/saved_query/folders.py
new file mode 100644
index 000000000000..4c2591db4203
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/folders.py
@@ -0,0 +1,116 @@
+"""Saved-query folders: the serializer and the viewset that organize views in the SQL editor."""
+
+import uuid
+from typing import Any
+
+from django.db.models import Count, IntegerField, OuterRef, Subquery
+from django.db.models.functions import Coalesce
+
+from rest_framework import request, response, serializers, status, viewsets
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+
+from products.access_control.backend.presentation.access_control import (
+ AccessControlViewSetMixin,
+ UserAccessControlSerializerMixin,
+)
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_tools.backend.facade.models import DataWarehouseSavedQueryFolder
+
+from . import lifecycle
+
+
+class DataWarehouseSavedQueryFolderSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
+ created_by = UserBasicSerializer(read_only=True)
+ view_count = serializers.IntegerField(read_only=True)
+
+ class Meta:
+ model = DataWarehouseSavedQueryFolder
+ fields = ["id", "name", "created_at", "created_by", "view_count", "user_access_level"]
+ read_only_fields = ["id", "created_at", "created_by", "view_count", "user_access_level"]
+ extra_kwargs = {
+ "name": {
+ "help_text": "Display name for the folder used to organize saved queries in the SQL editor sidebar."
+ }
+ }
+
+ def validate_name(self, name: str) -> str:
+ normalized_name = name.strip()
+ if not normalized_name:
+ raise serializers.ValidationError("Folder name cannot be empty.")
+
+ team_id = self.context["team_id"]
+ queryset = DataWarehouseSavedQueryFolder.objects.filter(team_id=team_id, name=normalized_name)
+ if self.instance is not None:
+ queryset = queryset.exclude(pk=self.instance.pk)
+
+ if queryset.exists():
+ raise serializers.ValidationError("A folder with this name already exists.")
+
+ return normalized_name
+
+
+class DataWarehouseSavedQueryFolderViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
+ scope_object = "warehouse_view"
+ queryset = DataWarehouseSavedQueryFolder.objects.all()
+ serializer_class = DataWarehouseSavedQueryFolderSerializer
+ pagination_class = None
+ http_method_names = ["get", "post", "patch", "delete"]
+ ordering = "name"
+
+ def safely_get_queryset(self, queryset):
+ return (
+ queryset.filter(team_id=self.team_id)
+ .select_related("created_by")
+ .annotate(
+ view_count=Coalesce(
+ Subquery(
+ DataWarehouseSavedQuery.objects.filter(folder=OuterRef("pk"), deleted=False)
+ .order_by()
+ .values("folder")
+ .annotate(c=Count("id"))
+ .values("c"),
+ output_field=IntegerField(),
+ ),
+ 0,
+ )
+ )
+ .order_by(self.ordering)
+ )
+
+ def perform_create(self, serializer):
+ serializer.save(team_id=self.team_id, created_by=self.request.user)
+
+ def destroy(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
+ from products.data_modeling.backend.facade.api import HasDependentsError
+
+ folder: DataWarehouseSavedQueryFolder = self.get_object()
+ remaining_queries = {
+ saved_query.id: saved_query
+ for saved_query in DataWarehouseSavedQuery.objects.filter(folder=folder, deleted=False).select_related(
+ "managed_viewset", "folder"
+ )
+ }
+
+ while remaining_queries:
+ deleted_ids: list[uuid.UUID] = []
+
+ for saved_query_id, saved_query in remaining_queries.items():
+ try:
+ lifecycle.delete_saved_query(saved_query)
+ deleted_ids.append(saved_query_id)
+ except HasDependentsError:
+ continue
+
+ if not deleted_ids:
+ blocked_names = ", ".join(sorted(saved_query.name for saved_query in remaining_queries.values()))
+ raise serializers.ValidationError(
+ f"Cannot delete this folder because these views still have dependencies outside the folder: {blocked_names}"
+ )
+
+ for saved_query_id in deleted_ids:
+ remaining_queries.pop(saved_query_id, None)
+
+ folder.delete()
+ return response.Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/incremental_config.py b/products/data_warehouse/backend/presentation/views/saved_query/incremental_config.py
new file mode 100644
index 000000000000..de3930a3dae7
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/incremental_config.py
@@ -0,0 +1,146 @@
+"""Incremental materialization: its config, its recorded state, and the eligibility check."""
+
+from typing import Any
+
+from rest_framework import serializers
+
+from posthog.rate_limit import PersonalApiKeyOrUserRateThrottle
+
+from products.data_modeling.backend.facade.api import MAX_LOOKBACK_SECONDS
+
+
+def _clickhouse_types(columns: Any) -> dict[str, str] | None:
+ """Pull the ClickHouse type out of each entry in a saved query's stored `columns` blob.
+
+ Only used to spot a nullable unique key, which would silently duplicate rows on every run.
+ """
+ if not isinstance(columns, dict):
+ return None
+ types: dict[str, str] = {}
+ for name, meta in columns.items():
+ if isinstance(meta, dict) and isinstance(meta.get("clickhouse"), str):
+ types[name] = meta["clickhouse"]
+ return types or None
+
+
+class IncrementalConfigSerializer(serializers.Serializer):
+ """How a view updates its materialized table in place rather than rebuilding it."""
+
+ enabled = serializers.BooleanField(
+ default=False, help_text="Whether runs update the table incrementally instead of rebuilding it."
+ )
+ incremental_key = serializers.CharField(
+ help_text="Output column whose advancing value marks rows as new. Each run reads only rows at "
+ "or after the last run's highest value for it. When the query groups, this must be one of the "
+ "grouped columns, so every group a run touches is recomputed in full.",
+ )
+ unique_key = serializers.ListField(
+ child=serializers.CharField(),
+ allow_empty=False,
+ help_text="Output columns that identify a row, used to match recomputed rows against stored "
+ "ones. Must include every GROUP BY column. These columns can never be null.",
+ )
+ lookback_seconds = serializers.IntegerField(
+ required=False,
+ default=0,
+ min_value=0,
+ max_value=MAX_LOOKBACK_SECONDS,
+ help_text="How far back before the last run's high point to re-read, so late-arriving data is "
+ "picked up. Only applies when the incremental key is a date or time.",
+ )
+
+
+class IncrementalStateSerializer(serializers.Serializer):
+ """Read-only progress written by the materialization run."""
+
+ watermark = serializers.CharField(
+ allow_null=True,
+ required=False,
+ help_text="Highest incremental key value written so far. The next run starts here.",
+ )
+ definition_fingerprint = serializers.CharField(
+ allow_null=True,
+ required=False,
+ help_text="Fingerprint of the query, incremental key, and unique key the stored rows were "
+ "built from. When it stops matching, the next run rebuilds the whole table. Lookback is "
+ "not part of it: changing lookback never forces a rebuild.",
+ )
+ last_full_refresh_at = serializers.CharField(
+ allow_null=True, required=False, help_text="When the table was last rebuilt from scratch."
+ )
+ last_run_mode = serializers.ChoiceField(
+ choices=[("incremental", "incremental"), ("full_refresh", "full_refresh")],
+ allow_null=True,
+ required=False,
+ help_text="Whether the last run updated the table or rebuilt it.",
+ )
+
+
+class IncrementalEligibilitySerializer(serializers.Serializer):
+ """Whether a query can be materialized incrementally, and what stands in the way."""
+
+ eligible = serializers.BooleanField(help_text="True when nothing blocks incremental materialization.")
+ key_candidates = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Output columns that could be used as the incremental key. Excludes aggregates, "
+ "columns whose type cannot serve as an advancing watermark (strings, booleans, arrays), "
+ "and for a union only includes columns every branch produces.",
+ )
+ unique_key_candidates = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Output columns the unique key may be built from. A superset of key_candidates: "
+ "identifying a row only needs equality, so strings qualify here even though they cannot "
+ "be the incremental key.",
+ )
+ key_candidate_types = serializers.DictField(
+ child=serializers.CharField(),
+ help_text="Coarse type per candidate, keyed by column name: datetime, date, integer, "
+ "decimal, float, string, or uuid. A candidate with no entry has a type the check could "
+ "not determine.",
+ )
+ blockers = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Reasons this query cannot be incremental. Each names the construct responsible.",
+ )
+ warnings = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Things that still work but are worth knowing, such as a filter that cannot be "
+ "pushed down so each run reads as much data as a full refresh.",
+ )
+
+
+class CheckIncrementalThrottle(PersonalApiKeyOrUserRateThrottle):
+ """check_incremental parses caller-supplied SQL synchronously on a read scope. The editor calls
+ it on a debounce, so a per-caller budget far above typing speed only stops scripted floods of
+ large bodies from tying up API workers."""
+
+ scope = "check_incremental"
+ rate = "120/minute"
+
+
+# The check parses synchronously on an API worker. The bound keeps a scripted flood of large bodies
+# from tying up workers while sitting well above any view the editor produces.
+CHECK_INCREMENTAL_MAX_QUERY_LENGTH = 256 * 1024
+
+
+class CheckIncrementalSerializer(serializers.Serializer):
+ """Body of the `check_incremental` action: a query and an optional config to check it against."""
+
+ query = serializers.CharField(max_length=CHECK_INCREMENTAL_MAX_QUERY_LENGTH, help_text="The HogQL query to check.")
+ incremental_key = serializers.CharField(
+ required=False,
+ allow_null=True,
+ help_text="Output column whose advancing value marks rows as new. Omit to only list candidates.",
+ )
+ unique_key = serializers.ListField(
+ child=serializers.CharField(),
+ required=False,
+ allow_null=True,
+ help_text="Output columns that identify a row. Must include every GROUP BY column.",
+ )
+ lookback_seconds = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ max_value=MAX_LOOKBACK_SECONDS,
+ help_text="How far back before the watermark to re-read each run, to pick up late-arriving data.",
+ )
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/lifecycle.py b/products/data_warehouse/backend/presentation/views/saved_query/lifecycle.py
new file mode 100644
index 000000000000..3dccb246166e
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/lifecycle.py
@@ -0,0 +1,39 @@
+"""Deleting a saved query: its DAG node, its joins, and its materialized table."""
+
+from django.db.models import Q
+
+import structlog
+from rest_framework import serializers
+
+from posthog.exceptions_capture import capture_exception
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_tools.backend.facade.models import DataWarehouseJoin
+
+logger = structlog.get_logger(__name__)
+
+
+def delete_saved_query(saved_query: DataWarehouseSavedQuery) -> None:
+ from products.data_modeling.backend.facade.api import HasDependentsError, delete_node_from_dag
+
+ if saved_query.managed_viewset is not None:
+ raise serializers.ValidationError(
+ "Cannot delete a query from a managed viewset directly. Disable the managed viewset instead."
+ )
+
+ try:
+ delete_node_from_dag(saved_query)
+ except HasDependentsError:
+ raise
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to delete node for saved query", saved_query_name=saved_query.name)
+
+ for join in DataWarehouseJoin.objects.filter(
+ Q(team_id=saved_query.team_id)
+ & (Q(source_table_name=saved_query.name) | Q(joining_table_name=saved_query.name))
+ ).exclude(deleted=True):
+ join.soft_delete()
+
+ saved_query.revert_materialization()
+ saved_query.soft_delete()
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/lineage.py b/products/data_warehouse/backend/presentation/views/saved_query/lineage.py
new file mode 100644
index 000000000000..6a8a5bd14bb8
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/lineage.py
@@ -0,0 +1,115 @@
+"""Walking a saved query's ancestors and descendants through the data modeling DAG."""
+
+from django.db.models import Q
+
+from rest_framework import request, serializers
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery, Edge, Node
+
+
+class SavedQueryLineageRequestSerializer(serializers.Serializer):
+ """Body of the `ancestors` and `descendants` actions."""
+
+ level = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ min_value=1,
+ help_text="How many hops to walk, so 1 gives the immediate neighbours. Omit to walk the whole cone.",
+ )
+
+
+class SavedQueryAncestorsSerializer(serializers.Serializer):
+ ancestors = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Ids of the saved queries and warehouse tables this query reads from, directly or "
+ "through other queries, and the names of the PostHog tables among them.",
+ )
+
+
+class SavedQueryDescendantsSerializer(serializers.Serializer):
+ descendants = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Ids of the saved queries that read from this query, directly or through other queries.",
+ )
+
+
+class SavedQueryDependenciesSerializer(serializers.Serializer):
+ upstream_count = serializers.IntegerField(help_text="How many tables and queries this query reads from directly.")
+ downstream_count = serializers.IntegerField(help_text="How many queries read from this query directly.")
+
+
+def _parse_level(request: request.Request) -> int | None:
+ """Read the `level` bound off a lineage request.
+
+ No level means walk the whole cone. Zero or less would walk nothing and return an empty
+ answer, so it is refused, as is anything that is not a whole number.
+ """
+ serializer = SavedQueryLineageRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ return serializer.validated_data.get("level")
+
+
+def _related_saved_queries(saved_query: DataWarehouseSavedQuery, *, upstream: bool, max_depth: int | None) -> set[str]:
+ """Walk the data modeling graph from a saved query and identify what it reaches.
+
+ The walk starts from every node that stands for the query and unions what they reach: a
+ saved query can hold a node in more than one DAG, and a query in a managed DAG is also
+ represented by a proxy table node in each DAG that reads from it. Without the proxies a
+ consumer would report the managed query upstream while the managed query reported no
+ consumer downstream.
+
+ Each reached node is identified the way the lineage endpoints have always identified it: a
+ query by its saved-query id, an imported warehouse table by its `DataWarehouseTable` id, a
+ cross-DAG proxy by the id of the saved query it stands in for, and a PostHog system table by
+ its name. A table node carries the id in its properties
+ (`saved_query_dag_sync.resolve_dependency_to_node`) rather than the `saved_query` FK.
+ """
+ start_node_ids = {
+ str(node_id)
+ for node_id in Node.objects.filter(team=saved_query.team)
+ .filter(Q(saved_query=saved_query) | Q(properties__saved_query_id=str(saved_query.id)))
+ .values_list("id", flat=True)
+ }
+ if not start_node_ids:
+ return set()
+
+ reached = _reachable_node_ids(saved_query.team_id, start_node_ids, upstream=upstream, max_depth=max_depth)
+
+ identifiers: set[str] = set()
+ for saved_query_id, name, properties in Node.objects.filter(team=saved_query.team, id__in=reached).values_list(
+ "saved_query_id", "name", "properties"
+ ):
+ properties = properties or {}
+ if saved_query_id is not None:
+ identifiers.add(str(saved_query_id))
+ elif properties.get("saved_query_id"):
+ identifiers.add(str(properties["saved_query_id"]))
+ elif properties.get("warehouse_table_id"):
+ identifiers.add(str(properties["warehouse_table_id"]))
+ else:
+ identifiers.add(name)
+ return identifiers
+
+
+def _reachable_node_ids(team_id: int, start_node_ids: set[str], *, upstream: bool, max_depth: int | None) -> set[str]:
+ """Node ids reachable from `start_node_ids` within `max_depth` hops, the start nodes excluded.
+
+ One query per hop, each reading the frontier's edges off the `Edge` foreign-key indexes, so
+ the work is bounded by the cone that is reached rather than by every edge the team owns.
+ Upstream follows edges into the frontier back to their sources; downstream follows edges
+ out of it to their targets.
+ """
+ edges = Edge.objects.filter(team_id=team_id)
+
+ reached: set[str] = set()
+ frontier = set(start_node_ids)
+ depth = 0
+ while frontier and (max_depth is None or depth < max_depth):
+ if upstream:
+ neighbor_ids = edges.filter(target_id__in=frontier).values_list("source_id", flat=True)
+ else:
+ neighbor_ids = edges.filter(source_id__in=frontier).values_list("target_id", flat=True)
+ frontier = {str(neighbor_id) for neighbor_id in neighbor_ids} - reached - start_node_ids
+ reached |= frontier
+ depth += 1
+ return reached
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py
new file mode 100644
index 000000000000..501562d81577
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py
@@ -0,0 +1,311 @@
+"""Sync cadence for a saved query: the choices, the lineage bounds, and the writable field."""
+
+from datetime import timedelta
+from typing import Any, cast
+
+from django.db import models
+from django.db.models import Model
+
+from rest_framework import serializers
+
+from products.access_control.backend.facade.user_access_control import UserAccessControl
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.warehouse_sources.backend.facade.models import (
+ DataWarehouseTable,
+ sync_frequency_interval_to_sync_frequency,
+)
+
+# Cadences offered for view materialization. 15min is the fastest — sub-15min intervals
+# (1min, 5min) are source-only and not meaningful for materialized views, matching the
+# frontend `DataModelingSyncInterval` type. All values are accepted by
+# `sync_frequency_to_sync_frequency_interval`.
+SYNC_FREQUENCY_CHOICES = [
+ ("never", "never"),
+ ("15min", "15min"),
+ ("30min", "30min"),
+ ("1hour", "1hour"),
+ ("6hour", "6hour"),
+ ("12hour", "12hour"),
+ ("24hour", "24hour"),
+ ("7day", "7day"),
+ ("30day", "30day"),
+]
+
+# Deprecated sub-15min cadences clamped up to the 15min floor for backwards compatibility
+# with any legacy caller still sending them.
+DEPRECATED_FAST_SYNC_FREQUENCIES = {"1min", "5min"}
+
+# What `materialize` enables at when the caller expresses no preference, preserving the
+# behavior from when the action had no request body at all.
+DEFAULT_MATERIALIZE_SYNC_FREQUENCY = "24hour"
+
+# `never` is missing on purpose: materializing is what starts the refreshes, so asking for none
+# has no meaning here. Callers stop them afterwards by setting the cadence to `never`.
+MATERIALIZE_SYNC_FREQUENCY_CHOICES = [choice for choice in SYNC_FREQUENCY_CHOICES if choice[0] != "never"]
+
+
+class SyncFrequencyBlockerSerializer(serializers.Serializer):
+ """The node holding a cadence back, named so a refusal points at something a person can open."""
+
+ id = serializers.CharField(help_text="Data modeling node ID of the source or view.")
+ name = serializers.CharField(help_text="Node name, as it appears in the data modeling graph.")
+
+
+class SyncFrequencyBoundSerializer(serializers.Serializer):
+ label = serializers.CharField( # type: ignore[assignment] # field name intentionally shadows Field.label
+ help_text="The bounding cadence in plain English, for example '6 hours'. Matches the wording "
+ "used in the error raised when an out-of-bounds cadence is written. Prose rather than a "
+ "`sync_frequency` value because a source can deliver on a cadence no `sync_frequency` names."
+ )
+ blocker = SyncFrequencyBlockerSerializer(
+ allow_null=True,
+ help_text="Node that set this bound. Null when nothing identifiable set it, and also when it "
+ "sits outside the caller's access grants: the bound still applies, it just goes unnamed.",
+ )
+
+
+class SyncFrequencyBlockedBy(models.TextChoices):
+ SOURCE = "source", "source"
+ CONSUMER = "consumer", "consumer"
+
+
+class SyncFrequencyOptionSerializer(serializers.Serializer):
+ cadence = serializers.ChoiceField(choices=MATERIALIZE_SYNC_FREQUENCY_CHOICES, help_text="A `sync_frequency` value.")
+ allowed = serializers.BooleanField(help_text="False when writing this cadence would be rejected.")
+ blocked_by = serializers.ChoiceField(
+ choices=SyncFrequencyBlockedBy.choices,
+ allow_null=True,
+ help_text="Which side withholds this cadence: 'source' when no upstream source syncs that "
+ "often, 'consumer' when a downstream view or endpoint refreshes more often than this. "
+ "Null when the cadence is allowed.",
+ )
+ blocker = SyncFrequencyBlockerSerializer(
+ allow_null=True,
+ help_text="The source or consumer named in `blocked_by`. Null when allowed, and also when the "
+ "blocker sits outside the caller's access grants, where `blocked_by` still gives the direction.",
+ )
+
+
+class SyncFrequencyBoundsSerializer(serializers.Serializer):
+ frequency_mode = serializers.ChoiceField(
+ choices=[
+ ("tiered", "tiered"),
+ ("managed_viewset", "managed_viewset"),
+ ("legacy", "legacy"),
+ ("no_node", "no_node"),
+ ],
+ help_text="What governs this view's cadence. 'tiered' is the only mode where `options` is "
+ "meaningful and `sync_frequency` is writable per view. 'managed_viewset' means PostHog owns "
+ "the view, 'legacy' means the v1 backend, where any cadence is accepted and no bounds apply, "
+ "and 'no_node' means the view has no data modeling node to store a cadence on.",
+ )
+ options = SyncFrequencyOptionSerializer(
+ many=True,
+ help_text="Every cadence a picker may show, coarsest-last, each marked allowed or blocked with "
+ "its cause. Empty outside 'tiered' mode.",
+ )
+ floor = SyncFrequencyBoundSerializer(
+ allow_null=True,
+ help_text="The fastest bound: no cadence finer than this is allowed, because the source named "
+ "here does not sync more often. Null when no source withholds a cadence.",
+ )
+ ceiling = SyncFrequencyBoundSerializer(
+ allow_null=True,
+ help_text="The slowest bound: no cadence coarser than this is allowed, because the consumer "
+ "named here refreshes that often. Null when no consumer withholds a cadence.",
+ )
+ best_effort_sources = SyncFrequencyBlockerSerializer(
+ many=True,
+ help_text="Upstream sources with no sync schedule, so the floor is a guess: these arrive when "
+ "someone runs them, and refreshing more often than they really sync will serve stale data. "
+ "Only sources the caller may read are listed.",
+ )
+ best_effort_sources_withheld = serializers.BooleanField(
+ help_text="True when at least one such source sits outside the caller's access grants, so the "
+ "list above is incomplete and the caveat still applies."
+ )
+
+
+SYNC_FREQUENCY_BOUNDS_HELP_TEXT = (
+ "Which cadences this view can actually be set to, and what withholds the rest. Computed from the "
+ "view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences "
+ "set a ceiling. Read-only, and present on retrieve, create and update responses only."
+)
+
+
+def _unbounded_frequency_payload(mode: str) -> dict[str, Any]:
+ """The payload for a view whose cadence no lineage governs, so there is nothing to withhold."""
+ return {
+ "frequency_mode": mode,
+ "options": [],
+ "floor": None,
+ "ceiling": None,
+ "best_effort_sources": [],
+ "best_effort_sources_withheld": False,
+ }
+
+
+def _blocker_node_ids(resolved: Any) -> set[str]:
+ """Every node the bounds would name, across the two bounds, the options and the best-effort list."""
+ node_ids: set[str] = set(resolved.best_effort_source_ids)
+ for bound in (resolved.bounds.floor, resolved.bounds.ceiling):
+ if bound is not None and bound.blocker is not None:
+ node_ids.add(bound.blocker)
+ node_ids.update(option.blocker for option in resolved.bounds.options if option.blocker is not None)
+ return node_ids
+
+
+def visible_blocker_names(
+ resolved: Any, user_access_control: UserAccessControl | None, *, team_id: int
+) -> dict[str, str]:
+ """The blocker names this caller may read, keyed by node id.
+
+ Fails closed, and withholds the node id along with the name: an id on its own still answers
+ "something upstream of this view exists", which is what the grant is there to withhold. A node
+ with no resolvable resource (predating the origin stamp) is withheld for the same reason.
+ """
+ node_ids = _blocker_node_ids(resolved)
+ if not node_ids or user_access_control is None:
+ return {}
+
+ visible: dict[str, str] = {}
+ # Lists, not single ids: one saved query or table can hold a node in several DAGs, and a grant
+ # covers the resource, so every node of it becomes visible together.
+ node_ids_by_saved_query: dict[str, list[str]] = {}
+ node_ids_by_table: dict[str, list[str]] = {}
+ for node_id in node_ids:
+ identity = resolved.identities.get(node_id)
+ name = resolved.names.get(node_id)
+ if identity is None or name is None:
+ continue
+ if identity.is_posthog_table:
+ visible[node_id] = name # events, persons and friends: readable by anyone on the project
+ elif identity.saved_query_id is not None:
+ node_ids_by_saved_query.setdefault(identity.saved_query_id, []).append(node_id)
+ elif identity.warehouse_table_id is not None:
+ node_ids_by_table.setdefault(identity.warehouse_table_id, []).append(node_id)
+
+ def reveal(resource_node_ids: list[str]) -> None:
+ visible.update({node_id: resolved.names[node_id] for node_id in resource_node_ids})
+
+ if node_ids_by_saved_query:
+ creators = DataWarehouseSavedQuery.objects.filter(id__in=node_ids_by_saved_query, team_id=team_id).values_list(
+ "id", "created_by_id"
+ )
+ levels = user_access_control.bulk_object_access_levels(
+ "warehouse_view", [(str(pk), created_by) for pk, created_by in creators]
+ )
+ for saved_query_id, level in levels.items():
+ if level is not None and level != "none":
+ reveal(node_ids_by_saved_query[saved_query_id])
+
+ if node_ids_by_table:
+ # One at a time rather than in bulk: `warehouse_table` falls back to `external_data_source`,
+ # and the bulk call refuses any resource with a fallback parent. Per object is also what
+ # honours a deny on one table, or on the source it came from. A table that no longer
+ # resolves keeps its name withheld.
+ tables = list(
+ DataWarehouseTable.objects.filter(id__in=node_ids_by_table, team_id=team_id).exclude(deleted=True)
+ )
+ user_access_control.preload_object_access_controls(cast(list[Model], tables))
+ for table in tables:
+ if user_access_control.check_access_level_for_object(table, "viewer"):
+ reveal(node_ids_by_table[str(table.id)])
+ return visible
+
+
+def _frequency_bounds_payload(resolved: Any, visible_names: dict[str, str]) -> dict[str, Any]:
+ from products.data_modeling.backend.facade.api import humanize_cadence
+
+ def blocker(node_id: str | None) -> dict[str, str] | None:
+ if node_id is None or node_id not in visible_names:
+ return None
+ return {"id": node_id, "name": visible_names[node_id]}
+
+ def bound(value: Any) -> dict[str, Any] | None:
+ if value is None:
+ return None
+ return {"label": humanize_cadence(value.value), "blocker": blocker(value.blocker)}
+
+ best_effort = sorted(resolved.best_effort_source_ids)
+ return {
+ "frequency_mode": "tiered",
+ "options": [
+ {
+ "cadence": sync_frequency_interval_to_sync_frequency(option.value),
+ "allowed": option.allowed,
+ "blocked_by": option.blocked_by,
+ "blocker": blocker(option.blocker),
+ }
+ for option in resolved.bounds.options
+ ],
+ "floor": bound(resolved.bounds.floor),
+ "ceiling": bound(resolved.bounds.ceiling),
+ "best_effort_sources": [blocker(node_id) for node_id in best_effort if node_id in visible_names],
+ "best_effort_sources_withheld": any(node_id not in visible_names for node_id in best_effort),
+ }
+
+
+def _node_frequency_targets(root: serializers.BaseSerializer, view: DataWarehouseSavedQuery) -> dict[str, timedelta]:
+ """Declared node targets for every view the root serializer renders, fetched once.
+
+ Resolved from the root's instance rather than the viewset context, because the context is
+ built without knowing which page of views is being serialized. Memoized on the root so a
+ `list` response costs one query instead of one per view.
+ """
+ cached = getattr(root, "_node_frequency_targets_cache", None)
+ if cached is not None:
+ return cached
+
+ from products.data_modeling.backend.facade.api import declared_targets_by_saved_query
+
+ instance = root.instance
+ if isinstance(instance, DataWarehouseSavedQuery):
+ views = [instance]
+ elif instance is None:
+ views = [view]
+ else:
+ views = list(instance)
+
+ targets = declared_targets_by_saved_query(view.team_id, [rendered.pk for rendered in views])
+ root._node_frequency_targets_cache = targets # type: ignore[attr-defined]
+ return targets
+
+
+def resolve_sync_frequency(root: serializers.BaseSerializer, view: DataWarehouseSavedQuery) -> str | None:
+ """Cadence string for a view, preferring its DAG node's declared freshness target.
+
+ On tiered v2 teams the node target is the only store of cadence — reconcile deliberately NULLs
+ `sync_frequency_interval` so a stale v1 schedule can't be revived from it — so reading the
+ column alone reports "never" for every scheduled view. The column still covers v1 and
+ single-schedule v2 teams, which have no node target.
+ """
+ target = _node_frequency_targets(root, view).get(str(view.pk))
+ if target is not None:
+ return sync_frequency_interval_to_sync_frequency(target)
+ return sync_frequency_interval_to_sync_frequency(view.sync_frequency_interval)
+
+
+class SyncFrequencyField(serializers.ChoiceField):
+ """Writable sync-cadence field for saved queries.
+
+ Reads resolve the cadence via `resolve_sync_frequency` (node target first, then the model's
+ `sync_frequency_interval`); writes are validated against the choices and consumed by the
+ serializer's `update()`. Declaring it as a real (non read-only) field is what lets the
+ cadence flow into the generated PATCH body and MCP tool schema.
+ """
+
+ def __init__(self, **kwargs: Any) -> None:
+ kwargs.setdefault("choices", SYNC_FREQUENCY_CHOICES)
+ kwargs.setdefault("required", False)
+ kwargs.setdefault("allow_null", True)
+ super().__init__(**kwargs)
+
+ def to_internal_value(self, data: Any) -> str:
+ # Clamp deprecated sub-15min cadences up to the floor before validating against choices.
+ if data in DEPRECATED_FAST_SYNC_FREQUENCIES:
+ data = "15min"
+ return super().to_internal_value(data)
+
+ def get_attribute(self, instance: DataWarehouseSavedQuery) -> str | None:
+ return resolve_sync_frequency(self.root, instance)
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/view_description.py b/products/data_warehouse/backend/presentation/views/saved_query/view_description.py
new file mode 100644
index 000000000000..d65a49880dea
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/view_description.py
@@ -0,0 +1,28 @@
+"""The view-level description, stored as a column annotation with an empty column name."""
+
+from rest_framework import serializers
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+from products.data_warehouse.backend.presentation.views.column_annotation_base import DESCRIPTION_HELP_TEXT
+
+VIEW_DESCRIPTION_HELP_TEXT = (
+ "Semantic description of what this view represents, surfaced to AI agents. Set it to describe the "
+ "view; send an empty string to clear it. Per-column descriptions are read back in `columns` and set "
+ "via the saved-query column annotation endpoints. " + DESCRIPTION_HELP_TEXT
+)
+
+
+def view_annotation_map(view: DataWarehouseSavedQuery) -> dict[str, str]:
+ """`{column_name: description}` from a view's column annotations (``""`` = view-level)."""
+ return {a.column_name: a.description for a in view.column_annotations.all()}
+
+
+class ViewDescriptionField(serializers.CharField):
+ """View-level description, stored as a column annotation with an empty `column_name`.
+
+ Reads the annotation for display; on write the serializer's create/update upserts or clears it. The
+ view model has no `description` column, so the value is resolved here rather than bound to the model.
+ """
+
+ def get_attribute(self, instance: DataWarehouseSavedQuery) -> str | None:
+ return view_annotation_map(instance).get("")
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/view_state.py b/products/data_warehouse/backend/presentation/views/saved_query/view_state.py
new file mode 100644
index 000000000000..f6b982adaead
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/view_state.py
@@ -0,0 +1,181 @@
+"""Read-side rendering of a saved query: run state, columns, and the list serializer."""
+
+from datetime import datetime
+from typing import Any, cast
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+from posthog.schema import DataWarehouseManagedViewsetKind
+
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.database.database import SerializedField, serialize_fields
+
+from posthog.api.shared import UserBasicSerializer
+
+from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+from products.data_modeling.backend.facade.api import get_incremental_config
+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQuery
+
+from . import sync_cadence, view_description
+
+# Only these two are still written to the column: MODIFIED on edit, CANCELLED by the cancel action.
+# Every other value was last written by the v1 materialization workflow, which no longer exists, so it
+# describes a run no current code path could have produced.
+STATUSES_STILL_WRITTEN = frozenset({DataWarehouseSavedQuery.Status.MODIFIED, DataWarehouseSavedQuery.Status.CANCELLED})
+
+
+class DataWarehouseSavedQuerySerializerMixin:
+ """Shared methods for DataWarehouseSavedQuery serializers.
+
+ This mixin is intended to be used with serializers.ModelSerializer subclasses.
+ """
+
+ def _serving_run(self, view: DataWarehouseSavedQuery) -> DataModelingJob | None:
+ """The newest materialization run that serves this view, or None if it has never run.
+
+ Prefers the prefetched job so a list of views costs one query. Falls back to a lookup for
+ the detail route, which has no prefetch.
+ """
+ try:
+ jobs = view.jobs # type: ignore[attr-defined]
+ return jobs[0] if jobs else None
+ except AttributeError:
+ return (
+ DataModelingJob.objects.filter(saved_query_id=view.id, engine=DataModelingJobEngine.CLICKHOUSE)
+ .order_by("-last_run_at")
+ .first()
+ )
+
+ @extend_schema_field(serializers.DateTimeField(allow_null=True))
+ def get_last_run_at(self, view: DataWarehouseSavedQuery) -> datetime | None:
+ run = self._serving_run(view)
+ return run.last_run_at if run is not None else None
+
+ @extend_schema_field(serializers.ChoiceField(choices=DataWarehouseSavedQuery.Status.choices, allow_null=True))
+ def get_status(self, view: DataWarehouseSavedQuery) -> str | None:
+ run = self._serving_run(view)
+ if run is None:
+ return view.status if view.status in STATUSES_STILL_WRITTEN else None
+ # Modified means "edited and not materialized since", which no run can express. A run that
+ # happened after the edit answers it, so the column only wins while the edit is the newer fact.
+ edited_since_the_run = (
+ view.status == DataWarehouseSavedQuery.Status.MODIFIED
+ and view.updated_at is not None
+ and view.updated_at > run.last_run_at
+ )
+ return view.status if edited_since_the_run else run.status
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_latest_error(self, view: DataWarehouseSavedQuery) -> str | None:
+ run = self._serving_run(view)
+ return run.error if run is not None else None
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_sync_frequency(self, schema: DataWarehouseSavedQuery):
+ return sync_cadence.resolve_sync_frequency(self.root, schema) # type: ignore[attr-defined]
+
+ @extend_schema_field(serializers.BooleanField())
+ def get_is_incremental(self, view: DataWarehouseSavedQuery) -> bool:
+ return get_incremental_config(view) is not None
+
+ @extend_schema_field(sync_cadence.SyncFrequencyBoundsSerializer())
+ def get_sync_frequency_bounds(self, view: DataWarehouseSavedQuery) -> dict[str, Any]:
+ from products.data_modeling.backend.facade.api import saved_query_target_bounds
+
+ if view.managed_viewset is not None:
+ return sync_cadence._unbounded_frequency_payload("managed_viewset")
+
+ resolved = saved_query_target_bounds(view.team_id, view.pk)
+ if resolved is None:
+ return sync_cadence._unbounded_frequency_payload("no_node")
+ visible = sync_cadence.visible_blocker_names(resolved, self.user_access_control, team_id=view.team_id) # type: ignore[attr-defined]
+ return sync_cadence._frequency_bounds_payload(resolved, visible)
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_managed_viewset_kind(self, view: DataWarehouseSavedQuery) -> DataWarehouseManagedViewsetKind | None:
+ return cast(DataWarehouseManagedViewsetKind, view.managed_viewset.kind) if view.managed_viewset else None
+
+ @extend_schema_field(serializers.ListField(child=serializers.DictField()))
+ def get_columns(self, view: DataWarehouseSavedQuery) -> list[SerializedField]:
+ # `hogql_fields` rather than `hogql_definition`, which would read the SQL body the list
+ # page defers.
+ hogql_fields = view.hogql_fields()
+ if not hogql_fields:
+ return []
+
+ # `hogql_fields` holds concrete `DatabaseField` subclasses only, and `serialize_fields`
+ # reads the context database for none of those, so this needs no HogQL database build.
+ context = HogQLContext(team_id=self.context["team_id"]) # type: ignore[attr-defined]
+
+ descriptions = view_description.view_annotation_map(view)
+ fields = serialize_fields(hogql_fields, context, view.name_chain, table_type="external")
+ return [
+ SerializedField(
+ key=field.name,
+ name=field.name,
+ type=field.type,
+ schema_valid=field.schema_valid,
+ fields=field.fields,
+ table=field.table,
+ chain=field.chain,
+ description=descriptions.get(field.name),
+ )
+ for field in fields
+ ]
+
+
+class DataWarehouseSavedQueryMinimalSerializer(
+ DataWarehouseSavedQuerySerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer
+):
+ """Lightweight serializer for list views - excludes large query field to reduce memory usage."""
+
+ created_by = UserBasicSerializer(read_only=True)
+ columns = serializers.SerializerMethodField(read_only=True)
+ description = view_description.ViewDescriptionField(
+ read_only=True, help_text=view_description.VIEW_DESCRIPTION_HELP_TEXT
+ )
+ sync_frequency = serializers.SerializerMethodField()
+ last_run_at = serializers.SerializerMethodField(read_only=True)
+ status = serializers.SerializerMethodField(read_only=True)
+ latest_error = serializers.SerializerMethodField(read_only=True)
+ managed_viewset_kind = serializers.SerializerMethodField(read_only=True)
+ folder_id = serializers.UUIDField(source="folder.id", read_only=True, allow_null=True)
+ folder_name = serializers.CharField(source="folder.name", read_only=True, allow_null=True)
+ is_incremental = serializers.SerializerMethodField(
+ read_only=True,
+ help_text="Whether this view is set up to update incrementally. A run can still rebuild the "
+ "whole table, for example on the first run or after the query changes.",
+ )
+
+ class Meta:
+ model = DataWarehouseSavedQuery
+ fields = [
+ "id",
+ "deleted",
+ "name",
+ "created_by",
+ "created_at",
+ "description",
+ "sync_frequency",
+ "columns",
+ "status",
+ "last_run_at",
+ "managed_viewset_kind",
+ "folder_id",
+ "folder_name",
+ "latest_error",
+ "is_materialized",
+ "is_incremental",
+ "origin",
+ "is_test",
+ "expires_at",
+ "user_access_level",
+ ]
+ read_only_fields = fields
+
+
+class SavedQuerySuspensionSerializer(serializers.Serializer):
+ at = serializers.DateTimeField(help_text="When materialization was suspended.")
+ reason = serializers.CharField(help_text="Error from the materialization run that tripped suspension.")
+ job_id = serializers.CharField(help_text="Materialization job that tripped suspension.")
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
new file mode 100644
index 000000000000..0b4b09c91524
--- /dev/null
+++ b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
@@ -0,0 +1,665 @@
+"""The saved-query viewset and the request bodies of its actions."""
+
+from dataclasses import dataclass
+from typing import Any, cast
+
+from django.db.models import Model, OuterRef, Prefetch, Subquery, TextField
+from django.db.models.functions import Cast
+
+import structlog
+import posthoganalytics
+from asgiref.sync import async_to_sync
+from drf_spectacular.utils import extend_schema
+from rest_framework import exceptions, filters, request, response, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.pagination import PageNumberPagination
+from rest_framework.response import Response
+
+from posthog.hogql.database.database import Database
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.exceptions_capture import capture_exception
+from posthog.helpers.impersonation import is_impersonated
+from posthog.models import User
+from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, load_activity, log_activity
+from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
+from posthog.rate_limit import MaterializationRateThrottle, RunSavedQueryRateThrottle
+from posthog.rbac.query_access import assert_user_can_read_query
+from posthog.temporal.common.client import sync_connect
+
+from products.access_control.backend.presentation.access_control import AccessControlViewSetMixin
+from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, DataWarehouseSavedQuery
+from products.warehouse_sources.backend.facade.models import sync_frequency_to_sync_frequency_interval
+
+from . import editing, incremental_config, lifecycle, lineage, sync_cadence, view_state
+
+logger = structlog.get_logger(__name__)
+
+
+@dataclass(frozen=True, kw_only=True)
+class _CancelTarget:
+ workflow_id: str
+ workflow_run_id: str | None
+
+
+class DataWarehouseSavedQueryPagination(PageNumberPagination):
+ page_size = 1000
+
+
+class SavedQueryResumeSerializer(serializers.Serializer):
+ resumed = serializers.BooleanField(help_text="False when the query's materialization was not suspended.")
+
+
+class SavedQueryResumeSchedulesRequestSerializer(serializers.Serializer):
+ """Body of the `resume_schedules` action."""
+
+ view_ids = serializers.ListField(
+ child=serializers.UUIDField(),
+ allow_empty=False,
+ help_text=(
+ "Ids of the saved queries to resume. An id is ignored when it is not in this project, "
+ "has been deleted, or you cannot edit it."
+ ),
+ )
+
+
+class SavedQueryRunSerializer(serializers.Serializer):
+ """Body of the `run` action."""
+
+ full_refresh = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text="Rebuild the whole table instead of updating it incrementally. Has no effect on a "
+ "view that is not incremental. This is how you reprocess history after changing what the "
+ "query means without changing its text, or after upstream data was corrected.",
+ )
+
+
+class SavedQueryMaterializeSerializer(serializers.Serializer):
+ """Body of the `materialize` action: which cadence to enable materialization at."""
+
+ sync_frequency = sync_cadence.SyncFrequencyField(
+ choices=sync_cadence.MATERIALIZE_SYNC_FREQUENCY_CHOICES,
+ allow_null=False,
+ default=sync_cadence.DEFAULT_MATERIALIZE_SYNC_FREQUENCY,
+ help_text=(
+ "How often to refresh the materialized table, defaulting to daily. Rejected with a 400 when it falls "
+ "outside what the query's lineage allows: no more often than its sources deliver new data, and no less "
+ "often than a downstream view or endpoint needs."
+ ),
+ )
+
+
+class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.ModelViewSet):
+ """
+ Create, Read, Update and Delete Warehouse Tables.
+ """
+
+ scope_object = "warehouse_view"
+ queryset = DataWarehouseSavedQuery.objects.all()
+ serializer_class = editing.DataWarehouseSavedQuerySerializer
+ pagination_class = DataWarehouseSavedQueryPagination
+ filter_backends = [filters.SearchFilter]
+ search_fields = ["name"]
+ ordering = "-created_at"
+
+ def get_serializer_context(self) -> dict[str, Any]:
+ context = super().get_serializer_context()
+ request_data = getattr(self.request, "data", {})
+ # Read actions stay out: building a database selects every view in the team, SQL body
+ # included, and neither serializer reads it. Only the write paths below do, to check a
+ # name collision and to resolve a query's source tables.
+ should_include_database = self.action == "create" or (
+ self.action in {"update", "partial_update"} and ("name" in request_data or "query" in request_data)
+ )
+
+ if should_include_database:
+ context["database"] = Database.create_for(team_id=self.team_id, user=cast(User, self.request.user))
+ return context
+
+ def get_serializer_class(self):
+ if self.action == "list":
+ return view_state.DataWarehouseSavedQueryMinimalSerializer
+ return editing.DataWarehouseSavedQuerySerializer
+
+ def safely_get_queryset(self, queryset):
+ base_queryset = (
+ queryset.prefetch_related(
+ "created_by",
+ "managed_viewset",
+ "column_annotations",
+ Prefetch(
+ "datamodelingjob_set",
+ queryset=DataModelingJob.objects.filter(engine=DataModelingJobEngine.CLICKHOUSE).order_by(
+ "-last_run_at"
+ )[:1],
+ to_attr="jobs",
+ ),
+ )
+ # Both serializers read `folder.id` and `folder.name`, so without the join Django
+ # fetches the folder once per foldered view.
+ .select_related("folder")
+ .exclude(deleted=True)
+ .order_by(self.ordering)
+ )
+
+ # Hide endpoint-origin saved queries from the list view — they belong to the endpoints UI.
+ # Allow retrieve so the Node detail page can fetch them by ID.
+ if self.action == "list":
+ # The list serializer reads none of these large JSONB columns. Left in the SELECT,
+ # Postgres detoasts each one per view, and a page holds up to a thousand views.
+ base_queryset = base_queryset.exclude(origin=DataWarehouseSavedQuery.Origin.ENDPOINT).defer(
+ "query", "external_tables", "incremental_state"
+ )
+
+ # Detect whether we should include managed views in the queryset
+ is_managed_viewset_enabled = posthoganalytics.feature_enabled(
+ "managed-viewsets",
+ str(self.team.uuid),
+ groups={
+ "organization": str(self.team.organization_id),
+ "project": str(self.team.id),
+ },
+ group_properties={
+ "organization": {
+ "id": str(self.team.organization_id),
+ },
+ "project": {
+ "id": str(self.team.id),
+ },
+ },
+ send_feature_flag_events=False,
+ )
+
+ if not is_managed_viewset_enabled:
+ base_queryset = base_queryset.filter(managed_viewset__isnull=True)
+
+ # Only the detail serializer returns `latest_history_id`, and the subquery costs a jsonb
+ # key-path filter the GIN index on `detail` cannot serve, so keep it off the list page.
+ if getattr(self, "action", None) == "retrieve":
+ # Scoped to query edits (see QUERY_CHANGE_ACTIVITY_FILTER) so materialization syncs
+ # don't advance the head.
+ latest_activity = (
+ ActivityLog.objects.filter(
+ scope="DataWarehouseSavedQuery",
+ item_id=Cast(OuterRef("id"), output_field=TextField()),
+ team_id=self.team_id,
+ **editing.QUERY_CHANGE_ACTIVITY_FILTER,
+ )
+ .order_by("-created_at")
+ .values("id")[:1]
+ )
+
+ return base_queryset.annotate(latest_activity_id=Subquery(latest_activity))
+
+ return base_queryset
+
+ def create(self, request, *args, **kwargs):
+ # Check for UPSERT logic
+ saved_query = DataWarehouseSavedQuery.objects.filter(
+ team_id=self.team_id, name=request.data.get("name")
+ ).first()
+ if saved_query:
+ # The UPSERT branch updates an existing row without going through get_object(),
+ # so run object-level permission checks explicitly to honor per-object access controls.
+ self.check_object_permissions(request, saved_query)
+ serializer = self.get_serializer(saved_query, data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ self.perform_update(serializer)
+ return Response(serializer.data, status=status.HTTP_200_OK)
+ else:
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ # Create logic
+ self.perform_create(serializer)
+ return Response(serializer.data, status=status.HTTP_201_CREATED)
+
+ def destroy(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
+ from products.data_modeling.backend.facade.api import HasDependentsError
+
+ instance: DataWarehouseSavedQuery = self.get_object()
+ name = instance.name
+ try:
+ lifecycle.delete_saved_query(instance)
+ except HasDependentsError:
+ raise serializers.ValidationError(
+ "Cannot delete this view because other views depend on it. Delete or update those views first."
+ )
+
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ item_id=instance.id,
+ scope="DataWarehouseSavedQuery",
+ activity="deleted",
+ detail=Detail(name=name),
+ )
+
+ return response.Response(status=status.HTTP_204_NO_CONTENT)
+
+ @extend_schema(request=SavedQueryRunSerializer, responses={200: None})
+ @action(
+ methods=["POST"],
+ detail=True,
+ required_scopes=["warehouse_view:write"],
+ throttle_classes=[RunSavedQueryRateThrottle],
+ )
+ def run(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Run this saved query."""
+ from products.data_modeling.backend.facade.api import (
+ MissingDagNodeError,
+ clear_incremental_state,
+ materialize_saved_query,
+ )
+
+ body = SavedQueryRunSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+
+ saved_query = self.get_object()
+
+ if body.validated_data["full_refresh"]:
+ # Dropping the watermark is the whole mechanism: the next run finds no progress to
+ # build on and rebuilds. Commit it before dispatch, and outside any transaction the
+ # dispatch could roll back, or the worker reads the old watermark and runs
+ # incrementally instead.
+ clear_incremental_state(saved_query)
+
+ try:
+ materialize_saved_query(saved_query, triggered_by_id=request.user.pk)
+ except MissingDagNodeError:
+ raise exceptions.ValidationError(
+ detail="This view isn't fully set up to materialize. Save the query again, then try syncing."
+ )
+
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="sync_triggered",
+ detail=Detail(name=saved_query.name),
+ )
+
+ return response.Response(status=status.HTTP_200_OK)
+
+ @extend_schema(
+ request=incremental_config.CheckIncrementalSerializer,
+ responses={200: incremental_config.IncrementalEligibilitySerializer},
+ )
+ @action(
+ methods=["POST"],
+ detail=False,
+ required_scopes=["warehouse_view:read"],
+ throttle_classes=[incremental_config.CheckIncrementalThrottle],
+ )
+ def check_incremental(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Report whether a query can be materialized incrementally, without running it.
+
+ Parses the SQL only, so it is cheap enough to call from the editor as the user types. Lets
+ the editor explain why the incremental option is unavailable before anything is saved.
+ """
+ from products.data_modeling.backend.facade.api import IncrementalConfig, check_incremental_eligibility
+
+ body = incremental_config.CheckIncrementalSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ data = body.validated_data
+
+ config = None
+ if data.get("incremental_key") and data.get("unique_key"):
+ config = IncrementalConfig(
+ incremental_key=data["incremental_key"],
+ unique_key=tuple(data["unique_key"]),
+ lookback_seconds=data.get("lookback_seconds", 0),
+ )
+
+ result = check_incremental_eligibility(
+ data["query"],
+ config,
+ database=Database.create_for(team_id=self.team_id, user=cast(User, request.user)),
+ )
+ return response.Response(
+ incremental_config.IncrementalEligibilitySerializer(
+ {
+ "eligible": result.eligible,
+ "key_candidates": result.key_candidates,
+ "unique_key_candidates": result.unique_key_candidates,
+ "key_candidate_types": result.key_candidate_types,
+ "blockers": result.blockers,
+ "warnings": result.warnings,
+ }
+ ).data,
+ status=status.HTTP_200_OK,
+ )
+
+ @extend_schema(request=None, responses={200: SavedQueryResumeSerializer})
+ @action(methods=["POST"], detail=True, required_scopes=["warehouse_view:write"])
+ def resume(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Resume materialization suspended after repeated failures.
+
+ Scheduled runs skip a suspended model and everything downstream of it, so it cannot succeed
+ its way back on its own.
+ """
+ from products.data_modeling.backend.facade.api import unsuspend_saved_query
+
+ resumed = unsuspend_saved_query(self.get_object())
+
+ return response.Response({"resumed": bool(resumed)}, status=status.HTTP_200_OK)
+
+ @action(
+ methods=["POST"],
+ detail=True,
+ required_scopes=["warehouse_view:write"],
+ throttle_classes=[MaterializationRateThrottle],
+ )
+ def revert_materialization(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """
+ Undo materialization, revert back to the original view.
+ (i.e. delete the materialized table and the schedule)
+ """
+ saved_query: DataWarehouseSavedQuery = self.get_object()
+
+ if saved_query.managed_viewset is not None:
+ raise serializers.ValidationError("Cannot revert materialization of a query from a managed viewset.")
+
+ saved_query.revert_materialization()
+
+ # set data modeling node type to view
+ try:
+ from products.data_modeling.backend.facade.api import update_node_type
+ from products.data_modeling.backend.facade.models import NodeType
+
+ update_node_type(saved_query, NodeType.VIEW)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to update node type to view", saved_query_name=saved_query.name)
+
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="materialization_disabled",
+ detail=Detail(name=saved_query.name),
+ )
+
+ return response.Response(status=status.HTTP_200_OK)
+
+ @extend_schema(request=SavedQueryMaterializeSerializer, responses={200: None})
+ @action(
+ methods=["POST"],
+ detail=True,
+ required_scopes=["warehouse_view:write"],
+ throttle_classes=[MaterializationRateThrottle],
+ )
+ def materialize(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """
+ Enable materialization for this saved query, at the requested sync frequency or daily.
+ """
+ saved_query: DataWarehouseSavedQuery = self.get_object()
+
+ if saved_query.managed_viewset is not None:
+ raise serializers.ValidationError("Cannot materialize a query from a managed viewset.")
+
+ assert_user_can_read_query(saved_query.query, self.team_id, cast(User, request.user))
+
+ params = SavedQueryMaterializeSerializer(data=request.data)
+ params.is_valid(raise_exception=True)
+ sync_frequency_interval = sync_frequency_to_sync_frequency_interval(params.validated_data["sync_frequency"])
+
+ from products.data_modeling.backend.facade.api import (
+ UnsatisfiableFrequencyError,
+ UnsupportedFrequencyTargetError,
+ check_saved_query_frequency_target,
+ saved_query_target_bounds,
+ )
+
+ if sync_frequency_interval is not None:
+ # Ask before writing, so the ordinary refusal never has to be undone below. Names only
+ # what this caller may read, matching the bounds payload — otherwise one rejected
+ # materialize reads back a node they were never shown.
+ bounds = saved_query_target_bounds(self.team_id, saved_query.pk)
+ try:
+ check_saved_query_frequency_target(
+ saved_query,
+ sync_frequency_interval,
+ visible_names=(
+ sync_cadence.visible_blocker_names(bounds, self.user_access_control, team_id=self.team_id)
+ if bounds
+ else {}
+ ),
+ )
+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:
+ raise serializers.ValidationError(str(e))
+
+ previous_interval = saved_query.sync_frequency_interval
+ previously_materialized = saved_query.is_materialized
+
+ saved_query.sync_frequency_interval = sync_frequency_interval
+ saved_query.is_materialized = True
+ saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])
+
+ # Enable materialization - this handles model path setup and schedule creation
+ # If this fails, it will set is_materialized = False
+ try:
+ saved_query.schedule_materialization(trigger_immediate_run=True, triggered_by_id=request.user.pk)
+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError):
+ # The check above already refused every cadence the lineage forbids, so reaching here
+ # means the lineage moved mid-request. Say so plainly rather than forwarding a message
+ # built from unredacted names. `schedule_materialization` re-raises these without
+ # applying its disable-on-failure contract, and this action is not inside an atomic
+ # block, so undo the enable by hand: otherwise the 400 leaves is_materialized=True
+ # behind and the UI reads the rejection as a success.
+ saved_query.sync_frequency_interval = previous_interval
+ saved_query.is_materialized = previously_materialized
+ saved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])
+ raise serializers.ValidationError(
+ "This view's lineage changed while we were setting it up. Reopen it and pick a cadence again."
+ )
+
+ # Refresh from DB to check if schedule_materialization set is_materialized = False on failure
+ saved_query.refresh_from_db()
+ if saved_query.is_materialized is False:
+ return response.Response(
+ {"error": "Materialization failed. Please try again or contact support."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
+ # set data modeling node type to matview
+ try:
+ from products.data_modeling.backend.facade.api import update_node_type
+ from products.data_modeling.backend.facade.models import NodeType
+
+ update_node_type(saved_query, NodeType.MAT_VIEW)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to update node type to matview", saved_query_name=saved_query.name)
+
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="materialization_enabled",
+ detail=Detail(
+ name=saved_query.name,
+ changes=[
+ Change(
+ field="sync_frequency_interval",
+ action="changed",
+ type="DataWarehouseSavedQuery",
+ before=str(previous_interval) if previous_interval else None,
+ after=str(sync_frequency_interval),
+ ),
+ ],
+ ),
+ )
+
+ return response.Response(status=status.HTTP_200_OK)
+
+ @extend_schema(request=SavedQueryResumeSchedulesRequestSerializer, responses={202: None})
+ @action(methods=["POST"], detail=False, required_scopes=["warehouse_view:write"])
+ def resume_schedules(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """
+ Resume materialization for several models that were suspended after repeated failures.
+
+ Accepts a list of view IDs in the request body: {"view_ids": ["id1", "id2", ...]}
+ This endpoint is idempotent - calling it on models that are already running is safe.
+ """
+ from products.data_modeling.backend.facade.api import unsuspend_saved_query
+
+ serializer = SavedQueryResumeSchedulesRequestSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ # Skip rather than refuse, so one id the caller cannot edit does not cost them the rest of
+ # the batch. Every skipped id looks the same from outside, whether it is absent, in another
+ # project, deleted, or denied - the response would otherwise confirm that a model exists.
+ candidates = list(
+ DataWarehouseSavedQuery.objects.filter(
+ id__in=serializer.validated_data["view_ids"], team_id=self.team_id
+ ).exclude(deleted=True)
+ )
+ self.user_access_control.preload_object_access_controls(cast(list[Model], candidates))
+ for saved_query in candidates:
+ if self.user_access_control.check_access_level_for_object(saved_query, "editor"):
+ unsuspend_saved_query(saved_query)
+ return response.Response(status=status.HTTP_202_ACCEPTED)
+
+ @extend_schema(
+ request=lineage.SavedQueryLineageRequestSerializer, responses={200: lineage.SavedQueryAncestorsSerializer}
+ )
+ @action(methods=["POST"], detail=True)
+ def ancestors(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Return the ancestors of this saved query.
+
+ By default, we return every ancestor. The `level` parameter bounds how many hops back
+ to walk, so 1 gives the immediate parents.
+ """
+ saved_query = self.get_object()
+ ancestors = lineage._related_saved_queries(saved_query, upstream=True, max_depth=lineage._parse_level(request))
+ return response.Response({"ancestors": ancestors})
+
+ @extend_schema(
+ request=lineage.SavedQueryLineageRequestSerializer, responses={200: lineage.SavedQueryDescendantsSerializer}
+ )
+ @action(methods=["POST"], detail=True)
+ def descendants(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Return the descendants of this saved query.
+
+ By default, we return every descendant. The `level` parameter bounds how many hops
+ forward to walk, so 1 gives the immediate children.
+ """
+ saved_query = self.get_object()
+ descendants = lineage._related_saved_queries(
+ saved_query, upstream=False, max_depth=lineage._parse_level(request)
+ )
+ return response.Response({"descendants": descendants})
+
+ @action(methods=["GET"], detail=True, required_scopes=["activity_log:read"])
+ def activity(self, request: request.Request, **kwargs):
+ page_params = parse_activity_page_params(request)
+
+ item_id = kwargs["pk"]
+ if not DataWarehouseSavedQuery.objects.filter(id=item_id, team_id=self.team_id).exists():
+ return Response(status=status.HTTP_404_NOT_FOUND)
+
+ activity_page = load_activity(
+ scope="DataWarehouseSavedQuery",
+ team_id=self.team_id,
+ item_ids=[str(item_id)],
+ limit=page_params.limit,
+ page=page_params.page,
+ )
+ return activity_page_response(activity_page, page_params.limit, page_params.page, request)
+
+ @action(methods=["POST"], detail=True)
+ def cancel(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Cancel a running saved query workflow."""
+ saved_query = self.get_object()
+
+ targets = {
+ _CancelTarget(workflow_id=job.workflow_id, workflow_run_id=job.workflow_run_id)
+ for job in DataModelingJob.objects.filter(
+ team_id=self.team_id,
+ saved_query=saved_query,
+ status=DataModelingJob.Status.RUNNING,
+ )
+ if job.workflow_id
+ }
+
+ if not targets:
+ return response.Response(
+ {"error": "Cannot cancel a query that is not running"}, status=status.HTTP_400_BAD_REQUEST
+ )
+
+ temporal = sync_connect()
+ failed = False
+
+ for target in sorted(targets, key=lambda target: target.workflow_id):
+ try:
+ workflow_handle = temporal.get_workflow_handle(target.workflow_id, run_id=target.workflow_run_id)
+ async_to_sync(workflow_handle.cancel)()
+ except Exception as e:
+ failed = True
+ logger.exception(
+ "Failed to cancel workflow",
+ saved_query_id=str(saved_query.id),
+ workflow_id=target.workflow_id,
+ error=str(e),
+ )
+
+ if failed:
+ return response.Response(
+ {"error": "Failed to cancel workflow"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
+ )
+
+ saved_query.status = DataWarehouseSavedQuery.Status.CANCELLED
+ saved_query.save()
+
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="sync_cancelled",
+ detail=Detail(name=saved_query.name),
+ )
+
+ return response.Response(status=status.HTTP_200_OK)
+
+ @extend_schema(request=None, responses={200: lineage.SavedQueryDependenciesSerializer})
+ @action(methods=["GET"], detail=True)
+ def dependencies(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Return the count of immediate upstream and downstream dependencies for this saved query."""
+ saved_query = self.get_object()
+ return response.Response(
+ {
+ "upstream_count": len(lineage._related_saved_queries(saved_query, upstream=True, max_depth=1)),
+ "downstream_count": len(lineage._related_saved_queries(saved_query, upstream=False, max_depth=1)),
+ }
+ )
+
+ @action(methods=["GET"], detail=True, required_scopes=["warehouse_view:read"])
+ def run_history(self, request: request.Request, *args, **kwargs) -> response.Response:
+ """Return the recent run history (up to 5 most recent) for this materialized view."""
+ saved_query = self.get_object()
+
+ # Get the 5 most recent runs
+ jobs = (
+ DataModelingJob.objects.filter(saved_query=saved_query)
+ .order_by("-last_run_at")[:5]
+ .values("status", "last_run_at")
+ )
+
+ run_history = [{"status": job["status"], "timestamp": job["last_run_at"]} for job in jobs]
+
+ return response.Response({"run_history": run_history})
diff --git a/products/data_warehouse/backend/routes.py b/products/data_warehouse/backend/routes.py
index e972cdd84733..cbd856f09234 100644
--- a/products/data_warehouse/backend/routes.py
+++ b/products/data_warehouse/backend/routes.py
@@ -9,12 +9,15 @@ from products.data_warehouse.backend.presentation.views import (
expression,
managed_viewset,
query_tab_state,
- saved_query,
saved_query_column_annotation,
saved_query_draft,
table,
view_link,
)
+from products.data_warehouse.backend.presentation.views.saved_query import (
+ folders as saved_query_folders,
+ viewset as saved_query_viewset,
+)
def register_routes(routers: RouterRegistry) -> None:
@@ -23,13 +26,13 @@ def register_routes(routers: RouterRegistry) -> None:
)
routers.projects.register(
r"warehouse_saved_query_folders",
- saved_query.DataWarehouseSavedQueryFolderViewSet,
+ saved_query_folders.DataWarehouseSavedQueryFolderViewSet,
"project_warehouse_saved_query_folders",
["team_id"],
)
saved_queries_router = routers.projects.register(
r"warehouse_saved_queries",
- saved_query.DataWarehouseSavedQueryViewSet,
+ saved_query_viewset.DataWarehouseSavedQueryViewSet,
"project_warehouse_saved_queries",
["team_id"],
)
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 c56b0e5ed87e..c047be3c03b0 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -32,7 +32,7 @@ from products.data_modeling.backend.facade.models import (
NodeType,
)
from products.data_tools.backend.models.datawarehouse_saved_query_folder import DataWarehouseSavedQueryFolder
-from products.data_warehouse.backend.presentation.views.saved_query import (
+from products.data_warehouse.backend.presentation.views.saved_query.viewset import (
SavedQueryMaterializeSerializer,
SavedQueryResumeSchedulesRequestSerializer,
)
@@ -985,7 +985,9 @@ class TestSavedQuery(APIBaseTest):
def test_sync_frequency_is_a_writable_field(self):
# Regression: sync_frequency used to be a read-only SerializerMethodField, so it was
# marked readOnly in the generated OpenAPI/MCP schemas and silently dropped from writes.
- from products.data_warehouse.backend.presentation.views.saved_query import DataWarehouseSavedQuerySerializer
+ from products.data_warehouse.backend.presentation.views.saved_query.editing import (
+ DataWarehouseSavedQuerySerializer,
+ )
field = DataWarehouseSavedQuerySerializer().fields["sync_frequency"]
self.assertFalse(field.read_only)
@@ -1071,7 +1073,7 @@ class TestSavedQuery(APIBaseTest):
def test_bounds_stay_off_the_list_page(self):
# Bounds cost a graph walk per view, so serving them on a page of views is an N+1. The
# picker only ever renders on one view's panel, so retrieve is the only place they belong.
- from products.data_warehouse.backend.presentation.views.saved_query import (
+ from products.data_warehouse.backend.presentation.views.saved_query.view_state import (
DataWarehouseSavedQueryMinimalSerializer,
)
@@ -2300,7 +2302,6 @@ class TestSavedQuery(APIBaseTest):
self.assertEqual(suspension_state(node), {})
def test_resume_schedules_clears_suspension_for_every_listed_query(self):
-
saved_queries = [
DataWarehouseSavedQuery.objects.create(
team=self.team,
@@ -2525,7 +2526,7 @@ class TestSavedQueryRun(APIBaseTest):
("v2", "materialize-view-019e4ccb-8369-71dd-9270-9bf570948062-2026-08-13T04:30:00Z"),
]
)
- @patch("products.data_warehouse.backend.presentation.views.saved_query.sync_connect")
+ @patch("products.data_warehouse.backend.presentation.views.saved_query.viewset.sync_connect")
def test_cancel_cancels_the_workflow_recorded_on_the_running_job(
self, _name: str, workflow_id: str, mock_sync_connect
):
@@ -2552,7 +2553,7 @@ class TestSavedQueryRun(APIBaseTest):
saved_query.refresh_from_db()
self.assertEqual(saved_query.status, DataWarehouseSavedQuery.Status.CANCELLED)
- @patch("products.data_warehouse.backend.presentation.views.saved_query.sync_connect")
+ @patch("products.data_warehouse.backend.presentation.views.saved_query.viewset.sync_connect")
def test_cancel_is_rejected_when_no_job_is_running(self, mock_sync_connect):
saved_query, _dag, _node = self._make_saved_query_with_node("idle_view")
DataModelingJob.objects.create(
@@ -2569,7 +2570,7 @@ class TestSavedQueryRun(APIBaseTest):
self.assertEqual(response.status_code, 400, response.content)
mock_sync_connect.assert_not_called()
- @patch("products.data_warehouse.backend.presentation.views.saved_query.sync_connect")
+ @patch("products.data_warehouse.backend.presentation.views.saved_query.viewset.sync_connect")
def test_cancel_attempts_every_running_workflow_when_one_fails(self, mock_sync_connect):
saved_query, _dag, _node = self._make_saved_query_with_node("partial_cancel_view")
for workflow_id in ("materialize-view-1-unreachable", "materialize-view-2-healthy"):
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py b/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py
index 734813aebd9c..3a0582b5c5cb 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query_incremental.py
@@ -2,11 +2,11 @@ from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
-from products.data_warehouse.backend.presentation.views.saved_query import (
+from products.data_warehouse.backend.presentation.views.saved_query.incremental_config import (
CHECK_INCREMENTAL_MAX_QUERY_LENGTH,
CheckIncrementalThrottle,
- DataWarehouseSavedQueryViewSet,
)
+from products.data_warehouse.backend.presentation.views.saved_query.viewset import DataWarehouseSavedQueryViewSet
GROUPED = "SELECT toStartOfDay(timestamp) AS day, count() AS c FROM events GROUP BY day"
CONFIG = {"enabled": True, "incremental_key": "day", "unique_key": ["day"]}
diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txt
index 2e21f42f2fd8..cfe2cebe8c02 100644
--- a/products/model_crossing_uses_baseline.txt
+++ b/products/model_crossing_uses_baseline.txt
@@ -809,7 +809,7 @@ warehouse_sources.DataWarehouseTable products.data_warehouse.backend.logic.data_
warehouse_sources.DataWarehouseTable products.data_warehouse.backend.logic.data_load.create_table write(create) 1
warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.column_annotation drf-field-queryset 1
warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.column_annotation other(Assign) 1
-warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.saved_query instance-many(exclude) 1
+warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.saved_query.sync_cadence instance-many(exclude) 1
warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table construct 2
warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table drf-model-serializer 2
warehouse_sources.DataWarehouseTable products.data_warehouse.backend.presentation.views.table instance-many(all) 1