:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): edit a view's query in the model page SQL editor (#122241)
Jovan Sakovicc6200d36b481
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8cd8a816fe39..c7cbdbc26b1a 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7423,25 +7423,25 @@ snapshots:products-data-modeling-node-detail-scene--deleted-model--light:hash: v1.k794b7964.d1862e22a973b0fb2725b4b6d613eb0ddbe2074d54d20b4dbb85eb5193a994b6.0uti-ZtW-QCeFNNJ3XmHjC7NRpp3dO35TR3L3v9_Zw0products-data-modeling-node-detail-scene--materialized-view--dark:- hash: v1.k794b7964.58a8839d5c900eaed0b737649081b40539b0e7940baf571534b83e5f506c7061.Uf_yvFlyMvL0fxzPy6y9r5-utRl9LowGOko9v-ARNBY+ hash: v1.k794b7964.08d6b729cf226a786d927b5357cfd76d258fce5ebbb593fab17c61f78ace7fe7.LBmzczD4f1wx2ipCusUyf88CNNjlnduvLOsNEVnycSMproducts-data-modeling-node-detail-scene--materialized-view--light:- hash: v1.k794b7964.82adf6bc8d2bd6e60134097e96040905a2a91c3e0d7b6a0fbcfa1cee34f547ff.2drU1_bHNGTIaek7WA83B5wfJtrn727wYIuF4CrtmPY+ hash: v1.k794b7964.b2112185e7d61a85c7f79e39cdd9d749aca2c8504032db7ebced9092f7e569a2._jsFUmHysc6h5i6BoelGMadIWYGfh4tlrFnqC7FejcEproducts-data-modeling-node-detail-scene--narrow-materialized-view--dark:- hash: v1.k794b7964.08d1d1b194143eed6ceab6782f5818e78071c4792f52745b2fdfc194b95a21ab.Mgs5G6P9Ycgk7xnl_2IaPXWcYuDY0BhbD9rAHfaxp10+ hash: v1.k794b7964.36987bbcfe6ac31dfc1e9412cfb71335ee666129d2488b6bac290ba0b30943b9.4C3xJQkTfuuE1fXoncAKstBGxhVdpalvd8KzSfSnB70products-data-modeling-node-detail-scene--narrow-materialized-view--light:- hash: v1.k794b7964.41f98a6954b927063854d9815cdaf89ce84a0fb1ffac1e7a55a16b0412d69fdb.Uv3S7f1GiyV_k6iRMBBQLuHmJr9C-Jr4XDwIYb4KQgM+ hash: v1.k794b7964.8dea1d866686fc26f47c833987da715d480b20559ce29743e66ff13f98d0a068.aAZWq76wOryGA6EoYryFc0NMKMWMiQMhP_WrxdrnMzgproducts-data-modeling-node-detail-scene--narrow-suspended-with-run-history--dark:hash: v1.k794b7964.61e9fdf103d31a89474fce6c238e7daf727a23734c93113d0ce6beda8bd6bde8.5xne6j1ft6cwHmCVvkk8XTwAJvjmbjYu0H_viJzPrwsproducts-data-modeling-node-detail-scene--narrow-suspended-with-run-history--light:hash: v1.k794b7964.bb01b3a50bc5b002f1cf7c9cbd6dc8ddca449d37abbdc6750623d2873630879e.AsQNacWMvT8ZkkMBKJH0Ux0tO2oE_Afzh9Y-qdCzTqcproducts-data-modeling-node-detail-scene--narrow-view--dark:- hash: v1.k794b7964.25a34e60b9c8a2f742c3357b7de9582b729e83f6495ca01440e7594d54e5051b.y0d9tum0sniHvMHHe-tQNen40sNqpnCRYyuIJnJZyHY+ hash: v1.k794b7964.76124a29a7a974fa389305d51f2c7a760961e26dee3256d036fcc9bc8d6a9131.C0A38nM7qfrcAZ1rZRksynXArDUfV3A-meKpG1vrX2Mproducts-data-modeling-node-detail-scene--narrow-view--light:- hash: v1.k794b7964.e336da3925495efba09641d7d55ae60447f25e34db60de4964935eb25b313586.08WjFpLXY0-1D76DZvm8-rxnZm44FU02rO39X8CGwHw+ hash: v1.k794b7964.ad25eea8a9b4a76d4174c0e7c465b4129ee2bf015eaa719aa14ebbddfb5eabcd.05aHcAacwMG0OtI7-cIYvAmS0HGn7UyaP-4o_AqSFQwproducts-data-modeling-node-detail-scene--paginated-columns--dark:- hash: v1.k794b7964.8ba9125eab82549cf3c968b011c30a507a2fe3bf2a651d3bff25e30cb4fb8fa6.PrjNUSmyms9gik_jkQPbO_0O-_MfNi8SJtv4Jr4nfjE+ hash: v1.k794b7964.6c06c7617b68576facc68611e01366e1f7ae74562f80dc229bc26a0fac1e8399.V3Qk10yFSonj-g6J-D1GtmEnTsT-6ldh9zWfd2yZTFsproducts-data-modeling-node-detail-scene--paginated-columns--light:- hash: v1.k794b7964.f61eaae027db3d08cb3c2121418110bfd75fdb60f4428e218a47b4d8f26cce33.ataBThPgwZ7aakJY6XgnmagVcYt1ddzqdXp2pQrSvK0+ hash: v1.k794b7964.b31c476c47d1978ff552fddbfcb77ad263c0c8f22dcbcc44b60e70e4653ac060.JNntlPiJsIrZcnvJLXSh7lRKeUdb7PKpKtQR-SLODAgproducts-data-modeling-node-detail-scene--post-hog-table--dark:hash: v1.k794b7964.4c6319ac95438cae6bdb4708f9e5df00ae41cdd530f5a6b627c874b539c370d2._qHdJB0ZxCNXW61GVlt-oRucyXgt-_H-hKbJ3pdoFikproducts-data-modeling-node-detail-scene--post-hog-table--light:@@ -7451,9 +7451,9 @@ snapshots:products-data-modeling-node-detail-scene--suspended-with-run-history--light:hash: v1.k794b7964.8e3a299698deffd2d09cc49fcef1f040cf40d0ec3be8fddf52ca34551c8f7e0a.uq9M5UbnFlUTEOem2aXKGYcYItgfYjMxhBk7AG-UvyQproducts-data-modeling-node-detail-scene--view--dark:- hash: v1.k794b7964.0aedbf7d575d33462e900758b5d7cd5a599542e982d157d998f198378863d28b.YRWr1jgXH75zwmMShTj6HaBQsaDWW_NraXqBq3h_G2k+ hash: v1.k794b7964.ac5fa6a35242c777015c6772fcf92d26b3842cdb2d9ca8b9721b9e8526ad5fb3.ZDY_3FNQjkPIwxgW7qZji5gjdLHcbQdL5Snu2WLrx2wproducts-data-modeling-node-detail-scene--view--light:- hash: v1.k794b7964.c5a6103b866e7ec5ffcc146f472a56a6ebac67de9fd4d383d883fdf5c013a9be.kcTlP88yxKcpwp_WBpM0v9WdPSbECiQszcpexP9ni5g+ hash: v1.k794b7964.e743a0848352753df7ab1cbbc6538044d9de0a387f319617de876b210d4bce47.n2hUpnRhsVX_Bo6mGpZaqgJ9kw0dbt46jONG85BMNdUproducts-data-modeling-node-detail-scene--warehouse-table--dark:hash: v1.k794b7964.1cd6cfb29f1510ee23c7bd3c54e8fd139f64e2c62796c85f2159f104562f56ab.8NkVqssgmL3BJGQBcZdXzZ_iGrYklaxHo_JUtIkinWQproducts-data-modeling-node-detail-scene--warehouse-table--light:diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex 0408e18f928d..114693ef24aa 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -16,6 +16,7 @@ import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { cn } from 'lib/utils/css-classes'import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'+import { urls } from 'scenes/urls'import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'import { SceneTitlePanelButton } from '~/layout/scenes/components/SceneTitlePanelButton'@@ -65,6 +66,10 @@ interface QueryWindowProps {autoFocusQueryPane?: booleanhideVariables?: booleanhideFilters?: boolean+ hideAiTools?: boolean+ showOpenInSqlEditor?: boolean+ /** False removes the button that expands the schema panel. Defaults to true. */+ canExpandDatabaseTree?: boolean}export function QueryWindow({@@ -87,6 +92,9 @@ export function QueryWindow({autoFocusQueryPane,hideVariables,hideFilters,+ hideAiTools,+ showOpenInSqlEditor,+ canExpandDatabaseTree = true,}: QueryWindowProps): JSX.Element {const codeEditorKey = `hogql-editor-${tabId}`const logic = sqlEditorLogic({ tabId })@@ -278,12 +286,14 @@ export function QueryWindow({)}><div className="flex flex-wrap items-center gap-2">- <ExpandDatabaseTreeButton- showDatabaseTree={showDatabaseTree}- onShowDatabaseTree={onShowDatabaseTree}- mode={mode}- hostProduct={hostProduct}- />+ {canExpandDatabaseTree ? (+ <ExpandDatabaseTreeButton+ showDatabaseTree={showDatabaseTree}+ onShowDatabaseTree={onShowDatabaseTree}+ mode={mode}+ hostProduct={hostProduct}+ />+ ) : null}{hideRunButton ? null : (<RunButtononRunQuery={onRunQuery}@@ -305,7 +315,7 @@ export function QueryWindow({) : null}{!hideFilters ? <QueryFiltersMenu /> : null}<QueryPlaceholdersMenu />- {editingView ? (+ {editingView && mode !== SQLEditorMode.Embedded ? (<AccessControlActionresourceType={AccessControlResourceType.WarehouseObjects}minAccessLevel={AccessControlLevel.Editor}@@ -324,7 +334,8 @@ export function QueryWindow({</div><div className="ml-auto flex items-center gap-2">- <FixErrorButton type="secondary" size="small" source="action-bar" />+ {showOpenInSqlEditor ? <OpenInSqlEditorButton /> : null}+ {hideAiTools ? null : <FixErrorButton type="secondary" size="small" source="action-bar" />}{editorSettingsItems.length > 0 ? (<LemonMenuitems={editorSettingsItems}@@ -343,7 +354,7 @@ export function QueryWindow({</LemonMenu>) : null}{vimModeFeatureEnabled ? <VimrcModal editorKey={codeEditorKey} /> : null}- {mode === SQLEditorMode.Embedded && (+ {mode === SQLEditorMode.Embedded && !hideAiTools && (<SceneTitlePanelButtonbuttonClassName="size-[26px]"maxToolProps={executeSqlMaxToolProps}@@ -486,6 +497,25 @@ const InternalQueryWindow = memo(function InternalQueryWindow({return <OutputPane tabId={tabId} biMode={biMode} onShareTab={onShareTab} />})+function OpenInSqlEditorButton(): JSX.Element {+ const { editingView, queryInput, hasEditorChanges } = useValues(sqlEditorLogic)++ // Unsaved edits travel with the link, so the view opens in the SQL editor with them applied and not saved.+ return (+ <LemonButton+ type="secondary"+ size="small"+ to={urls.sqlEditor({+ view_id: editingView?.id,+ query: !editingView || hasEditorChanges ? (queryInput ?? '') : undefined,+ })}+ data-attr="sql-editor-open-in-sql-editor"+ >+ Open in SQL editor+ </LemonButton>+ )+}+function CollapsedConnectionSelector({ tabId, mode }: { tabId: string; mode?: SQLEditorMode }): JSX.Element | null {const { isDatabaseTreeCollapsed } = useValues(editorSizingLogic)diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex 1d123b8373df..700f5091413c 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -58,6 +58,7 @@ import { QueryWindow } from './QueryWindow'import { QuillSQLEditorSceneActions } from './QuillSQLEditorSceneActions'import { sqlEditorLogic } from './sqlEditorLogic'import { SQLEditorMode, isEmbeddedSQLEditorMode } from './sqlEditorModes'+import { useUpdateEditingView } from './useUpdateEditingView'export enum SQLEditorPanel {Full = 'full',@@ -73,6 +74,7 @@ interface SQLEditorProps {tabId?: stringmode?: SQLEditorMode+ /** Pass false to leave out the schema panel and the button that expands it. */showDatabaseTree?: booleandefaultShowDatabaseTree?: boolean/** Extra top-level sections for the database tree, owned by the embedder — see QueryDatabase. */@@ -102,6 +104,12 @@ interface SQLEditorProps {hideAgentHints?: booleanhideVariables?: booleanhideFilters?: boolean+ /** Leave out the toolbar's AI buttons. */+ hideAiTools?: boolean+ /** Adds an "Open in SQL editor" button to the query toolbar. */+ showOpenInSqlEditor?: boolean+ /** Rendered inside the editor's logic bindings and draws nothing, so a host can read editor state. */+ hostSync?: ReactNode}export function SQLEditor({@@ -129,6 +137,9 @@ export function SQLEditor({hideAgentHints,hideVariables,hideFilters,+ hideAiTools,+ showOpenInSqlEditor,+ hostSync,}: SQLEditorProps): JSX.Element {const ref = useRef(null)const navigatorRef = useRef(null)@@ -305,6 +316,7 @@ export function SQLEditor({props={{ tabId, mode, monaco, editor, singleStatement, hideAgentHints }}>{showQueryPanel ? <VariablesQuerySync /> : null}+ {hostSync}{panel === SQLEditorPanel.Output ? (<div className="flex h-full min-h-0 flex-col overflow-hidden"><OutputPane@@ -355,6 +367,9 @@ export function SQLEditor({autoFocusQueryPane={autoFocusQueryPane}hideVariables={hideVariables}hideFilters={hideFilters}+ hideAiTools={hideAiTools}+ showOpenInSqlEditor={showOpenInSqlEditor}+ canExpandDatabaseTree={showDatabaseTree !== false}/>)}</div>@@ -497,16 +512,12 @@ function SQLEditorSceneTitle(): JSX.Element | null {editingInsight,insightLoading,sourceQuery,- changesToSave,- inProgressViewEdits,isSourceQueryLastRun,- isMultiQuery,selectedConnectionId,hasEditorChanges,} = useValues(sqlEditorLogic)const { convertToNotebook, openHistoryModal } = useActions(editorSceneLogic)const {- reviewViewUpdate,updateInsight,closeEditingObject,saveAsInsight,@@ -650,58 +661,14 @@ function SQLEditorSceneTitle(): JSX.Element | null {return undefined}, [insightLoading, isSourceQueryLastRun, responseLoading, responseError, response])- const { editingViewDisabledReason, editingViewLoading } = useMemo((): {- editingViewDisabledReason: string | undefined- editingViewLoading: boolean- } => {- if (updatingDataWarehouseSavedQuery) {- return { editingViewDisabledReason: 'Saving...', editingViewLoading: true }- }-- if (isMultiQuery) {- return {- editingViewDisabledReason: 'Views must be a single query — remove extra statements to update',- editingViewLoading: false,- }- }-- if (!changesToSave) {- return { editingViewDisabledReason: 'No changes to save', editingViewLoading: false }- }-- // Require the current (edited) query to have been run successfully before updating — a stale- // response from a previous run must not enable the button after further edits.- if (!isSourceQueryLastRun) {- return {- editingViewDisabledReason: 'Run the latest query before updating the view',- editingViewLoading: false,- }- }-- if (responseLoading) {- return { editingViewDisabledReason: 'Running query...', editingViewLoading: true }- }-- if (responseError || !response) {- return {- editingViewDisabledReason: 'Run the query successfully before updating the view',- editingViewLoading: false,- }- }-- return { editingViewDisabledReason: undefined, editingViewLoading: false }- }, [- updatingDataWarehouseSavedQuery,- changesToSave,- isSourceQueryLastRun,- responseLoading,- responseError,- response,- isMultiQuery,- ])+ const {+ disabledReason: editingViewDisabledReason,+ loading: editingViewLoading,+ isMaterializedView,+ update: updateEditingView,+ } = useUpdateEditingView()const EditingViewButtonIcon = editingViewLoading ? Spinner : IconDownload- const isMaterializedView = editingView?.is_materialized === trueconst closeObjectTooltip = editingInsight? 'Close this insight and reset the SQL editor to an unsaved query without clearing your SQL or visualization settings.': editingView@@ -798,19 +765,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {closeObjectTooltip={closeObjectTooltip}editingViewDisabledReason={editingViewDisabledReason}editingViewLoading={editingViewLoading}- onUpdateView={() =>- editingView &&- reviewViewUpdate({- id: editingView.id,- query: {- ...sourceQuery.source,- query: queryInput ?? '',- },- types: response && 'types' in response ? (response?.types ?? []) : [],- shouldRematerialize: isMaterializedView,- edited_history_id: inProgressViewEdits[editingView.id],- })- }+ onUpdateView={updateEditingView}saveAsInsightDisabledReason={saveAsInsightDisabledReason}saveAsDisabledReason={saveAsDisabledReason}saveAsViewAccessDisabledReason={saveAsViewAccessDisabledReason}@@ -838,19 +793,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {userAccessLevel={editingView.user_access_level}><LemonButton- onClick={() =>- reviewViewUpdate({- id: editingView.id,- query: {- ...sourceQuery.source,- query: queryInput ?? '',- },- types:- response && 'types' in response ? (response?.types ?? []) : [],- shouldRematerialize: isMaterializedView,- edited_history_id: inProgressViewEdits[editingView.id],- })- }+ onClick={updateEditingView}disabledReason={editingViewDisabledReason}icon={<EditingViewButtonIcon />}type="primary"diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 29f5070b706c..360bf89c5604 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -461,6 +461,18 @@ describe('sqlEditorLogic', () => {.toMatchValues({ queryInput: restoredQuery, hasEditorChanges: false })})+ it('opens a view with the query in the link as unsaved edits', async () => {+ mountEditor()+ await expectLogic(logic, () =>+ router.actions.push(urls.sqlEditor({ view_id: MOCK_VIEW.id, query: 'SELECT edited' }))+ )+ .toDispatchActions(['createTab', 'setQueryInput'])+ .toFinishAllListeners()+ .toMatchValues({ queryInput: 'SELECT edited', hasEditorChanges: true })+ expect(logic.values.editingView?.id).toBe(MOCK_VIEW.id)+ expect(logic.values.editingView?.query?.query).toBe(MOCK_VIEW.query.query)+ })+it.each([false, true])('refreshes a discarded draft without overwriting new edits (%s)', async (editAgain) => {mountEditor()await expectLogic(logic, () => router.actions.push(urls.sqlEditor(), { open_view: MOCK_VIEW.id }))@@ -2198,6 +2210,40 @@ describe('sqlEditorLogic', () => {expect(logic.values.suggestionPayload?.acceptText).toBe(acceptText)})++ it('reviewEditingViewUpdate builds the update from the open view, the edit and the last run', async () => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ mode: SQLEditorMode.Embedded,+ })+ logic.mount()++ logic.actions.editView(MOCK_VIEW.query.query, { ...MOCK_VIEW, is_materialized: true })+ await expectLogic(logic).toDispatchActions(['editView', 'createTab', 'updateTab'])+ logic.actions.setQueryInput('SELECT 2')++ // The data node is mounted by the editor's visualization in the app, and not reachable from a host.+ const editorDataNodeLogic = dataNodeLogic({+ key: logic.values.dataLogicKey,+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' },+ })+ editorDataNodeLogic.mount()+ editorDataNodeLogic.actions.loadDataSuccess({ results: [], types: [['two', 'UInt8']] } as any)++ logic.actions.reviewEditingViewUpdate()+ await expectLogic(logic)+ .toDispatchActions([+ 'reviewEditingViewUpdate',+ (action) =>+ action.type === logic.actionTypes.reviewViewUpdate &&+ action.payload.view.id === MOCK_VIEW.id &&+ action.payload.view.query.query === 'SELECT 2' &&+ action.payload.view.shouldRematerialize === true &&+ JSON.stringify(action.payload.view.types) === JSON.stringify([['two', 'UInt8']]),+ ])+ .toFinishAllListeners()+ editorDataNodeLogic.unmount()+ })})describe('inline insight metadata editing', () => {diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex ecbad9c02f40..97c87aeb7b5f 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -991,6 +991,9 @@ export interface sqlEditorLogicActions {reportAIQueryRejected: () => {value: true}+ reviewEditingViewUpdate: () => {+ value: true+ }reviewViewUpdate: (view: UpdateViewPayload,draftId?: string@@ -1496,6 +1499,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([inProgressDraftEdits,}),deleteInProgressDraftEdit: (draftId: string) => ({ draftId }),+ reviewEditingViewUpdate: true,reviewViewUpdate: (view: UpdateViewPayload, draftId?: string) => ({view,draftId,@@ -3416,6 +3420,21 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}}},+ reviewEditingViewUpdate: () => {+ const view = values.editingView+ if (!view) {+ return+ }+ // The data node is bound inside the editor, so the response is read from the mounted instance.+ const response = dataNodeLogic.findMounted({ key: values.dataLogicKey })?.values.response+ actions.reviewViewUpdate({+ id: view.id,+ query: { ...values.sourceQuery.source, query: values.queryInput ?? '' },+ types: response && 'types' in response ? (response.types ?? []) : [],+ shouldRematerialize: view.is_materialized === true,+ edited_history_id: values.inProgressViewEdits[view.id],+ })+ },reviewViewUpdate: ({ view, draftId }) => {// Reuse the editor's inline accept/reject diff (QueryPane) instead of a separate// modal: show the saved query alongside the user's edits, and only run the updatediff --git a/frontend/src/scenes/data-warehouse/editor/useUpdateEditingView.ts b/frontend/src/scenes/data-warehouse/editor/useUpdateEditingView.tsnew file mode 100644index 000000000000..3726ef02754e--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/useUpdateEditingView.ts@@ -0,0 +1,67 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'++import { dataWarehouseViewsLogic } from '../saved_queries/dataWarehouseViewsLogic'+import { sqlEditorLogic } from './sqlEditorLogic'++interface UpdateEditingView {+ disabledReason: string | undefined+ loading: boolean+ isMaterializedView: boolean+ update: () => void+}++/** Update state for the view open in the editor. Call it below the SQLEditor bindings. */+export function useUpdateEditingView(): UpdateEditingView {+ const { editingView, changesToSave, isSourceQueryLastRun, isMultiQuery } = useValues(sqlEditorLogic)+ const { reviewEditingViewUpdate } = useActions(sqlEditorLogic)+ const { response, responseError, responseLoading } = useValues(dataNodeLogic)+ const { updatingDataWarehouseSavedQuery } = useValues(dataWarehouseViewsLogic)++ const isMaterializedView = editingView?.is_materialized === true++ const { disabledReason, loading } = useMemo((): { disabledReason: string | undefined; loading: boolean } => {+ if (updatingDataWarehouseSavedQuery) {+ return { disabledReason: 'Saving...', loading: true }+ }++ if (isMultiQuery) {+ return {+ disabledReason: 'Views must be a single query — remove extra statements to update',+ loading: false,+ }+ }++ if (!changesToSave) {+ return { disabledReason: 'No changes to save', loading: false }+ }++ // Require the current (edited) query to have been run successfully before updating — a stale+ // response from a previous run must not enable the button after further edits.+ if (!isSourceQueryLastRun) {+ return { disabledReason: 'Run the latest query before updating the view', loading: false }+ }++ if (responseLoading) {+ return { disabledReason: 'Running query...', loading: true }+ }++ if (responseError || !response) {+ return { disabledReason: 'Run the query successfully before updating the view', loading: false }+ }++ return { disabledReason: undefined, loading: false }+ }, [+ updatingDataWarehouseSavedQuery,+ changesToSave,+ isSourceQueryLastRun,+ responseLoading,+ responseError,+ response,+ isMultiQuery,+ ])++ return { disabledReason, loading, isMaterializedView, update: reviewEditingViewUpdate }+}diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.tsindex 31f92f9352f8..b425d42e37aa 100644--- a/frontend/src/scenes/urls.ts+++ b/frontend/src/scenes/urls.ts@@ -121,6 +121,10 @@ export const urls = {if (query) {params.set('open_query', typeof query === 'string' ? query : JSON.stringify(query))+ // With a view, the query opens as unsaved edits on top of that view+ if (view_id) {+ params.set('open_view', view_id)+ }} else if (view_id) {params.set('open_view', view_id)} else if (insightShortId) {diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsxindex dc6a680fdece..4c517b77d1c8 100644--- a/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsx+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailActions.tsx@@ -1,32 +1,27 @@-import { useValues } from 'kea'-import { LemonButton } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { materializationJobsLogic } from 'scenes/data-warehouse/saved_queries/materializationJobsLogic'-import { urls } from 'scenes/urls'-import { AccessControlLevel, AccessControlResourceType, DataModelingNode, DataWarehouseSavedQuery } from '~/types'+import { DataModelingNode, DataWarehouseSavedQuery } from '~/types'import { nodeEndpointUrl } from 'products/data_modeling/frontend/endpointModelName'import { MaterializationRunActions } from 'products/data_warehouse/frontend/shared/components/MaterializationRunActions'+import { NodeDetailQueryEditorActions } from './NodeDetailQueryEditorActions'import { QuillNodeDetailActions } from './QuillNodeDetailActions'export function NodeDetailActions({+ id,node,savedQuery,}: {+ id: stringnode: DataModelingNodesavedQuery: DataWarehouseSavedQuery}): JSX.Element {- const { hasMaterializationChanges, savingMaterialization } = useValues(- materializationJobsLogic({ viewId: savedQuery.id, kind: node.type === 'endpoint' ? 'endpoint' : 'view' })- )const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')if (todayRailNav) {- return <QuillNodeDetailActions node={node} savedQuery={savedQuery} />+ return <QuillNodeDetailActions id={id} node={node} savedQuery={savedQuery} />}return (<>@@ -35,23 +30,7 @@ export function NodeDetailActions({Open endpoint</LemonButton>) : (- <AccessControlAction- resourceType={AccessControlResourceType.WarehouseObjects}- minAccessLevel={AccessControlLevel.Editor}- userAccessLevel={savedQuery.user_access_level}- >- <LemonButton- type="secondary"- size="small"- to={urls.sqlEditor({ view_id: savedQuery.id })}- disabledReason={- (hasMaterializationChanges || savingMaterialization) && 'Save or discard your changes first'- }- data-attr="node-detail-edit-in-sql-editor"- >- Edit in SQL editor- </LemonButton>- </AccessControlAction>+ <NodeDetailQueryEditorActions id={id} />)}<MaterializationRunActions viewId={savedQuery.id} kind={node.type === 'endpoint' ? 'endpoint' : 'view'} /></>diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailHeader.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailHeader.tsxindex c39adce11e4a..9826219b0b13 100644--- a/products/data_modeling/frontend/nodeDetail/NodeDetailHeader.tsx+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailHeader.tsx@@ -59,7 +59,7 @@ export function NodeDetailHeader({ id }: { id: string }): JSX.Element {// A failed saved query never resolves on its own, so the placeholder must not// outlive it. The Materialization and Query tabs carry the retry.node && savedQuery ? (- <NodeDetailActions node={node} savedQuery={savedQuery} />+ <NodeDetailActions id={id} node={node} savedQuery={savedQuery} />) : node?.saved_query_id && !savedQueryError ? (todayRailNav ? (<Skeleton className="h-8 w-56" />diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailQuery.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailQuery.tsxindex 8ce2e3e63605..5b5f6a675fba 100644--- a/products/data_modeling/frontend/nodeDetail/NodeDetailQuery.tsx+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailQuery.tsx@@ -6,22 +6,26 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { DatabaseSchemaField } from '~/queries/schema/schema-general'+import { NodeDetailQueryEditor } from './NodeDetailQueryEditor'import { nodeDetailSceneLogic } from './nodeDetailSceneLogic'export function NodeDetailQuery({ id }: { id: string }): JSX.Element {- const { savedQuery, savedQueryLoading, savedQueryError } = useValues(nodeDetailSceneLogic({ id }))+ const { savedQuery, savedQueryLoading, savedQueryError, canEditQuery } = useValues(nodeDetailSceneLogic({ id }))const { loadSavedQuery } = useActions(nodeDetailSceneLogic({ id }))if (savedQueryLoading && !savedQuery) {return <LemonSkeleton className="h-64 w-full" />}- if (savedQueryError) {- return (- <LemonBanner type="error" action={{ children: 'Retry', onClick: loadSavedQuery }}>- Couldn't load this model's query.- </LemonBanner>- )+ const refreshErrorBanner = (+ <LemonBanner type="error" action={{ children: 'Retry', onClick: loadSavedQuery }}>+ Couldn't load this model's query.+ </LemonBanner>+ )++ // With a cached query, keep the editor mounted so unsaved edits survive a failed refresh.+ if (savedQueryError && !savedQuery) {+ return refreshErrorBanner}const queryString = savedQuery?.query?.query@@ -29,8 +33,11 @@ export function NodeDetailQuery({ id }: { id: string }): JSX.Element {return (<div className="flex flex-col gap-4">+ {savedQueryError && refreshErrorBanner}<div className="flex flex-col gap-2">- {queryString ? (+ {queryString && savedQuery && canEditQuery ? (+ <NodeDetailQueryEditor key={savedQuery.id} id={id} savedQuery={savedQuery} />+ ) : queryString ? (<CodeSnippetlanguage={Language.SQL}// Scales with the viewport so the query gets the space the collapsed columns free up.diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditor.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditor.tsxnew file mode 100644index 000000000000..aa125f931074--- /dev/null+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditor.tsx@@ -0,0 +1,51 @@+import { useActions, useValues } from 'kea'++import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { SQLEditor } from 'scenes/data-warehouse/editor/SQLEditor'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'++import { DataWarehouseSavedQuery } from '~/types'++import { NodeDetailQueryEditorSync } from './NodeDetailQueryEditorSync'+import { nodeDetailQueryEditorTabId } from './nodeDetailSceneLogic'++export function NodeDetailQueryEditor({+ id,+ savedQuery,+}: {+ id: string+ savedQuery: DataWarehouseSavedQuery+}): JSX.Element {+ const tabId = nodeDetailQueryEditorTabId(savedQuery.id)+ const editorLogic = sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded })+ const { queryInput } = useValues(editorLogic)+ const { editView } = useActions(editorLogic)++ // The logic outlives a tab switch, so only a fresh one is seeded. Opening the view as the editor's+ // tab gives the update the saved query as its baseline, for the conflict check and history head.+ useOnMountEffect(() => {+ if (queryInput === null) {+ editView(savedQuery.query?.query ?? '', savedQuery)+ }+ })++ return (+ // The editor fills its parent, so the parent needs a height.+ <div className="h-[70vh] min-h-96 overflow-hidden rounded border" data-attr="node-detail-query-editor">+ <SQLEditor+ tabId={tabId}+ mode={SQLEditorMode.Embedded}+ showDatabaseTree={false}+ singleStatement+ hideVariables+ hideFilters+ hideAgentHints+ hideAiTools+ showOpenInSqlEditor+ autoFocusQueryPane={false}+ hostSync={<NodeDetailQueryEditorSync id={id} />}+ />+ </div>+ )+}diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditorActions.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditorActions.tsxnew file mode 100644index 000000000000..96c24af53f93--- /dev/null+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditorActions.tsx@@ -0,0 +1,38 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++import { nodeDetailSceneLogic } from './nodeDetailSceneLogic'++export function NodeDetailQueryEditorActions({ id }: { id: string }): JSX.Element | null {+ const { queryEditorState, effectiveTab } = useValues(nodeDetailSceneLogic({ id }))+ const { discardQueryEditorChanges, updateViewFromQueryEditor } = useActions(nodeDetailSceneLogic({ id }))++ if (!queryEditorState || effectiveTab !== 'query') {+ return null+ }++ return (+ <>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => discardQueryEditorChanges()}+ disabledReason={queryEditorState.discardDisabledReason}+ data-attr="node-detail-discard-changes"+ >+ Discard changes+ </LemonButton>+ <LemonButton+ type="primary"+ size="small"+ onClick={() => updateViewFromQueryEditor()}+ disabledReason={queryEditorState.updateDisabledReason}+ loading={queryEditorState.updateLoading}+ data-attr="node-detail-update-view"+ >+ {queryEditorState.isMaterializedView ? 'Update and re-materialize view' : 'Update view'}+ </LemonButton>+ </>+ )+}diff --git a/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditorSync.tsx b/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditorSync.tsxnew file mode 100644index 000000000000..4cbd2c401419--- /dev/null+++ b/products/data_modeling/frontend/nodeDetail/NodeDetailQueryEditorSync.tsx@@ -0,0 +1,35 @@+import { useActions, useValues } from 'kea'+import { useEffect } from 'react'++import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { useUpdateEditingView } from 'scenes/data-warehouse/editor/useUpdateEditingView'+import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'++import { nodeDetailSceneLogic } from './nodeDetailSceneLogic'++export function NodeDetailQueryEditorSync({ id }: { id: string }): null {+ const { disabledReason, loading, isMaterializedView } = useUpdateEditingView()+ const { hasEditorChanges } = useValues(sqlEditorLogic)+ const { updatingDataWarehouseSavedQuery } = useValues(dataWarehouseViewsLogic)+ const { setQueryEditorState } = useActions(nodeDetailSceneLogic({ id }))++ const discardDisabledReason = updatingDataWarehouseSavedQuery+ ? 'Wait for the current operation to finish'+ : !hasEditorChanges+ ? 'No changes to discard'+ : undefined++ useEffect(() => {+ setQueryEditorState({+ updateDisabledReason: disabledReason,+ updateLoading: loading,+ discardDisabledReason,+ isMaterializedView,+ })+ }, [disabledReason, loading, discardDisabledReason, isMaterializedView, setQueryEditorState])++ useOnMountEffect(() => () => setQueryEditorState(null))++ return null+}diff --git a/products/data_modeling/frontend/nodeDetail/QuillNodeDetailActions.tsx b/products/data_modeling/frontend/nodeDetail/QuillNodeDetailActions.tsxindex 537b8651ddc0..b46cab0be4ac 100644--- a/products/data_modeling/frontend/nodeDetail/QuillNodeDetailActions.tsx+++ b/products/data_modeling/frontend/nodeDetail/QuillNodeDetailActions.tsx@@ -1,36 +1,23 @@-import { useValues } from 'kea'-import { Button } from '@posthog/quill'-import { AccessControlAction } from 'lib/components/AccessControlAction'import { LinkPrimitive } from 'lib/lemon-ui/Link'-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'-import { materializationJobsLogic } from 'scenes/data-warehouse/saved_queries/materializationJobsLogic'-import { urls } from 'scenes/urls'-import { AccessControlLevel, AccessControlResourceType, DataModelingNode, DataWarehouseSavedQuery } from '~/types'+import { DataModelingNode, DataWarehouseSavedQuery } from '~/types'import { nodeEndpointUrl } from 'products/data_modeling/frontend/endpointModelName'import { MaterializationRunActions } from 'products/data_warehouse/frontend/shared/components/MaterializationRunActions'+import { QuillNodeDetailQueryEditorActions } from './QuillNodeDetailQueryEditorActions'+export function QuillNodeDetailActions({+ id,node,savedQuery,}: {+ id: stringnode: DataModelingNodesavedQuery: DataWarehouseSavedQuery}): JSX.Element {- const { hasMaterializationChanges, savingMaterialization } = useValues(- materializationJobsLogic({ viewId: savedQuery.id, kind: node.type === 'endpoint' ? 'endpoint' : 'view' })- )- const editDisabledReason =- hasMaterializationChanges || savingMaterialization- ? 'Save or discard your changes first'- : getAccessControlDisabledReason(- AccessControlResourceType.WarehouseObjects,- AccessControlLevel.Editor,- savedQuery.user_access_level- )return (<>{node.type === 'endpoint' ? (@@ -38,24 +25,7 @@ export function QuillNodeDetailActions({Open endpoint</Button>) : (- <AccessControlAction- resourceType={AccessControlResourceType.WarehouseObjects}- minAccessLevel={AccessControlLevel.Editor}- userAccessLevel={savedQuery.user_access_level}- >- <Button- variant="outline"- render={- <LinkPrimitive- to={editDisabledReason ? undefined : urls.sqlEditor({ view_id: savedQuery.id })}- />- }- disabledReason={editDisabledReason ?? undefined}- data-attr="node-detail-edit-in-sql-editor"- >- Edit in SQL editor- </Button>- </AccessControlAction>+ <QuillNodeDetailQueryEditorActions id={id} />)}<MaterializationRunActions viewId={savedQuery.id} kind={node.type === 'endpoint' ? 'endpoint' : 'view'} /></>diff --git a/products/data_modeling/frontend/nodeDetail/QuillNodeDetailQueryEditorActions.tsx b/products/data_modeling/frontend/nodeDetail/QuillNodeDetailQueryEditorActions.tsxnew file mode 100644index 000000000000..14503b4addfc--- /dev/null+++ b/products/data_modeling/frontend/nodeDetail/QuillNodeDetailQueryEditorActions.tsx@@ -0,0 +1,36 @@+import { useActions, useValues } from 'kea'++import { Button } from '@posthog/quill'++import { nodeDetailSceneLogic } from './nodeDetailSceneLogic'++export function QuillNodeDetailQueryEditorActions({ id }: { id: string }): JSX.Element | null {+ const { queryEditorState, effectiveTab } = useValues(nodeDetailSceneLogic({ id }))+ const { discardQueryEditorChanges, updateViewFromQueryEditor } = useActions(nodeDetailSceneLogic({ id }))++ if (!queryEditorState || effectiveTab !== 'query') {+ return null+ }++ return (+ <>+ <Button+ variant="outline"+ onClick={() => discardQueryEditorChanges()}+ disabledReason={queryEditorState.discardDisabledReason}+ data-attr="node-detail-discard-changes"+ >+ Discard changes+ </Button>+ <Button+ variant="primary"+ onClick={() => updateViewFromQueryEditor()}+ disabledReason={queryEditorState.updateDisabledReason}+ loading={queryEditorState.updateLoading}+ data-attr="node-detail-update-view"+ >+ {queryEditorState.isMaterializedView ? 'Update and re-materialize view' : 'Update view'}+ </Button>+ </>+ )+}diff --git a/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.ts b/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.tsindex f1ee4d63dde2..f938536e51a2 100644--- a/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.ts+++ b/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.test.ts@@ -3,17 +3,23 @@ import { combineUrl, router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { createElement } from 'react'-import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'+import {+ DataWarehouseSavedQueryUpdate,+ dataWarehouseViewsLogic,+} from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'import { materializationJobsLogic } from 'scenes/data-warehouse/saved_queries/materializationJobsLogic'import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'+import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'-import { DataModelingNode, DataModelingNodeType, DataWarehouseSavedQuery } from '~/types'+import { AccessControlLevel, DataModelingNode, DataModelingNodeType, DataWarehouseSavedQuery } from '~/types'import { NodeDetailOverview } from './NodeDetailOverview'import { NodeDetailQuery } from './NodeDetailQuery'-import { NodeDetailSceneTab, nodeDetailSceneLogic } from './nodeDetailSceneLogic'+import { NodeDetailSceneTab, nodeDetailQueryEditorTabId, nodeDetailSceneLogic } from './nodeDetailSceneLogic'import { NodeDetailTests } from './NodeDetailTests'const NODE_ID = 'node-1'@@ -102,6 +108,74 @@ describe('nodeDetailSceneLogic', () => {expect(logic.values.currentTab).toEqual(expectedTab)})+ // An endpoint's query is versioned by the endpoint, and a viewer cannot save a view, so only+ // an editor on a plain or materialized view gets the editable query.+ it.each<[string, DataModelingNodeType, AccessControlLevel, boolean]>([+ ['an editor on a view', 'view', AccessControlLevel.Editor, true],+ ['an editor on a materialized view', 'matview', AccessControlLevel.Editor, true],+ ['a viewer on a view', 'view', AccessControlLevel.Viewer, false],+ ['an editor on an endpoint', 'endpoint', AccessControlLevel.Editor, false],+ ])('decides whether the query is editable for %s', async (_case, type, accessLevel, expected) => {+ node = buildNode(type)+ savedQuery = {+ ...savedQuery,+ user_access_level: accessLevel,+ query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' },+ }++ await mountScene(urls.nodeDetail(NODE_ID))++ expect(logic.values.canEditQuery).toBe(expected)+ })++ // The buttons above the editor have no access to its bindings, so they act through the editor+ // mounted under the scene's tab id. A wrong id would leave them clicking into nothing.+ it('sends Update view and Discard changes to the mounted query editor', async () => {+ savedQuery = { ...savedQuery, query: { kind: NodeKind.HogQLQuery, query: 'SELECT 1' } }+ await mountScene(urls.nodeDetail(NODE_ID))+ const editor = sqlEditorLogic({+ tabId: nodeDetailQueryEditorTabId(SAVED_QUERY_ID),+ mode: SQLEditorMode.Embedded,+ })+ editor.mount()+ try {+ editor.actions.editView('SELECT 1', savedQuery as DataWarehouseSavedQuery)+ await expectLogic(editor).toDispatchActions(['editView', 'createTab', 'updateTab'])+ editor.actions.setQueryInput('SELECT 2')++ logic.actions.updateViewFromQueryEditor()+ await expectLogic(editor).toDispatchActions(['reviewEditingViewUpdate', 'reviewViewUpdate'])++ logic.actions.discardQueryEditorChanges()+ await expectLogic(editor).toDispatchActions(['discardChanges'])+ } finally {+ editor.unmount()+ }+ })++ // Saving a new query from this page changes what the model depends on, and the lineage tab stays+ // mounted, so it must reload. A frequency change reaches the same success action without a query.+ it.each<[string, Partial<DataWarehouseSavedQueryUpdate>, number]>([+ ['changes the query', { query: { kind: NodeKind.HogQLQuery, query: 'SELECT 2' } }, 1],+ ['changes only the sync frequency', { sync_frequency: '24hour' }, 0],+ ])('reloads the lineage graph only when an update %s', async (_case, change, expectedReloads) => {+ const lineageRequests = jest.fn(() => [200, { nodes: [], edges: [] }])+ useMocks({+ get: {+ '/api/environments/:team_id/data_modeling_nodes/lineage/': lineageRequests,+ '/api/environments/:team_id/data_modeling_nodes/:id/': () => [200, node],+ '/api/environments/:team_id/warehouse_saved_queries/:id/': () => [200, savedQuery],+ },+ })+ await mountScene(urls.nodeDetail(NODE_ID))+ const requestsBefore = lineageRequests.mock.calls.length++ dataWarehouseViewsLogic.actions.updateDataWarehouseSavedQuerySuccess([], { id: SAVED_QUERY_ID, ...change })+ await expectLogic(logic).toFinishAllListeners()++ expect(lineageRequests.mock.calls.length - requestsBefore).toBe(expectedReloads)+ })+it.each(['table', 'metric'] as const)('offers a %s only its lineage, and opens on it', async (type) => {node = buildNode(type)diff --git a/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.ts b/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.tsindex 927716918fe7..0bb703d7ba2c 100644--- a/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.ts+++ b/products/data_modeling/frontend/nodeDetail/nodeDetailSceneLogic.ts@@ -4,6 +4,9 @@ import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'import api from 'lib/api'+import { userHasAccess } from 'lib/utils/accessControlUtils'+import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'+import { SQLEditorMode } from 'scenes/data-warehouse/editor/sqlEditorModes'import type { DataWarehouseSavedQuerySummary } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'import { teamLogic } from 'scenes/teamLogic'@@ -11,6 +14,8 @@ import { urls } from 'scenes/urls'import type { DatabaseSchemaField } from '~/queries/schema/schema-general'import {+ AccessControlLevel,+ AccessControlResourceType,Breadcrumb,DataModelingEdge,DataModelingNode,@@ -34,6 +39,16 @@ export interface NodeDetailSceneLogicProps {id: string}+/** What the embedded query editor reports for the Update view and Discard changes buttons above it. */+export interface NodeDetailQueryEditorState {+ updateDisabledReason: string | undefined+ updateLoading: boolean+ discardDisabledReason: string | undefined+ isMaterializedView: boolean+}++export const nodeDetailQueryEditorTabId = (savedQueryId: string): string => `node-detail-query-${savedQueryId}`+function isNodeLookup(value: unknown): value is DataModelingNodesRetrieveLookup {return (typeof value === 'string' &&@@ -72,6 +87,7 @@ export interface nodeDetailSceneLogicValues {currentProjectId: number | string // teamLogicavailableTabs: NodeDetailSceneTab[]breadcrumbs: Breadcrumb[]+ canEditQuery: booleancurrentTab: NodeDetailSceneTab | nulldataQualitySubject: NodeDetailDataQualitySubject | nulldefaultTab: NodeDetailSceneTab@@ -91,6 +107,7 @@ export interface nodeDetailSceneLogicValues {postHogSubjectAccessDenied: booleanpostHogSubjectError: booleanpostHogSubjectLoading: boolean+ queryEditorState: NodeDetailQueryEditorState | nullsavedQuery: DataWarehouseSavedQuery | nullsavedQueryDeleted: booleansavedQueryError: boolean@@ -128,6 +145,9 @@ export interface nodeDetailSceneLogicActions {closeLineageModal: () => {value: true}+ discardQueryEditorChanges: () => {+ value: true+ }lineageNodeDragStopped: (nodeId: string,position: XYPosition@@ -238,6 +258,9 @@ export interface nodeDetailSceneLogicActions {setCurrentTab: (tab: NodeDetailSceneTab | null) => {tab: 'data-quality' | 'history' | 'lineage' | 'materialization' | 'query' | null}+ setQueryEditorState: (state: NodeDetailQueryEditorState | null) => {+ state: NodeDetailQueryEditorState | null+ }updateNodeDescription: (description: string) => {description: string}@@ -259,6 +282,9 @@ export interface nodeDetailSceneLogicActions {description: string}}+ updateViewFromQueryEditor: () => {+ value: true+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -285,6 +311,7 @@ export interface nodeDetailSceneLogicMeta {node: DataModelingNode | null,savedQuery: DataWarehouseSavedQuery | null) => string | null+ canEditQuery: (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null) => boolean}}@@ -310,6 +337,9 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([updateNodeDescription: (description: string) => ({ description }),setCurrentTab: (tab: NodeDetailSceneTab | null) => ({ tab }),canonicalizeTab: true,+ setQueryEditorState: (state: NodeDetailQueryEditorState | null) => ({ state }),+ updateViewFromQueryEditor: true,+ discardQueryEditorChanges: true,openLineageModal: true,closeLineageModal: true,lineageNodeDragStopped: (nodeId: string, position: XYPosition) => ({ nodeId, position }),@@ -317,6 +347,13 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([markSavedQueryDeleted: true,}),reducers({+ // Reported by the embedded query editor while it is mounted, and null otherwise.+ queryEditorState: [+ null as NodeDetailQueryEditorState | null,+ {+ setQueryEditorState: (_, { state }) => state,+ },+ ],// What the address bar asks for. Tab links navigate, so nothing else may write this.currentTab: [null as NodeDetailSceneTab | null,@@ -638,51 +675,79 @@ export const nodeDetailSceneLogic = kea<nodeDetailSceneLogicType>([(node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null): string | null =>savedQuery?.status ?? node?.last_run_status ?? null,],+ // An endpoint's query is versioned by the endpoint, so it is edited there and not as a view.+ canEditQuery: [+ (s) => [s.node, s.savedQuery],+ (node: DataModelingNode | null, savedQuery: DataWarehouseSavedQuery | null): boolean =>+ !!node?.saved_query_id &&+ node.type !== 'endpoint' &&+ typeof savedQuery?.query?.query === 'string' &&+ userHasAccess(+ AccessControlResourceType.WarehouseObjects,+ AccessControlLevel.Editor,+ savedQuery.user_access_level+ ),+ ],+ }),+ listeners(({ actions, props, values }) => {+ const embeddedQueryEditor = (): ReturnType<typeof sqlEditorLogic.findMounted> =>+ values.node?.saved_query_id+ ? sqlEditorLogic.findMounted({+ tabId: nodeDetailQueryEditorTabId(values.node.saved_query_id),+ mode: SQLEditorMode.Embedded,+ })+ : null+ return {+ loadNodeSuccess: () => {+ const node = values.node+ if (node && node.id !== props.id) {+ router.actions.replace(urls.nodeDetail(node.id, values.currentTab ?? 'lineage'))+ return+ }+ if (node?.saved_query_id) {+ actions.loadSavedQuery()+ }+ if (node?.type === 'table' && node.warehouse_table_id) {+ actions.loadTableDetails()+ }+ if (node?.type === 'table' && node.origin === 'posthog') {+ actions.loadPostHogSubject()+ }+ actions.loadLineageGraph()+ actions.canonicalizeTab()+ },+ loadSavedQuerySuccess: () => actions.canonicalizeTab(),+ loadSavedQueryFailure: () => actions.canonicalizeTab(),+ // The address bar decides which tab shows, so once the data says which tabs exist, a URL+ // asking for one this model has no page for is corrected in place. Replace, not push: a+ // redirect the user did not ask for is not a history step.+ canonicalizeTab: () => {+ const tab = values.effectiveTab+ if (tab && tab !== values.currentTab) {+ router.actions.replace(urls.nodeDetail(props.id, tab))+ }+ },+ updateViewFromQueryEditor: () => embeddedQueryEditor()?.actions.reviewEditingViewUpdate(),+ discardQueryEditorChanges: () => embeddedQueryEditor()?.actions.discardChanges(),+ updateDataWarehouseSavedQuerySuccess: ({ payload }) => {+ if (values.node?.saved_query_id) {+ actions.loadSavedQuery()+ // The server rebuilds the model's dependencies when its query changes.+ if (payload?.query && payload.id === values.node.saved_query_id) {+ actions.loadLineageGraph()+ }+ }+ },+ // This page is about the deleted view, so it has nowhere left to stand. The same delete runs+ // from the SQL editor, which keeps its own tab, so the navigation belongs here and not in the+ // shared materialization logic.+ deleteDataWarehouseSavedQuerySuccess: ({ payload }) => {+ if (payload && payload === values.node?.saved_query_id) {+ router.actions.push(urls.models())+ }+ },+ }}),- listeners(({ actions, props, values }) => ({- loadNodeSuccess: () => {- const node = values.node- if (node && node.id !== props.id) {- router.actions.replace(urls.nodeDetail(node.id, values.currentTab ?? 'lineage'))- return- }- if (node?.saved_query_id) {- actions.loadSavedQuery()- }- if (node?.type === 'table' && node.warehouse_table_id) {- actions.loadTableDetails()- }- if (node?.type === 'table' && node.origin === 'posthog') {- actions.loadPostHogSubject()- }- actions.loadLineageGraph()- actions.canonicalizeTab()- },- loadSavedQuerySuccess: () => actions.canonicalizeTab(),- loadSavedQueryFailure: () => actions.canonicalizeTab(),- // The address bar decides which tab shows, so once the data says which tabs exist, a URL- // asking for one this model has no page for is corrected in place. Replace, not push: a- // redirect the user did not ask for is not a history step.- canonicalizeTab: () => {- const tab = values.effectiveTab- if (tab && tab !== values.currentTab) {- router.actions.replace(urls.nodeDetail(props.id, tab))- }- },- updateDataWarehouseSavedQuerySuccess: () => {- if (values.node?.saved_query_id) {- actions.loadSavedQuery()- }- },- // This page is about the deleted view, so it has nowhere left to stand. The same delete runs- // from the SQL editor, which keeps its own tab, so the navigation belongs here and not in the- // shared materialization logic.- deleteDataWarehouseSavedQuerySuccess: ({ payload }) => {- if (payload && payload === values.node?.saved_query_id) {- router.actions.push(urls.models())- }- },- })),urlToAction(({ actions, props }) => {// Clicking a node in the lineage graph navigates model to model. The outgoing model's logic// is still mounted while the new URL lands, so it must ignore routes for another id.