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(sql-editor): convert queries to notebooks (#76646)

Marius Andra37c5683de181
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
index 2f754f026a46..1fc93173de59 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx
@@ -361,7 +361,8 @@ function AccessControlModal(): JSX.Element | null {
}
function SQLEditorSceneTitle(): JSX.Element | null {
- const { titleSectionProps, updateInsightButtonEnabled, saveAsMenuItems } = useValues(editorSceneLogic)
+ const { titleSectionProps, updateInsightButtonEnabled, saveAsMenuItems, notebooksLoading } =
+ useValues(editorSceneLogic)
const {
queryInput,
editingView,
@@ -374,7 +375,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
isMultiQuery,
featureFlags,
} = useValues(sqlEditorLogic)
- const { openHistoryModal } = useActions(editorSceneLogic)
+ const { convertToNotebook, openHistoryModal } = useActions(editorSceneLogic)
const {
reviewViewUpdate,
updateInsight,
@@ -413,6 +414,11 @@ function SQLEditorSceneTitle(): JSX.Element | null {
AccessControlLevel.Editor
)
+ const continueInNotebookAccessDisabledReason = getAccessControlDisabledReason(
+ AccessControlResourceType.Notebook,
+ AccessControlLevel.Editor
+ )
+
const secondarySaveMenuItems = useMemo(
() =>
saveAsMenuItems.secondary.map((item) => ({
@@ -536,6 +542,10 @@ 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'
return (
<>
@@ -670,24 +680,31 @@ function SQLEditorSceneTitle(): JSX.Element | null {
History
</LemonButton>
<LemonButton
- disabledReason={
- !isSourceQueryLastRun
- ? 'Run latest query changes before saving'
- : !updateInsightButtonEnabled
- ? 'No updates to save'
- : undefined
- }
- loading={insightLoading}
+ disabledReason={continueInNotebookDisabledReason}
+ loading={notebooksLoading}
type="primary"
size="small"
- onClick={() => updateInsight()}
+ onClick={() => convertToNotebook()}
+ data-attr="sql-editor-continue-in-notebook-button"
sideAction={{
icon: <IconChevronDown />,
+ 'data-attr': 'sql-editor-save-options-button',
dropdown: {
placement: 'bottom-end',
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,
@@ -716,7 +733,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {
},
}}
>
- Update insight
+ Continue in a notebook
</LemonButton>
<LemonButton
onClick={() => closeEditingObject()}
@@ -768,14 +785,20 @@ function SQLEditorSceneTitle(): JSX.Element | null {
<LemonButton
type="primary"
size="small"
- onClick={onPrimarySaveClick}
+ onClick={continueInNotebookIsPrimary ? () => convertToNotebook() : onPrimarySaveClick}
+ loading={continueInNotebookIsPrimary && notebooksLoading}
disabledReason={
- saveAsDisabledReason ??
- (saveAsMenuItems.primary.action === 'endpoint'
- ? saveAsEndpointAccessDisabledReason
- : saveAsMenuItems.primary.action === 'view'
- ? saveAsViewAccessDisabledReason
- : undefined)
+ 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 />,
@@ -784,16 +807,28 @@ function SQLEditorSceneTitle(): JSX.Element | null {
placement: 'bottom-end',
overlay: (
<LemonMenuOverlay
- items={secondarySaveMenuItems.map((item) => ({
- ...item,
- disabledReason: saveAsDisabledReason ?? item.accessDisabledReason,
- }))}
+ items={[
+ ...(continueInNotebookIsPrimary
+ ? [
+ {
+ label: saveAsMenuItems.primary.label,
+ onClick: onPrimarySaveClick,
+ disabledReason: saveAsDisabledReason,
+ },
+ ]
+ : []),
+ ...secondarySaveMenuItems.map((item) => ({
+ ...item,
+ disabledReason:
+ saveAsDisabledReason ?? item.accessDisabledReason,
+ })),
+ ]}
/>
),
},
}}
>
- {saveAsMenuItems.primary.label}
+ {continueInNotebookIsPrimary ? 'Continue in a notebook' : saveAsMenuItems.primary.label}
</LemonButton>
)}
</div>
diff --git a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
index 483ff67c136f..c14b25598f40 100644
--- a/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/editorSceneLogic.tsx
@@ -2,19 +2,23 @@ import { deepEqual as equal } from 'fast-equals'
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import posthog from 'posthog-js'
+import { JSONContent } from 'lib/components/RichContentEditor/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
+import { uuid } from 'lib/utils/dom'
import { removeUndefinedAndNull } from 'lib/utils/objects'
+import { NotebookNodeType, NotebookTarget } from 'scenes/notebooks/types'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
+import { notebooksModel } from '~/models/notebooksModel'
import { DataVisualizationNode, FileSystemIconType, HogQLFilters, NodeKind } from '~/queries/schema/schema-general'
import { Breadcrumb } from '~/types'
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { DataWarehouseSavedQuery, LinkBreadcrumb, QueryBasedInsightModel } from '../../../types'
-import { normalizeFiltersForUrl, sqlEditorLogic, toDataVisualizationNode } from './sqlEditorLogic'
+import { NEW_QUERY, normalizeFiltersForUrl, sqlEditorLogic, toDataVisualizationNode } from './sqlEditorLogic'
import type { QueryTab, SqlEditorSource } from './sqlEditorLogic'
export interface SaveAsMenuItem {
@@ -55,8 +59,46 @@ export interface EditorSceneLogicProps {
tabId: string
}
+export function buildSqlNotebook(
+ queryInput: string,
+ activeTab: QueryTab | null,
+ editingInsight: QueryBasedInsightModel | null,
+ featureFlags: FeatureFlagsSet
+): { title: string; content: JSONContent[] } {
+ const activeTabName = activeTab?.name === NEW_QUERY ? undefined : activeTab?.name
+ const sqlNode = featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]
+ ? {
+ type: NotebookNodeType.SQLV2,
+ attrs: {
+ nodeId: uuid(),
+ code: queryInput,
+ returnVariable: '',
+ edit: true,
+ },
+ }
+ : {
+ type: NotebookNodeType.Query,
+ attrs: {
+ query: {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: queryInput,
+ },
+ },
+ edit: true,
+ },
+ }
+
+ return {
+ title: editingInsight?.name || editingInsight?.derived_name || activeTabName || 'SQL query',
+ content: [sqlNode],
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface editorSceneLogicValues {
+ notebooksLoading: boolean // notebooksModel
activeTab: QueryTab | null // sqlEditorLogic
dashboardId: number | null // sqlEditorLogic
dataLogicKey: string // sqlEditorLogic
@@ -105,9 +147,37 @@ export interface editorSceneLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface editorSceneLogicActions {
+ createNotebook: (
+ location: NotebookTarget,
+ title?: string | undefined,
+ content?: JSONContent[] | undefined,
+ onCreate?:
+ | ((
+ notebook: import('node_modules/kea/lib').BuiltLogic<
+ import('../../notebooks/Notebook/notebookLogic').notebookLogicType
+ >
+ ) => void)
+ | undefined,
+ shortId?: string | undefined
+ ) => {
+ content: JSONContent[] | undefined
+ location: NotebookTarget
+ onCreate:
+ | ((
+ notebook: import('node_modules/kea/lib').BuiltLogic<
+ import('../../notebooks/Notebook/notebookLogic').notebookLogicType
+ >
+ ) => void)
+ | undefined
+ shortId: string | undefined
+ title: string | undefined
+ } // notebooksModel
closeHistoryModal: () => {
value: true
}
+ convertToNotebook: () => {
+ value: true
+ }
openHistoryModal: () => {
value: true
}
@@ -201,9 +271,13 @@ export const editorSceneLogic = kea<editorSceneLogicType>([
'sourceQuery',
'viewLoading',
],
+ notebooksModel,
+ ['notebooksLoading'],
],
+ actions: [notebooksModel, ['createNotebook']],
})),
actions({
+ convertToNotebook: true,
shareTab: true,
openHistoryModal: true,
closeHistoryModal: true,
@@ -484,7 +558,16 @@ export const editorSceneLogic = kea<editorSceneLogicType>([
},
],
}),
- listeners(({ values }) => ({
+ listeners(({ actions, values }) => ({
+ convertToNotebook: () => {
+ const { title, content } = buildSqlNotebook(
+ values.queryInput ?? '',
+ values.activeTab,
+ values.editingInsight,
+ values.featureFlags
+ )
+ actions.createNotebook(NotebookTarget.Scene, title, content)
+ },
openHistoryModal: () => {
posthog.capture('sql-editor-history-modal-opened', {
object: values.editingView ? 'view' : 'insight',
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 91783dc84a3e..d9ad24e21600 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -1,9 +1,13 @@
import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { insightsApi } from 'scenes/insights/utils/api'
+import { getMarkdownNotebookMarkdown } from 'scenes/notebooks/Notebook/markdownNotebookV2'
+import { NotebookNodeType } from 'scenes/notebooks/types'
+import { defaultNotebookContent } from 'scenes/notebooks/utils'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -22,7 +26,7 @@ import {
import { initKeaTests } from '~/test/init'
import { ChartDisplayType, InsightShortId, QueryBasedInsightModel } from '~/types'
-import { editorSceneLogic } from './editorSceneLogic'
+import { buildSqlNotebook, editorSceneLogic } from './editorSceneLogic'
import { OutputTab } from './outputPaneLogic'
import {
activeTabMatchesUrlTarget,
@@ -437,6 +441,59 @@ describe('sqlEditorLogic', () => {
})
describe('title section', () => {
+ it.each([
+ [
+ 'SQL v2',
+ true,
+ null,
+ 'SQL query',
+ {
+ type: NotebookNodeType.SQLV2,
+ attrs: {
+ nodeId: expect.any(String),
+ code: 'SELECT * FROM events LIMIT 10',
+ returnVariable: '',
+ edit: true,
+ },
+ },
+ ],
+ [
+ 'legacy SQL',
+ false,
+ MOCK_INSIGHT,
+ MOCK_INSIGHT.name,
+ {
+ type: NotebookNodeType.Query,
+ attrs: {
+ query: {
+ kind: NodeKind.DataTableNode,
+ source: {
+ kind: NodeKind.HogQLQuery,
+ query: 'SELECT * FROM events LIMIT 10',
+ },
+ },
+ edit: true,
+ },
+ },
+ ],
+ ])(
+ 'builds a %s notebook from the current SQL',
+ (_case, isFlagOn, editingInsight, expectedTitle, expectedNode) => {
+ const notebook = buildSqlNotebook('SELECT * FROM events LIMIT 10', null, editingInsight, {
+ [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]: isFlagOn,
+ })
+
+ expect(notebook).toMatchObject({
+ title: expectedTitle,
+ content: [expectedNode],
+ })
+
+ const markdown = getMarkdownNotebookMarkdown(defaultNotebookContent(notebook.title, notebook.content))
+
+ expect(markdown).not.toContain('hideFilters')
+ }
+ )
+
it('shows loading view title when opening a view from URL before view loads', async () => {
logic = sqlEditorLogic({
tabId: TAB_ID,
diff --git a/playwright/e2e/product-analytics/dashboards.spec.ts b/playwright/e2e/product-analytics/dashboards.spec.ts
index 5af895389a1e..81763881e4ee 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
- // "Save as insight" never enables. Wait for the reload before using the variable.
+ // The insight save option never enables. Wait for the reload before using the variable.
const variablesReloaded = page.waitForResponse(
(response) =>
response.url().includes('/insight_variables') &&
@@ -211,19 +211,22 @@ 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 "Save as insight" disabled.
+ // produce a malformed query that leaves the insight save option 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
- // "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' })
+ // 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' })
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 1a0dc4ae8eba..f9dbf34fa2f3 100644
--- a/playwright/e2e/sql-editor-axis-labels.spec.ts
+++ b/playwright/e2e/sql-editor-axis-labels.spec.ts
@@ -7,10 +7,19 @@ import { expect, test, PlaywrightWorkspaceSetupResult } from '../utils/workspace
async function goToSavedSqlInsight(page: Page, insightShortId: InsightShortId): Promise<void> {
await page.goto(`/sql#insight=${insightShortId}`, { waitUntil: 'domcontentloaded' })
await expect(page).toHaveURL(/\/sql#.*insight=/)
- await expect(page.getByRole('button', { name: 'Update insight' })).toBeVisible({ timeout: 30_000 })
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 })
+}
+
test.describe('SQL editor axis labels', () => {
test.setTimeout(120_000)
@@ -78,15 +87,9 @@ 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')
- 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 openUpdateInsightOption(page)
+ await page.getByRole('menuitem', { name: 'Update insight' }).click()
+ await expect(page).toHaveURL(/\/insights\//, { timeout: 60_000 })
await goToSavedSqlInsight(page, insightShortId)
diff --git a/playwright/e2e/sql-editor-history.spec.ts b/playwright/e2e/sql-editor-history.spec.ts
index 8219443a47c2..6211b6e56292 100644
--- a/playwright/e2e/sql-editor-history.spec.ts
+++ b/playwright/e2e/sql-editor-history.spec.ts
@@ -1,8 +1,21 @@
+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)
@@ -40,7 +53,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 expect(page.getByRole('button', { name: 'Update insight' })).toBeVisible({ timeout: 30000 })
+ await expectSaveOptions(page, 'Update insight')
})
await test.step('navigating to a plain SQL query in the same editor switches to save-as-new mode', async () => {
@@ -52,21 +65,19 @@ test.describe('SQL editor history', () => {
window.dispatchEvent(new PopStateEvent('popstate'))
})
- await expect(page.getByRole('button', { name: 'Save as insight' })).toBeVisible()
- await expect(page.getByRole('button', { name: 'Update insight' })).toHaveCount(0)
+ await expectSaveOptions(page, 'Save as insight')
})
await test.step('browser back restores the saved SQL insight editor state', async () => {
await page.goBack()
await page.waitForURL(/insight=/)
- await expect(page.getByRole('button', { name: 'Update insight' })).toBeVisible({ timeout: 30000 })
+ await expectSaveOptions(page, 'Update insight')
})
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 expect(page.getByRole('button', { name: 'Save as insight' })).toBeVisible()
- await expect(page.getByRole('button', { name: 'Update insight' })).toHaveCount(0)
+ await expectSaveOptions(page, 'Save as insight')
})
})
})