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.

fix(sql-editor): keep saving as the primary editor action (#77637)

Marius Andra4a426ca52105
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 1fc93173de59..ec5a5e82e643 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -3,7 +3,7 @@ import { BindLogic, useActions, useValues } from 'kea'
import type { editor as importedEditor } from 'monaco-editor'
import { useEffect, useMemo, useRef, useState } from 'react'
-import { IconBook, IconChevronDown, IconDownload, IconX } from '@posthog/icons'
+import { IconBook, IconChevronDown, IconDownload, IconNotebook, IconX } from '@posthog/icons'
import { LemonModal, Spinner } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
@@ -542,10 +542,21 @@ function SQLEditorSceneTitle(): JSX.Element | null {
: editingView
? 'Close this view and reset the SQL editor to an unsaved query without clearing your SQL or visualization settings.'
: 'Reset the SQL editor to an unsaved query without clearing your SQL or visualization settings.'
- const continueInNotebookDisabledReason = queryInput?.trim()
- ? continueInNotebookAccessDisabledReason
- : 'Write a SQL query before continuing'
- const continueInNotebookIsPrimary = saveAsMenuItems.primary.action === 'insight'
+ const continueInNotebookButton = (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconNotebook />}
+ onClick={() => convertToNotebook()}
+ loading={notebooksLoading}
+ disabledReason={
+ queryInput?.trim() ? continueInNotebookAccessDisabledReason : 'Write a SQL query before continuing'
+ }
+ data-attr="sql-editor-continue-in-notebook-button"
+ >
+ Continue in a notebook
+ </LemonButton>
+ )
return (
<>
@@ -679,13 +690,19 @@ function SQLEditorSceneTitle(): JSX.Element | null {
>
History
</LemonButton>
+ {continueInNotebookButton}
<LemonButton
- disabledReason={continueInNotebookDisabledReason}
- loading={notebooksLoading}
+ disabledReason={
+ !isSourceQueryLastRun
+ ? 'Run latest query changes before saving'
+ : !updateInsightButtonEnabled
+ ? 'No updates to save'
+ : undefined
+ }
+ loading={insightLoading}
type="primary"
size="small"
- onClick={() => convertToNotebook()}
- data-attr="sql-editor-continue-in-notebook-button"
+ onClick={() => updateInsight()}
sideAction={{
icon: <IconChevronDown />,
'data-attr': 'sql-editor-save-options-button',
@@ -694,17 +711,6 @@ function SQLEditorSceneTitle(): JSX.Element | null {
overlay: (
<LemonMenuOverlay
items={[
- {
- label: 'Update insight',
- disabledReason: insightLoading
- ? 'Updating insight...'
- : !isSourceQueryLastRun
- ? 'Run latest query changes before saving'
- : !updateInsightButtonEnabled
- ? 'No updates to save'
- : undefined,
- onClick: () => updateInsight(),
- },
{
label: 'Save as new insight...',
disabledReason: saveAsDisabledReason,
@@ -733,7 +739,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
},
}}
>
- Continue in a notebook
+ Update insight
</LemonButton>
<LemonButton
onClick={() => closeEditingObject()}
@@ -782,54 +788,40 @@ function SQLEditorSceneTitle(): JSX.Element | null {
/>
</>
) : (
- <LemonButton
- type="primary"
- size="small"
- onClick={continueInNotebookIsPrimary ? () => convertToNotebook() : onPrimarySaveClick}
- loading={continueInNotebookIsPrimary && notebooksLoading}
- disabledReason={
- continueInNotebookIsPrimary
- ? continueInNotebookDisabledReason
- : (saveAsDisabledReason ??
- (saveAsMenuItems.primary.action === 'endpoint'
- ? saveAsEndpointAccessDisabledReason
- : saveAsMenuItems.primary.action === 'view'
- ? saveAsViewAccessDisabledReason
- : undefined))
- }
- data-attr={
- continueInNotebookIsPrimary ? 'sql-editor-continue-in-notebook-button' : undefined
- }
- sideAction={{
- icon: <IconChevronDown />,
- 'data-attr': 'sql-editor-save-options-button',
- dropdown: {
- placement: 'bottom-end',
- overlay: (
- <LemonMenuOverlay
- items={[
- ...(continueInNotebookIsPrimary
- ? [
- {
- label: saveAsMenuItems.primary.label,
- onClick: onPrimarySaveClick,
- disabledReason: saveAsDisabledReason,
- },
- ]
- : []),
- ...secondarySaveMenuItems.map((item) => ({
+ <>
+ {saveAsMenuItems.primary.action === 'insight' && continueInNotebookButton}
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={onPrimarySaveClick}
+ disabledReason={
+ saveAsDisabledReason ??
+ (saveAsMenuItems.primary.action === 'endpoint'
+ ? saveAsEndpointAccessDisabledReason
+ : saveAsMenuItems.primary.action === 'view'
+ ? saveAsViewAccessDisabledReason
+ : undefined)
+ }
+ sideAction={{
+ icon: <IconChevronDown />,
+ 'data-attr': 'sql-editor-save-options-button',
+ dropdown: {
+ placement: 'bottom-end',
+ overlay: (
+ <LemonMenuOverlay
+ items={secondarySaveMenuItems.map((item) => ({
...item,
disabledReason:
saveAsDisabledReason ?? item.accessDisabledReason,
- })),
- ]}
- />
- ),
- },
- }}
- >
- {continueInNotebookIsPrimary ? 'Continue in a notebook' : saveAsMenuItems.primary.label}
- </LemonButton>
+ }))}
+ />
+ ),
+ },
+ }}
+ >
+ {saveAsMenuItems.primary.label}
+ </LemonButton>
+ </>
)}
</div>
}
diff --git a/playwright/e2e/product-analytics/dashboards.spec.ts b/playwright/e2e/product-analytics/dashboards.spec.ts
index 81763881e4ee..5af895389a1e 100644
--- a/playwright/e2e/product-analytics/dashboards.spec.ts
+++ b/playwright/e2e/product-analytics/dashboards.spec.ts
@@ -193,7 +193,7 @@ test.describe('Dashboards', () => {
// editor can only substitute {variables.test_number} once that list has loaded.
// Running the query before the reload returns sends the placeholder unresolved,
// the backend errors with "Global variable not found: variables", and
- // The insight save option never enables. Wait for the reload before using the variable.
+ // "Save as insight" never enables. Wait for the reload before using the variable.
const variablesReloaded = page.waitForResponse(
(response) =>
response.url().includes('/insight_variables') &&
@@ -211,22 +211,19 @@ test.describe('Dashboards', () => {
await page.keyboard.press('ControlOrMeta+a')
// insertText() inserts the whole string at once, so Monaco's bracket
// auto-close and autocomplete don't intercept the `{`/`}` mid-type and
- // produce a malformed query that leaves the insight save option disabled.
+ // produce a malformed query that leaves "Save as insight" disabled.
await page.keyboard.insertText('SELECT {variables.test_number}')
await page.keyboard.press('Escape')
// The editor attaches the variable to the query through a short debounce, so a
- // fast first Run can execute before {variables.test_number} is substituted.
- // The query then errors with "Global variable not found: variables" and leaves
- // the insight save option disabled. Re-run until the variable resolves and the query
- // succeeds because a successful run is the only thing that enables saving.
- const saveOptionsButton = page.getByTestId('sql-editor-save-options-button')
- const saveAsInsight = page.getByRole('menuitem', { name: 'Save as insight' })
+ // fast first Run can execute before {variables.test_number} is substituted —
+ // the query then errors with "Global variable not found: variables" and leaves
+ // "Save as insight" disabled. Re-run until the variable resolves and the query
+ // succeeds (a successful run is the only thing that enables "Save as insight").
+ const saveAsInsight = page.getByRole('button', { name: 'Save as insight' })
await expect(async () => {
- await page.keyboard.press('Escape')
await page.getByRole('button', { name: 'Run' }).click()
await expect(page.locator('[data-attr=sql-editor-output-pane-empty-state]')).not.toBeVisible()
- await saveOptionsButton.click()
await expect(saveAsInsight).toBeEnabled({ timeout: 15000 })
}).toPass({ timeout: 60000 })
await saveAsInsight.click()
diff --git a/playwright/e2e/sql-editor-axis-labels.spec.ts b/playwright/e2e/sql-editor-axis-labels.spec.ts
index f9dbf34fa2f3..37a62f2bc389 100644
--- a/playwright/e2e/sql-editor-axis-labels.spec.ts
+++ b/playwright/e2e/sql-editor-axis-labels.spec.ts
@@ -8,16 +8,7 @@ async function goToSavedSqlInsight(page: Page, insightShortId: InsightShortId):
await page.goto(`/sql#insight=${insightShortId}`, { waitUntil: 'domcontentloaded' })
await expect(page).toHaveURL(/\/sql#.*insight=/)
await expect(page.locator('.DataVisualization canvas').last()).toBeVisible({ timeout: 60_000 })
-}
-
-async function openUpdateInsightOption(page: Page): Promise<void> {
- const updateInsightOption = page.getByRole('menuitem', { name: 'Update insight' })
-
- await expect(async () => {
- await page.keyboard.press('Escape')
- await page.getByTestId('sql-editor-save-options-button').click()
- await expect(updateInsightOption).toBeVisible({ timeout: 5_000 })
- }).toPass({ timeout: 30_000 })
+ await expect(page.getByRole('button', { name: 'Update insight' })).toBeVisible({ timeout: 30_000 })
}
test.describe('SQL editor axis labels', () => {
@@ -87,9 +78,15 @@ test.describe('SQL editor axis labels', () => {
await page.getByText('Right Y-axis').click()
await page.getByTestId('data-visualization-right-y-axis-label-input').fill('People')
- await openUpdateInsightOption(page)
- await page.getByRole('menuitem', { name: 'Update insight' }).click()
- await expect(page).toHaveURL(/\/insights\//, { timeout: 60_000 })
+ const saveRequestPromise = page.waitForResponse(
+ (response) =>
+ /\/api\/(?:projects|environments)\/\d+\/insights(?:\/\d+)?\/?(?:\?.*)?$/.test(response.url()) &&
+ response.request().method() === 'PATCH',
+ { timeout: 60_000 }
+ )
+
+ await page.getByRole('button', { name: 'Update insight' }).click()
+ await expect((await saveRequestPromise).ok()).toBe(true)
await goToSavedSqlInsight(page, insightShortId)
diff --git a/playwright/e2e/sql-editor-history.spec.ts b/playwright/e2e/sql-editor-history.spec.ts
index 6211b6e56292..8219443a47c2 100644
--- a/playwright/e2e/sql-editor-history.spec.ts
+++ b/playwright/e2e/sql-editor-history.spec.ts
@@ -1,21 +1,8 @@
-import { Page } from '@playwright/test'
-
import { NodeKind } from '../../frontend/src/queries/schema/schema-general'
import { InsightShortId } from '../../frontend/src/types'
import { InsightPage } from '../page-models/insightPage'
import { expect, test, PlaywrightWorkspaceSetupResult } from '../utils/workspace-test-base'
-async function expectSaveOptions(page: Page, expectedOption: string): Promise<void> {
- const saveOption = page.getByRole('menuitem', { name: expectedOption, exact: true })
-
- await expect(async () => {
- await page.keyboard.press('Escape')
- await page.getByTestId('sql-editor-save-options-button').click()
- await expect(saveOption).toBeVisible({ timeout: 5_000 })
- }).toPass({ timeout: 30_000 })
- await page.keyboard.press('Escape')
-}
-
test.describe('SQL editor history', () => {
test.setTimeout(120_000)
@@ -53,7 +40,7 @@ test.describe('SQL editor history', () => {
await test.step('open a saved SQL insight in the SQL editor', async () => {
await insight.goToInsight(insightShortId, { edit: true })
await page.waitForURL(/\/sql/)
- await expectSaveOptions(page, 'Update insight')
+ await expect(page.getByRole('button', { name: 'Update insight' })).toBeVisible({ timeout: 30000 })
})
await test.step('navigating to a plain SQL query in the same editor switches to save-as-new mode', async () => {
@@ -65,19 +52,21 @@ test.describe('SQL editor history', () => {
window.dispatchEvent(new PopStateEvent('popstate'))
})
- await expectSaveOptions(page, 'Save as insight')
+ await expect(page.getByRole('button', { name: 'Save as insight' })).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Update insight' })).toHaveCount(0)
})
await test.step('browser back restores the saved SQL insight editor state', async () => {
await page.goBack()
await page.waitForURL(/insight=/)
- await expectSaveOptions(page, 'Update insight')
+ await expect(page.getByRole('button', { name: 'Update insight' })).toBeVisible({ timeout: 30000 })
})
await test.step('browser forward restores the plain SQL query state', async () => {
await page.goForward()
await page.waitForURL((url) => url.hash.includes('q=SELECT%201') && !url.hash.includes('insight='))
- await expectSaveOptions(page, 'Save as insight')
+ await expect(page.getByRole('button', { name: 'Save as insight' })).toBeVisible()
+ await expect(page.getByRole('button', { name: 'Update insight' })).toHaveCount(0)
})
})
})