Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add saved view rename flow (#122262)

Jovan Sakovic1c7d44833937
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 7640415d4575..bb9c49b22e1f 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -45,6 +45,8 @@ The SQL editor keeps unrun edits in browser storage, scoped to the user, project
An **Edited** label marks changes to a saved view or insight. **Discard changes** restores the saved copy already loaded in memory, then refreshes it from the server. The refresh preserves edits made after discarding.
Insights can be saved or updated before running the SQL. Updating a view still requires a successful run of the current SQL so its result types match the saved query. **Continue in a notebook** is in the update button's dropdown for saved views and insights.
+The data warehouse sidebar lets you rename saved views. The dialog lists references from data model lineage. Renaming does not update SQL references in saved views, materialized views, endpoints, insights, dashboards, notebooks, or external systems.
+
Returning to a notebook can reuse completed query results from the last two minutes in the same browser session. Saved insights still fetch their latest definition; changed queries load their own results. Explicit **Run** and refresh actions fetch results again. This browser cache is bounded and excludes shared notebooks, errors, incomplete responses, and large results; it does not change server cache freshness.
## Choosing data in Business intelligence
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c64e87113ded..b57ca7644cd5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10392,6 +10392,10 @@ snapshots:
hash: v1.k794b7964.d8a99a7d7bcfe36920f9d8173ae8f480b93997229c986f058768b5eddeb5474c.RfV4yI1Hovb47bR9_HJMKzYxTqZJJfFjz2MkCzoWP-s
scenes-app-data-warehouse-query-index-usage-fix-actions--report-still-catching-up--wide--light:
hash: v1.k794b7964.0c5a2526511088eca0ef17402714414283b393d4ca94fb375a3f63f32e13999a.Am5ahhnXBQ0aZ3GyFwRzL_3wes-0XTj4uS5pw4WAJCY
+ scenes-app-data-warehouse-rename-view-modal--with-known-references--dark:
+ hash: v1.k794b7964.eb22a575000714f6695e91cbeac695e1999232d8b628cf059cff3cff6f3ebb9b.Jg5TpsINiav24GVDoQ2Ra4XIKWet2w8bbw3wLEAKdzk
+ scenes-app-data-warehouse-rename-view-modal--with-known-references--light:
+ hash: v1.k794b7964.e677d5b5fc832a7c6799a9b514e4f202ed8d272235aec67c32c73901f02afe34.zRrN3Lp3uzPAXR5PsGfjWMvVwCk6TYEUqFEz6JaTdWY
scenes-app-data-warehouse-settings-api-version-deprecation-banner--with-sunset-date--dark:
hash: v1.k794b7964.5a4d9d3ac30fd4e7a83925bb77a89685f5ad1b95e44431dc87696251acd62941.STCVyoJPmpKL8izqztWRz12VuY1AJPSbVh74dSG4k4U
scenes-app-data-warehouse-settings-api-version-deprecation-banner--with-sunset-date--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b2b1810e4a7c..81e940ff35fe 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -300,6 +300,7 @@ export const FEATURE_FLAGS = {
DATA_MODELING_USAGE: 'data-modeling-usage', // owner: #team-data-modeling, gates the Models usage tab
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sources
+ DATA_WAREHOUSE_RENAME_SAVED_VIEW: 'data-warehouse-rename-saved-view', // owner: #team-data-modeling
DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modeling
DISCUSSIONS_SLACK_SYNC: 'discussions-slack-sync', // owner: #team-platform-features
DROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analytics
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
index 29eb0a4c6405..aa6b6d58d90f 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx
@@ -54,6 +54,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { endpointModelUrl } from 'products/data_modeling/frontend/endpointModelName'
import { MaterializationStatusIcon } from 'products/data_modeling/frontend/MaterializationStatusIcon'
+import { RenameViewModal } from 'products/data_warehouse/frontend/shared/components/RenameViewModal'
import { TableCertificationIcon } from 'products/data_warehouse/frontend/shared/components/TableCertificationBadge'
import { POSTHOG_WAREHOUSE } from 'products/data_warehouse/frontend/shared/logics/connectionSelectorLogic'
import { expressionModalLogic } from 'products/data_warehouse/frontend/shared/logics/expressionModalLogic'
@@ -157,6 +158,7 @@ export const QueryDatabase = ({
editingPropertyDefinition,
materializationStatusFilters,
dataWarehouseSavedQueriesLoading,
+ renameView,
} = useValues(queryDatabaseLogic)
const {
setExpandedFolders,
@@ -177,8 +179,13 @@ export const QueryDatabase = ({
openPropertyDefinitionEditor,
closePropertyDefinitionEditor,
updatePropertyDefinition,
+ openRenameView,
+ closeRenameView,
+ setRenameViewName,
+ submitRenameView,
} = useActions(queryDatabaseLogic)
- const { dataWarehouseSavedQueriesLoaded } = useValues(dataWarehouseViewsLogic)
+ const { dataWarehouseSavedQueriesLoaded, dataWarehouseSavedQueryDownstreamReferences } =
+ useValues(dataWarehouseViewsLogic)
const {
createDataWarehouseSavedQueryFolder,
deleteDataWarehouseSavedQueryFolder,
@@ -213,6 +220,7 @@ export const QueryDatabase = ({
// item there opens nothing. Most embedded callers hide the tree entirely, but not all.
const warehouseAccessControlEnabled =
!!featureFlags[FEATURE_FLAGS.HOGQL_WAREHOUSE_ACCESS_CONTROL] && !isEmbeddedMode
+ const renameSavedViewEnabled = !!featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_RENAME_SAVED_VIEW]
const formatTraversalChain = (chain?: (string | number)[]): string | null => {
if (!chain || chain.length === 0) {
return null
@@ -1065,6 +1073,31 @@ export const QueryDatabase = ({
>
<ButtonPrimitive menuItem>Query</ButtonPrimitive>
</DropdownMenuItem>
+ {renameSavedViewEnabled &&
+ !isEmbeddedMode &&
+ item.record.type === 'view' &&
+ item.record.isSavedQuery &&
+ item.record.view?.managed_viewset_kind === null ? (
+ <DropdownMenuItem
+ asChild
+ onClick={(e) => {
+ e.stopPropagation()
+ if (!editViewAccessDisabledReason && item.record?.view) {
+ openRenameView({ id: item.record.view.id, name: item.record.view.name })
+ }
+ }}
+ >
+ <ButtonPrimitive
+ menuItem
+ disabledReasons={
+ editViewAccessDisabledReason ? { [editViewAccessDisabledReason]: true } : {}
+ }
+ data-attr="data-warehouse-view-rename"
+ >
+ Rename view
+ </ButtonPrimitive>
+ </DropdownMenuItem>
+ ) : null}
{!isEmbeddedMode && item.record.type === 'view' && item.record.isSavedQuery ? (
<SeeLineageMenuItem target={{ lookup: 'saved_query', id: item.record.view.id }} />
) : null}
@@ -1444,6 +1477,22 @@ export const QueryDatabase = ({
onSave={updatePropertyDefinition}
/>
) : null}
+ {renameSavedViewEnabled && renameView ? (
+ <RenameViewModal
+ key={renameView.id}
+ viewName={renameView.originalName}
+ name={renameView.name}
+ nameError={renameView.nameError}
+ submitError={renameView.submitError}
+ isSaving={renameView.isSaving}
+ references={dataWarehouseSavedQueryDownstreamReferences[renameView.id]?.references ?? []}
+ referencesLoading={dataWarehouseSavedQueryDownstreamReferences[renameView.id]?.loading ?? true}
+ referencesError={dataWarehouseSavedQueryDownstreamReferences[renameView.id]?.error ?? false}
+ onNameChange={setRenameViewName}
+ onClose={closeRenameView}
+ onSubmit={submitRenameView}
+ />
+ ) : null}
</>
)
}
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
index 15fc70b0989f..9dcaf0af7821 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.test.ts
@@ -9,6 +9,7 @@ import {
} from 'scenes/data-management/database/databaseTableListLogic'
import { propertyDefinitionsList } from '~/generated/core/api'
+import { useMocks } from '~/mocks/jest'
import { performQuery } from '~/queries/query'
import { NodeKind } from '~/queries/schema/schema-general'
import type { DatabaseSchemaField } from '~/queries/schema/schema-general'
@@ -103,6 +104,103 @@ describe('queryDatabaseLogic', () => {
})
})
+ it('stores and resets rename view state in the logic', () => {
+ initKeaTests()
+ const logic = queryDatabaseLogic()
+ logic.mount()
+
+ logic.actions.openRenameView({ id: 'view-1', name: 'orders_by_day' })
+ expect(logic.values.renameView).toEqual({
+ id: 'view-1',
+ originalName: 'orders_by_day',
+ name: 'orders_by_day',
+ isSaving: false,
+ })
+
+ logic.actions.setRenameViewName('orders_by_week')
+ logic.actions.setRenameViewNameError('Invalid name')
+ logic.actions.setRenameViewSubmitError('Rename failed')
+ logic.actions.setRenameViewSaving(true)
+ expect(logic.values.renameView).toMatchObject({
+ name: 'orders_by_week',
+ nameError: 'Invalid name',
+ submitError: 'Rename failed',
+ isSaving: true,
+ })
+
+ logic.actions.closeRenameView()
+ expect(logic.values.renameView).toBeNull()
+
+ logic.unmount()
+ })
+
+ it('rejects a rename that matches a warehouse table', () => {
+ initKeaTests()
+ const logic = queryDatabaseLogic()
+ logic.mount()
+ databaseTableListLogic.findMounted()?.actions.loadDatabaseSuccess({
+ tables: {
+ orders: {
+ id: 'table-1',
+ name: 'orders',
+ type: 'data_warehouse',
+ fields: {},
+ },
+ },
+ joins: [],
+ } as any)
+
+ logic.actions.openRenameView({ id: 'view-1', name: 'orders_by_day' })
+ dataWarehouseViewsLogic
+ .findMounted()
+ ?.actions.loadDataWarehouseSavedQueryDownstreamReferencesSuccess('view-1', [])
+ logic.actions.setRenameViewName('orders')
+ logic.actions.submitRenameView()
+
+ expect(logic.values.renameView?.nameError).toBe(
+ 'A table or view with this name already exists. Choose a different name.'
+ )
+ logic.unmount()
+ })
+
+ it('shows a structured name validation error on the rename field', async () => {
+ const nameError = 'This name is already in use.'
+ useMocks({
+ get: {
+ '/api/projects/:team_id/warehouse_saved_queries/': { results: [] },
+ '/api/projects/:team_id/data_modeling_nodes/lineage/': { nodes: [], edges: [] },
+ },
+ patch: {
+ '/api/projects/:team_id/warehouse_saved_queries/:id/': [
+ 400,
+ {
+ type: 'validation_error',
+ code: 'invalid_input',
+ detail: 'Invalid input.',
+ attr: null,
+ errors: [{ code: 'invalid', detail: nameError, attr: 'name' }],
+ },
+ ],
+ },
+ })
+ initKeaTests()
+ const logic = queryDatabaseLogic()
+ logic.mount()
+ const viewsLogic = dataWarehouseViewsLogic.findMounted()!
+
+ await expectLogic(viewsLogic, () => {
+ logic.actions.openRenameView({ id: 'view-1', name: 'orders_by_day' })
+ }).toDispatchActions(['loadDataWarehouseSavedQueryDownstreamReferencesSuccess'])
+
+ logic.actions.setRenameViewName('orders_by_week')
+ await expectLogic(logic, () => {
+ logic.actions.submitRenameView()
+ }).toFinishAllListeners()
+
+ expect(logic.values.renameView).toMatchObject({ nameError, submitError: undefined })
+ logic.unmount()
+ })
+
it('loads pre-expanded properties, paginates, and filters them', async () => {
initKeaTests()
mockPropertyDefinitionsList
diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
index f469dab6f9c5..3c9c0aad3199 100644
--- a/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/queryDatabaseLogic.tsx
@@ -14,11 +14,10 @@ import {
IconRefresh,
IconWarning,
} from '@posthog/icons'
-import { LemonMenuItem } from '@posthog/lemon-ui'
-import { Spinner } from '@posthog/lemon-ui'
+import { LemonMenuItem, Spinner, lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
-import { isAccessDeniedError } from 'lib/api-error'
+import { ApiError, isAccessDeniedError, readableErrorMessage } from 'lib/api-error'
import { TreeItem } from 'lib/components/DatabaseTableTree/DatabaseTableTree'
import { FEATURE_FLAGS } from 'lib/constants'
import { LemonTreeRef, TreeDataItem } from 'lib/lemon-ui/LemonTree/LemonTree'
@@ -83,11 +82,44 @@ import type { ExternalDataSourceConnectionOptionApi } from 'products/warehouse_s
import type { DatabaseSchemaViewTable } from '../../../../queries/schema/schema-general'
import type { UserType } from '../../../../types'
-import { DataWarehouseSavedQuerySummary, dataWarehouseViewsLogic } from '../../saved_queries/dataWarehouseViewsLogic'
+import {
+ DataWarehouseSavedQueryDownstreamReferenceState,
+ DataWarehouseSavedQuerySummary,
+ dataWarehouseViewsLogic,
+ renameDataWarehouseSavedQuery,
+} from '../../saved_queries/dataWarehouseViewsLogic'
+import { validateSavedQueryName } from '../../saved_queries/savedQueryNameValidation'
import { draftsLogic } from '../draftsLogic'
export type EditorSidebarTreeRef = React.RefObject<LemonTreeRef> | null
+export interface RenameViewState {
+ id: string
+ originalName: string
+ name: string
+ nameError?: string
+ submitError?: string
+ isSaving: boolean
+}
+
+function getRenameViewNameError(error: unknown): string | undefined {
+ if (!(error instanceof ApiError)) {
+ return undefined
+ }
+
+ const fieldErrors: unknown[] = Array.isArray(error.data?.errors) ? error.data.errors : []
+ const nameError = fieldErrors.find(
+ (fieldError): fieldError is { attr: string; detail: string } =>
+ typeof fieldError === 'object' &&
+ fieldError !== null &&
+ 'attr' in fieldError &&
+ fieldError.attr === 'name' &&
+ 'detail' in fieldError &&
+ typeof fieldError.detail === 'string'
+ )
+ return nameError?.detail ?? (error.attr === 'name' && error.detail ? error.detail : undefined)
+}
+
export interface FuseSearchMatch {
// kea-typegen has a problem importing Fuse itself, so we have to duplicate this type
indices: readonly [number, number][]
@@ -1711,6 +1743,7 @@ export interface queryDatabaseLogicValues {
connectionOptions: ExternalDataSourceConnectionOptionApi[] | null // connectionSelectorLogic
dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[] // dataWarehouseViewsLogic
dataWarehouseSavedQueriesLoading: boolean // dataWarehouseViewsLogic
+ dataWarehouseSavedQueryDownstreamReferences: Record<string, DataWarehouseSavedQueryDownstreamReferenceState> // dataWarehouseViewsLogic
dataWarehouseSavedQueryFolders: DataWarehouseSavedQueryFolder[] // dataWarehouseViewsLogic
dataWarehouseSavedQueryMapById: Record<string, DataWarehouseSavedQuerySummary> // dataWarehouseViewsLogic
materializingViewIds: string[] // dataWarehouseViewsLogic
@@ -1769,6 +1802,7 @@ export interface queryDatabaseLogicValues {
relevantSavedQueries: [DataWarehouseSavedQuerySummary, FuseSearchMatch[] | null][]
relevantSavedQueryFolders: [DataWarehouseSavedQueryFolder, FuseSearchMatch[] | null][]
relevantSystemTables: [DatabaseSchemaTable, FuseSearchMatch[] | null][]
+ renameView: RenameViewState | null
searchTerm: string
searchText: string
searchTreeData: TreeDataItem[]
@@ -1804,6 +1838,10 @@ export interface queryDatabaseLogicActions {
types: string[][]
}
} // dataWarehouseViewsLogic
+ loadDataWarehouseSavedQueries: () => any // dataWarehouseViewsLogic
+ loadDataWarehouseSavedQueryDownstreamReferences: (viewId: string) => {
+ viewId: string
+ } // dataWarehouseViewsLogic
updateDataWarehouseSavedQuery: (
view: import('../../saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate
) => import('../../saved_queries/dataWarehouseViewsLogic').DataWarehouseSavedQueryUpdate // dataWarehouseViewsLogic
@@ -1884,6 +1922,9 @@ export interface queryDatabaseLogicActions {
closePropertyDefinitionEditor: () => {
value: true
}
+ closeRenameView: () => {
+ value: true
+ }
deleteUnsavedQuery: (record: Record<string, any>) => {
record: Record<string, any>
}
@@ -1987,6 +2028,12 @@ export interface queryDatabaseLogicActions {
openPropertyDefinitionEditor: (propertyDefinition: EnterprisePropertyDefinitionApi) => {
propertyDefinition: EnterprisePropertyDefinitionApi
}
+ openRenameView: (view: { id: string; name: string }) => {
+ view: {
+ id: string
+ name: string
+ }
+ }
openUnsavedQuery: (record: Record<string, any>) => {
record: Record<string, any>
}
@@ -2032,6 +2079,18 @@ export interface queryDatabaseLogicActions {
search: string
target: SidebarPropertyDefinitionTarget
}
+ setRenameViewName: (name: string) => {
+ name: string
+ }
+ setRenameViewNameError: (error: string | undefined) => {
+ error: string | undefined
+ }
+ setRenameViewSaving: (isSaving: boolean) => {
+ isSaving: boolean
+ }
+ setRenameViewSubmitError: (error: string | undefined) => {
+ error: string | undefined
+ }
setSearchTerm: (searchTerm: string) => {
searchTerm: string
}
@@ -2044,6 +2103,9 @@ export interface queryDatabaseLogicActions {
startDraggingView: (viewId: string) => {
viewId: string
}
+ submitRenameView: () => {
+ value: true
+ }
toggleFolderOpen: (
folderId: string,
isExpanded: boolean
@@ -2281,6 +2343,13 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
moveDraggedViewToDropTarget: (viewId: string, dropTargetId: string | null) => ({ viewId, dropTargetId }),
openUnsavedQuery: (record: Record<string, any>) => ({ record }),
deleteUnsavedQuery: (record: Record<string, any>) => ({ record }),
+ openRenameView: (view: { id: string; name: string }) => ({ view }),
+ closeRenameView: true,
+ setRenameViewName: (name: string) => ({ name }),
+ setRenameViewNameError: (error: string | undefined) => ({ error }),
+ setRenameViewSubmitError: (error: string | undefined) => ({ error }),
+ setRenameViewSaving: (isSaving: boolean) => ({ isSaving }),
+ submitRenameView: true,
}),
connect(() => ({
values: [
@@ -2311,6 +2380,7 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
'dataWarehouseSavedQueries',
'dataWarehouseSavedQueryFolders',
'dataWarehouseSavedQueryMapById',
+ 'dataWarehouseSavedQueryDownstreamReferences',
'dataWarehouseSavedQueriesLoading',
'materializingViewIds',
],
@@ -2336,6 +2406,8 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
'updateDataWarehouseSavedQuerySuccess',
'updateDataWarehouseSavedQueryFailure',
'updateDataWarehouseSavedQuery',
+ 'loadDataWarehouseSavedQueryDownstreamReferences',
+ 'loadDataWarehouseSavedQueries',
],
draftsLogic,
['loadDrafts', 'renameDraft', 'loadMoreDrafts'],
@@ -2368,6 +2440,22 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
updatePropertyDefinition: () => null,
},
],
+ renameView: [
+ null as RenameViewState | null,
+ {
+ openRenameView: (_, { view }) => ({
+ id: view.id,
+ originalName: view.name,
+ name: view.name,
+ isSaving: false,
+ }),
+ closeRenameView: () => null,
+ setRenameViewName: (state, { name }) => (state ? { ...state, name, nameError: undefined } : state),
+ setRenameViewNameError: (state, { error }) => (state ? { ...state, nameError: error } : state),
+ setRenameViewSubmitError: (state, { error }) => (state ? { ...state, submitError: error } : state),
+ setRenameViewSaving: (state, { isSaving }) => (state ? { ...state, isSaving } : state),
+ },
+ ],
selectedSchema: [
null as DatabaseSchemaDataWarehouseTable | DatabaseSchemaTable | DataWarehouseSavedQuerySummary | null,
{
@@ -2568,6 +2656,62 @@ export const queryDatabaseLogic = kea<queryDatabaseLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ openRenameView: ({ view }) => {
+ actions.loadDataWarehouseSavedQueryDownstreamReferences(view.id)
+ },
+ submitRenameView: async () => {
+ const view = values.renameView
+ if (
+ !view ||
+ view.isSaving ||
+ (values.dataWarehouseSavedQueryDownstreamReferences[view.id]?.loading ?? true)
+ ) {
+ return
+ }
+
+ const name = view.name.trim()
+ const validationError = validateSavedQueryName(name)
+ if (validationError) {
+ actions.setRenameViewNameError(validationError)
+ return
+ }
+ if (
+ name !== view.originalName &&
+ (values.dataWarehouseSavedQueries.some((savedView) => savedView.name === name) ||
+ values.dataWarehouseTables.some((table) => table.name === name))
+ ) {
+ actions.setRenameViewNameError(
+ 'A table or view with this name already exists. Choose a different name.'
+ )
+ return
+ }
+ if (name === view.originalName) {
+ actions.closeRenameView()
+ return
+ }
+
+ actions.setRenameViewNameError(undefined)
+ actions.setRenameViewSubmitError(undefined)
+ actions.setRenameViewSaving(true)
+ try {
+ await renameDataWarehouseSavedQuery(view.id, name)
+ actions.loadDataWarehouseSavedQueries()
+ actions.refreshDatabaseSchema()
+ lemonToast.success('View renamed')
+ actions.closeRenameView()
+ } catch (error) {
+ const nameError = getRenameViewNameError(error)
+ if (nameError) {
+ actions.setRenameViewNameError(nameError)
+ } else {
+ actions.setRenameViewSubmitError(
+ readableErrorMessage(error) ?? 'Could not rename the view. Try again.'
+ )
+ }
+ } finally {
+ actions.setRenameViewSaving(false)
+ }
+ },
createDataWarehouseSavedQuerySuccess: ({ payload }) => {
if (payload?.folder_id) {
const folderNodeId = `view-folder-${payload.folder_id}`
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
index 3ce5e1107e8b..5eb1be92ea3c 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts
@@ -128,6 +128,26 @@ describe('dataWarehouseViewsLogic', () => {
expect(logic.values.dataWarehouseSavedQueries).toEqual([])
})
+ it('treats a missing lineage node as no downstream references', async () => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/data_modeling_nodes/lineage/': [404, { detail: 'Node not found.' }],
+ },
+ })
+
+ await expectLogic(logic, () => {
+ logic.actions.loadDataWarehouseSavedQueryDownstreamReferences('view-404')
+ })
+ .toDispatchActions(['loadDataWarehouseSavedQueryDownstreamReferencesSuccess'])
+ .toNotHaveDispatchedActions(['loadDataWarehouseSavedQueryDownstreamReferencesFailure'])
+
+ expect(logic.values.dataWarehouseSavedQueryDownstreamReferences['view-404']).toEqual({
+ error: false,
+ loading: false,
+ references: [],
+ })
+ })
+
// Regression: the blocked node's id arrives on the response body's `extra`, which the error
// object keeps on `data`. Read off the error's root it was always undefined, so a refused
// delete offered no way to see what reads the view.
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
index 3f50b948dbb3..6afe20f8160e 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.tsx
@@ -6,6 +6,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api, { ApiConfig } from 'lib/api'
+import { isUnavailableEndpointError } from 'lib/api-error'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { urls } from 'scenes/urls'
@@ -19,9 +20,11 @@ import {
} from '~/types'
import { dataModelingNodesLineageRetrieve } from 'products/data_modeling/frontend/generated/api'
+import type { LineageResponseApi, NodeApi } from 'products/data_modeling/frontend/generated/api.schemas'
import {
warehouseSavedQueriesList,
warehouseSavedQueriesMaterializeCreate,
+ warehouseSavedQueriesPartialUpdate,
} from 'products/data_warehouse/frontend/generated/api'
import type { DatabaseSchemaViewTable } from '../../../queries/schema/schema-general'
@@ -39,6 +42,45 @@ export const DEFAULT_MATERIALIZE_SYNC_FREQUENCY: DataModelingSyncInterval = '24h
export type DataWarehouseSavedQuerySummary = Omit<DataWarehouseSavedQuery, 'columns' | 'query'>
+export type DataWarehouseSavedQueryDownstreamReference = Pick<NodeApi, 'id' | 'name' | 'type'>
+
+export interface DataWarehouseSavedQueryDownstreamReferenceState {
+ error: boolean
+ loading: boolean
+ references: DataWarehouseSavedQueryDownstreamReference[]
+}
+
+function getDataWarehouseSavedQueryDownstreamReferences(
+ lineage: LineageResponseApi,
+ viewId: string
+): DataWarehouseSavedQueryDownstreamReference[] {
+ const source = lineage.nodes.find((node) => node.saved_query_id === viewId)
+ if (!source) {
+ return []
+ }
+
+ const downstreamBySource = new Map<string, string[]>()
+ for (const edge of lineage.edges) {
+ downstreamBySource.set(edge.source_id, [...(downstreamBySource.get(edge.source_id) ?? []), edge.target_id])
+ }
+
+ const downstreamIds = new Set<string>([source.id])
+ const queue = [source.id]
+ while (queue.length > 0) {
+ const currentId = queue.shift()!
+ for (const downstreamId of downstreamBySource.get(currentId) ?? []) {
+ if (!downstreamIds.has(downstreamId)) {
+ downstreamIds.add(downstreamId)
+ queue.push(downstreamId)
+ }
+ }
+ }
+
+ return lineage.nodes
+ .filter((node) => node.id !== source.id && downstreamIds.has(node.id))
+ .map(({ id, name, type }) => ({ id, name, type }))
+}
+
export interface DataWarehouseSavedQueryUpdate extends Partial<DataWarehouseSavedQuery> {
id: string
types?: string[][]
@@ -50,6 +92,10 @@ export interface DataWarehouseSavedQueryUpdate extends Partial<DataWarehouseSave
soft_update?: boolean
}
+export async function renameDataWarehouseSavedQuery(viewId: string, name: string): Promise<void> {
+ await warehouseSavedQueriesPartialUpdate(String(ApiConfig.getCurrentTeamId()), viewId, { name })
+}
+
// A plain function, not a logic action: the toast that calls it can outlive the logic, and an
// unmounted logic has no listeners.
async function openViewPage(viewId: string): Promise<void> {
@@ -93,6 +139,7 @@ export interface dataWarehouseViewsLogicValues {
dataWarehouseSavedQueriesFailed: boolean
dataWarehouseSavedQueriesLoaded: boolean
dataWarehouseSavedQueriesLoading: boolean
+ dataWarehouseSavedQueryDownstreamReferences: Record<string, DataWarehouseSavedQueryDownstreamReferenceState>
dataWarehouseSavedQueryFolders: DataWarehouseSavedQueryFolder[]
dataWarehouseSavedQueryFoldersById: Record<string, DataWarehouseSavedQueryFolder>
dataWarehouseSavedQueryFoldersLoading: boolean
@@ -233,6 +280,19 @@ export interface dataWarehouseViewsLogicActions {
dataWarehouseSavedQueries: DataWarehouseSavedQuerySummary[]
payload?: any
}
+ loadDataWarehouseSavedQueryDownstreamReferences: (viewId: string) => {
+ viewId: string
+ }
+ loadDataWarehouseSavedQueryDownstreamReferencesFailure: (viewId: string) => {
+ viewId: string
+ }
+ loadDataWarehouseSavedQueryDownstreamReferencesSuccess: (
+ viewId: string,
+ references: DataWarehouseSavedQueryDownstreamReference[]
+ ) => {
+ references: DataWarehouseSavedQueryDownstreamReference[]
+ viewId: string
+ }
loadDataWarehouseSavedQueryFolders: () => any
loadDataWarehouseSavedQueryFoldersFailure: (
error: string,
@@ -427,6 +487,23 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
updateDataWarehouseSavedQueryFailure: () => false,
},
],
+ dataWarehouseSavedQueryDownstreamReferences: [
+ {} as Record<string, DataWarehouseSavedQueryDownstreamReferenceState>,
+ {
+ loadDataWarehouseSavedQueryDownstreamReferences: (state, { viewId }) => ({
+ ...state,
+ [viewId]: { error: false, loading: true, references: [] },
+ }),
+ loadDataWarehouseSavedQueryDownstreamReferencesFailure: (state, { viewId }) => ({
+ ...state,
+ [viewId]: { error: true, loading: false, references: [] },
+ }),
+ loadDataWarehouseSavedQueryDownstreamReferencesSuccess: (state, { viewId, references }) => ({
+ ...state,
+ [viewId]: { error: false, loading: false, references },
+ }),
+ },
+ ],
// Views whose materialization is in flight. Reactive so the sidebar can show a spinner in
// place of the view icon while it materializes (a stable state, unlike the transient list
// loading flag), then flip to the materialized icon once it settles.
@@ -439,6 +516,12 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
],
}),
actions({
+ loadDataWarehouseSavedQueryDownstreamReferences: (viewId: string) => ({ viewId }),
+ loadDataWarehouseSavedQueryDownstreamReferencesFailure: (viewId: string) => ({ viewId }),
+ loadDataWarehouseSavedQueryDownstreamReferencesSuccess: (
+ viewId: string,
+ references: DataWarehouseSavedQueryDownstreamReference[]
+ ) => ({ viewId, references }),
updateDataWarehouseSavedQueryFailed: (viewId: string) => ({ viewId }),
materializationChanged: (viewId: string) => ({ viewId }),
runDataWarehouseSavedQuerySuccess: (viewId: string) => ({ viewId }),
@@ -630,6 +713,23 @@ export const dataWarehouseViewsLogic = kea<dataWarehouseViewsLogicType>([
],
})),
listeners(({ actions, values, cache }) => ({
+ loadDataWarehouseSavedQueryDownstreamReferences: async ({ viewId }) => {
+ try {
+ const lineage = await dataModelingNodesLineageRetrieve(String(ApiConfig.getCurrentTeamId()), {
+ saved_query_id: viewId,
+ })
+ actions.loadDataWarehouseSavedQueryDownstreamReferencesSuccess(
+ viewId,
+ getDataWarehouseSavedQueryDownstreamReferences(lineage, viewId)
+ )
+ } catch (error) {
+ if (isUnavailableEndpointError(error)) {
+ actions.loadDataWarehouseSavedQueryDownstreamReferencesSuccess(viewId, [])
+ } else {
+ actions.loadDataWarehouseSavedQueryDownstreamReferencesFailure(viewId)
+ }
+ }
+ },
loadDataWarehouseSavedQueriesSuccess: ({ dataWarehouseSavedQueries }) => {
const materializing = values.materializingViewIds
if (materializing.length === 0) {
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/editing.py b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
index 0b1c1546240e..7e0c72d73c3c 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/editing.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
@@ -538,6 +538,7 @@ class DataWarehouseSavedQuerySerializer(
validated_data["sync_frequency_interval"] = None
view: DataWarehouseSavedQuery = super().update(locked_instance, validated_data)
+ name_changed = before_update.name != view.name
if frequency_changed:
previous_target = modeling_api.declared_targets_by_saved_query(view.team_id, [view.pk]).get(
@@ -592,7 +593,7 @@ class DataWarehouseSavedQuerySerializer(
# Best effort sync to the data modeling DAG representation. The savepoint keeps a
# failed sync best effort without poisoning the update's own transaction.
- if "query" in validated_data:
+ if "query" in validated_data or name_changed:
try:
with transaction.atomic():
modeling_api.sync_saved_query_to_dag(view)
diff --git a/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py b/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py
index cd0ea1706b60..61a09989d2e9 100644
--- a/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py
+++ b/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py
@@ -33,7 +33,7 @@ class TestSavedQueryDagSyncIntegration(APIBaseTest):
assert node.dag is not None
self.assertEqual(node.dag.name, DEFAULT_DAG_NAME)
- def test_update_saved_query_syncs_to_dag(self):
+ def test_rename_saved_query_syncs_name_to_dag(self):
# create
create_response = self.client.post(
f"/api/environments/{self.team.id}/warehouse_saved_queries/",
@@ -48,19 +48,11 @@ class TestSavedQueryDagSyncIntegration(APIBaseTest):
)
self.assertEqual(create_response.status_code, status.HTTP_201_CREATED)
saved_query_id = create_response.json()["id"]
- latest_history_id = create_response.json().get("latest_history_id")
- # update
+ # rename
update_response = self.client.patch(
f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}/",
- {
- "name": "dag_sync_update_test_renamed",
- "query": {
- "kind": "HogQLQuery",
- "query": "SELECT 2",
- },
- "edited_history_id": latest_history_id,
- },
+ {"name": "dag_sync_update_test_renamed"},
format="json",
)
self.assertEqual(update_response.status_code, status.HTTP_200_OK)
@@ -69,6 +61,7 @@ class TestSavedQueryDagSyncIntegration(APIBaseTest):
assert node is not None
assert node.saved_query is not None
self.assertEqual(node.saved_query.name, "dag_sync_update_test_renamed")
+ self.assertEqual(node.name, "dag_sync_update_test_renamed")
def test_delete_saved_query_removes_from_dag(self):
# create
diff --git a/products/data_warehouse/frontend/shared/components/RenameViewModal.stories.tsx b/products/data_warehouse/frontend/shared/components/RenameViewModal.stories.tsx
new file mode 100644
index 000000000000..0f279722b278
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/RenameViewModal.stories.tsx
@@ -0,0 +1,39 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { RenameViewModal } from './RenameViewModal'
+
+const meta: Meta<typeof RenameViewModal> = {
+ title: 'Scenes-App/Data Warehouse/Rename view modal',
+ component: RenameViewModal,
+ decorators: [
+ (Story) => (
+ <div className="bg-default p-4">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof RenameViewModal>
+
+export const WithKnownReferences: Story = {
+ args: {
+ viewName: 'orders_by_day',
+ name: 'orders_by_day',
+ nameError: undefined,
+ submitError: undefined,
+ isSaving: false,
+ references: [
+ { id: 'daily-revenue', name: 'daily_revenue', type: 'view' },
+ { id: 'revenue-report', name: 'revenue_report', type: 'matview' },
+ { id: 'orders-endpoint', name: 'orders', type: 'endpoint' },
+ ],
+ referencesLoading: false,
+ referencesError: false,
+ inline: true,
+ onNameChange: () => undefined,
+ onClose: () => undefined,
+ onSubmit: () => undefined,
+ },
+}
diff --git a/products/data_warehouse/frontend/shared/components/RenameViewModal.tsx b/products/data_warehouse/frontend/shared/components/RenameViewModal.tsx
new file mode 100644
index 000000000000..f1a065c9518a
--- /dev/null
+++ b/products/data_warehouse/frontend/shared/components/RenameViewModal.tsx
@@ -0,0 +1,148 @@
+import { LemonBanner, LemonButton, LemonInput, LemonModal, Spinner } from '@posthog/lemon-ui'
+
+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { Link } from 'lib/lemon-ui/Link'
+import { urls } from 'scenes/urls'
+
+export interface RenameViewReference {
+ id: string
+ name: string
+ type?: string
+}
+
+export interface RenameViewModalProps {
+ viewName: string
+ name: string
+ nameError?: string
+ submitError?: string
+ isSaving: boolean
+ references: RenameViewReference[]
+ referencesLoading: boolean
+ referencesError: boolean
+ inline?: boolean
+ onNameChange: (name: string) => void
+ onClose: () => void
+ onSubmit: () => void
+}
+
+function getReferenceTypeLabel(type?: string): string {
+ switch (type) {
+ case 'table':
+ return 'Table'
+ case 'view':
+ return 'View'
+ case 'matview':
+ return 'Materialized view'
+ case 'endpoint':
+ return 'Endpoint'
+ case 'metric':
+ return 'Metric'
+ default:
+ return type ? type.replaceAll('_', ' ') : 'Reference'
+ }
+}
+
+export function RenameViewModal({
+ viewName,
+ name,
+ nameError,
+ submitError,
+ isSaving,
+ references,
+ referencesLoading,
+ referencesError,
+ inline,
+ onNameChange,
+ onClose,
+ onSubmit,
+}: RenameViewModalProps): JSX.Element {
+ const submit = (): void => {
+ if (isSaving || referencesLoading) {
+ return
+ }
+ onSubmit()
+ }
+
+ return (
+ <LemonModal
+ isOpen
+ inline={inline}
+ onClose={onClose}
+ closable={!isSaving}
+ title="Rename view"
+ width={560}
+ hasUnsavedInput={name.trim() !== viewName}
+ data-attr="data-warehouse-rename-view-modal"
+ footer={
+ <>
+ <LemonButton type="tertiary" onClick={onClose} disabledReason={isSaving ? 'Renaming view' : null}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ loading={isSaving}
+ disabledReason={referencesLoading ? 'Loading known references' : undefined}
+ onClick={submit}
+ data-attr="data-warehouse-rename-view-submit"
+ >
+ Rename view
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <LemonField.Pure label="View name" error={nameError}>
+ <LemonInput
+ value={name}
+ onChange={onNameChange}
+ onPressEnter={submit}
+ disabled={isSaving}
+ autoFocus
+ />
+ </LemonField.Pure>
+
+ {referencesLoading ? (
+ <div className="flex items-center gap-2 text-secondary text-sm">
+ <Spinner />
+ <span>Loading known references</span>
+ </div>
+ ) : referencesError ? (
+ <p className="text-danger text-sm">Could not load known references from data model lineage.</p>
+ ) : references.length > 0 ? (
+ <LemonCollapse
+ panels={[
+ {
+ key: 'references',
+ header: `Known references (${references.length})`,
+ content: (
+ <ul className="space-y-1 text-sm">
+ {references.map((reference) => (
+ <li key={reference.id} className="break-words">
+ <span className="text-secondary">
+ {getReferenceTypeLabel(reference.type)}:
+ </span>{' '}
+ <Link to={urls.nodeDetail(reference.id)} target="_blank">
+ {reference.name}
+ </Link>
+ </li>
+ ))}
+ </ul>
+ ),
+ },
+ ]}
+ />
+ ) : (
+ <p className="text-secondary text-sm">No downstream references found in data model lineage.</p>
+ )}
+
+ <LemonBanner type="warning" alignItems="start">
+ This changes the view name only. SQL in saved views, materialized views, endpoints, insights,
+ dashboards, notebooks, and external systems is not updated and can stop working after the rename.
+ </LemonBanner>
+
+ {submitError ? <p className="text-danger text-sm">{submitError}</p> : null}
+ </div>
+ </LemonModal>
+ )
+}