: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
fix(data-warehouse): refuse to save a partial SQL selection (#106859)
Jovan Sakovic124a64f650f1
diff --git a/frontend/src/scenes/data-warehouse/editor/SaveTargetCycler.tsx b/frontend/src/scenes/data-warehouse/editor/SaveTargetCycler.tsxindex 34a19df9af4c..3974f606d21b 100644--- a/frontend/src/scenes/data-warehouse/editor/SaveTargetCycler.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SaveTargetCycler.tsx@@ -6,6 +6,8 @@ import { CodeSnippet, Language } from 'lib/components/CodeSnippet'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { findQueryAtCursor, splitQueries } from 'lib/monaco/multiQueryUtils'+export const SELECTION_LABEL = 'Selection'+export interface SaveCandidates {queries: string[]initialIndex: number@@ -30,7 +32,7 @@ export function resolveSaveCandidates(if (selectionText) {const trimmed = selectionText.trim()if (trimmed) {- return { queries: [trimmed], initialIndex: 0, selectionLabel: 'Selection' }+ return { queries: [trimmed], initialIndex: 0, selectionLabel: SELECTION_LABEL }}}diff --git a/frontend/src/scenes/data-warehouse/editor/saveCandidateProblems.test.ts b/frontend/src/scenes/data-warehouse/editor/saveCandidateProblems.test.tsnew file mode 100644index 000000000000..55ff25821484--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/saveCandidateProblems.test.ts@@ -0,0 +1,45 @@+import { parseSelect } from './hogqlParserSingleton'+import { SELECTION_NOT_A_QUERY, findSelectionProblem } from './saveCandidateProblems'+import { SELECTION_LABEL, SaveCandidates } from './SaveTargetCycler'++jest.mock('./hogqlParserSingleton', () => {+ const actual = jest.requireActual('./hogqlParserSingleton')+ return { ...actual, parseSelect: jest.fn(actual.parseSelect) }+})++const candidates = (queries: string[], selectionLabel: string | null = null): SaveCandidates => ({+ queries,+ initialIndex: 0,+ selectionLabel,+})++describe('findSelectionProblem', () => {+ it('flags a highlighted identifier and points at the selection', async () => {+ const problem = await findSelectionProblem(candidates(['weekly_active_users'], SELECTION_LABEL), false)+ expect(problem).toEqual(SELECTION_NOT_A_QUERY)+ })++ it('accepts a selection that is a whole query', async () => {+ const problem = await findSelectionProblem(candidates(['SELECT 1'], SELECTION_LABEL), false)+ expect(problem).toBeNull()+ })++ it('leaves the editor contents to the API when nothing is selected', async () => {+ const problem = await findSelectionProblem(candidates(['weekly_active_users']), false)+ expect(problem).toBeNull()+ })++ it('leaves a raw connection selection alone, because it is not HogQL', async () => {+ const problem = await findSelectionProblem(+ candidates(['SELECT DISTINCT ON (id) id FROM t'], SELECTION_LABEL),+ true+ )+ expect(problem).toBeNull()+ })++ it('reports no problem when the parser cannot be loaded', async () => {+ ;(parseSelect as jest.Mock).mockRejectedValueOnce(new Error('parser unavailable'))+ const problem = await findSelectionProblem(candidates(['weekly_active_users'], SELECTION_LABEL), false)+ expect(problem).toBeNull()+ })+})diff --git a/frontend/src/scenes/data-warehouse/editor/saveCandidateProblems.ts b/frontend/src/scenes/data-warehouse/editor/saveCandidateProblems.tsnew file mode 100644index 000000000000..bef5baf870e4--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/saveCandidateProblems.ts@@ -0,0 +1,39 @@+import { parseSelect } from './hogqlParserSingleton'+import { SELECTION_LABEL, SaveCandidates } from './SaveTargetCycler'++export const SELECTION_NOT_A_QUERY =+ 'The selected text is not a complete query. Close this dialog and clear the selection in the editor, then save again.'++/**+ * Report why the chosen save candidate cannot be saved, or null when it is fine.+ *+ * Only a selection is judged. It is the one candidate a person does not mean to choose: a+ * double-click leaves a single identifier highlighted, and that then wins over the whole editor+ * contents. Clearing the selection is always a way forward, so a wrong verdict here cannot trap+ * anyone. The whole editor contents are left to the API, whose parser is the one that decides.+ *+ * Fails open. When the parser is unavailable we cannot tell a broken query from an unchecked one.+ * Raw connection mode is skipped for the same reason: the text goes to the connection's own engine+ * in its own dialect, so a HogQL parse of it would refuse valid SQL.+ */+export async function findSelectionProblem(+ candidates: SaveCandidates,+ sendRawQueryEnabled: boolean+): Promise<string | null> {+ if (sendRawQueryEnabled || candidates.selectionLabel !== SELECTION_LABEL) {+ return null+ }+ const selected = candidates.queries[candidates.initialIndex] ?? ''+ return (await isParsable(selected)) ? null : SELECTION_NOT_A_QUERY+}++async function isParsable(query: string): Promise<boolean> {+ try {+ // parseSelect reports a syntax error inside its result rather than rejecting, so a+ // rejection here means the parser itself failed to load.+ const parsed = JSON.parse(await parseSelect(query))+ return parsed?.error !== true+ } catch {+ return true+ }+}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 030caefd45e4..cd5060828b71 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -36,6 +36,7 @@ import { biEditorLogic } from './bi/biEditorLogic'import { BIConfig, BIEditorView, BIField } from './bi/biEditorTypes'import { buildSqlNotebook, editorSceneLogic } from './editorSceneLogic'import { OutputTab } from './outputPaneLogic'+import { SELECTION_NOT_A_QUERY } from './saveCandidateProblems'import {activeTabMatchesUrlTarget,getDisplayTypeToSaveInsight,@@ -1398,7 +1399,7 @@ describe('sqlEditorLogic', () => {logic.actions.saveAsMetric()await expectLogic(logic).toFinishAllListeners()- expect(openForm.mock.calls.at(-1)?.[0].initialValues).toEqual(PREFILL)+ expect(openForm.mock.calls.at(-1)?.[0].initialValues).toEqual({ saveTarget: 0, ...PREFILL })openForm.mockRestore()})@@ -1466,6 +1467,41 @@ describe('sqlEditorLogic', () => {})})+ describe('save dialog selection guard', () => {+ // Monaco reports a non-empty selection after a double-click, which is the editor state+ // that let a single identifier reach the API as the query to save.+ function createEditorWithSelection(selected: string): any {+ return {+ ...createMockEditor(),+ getModel: () => ({ getValueInRange: () => selected }),+ getSelection: () => ({ isEmpty: () => false }),+ }+ }++ it.each([+ ['view', (): void => logic.actions.saveAsView()],+ ['endpoint', (): void => logic.actions.saveAsEndpoint()],+ ['metric', (): void => logic.actions.saveAsMetric()],+ ])('refuses to save a selected identifier as a %s', async (_target, openDialog) => {+ const openForm = jest.spyOn(LemonDialog, 'openForm').mockImplementation(() => {})+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createEditorWithSelection('weekly_active_users'),+ })+ logic.mount()++ openDialog()+ await expectLogic(logic).toFinishAllListeners()++ const form = openForm.mock.calls.at(-1)?.[0] as any+ expect(form.errors.saveTarget(form.initialValues.saveTarget, form.initialValues)).toEqual(+ SELECTION_NOT_A_QUERY+ )+ openForm.mockRestore()+ })+ })+describe('Update view', () => {it('advances the saved baseline after updating so reverting to the original query re-enables Update view', async () => {logic = sqlEditorLogic({diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 2f1643f5b21d..6c6dd6342877 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -123,6 +123,7 @@ import type { Response } from './fixSQLErrorsLogic'import { IncrementalConfigFields } from './IncrementalConfigFields'import { findInnermostSelectAtOffset } from './multiQueryUtils'import { OutputTab, outputPaneLogic } from './outputPaneLogic'+import { findSelectionProblem } from './saveCandidateProblems'import { resolveSaveCandidates as resolveSaveCandidatesPure, SaveTargetCycler } from './SaveTargetCycler'import { SQLEditorMode, isEmbeddedSQLEditorMode } from './sqlEditorModes'import {@@ -2255,6 +2256,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([const selectedRef = {current: candidates.queries[candidates.initialIndex],}+ const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)// Checked once as the dialog opens rather than on every keystroke: it only depends// on the SQL being saved, which cannot change while the dialog is up. A failure@@ -2307,6 +2309,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([title: 'Save as view',showErrorsOnTouch: true,initialValues: {+ saveTarget: candidates.initialIndex,viewName: values.activeTab?.name || '',folderId: null,isTest: false,@@ -2324,6 +2327,17 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([</div>) : (<>+ <LemonField name="saveTarget">+ {({ onChange }) => (+ <SaveTargetCycler+ candidates={candidates}+ onChange={(query, index) => {+ selectedRef.current = query+ onChange(index)+ }}+ />+ )}+ </LemonField><LemonField name="viewName" label="Name"><LemonInputdata-attr="sql-editor-input-save-view-name"@@ -2397,15 +2411,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([</>)}</LemonField>- <SaveTargetCycler- candidates={candidates}- onChange={(q) => {- selectedRef.current = q- }}- /></>),errors: {+ saveTarget: () => selectionProblem ?? undefined,viewName: validateSavedQueryName,incrementalKey: (key, { incrementalEnabled, materializeAfterSave: materialize }) =>incrementalEnabled && materialize && !key ? 'Select the incremental column' : undefined,@@ -2684,14 +2693,27 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([const selectedRef = {current: candidates.queries[candidates.initialIndex],}+ const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)LemonDialog.openForm({title: 'Save as endpoint',initialValues: {+ saveTarget: candidates.initialIndex,name: '',description: '',},content: (<>+ <LemonField name="saveTarget">+ {({ onChange }) => (+ <SaveTargetCycler+ candidates={candidates}+ onChange={(query, index) => {+ selectedRef.current = query+ onChange(index)+ }}+ />+ )}+ </LemonField><LemonField name="name"><LemonInputdata-attr="endpoint-name"@@ -2705,15 +2727,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([placeholder="Please enter a description (optional)"/></LemonField>- <SaveTargetCycler- candidates={candidates}- onChange={(q) => {- selectedRef.current = q- }}- /></>),errors: {+ saveTarget: () => selectionProblem ?? undefined,name: (name) => validateEndpointName(name?.trim() || ''),},onSubmit: async ({ name, description }) =>@@ -2742,9 +2759,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([saveAsMetric: async () => {const candidates = resolveSaveCandidates()const selectedRef = { current: candidates.queries[candidates.initialIndex] }+ const selectionProblem = await findSelectionProblem(candidates, values.sendRawQueryEnabled)LemonDialog.openForm({title: 'Save as metric',initialValues: {+ saveTarget: candidates.initialIndex,name: '',display_name: '',description: '',@@ -2753,6 +2772,17 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([},content: (<>+ <LemonField name="saveTarget">+ {({ onChange }) => (+ <SaveTargetCycler+ candidates={candidates}+ onChange={(query, index) => {+ selectedRef.current = query+ onChange(index)+ }}+ />+ )}+ </LemonField><LemonField name="name" label={METRIC_FIELD_COPY.name.label}><LemonInput placeholder={METRIC_FIELD_COPY.name.placeholder} autoFocus /></LemonField>@@ -2774,15 +2804,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([<LemonField name="unit" label={METRIC_FIELD_COPY.unit.label} className="mt-2"><LemonInput placeholder={METRIC_FIELD_COPY.unit.placeholder} /></LemonField>- <SaveTargetCycler- candidates={candidates}- onChange={(q) => {- selectedRef.current = q- }}- /></>),errors: {+ saveTarget: () => selectionProblem ?? undefined,name: (name) => validateMetricName(name?.trim() || ''),description: (description) =>!description?.trim() ? 'Add a description' : validateMetricDescription(description.trim()),