: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-warehouse): let hosts configure the embedded sql editor (#113206)
Rossca980ecc9807
diff --git a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsxindex 5beb0e64fca9..4cf60b86f4c7 100644--- a/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx+++ b/frontend/src/scenes/data-warehouse/editor/OutputPane.tsx@@ -1289,7 +1289,7 @@ const Content = ({showQueryScan,isEmbeddedMode,}: any): JSX.Element | null => {- const { selectedDirectSource } = useValues(sqlEditorLogic)+ const { selectedDirectSource, singleStatement, showAgentHints } = useValues(sqlEditorLogic)// dataNodeLogic's timer resets on every loadData dispatch, so a rerun issued while a// query is still in flight restarts the count (a local isLoading-keyed timer wouldn't).const { loadingTimeSeconds } = useValues(dataNodeLogic)@@ -1364,16 +1364,18 @@ const Content = ({Query results will be visualized here. Press <KeyboardShortcut command enter /> to run thequery.</span>- <WarehouseWizardHint- className="max-w-140"- fallback={- <MCPUseCaseCard- surfaceKey="sql.execute"- expiresAfterMs={ONE_DAY_IN_MILLISECONDS}- className="max-w-140"- />- }- />+ {showAgentHints ? (+ <WarehouseWizardHint+ className="max-w-140"+ fallback={+ <MCPUseCaseCard+ surfaceKey="sql.execute"+ expiresAfterMs={ONE_DAY_IN_MILLISECONDS}+ className="max-w-140"+ />+ }+ />+ ) : null}</div>)}@@ -1431,20 +1433,28 @@ const Content = ({className="flex flex-1 flex-col justify-center items-center border-t px-4 py-6 gap-4 text-center"data-attr="sql-editor-output-pane-empty-state">- <span className="text-secondary max-w-xl">- {msg} Press <KeyboardShortcut command enter /> to run the query at your cursor. Separate multiple- statements with <code>;</code> to run them independently.- </span>- <WarehouseWizardHint- className="max-w-140"- fallback={- <MCPUseCaseCard- surfaceKey="sql.execute"- expiresAfterMs={ONE_DAY_IN_MILLISECONDS}- className="max-w-140"- />- }- />+ {singleStatement ? (+ <span className="text-secondary max-w-xl">+ {msg} Press <KeyboardShortcut command enter /> to run the query.+ </span>+ ) : (+ <span className="text-secondary max-w-xl">+ {msg} Press <KeyboardShortcut command enter /> to run the query at your cursor. Separate+ multiple statements with <code>;</code> to run them independently.+ </span>+ )}+ {showAgentHints ? (+ <WarehouseWizardHint+ className="max-w-140"+ fallback={+ <MCPUseCaseCard+ surfaceKey="sql.execute"+ expiresAfterMs={ONE_DAY_IN_MILLISECONDS}+ className="max-w-140"+ />+ }+ />+ ) : null}</div>)}diff --git a/frontend/src/scenes/data-warehouse/editor/QueryPlaceholdersMenu.tsx b/frontend/src/scenes/data-warehouse/editor/QueryPlaceholdersMenu.tsxnew file mode 100644index 000000000000..98a59d9bcd04--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/QueryPlaceholdersMenu.tsx@@ -0,0 +1,36 @@+import { useActions, useValues } from 'kea'++import { IconClock } from '@posthog/icons'+import { LemonButton, LemonMenu, LemonMenuItem } from '@posthog/lemon-ui'++import { sqlEditorLogic } from './sqlEditorLogic'++export function QueryPlaceholdersMenu(): JSX.Element | null {+ const { placeholders } = useValues(sqlEditorLogic)+ const { insertTextAtCursor } = useActions(sqlEditorLogic)++ if (placeholders.length === 0) {+ return null+ }++ const items: LemonMenuItem[] = placeholders.map((placeholder) => ({+ key: placeholder.name,+ custom: true,+ label: (+ <span className="flex flex-col gap-0.5 py-0.5">+ <code className="text-xs">{`{${placeholder.name}}`}</code>+ <span className="text-xs text-secondary">{placeholder.description}</span>+ <span className="text-xxs text-muted-alt">Preview value: {placeholder.previewValue}</span>+ </span>+ ),+ onClick: () => insertTextAtCursor(`{${placeholder.name}}`),+ }))++ return (+ <LemonMenu items={[{ title: 'Insert into query', items }]} placement="bottom-start">+ <LemonButton type="secondary" size="small" icon={<IconClock />} data-attr="sql-editor-placeholders-button">+ Placeholders+ </LemonButton>+ </LemonMenu>+ )+}diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex 0f8dffa3bfa1..924ed1d0a73a 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -33,6 +33,7 @@ import { applyExecuteSqlToolOutput, getExecuteSqlToolContext } from './maxSqlTooimport { OutputPane } from './OutputPane'import { QueryFiltersMenu } from './QueryFiltersMenu'import { QueryPane } from './QueryPane'+import { QueryPlaceholdersMenu } from './QueryPlaceholdersMenu'import { QueryVariablesMenu } from './QueryVariablesMenu'import { RunButton } from './RunButton'import { sqlEditorLogic, tabModelPath } from './sqlEditorLogic'@@ -62,6 +63,8 @@ interface QueryWindowProps {onShareTab?: () => void/** Whether the query pane's code editor may grab focus on mount. Defaults to true. */autoFocusQueryPane?: boolean+ hideVariables?: boolean+ hideFilters?: boolean}export function QueryWindow({@@ -82,6 +85,8 @@ export function QueryWindow({hideRunButton,onShareTab,autoFocusQueryPane,+ hideVariables,+ hideFilters,}: QueryWindowProps): JSX.Element {const codeEditorKey = `hogql-editor-${tabId}`const logic = sqlEditorLogic({ tabId })@@ -97,6 +102,8 @@ export function QueryWindow({selectedConnectionId,sendRawQueryEnabled,selectedConnectionSupportsHogQL,+ placeholderValues,+ singleStatementDisabledReason,} = useValues(logic)const {@@ -264,11 +271,11 @@ export function QueryWindow({{showQueryPanel ? (<divclassName={cn(- 'flex flex-row justify-start align-center w-full pl-2 pr-2 bg-white dark:bg-black border-b border-t py-1',+ 'flex flex-row flex-wrap gap-y-1 justify-start align-center w-full pl-2 pr-2 bg-white dark:bg-black border-b border-t py-1',isDatabaseTreeCollapsed || mode !== SQLEditorMode.FullScene ? '' : 'rounded-tl-lg')}>- <div className="flex items-center gap-2">+ <div className="flex flex-wrap items-center gap-2"><ExpandDatabaseTreeButtonshowDatabaseTree={showDatabaseTree}onShowDatabaseTree={onShowDatabaseTree}@@ -279,7 +286,9 @@ export function QueryWindow({<RunButtononRunQuery={onRunQuery}runQueryLoading={runQueryLoading}- runQueryDisabledReason={runQueryDisabledReason}+ runQueryDisabledReason={+ runQueryDisabledReason ?? singleStatementDisabledReason ?? undefined+ }runQueryTooltip={runQueryTooltip}onCancelQuery={onCancelQuery}cancelQueryLoading={cancelQueryLoading}@@ -287,10 +296,13 @@ export function QueryWindow({)}<CollapsedConnectionSelector tabId={tabId} mode={mode} /><LemonDivider vertical />- <QueryVariablesMenu- disabledReason={editingView ? 'Variables are not allowed in views.' : undefined}- />- <QueryFiltersMenu />+ {!hideVariables ? (+ <QueryVariablesMenu+ disabledReason={editingView ? 'Variables are not allowed in views.' : undefined}+ />+ ) : null}+ {!hideFilters ? <QueryFiltersMenu /> : null}+ <QueryPlaceholdersMenu />{editingView ? (<AccessControlActionresourceType={AccessControlResourceType.WarehouseObjects}@@ -363,6 +375,8 @@ export function QueryWindow({// that mounts against an existing model never runs that path, and would then// ask for metadata without the index report.indexUsage: true,+ // Lets error checking resolve the host's placeholders instead of flagging them+ globals: placeholderValues ?? undefined,onFixWithAI: (prompt) => fixIndexUsageWithAI(prompt),onChange: (v) => {setQueryInput(v ?? '')diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex 52c7b5b71191..e5d6b34de8a3 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -94,6 +94,12 @@ interface SQLEditorProps {queryPaneMinHeight?: number/** Whether the query pane's code editor may grab focus on mount. Defaults to true. */autoFocusQueryPane?: boolean+ /** Refuse to run more than one statement, for hosts that save the editor text as one query. A selection still runs on its own. */+ singleStatement?: boolean+ /** Leave out the setup agent and MCP suggestions, for hosts where they do not apply. */+ hideAgentHints?: boolean+ hideVariables?: boolean+ hideFilters?: boolean}export function SQLEditor({@@ -117,6 +123,10 @@ export function SQLEditor({queryPaneDefaultHeight,queryPaneMinHeight,autoFocusQueryPane,+ singleStatement,+ hideAgentHints,+ hideVariables,+ hideFilters,}: SQLEditorProps): JSX.Element {const ref = useRef(null)const navigatorRef = useRef(null)@@ -210,6 +220,8 @@ export function SQLEditor({mode,monaco,editor,+ singleStatement,+ hideAgentHints,})const { sourceQuery, dataLogicKey } = useValues(logic)@@ -286,7 +298,10 @@ export function SQLEditor({<BindLogic logic={variablesLogic} props={variablesLogicProps}><BindLogic logic={variableModalLogic} props={{ key: dataVisualizationLogicProps.key }}><BindLogic logic={outputPaneLogic} props={{ tabId }}>- <BindLogic logic={sqlEditorLogic} props={{ tabId, mode, monaco, editor }}>+ <BindLogic+ logic={sqlEditorLogic}+ props={{ tabId, mode, monaco, editor, singleStatement, hideAgentHints }}+ >{showQueryPanel ? <VariablesQuerySync /> : null}{panel === SQLEditorPanel.Output ? (<div className="flex h-full min-h-0 flex-col overflow-hidden">@@ -336,6 +351,8 @@ export function SQLEditor({hideRunButton={hideRunButton}onShareTab={onShareTab}autoFocusQueryPane={autoFocusQueryPane}+ hideVariables={hideVariables}+ hideFilters={hideFilters}/>)}</div>diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex a642775bf48c..3353b7cdf4e9 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -3565,4 +3565,79 @@ describe('sqlEditorLogic', () => {expect(logic.values.upstreamLoadFailed).toBe(true)})})++ // Hosts that embed the editor (batch exports) pass preview values, query modifiers and the single-statement+ // option. They must reach the query that runs, and must stay out of `sourceQuery`, which hosts read back and save.+ describe('embedded host options', () => {+ let performQuerySpy: jest.SpyInstance++ const mountEmbedded = (singleStatement?: boolean): void => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ mode: SQLEditorMode.Embedded,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ singleStatement,+ })+ logic.mount()+ }++ const executedHogQLQueries = (): HogQLQuery[] =>+ performQuerySpy.mock.calls+ .map(([query]) => query)+ .filter((query): query is HogQLQuery => query?.kind === NodeKind.HogQLQuery)++ const runAndSettle = async (): Promise<void> => {+ logic.actions.runQuery()+ await expectLogic(logic).toFinishAllListeners()+ await new Promise((resolve) => setTimeout(resolve, 0))+ }++ beforeEach(() => {+ performQuerySpy = jest+ .spyOn(queryRunner, 'performQuery')+ .mockResolvedValue({ results: [], columns: [], types: [] } as never)+ })++ afterEach(() => {+ performQuerySpy.mockRestore()+ })++ it('runs with the host preview values and modifiers without saving them in the source query', async () => {+ mountEmbedded()+ logic.actions.setQueryInput('SELECT event FROM events WHERE timestamp >= {data_interval_start}')+ logic.actions.setPlaceholders([+ { name: 'data_interval_start', description: 'Start', previewValue: '2024-01-14 23:00:00' },+ ])+ logic.actions.setQueryModifiers({ convertToProjectTimezone: false })++ await runAndSettle()++ expect(executedHogQLQueries().at(-1)).toMatchObject({+ values: { data_interval_start: '2024-01-14 23:00:00' },+ modifiers: { convertToProjectTimezone: false },+ })+ expect(logic.values.sourceQuery.source).not.toHaveProperty('values')+ expect(logic.values.sourceQuery.source).not.toHaveProperty('modifiers')+ })++ it.each([+ ['runs a single statement', true, 'SELECT 1', ['SELECT 1']],+ ['does not run more than one statement', true, 'SELECT 1; SELECT 2', []],+ [+ 'still runs several statements without the option',+ undefined,+ 'SELECT 1; SELECT 2',+ ['SELECT 1; SELECT 2'],+ ],+ ])('singleStatement %s', async (_, singleStatement, queryInput, expectedQueries) => {+ mountEmbedded(singleStatement)+ logic.actions.setQueryInput(queryInput)++ await runAndSettle()++ // The data layer can call performQuery more than once per run, so compare the distinct queries+ expect([...new Set(executedHogQLQueries().map((query) => query.query))]).toEqual(expectedQueries)+ })+ })})diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex dae14a751c8f..451b2280ce8c 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -76,6 +76,7 @@ import {HogQLMetadata,HogQLMetadataResponse,HogQLQuery,+ HogQLQueryModifiers,NodeKind,PredicateQuickfix,} from '~/queries/schema/schema-general'@@ -142,6 +143,7 @@ import { OutputTab, outputPaneLogic } from './outputPaneLogic'import { findSelectionProblem } from './saveCandidateProblems'import { resolveSaveCandidates as resolveSaveCandidatesPure, SaveTargetCycler } from './SaveTargetCycler'import { SQLEditorMode, isEmbeddedSQLEditorMode } from './sqlEditorModes'+import { SQLEditorPlaceholder, placeholderPreviewValues } from './sqlEditorPlaceholders'import {aiSuggestionOnAccept,aiSuggestionOnAcceptText,@@ -159,6 +161,8 @@ import { ViewEmptyState } from './ViewLoadingState'export interface SqlEditorLogicProps {tabId: stringmode?: SQLEditorMode+ singleStatement?: boolean+ hideAgentHints?: booleanmonaco?: Monaco | nulleditor?: editor.IStandaloneCodeEditor | null}@@ -649,7 +653,10 @@ export interface sqlEditorLogicValues {metricPrefill: MetricFormPrefill | nullmetricUpdating: booleanoriginalQueryInput: string | null | undefined+ placeholderValues: Record<string, string> | null+ placeholders: SQLEditorPlaceholder[]queryInput: string | null+ queryModifiers: HogQLQueryModifiers | nullrejectText: stringselectedConnectionId: string | undefinedselectedConnectionSupportsHogQL: boolean@@ -657,6 +664,9 @@ export interface sqlEditorLogicValues {selectedQueryColumns: Record<string, boolean>selectedQueryTablesAndColumns: Record<string, Record<string, boolean>>sendRawQueryEnabled: boolean+ showAgentHints: boolean+ singleStatement: boolean+ singleStatementDisabledReason: string | nullsourceQuery: DataVisualizationNodesplitQueryRanges: QueryRange[]suggestedQueryInput: string@@ -1121,9 +1131,15 @@ export interface sqlEditorLogicActions {setMetricUpdating: (updating: boolean) => {updating: boolean}+ setPlaceholders: (placeholders: SQLEditorPlaceholder[]) => {+ placeholders: SQLEditorPlaceholder[]+ }setQueryInput: (queryInput: string | null) => {queryInput: string | null}+ setQueryModifiers: (queryModifiers: HogQLQueryModifiers | null) => {+ queryModifiers: HogQLQueryModifiers | null+ }setSelectedQueryTablesAndColumns: (tablesAndColumns: Record<string, Record<string, boolean>>) => {tablesAndColumns: Record<string, Record<string, boolean>>}@@ -1184,6 +1200,7 @@ export interface sqlEditorLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {editorUrl: (arg: SQLEditorMode | undefined) => string+ placeholderValues: (placeholders: SQLEditorPlaceholder[]) => Record<string, string> | nullsuggestedSource: (suggestionPayload: SuggestionPayload | null) => 'hogql_fixer' | 'materialization_fix' | 'max_ai' | 'query_history' | null@@ -1217,6 +1234,9 @@ export interface sqlEditorLogicMeta {isEditingMaterializedView: (editingView: DataWarehouseSavedQuery | undefined) => booleansplitQueryRanges: (queryInput: string | null) => QueryRange[]isMultiQuery: (splitQueryRanges: QueryRange[]) => boolean+ singleStatement: (arg: any) => boolean+ showAgentHints: (arg: any) => boolean+ singleStatementDisabledReason: (singleStatement: boolean, isMultiQuery: boolean) => string | nullisSourceQueryLastRun: (queryInput: string | null,lastRunQuery: DataVisualizationNode | null,@@ -1465,6 +1485,8 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([}),syncUrlWithQuery: true,insertTextAtCursor: (text: string) => ({ text }),+ setPlaceholders: (placeholders: SQLEditorPlaceholder[]) => ({ placeholders }),+ setQueryModifiers: (queryModifiers: HogQLQueryModifiers | null) => ({ queryModifiers }),applyIndexQuickfix: (quickfix: PredicateQuickfix) => ({ quickfix }),fixIndexUsageWithAI: (prompt: string) => ({ prompt }),setEditorSource: (source: SqlEditorSource) => ({ source }),@@ -1617,6 +1639,18 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([setSourceQuery: (_, { sourceQuery }) => sanitizeSourceQuery(sourceQuery),},],+ placeholders: [+ [] as SQLEditorPlaceholder[],+ {+ setPlaceholders: (_, { placeholders }) => placeholders,+ },+ ],+ queryModifiers: [+ null as HogQLQueryModifiers | null,+ {+ setQueryModifiers: (_, { queryModifiers }) => queryModifiers,+ },+ ],lastRunQuery: [null as DataVisualizationNode | null,{@@ -2270,6 +2304,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([})},runQuery: ({ queryOverride, switchTab }) => {+ // Cmd+Enter reaches this listener even while the run button is disabled+ if (values.singleStatementDisabledReason) {+ return+ }const biEditorState = getActiveBIEditorState()if (!queryOverride &&@@ -2323,6 +2361,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([// insights/views and change detection never pick them upconst executedSource: HogQLQuery = {...newSource,+ // Like tags, the host's preview values and modifiers stay out of sourceQuery so it never saves them+ ...(values.placeholderValues+ ? { values: { ...newSource.values, ...values.placeholderValues } }+ : {}),+ ...(values.queryModifiers+ ? { modifiers: { ...newSource.modifiers, ...values.queryModifiers } }+ : {}),tags: { ...newSource.tags, productKey: 'sql_editor' },}@@ -2359,7 +2404,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.RunFirstQuery)const compactQuery = query.replace(/\s+/g, ' ').trim()const truncated = compactQuery.length > 80 ? compactQuery.slice(0, 77) + '…' : compactQuery- tryShowMCPHint('sql.execute', truncated ? { derivedPrompt: `Run this SQL: ${truncated}` } : undefined)+ if (values.showAgentHints) {+ tryShowMCPHint(+ 'sql.execute',+ truncated ? { derivedPrompt: `Run this SQL: ${truncated}` } : undefined+ )+ }},saveAsView: async ({ fromDraft, materializeAfterSave = false }) => {const isStaff = values.user?.is_staff ?? false@@ -3497,6 +3547,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([(mode: SQLEditorMode | undefined) =>mode === SQLEditorMode.BusinessIntelligence ? urls.businessIntelligence() : urls.sqlEditor(),],+ placeholderValues: [+ (s) => [s.placeholders],+ (placeholders: SQLEditorPlaceholder[]): Record<string, string> | null =>+ placeholderPreviewValues(placeholders),+ ],suggestedSource: [(s) => [s.suggestionPayload],(suggestionPayload: SuggestionPayload | null) => {@@ -3654,6 +3709,21 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([(queryInput: string | null): QueryRange[] => splitQueries(queryInput ?? ''),],isMultiQuery: [(s) => [s.splitQueryRanges], (ranges: QueryRange[]): boolean => ranges.length > 1],+ singleStatement: [+ () => [(_, props) => props.singleStatement],+ (singleStatement?: boolean): boolean => !!singleStatement,+ ],+ showAgentHints: [+ () => [(_, props) => props.hideAgentHints],+ (hideAgentHints?: boolean): boolean => !hideAgentHints,+ ],+ singleStatementDisabledReason: [+ (s) => [s.singleStatement, s.isMultiQuery],+ (singleStatement: boolean, isMultiQuery: boolean): string | null =>+ singleStatement && isMultiQuery+ ? 'Only one query can run here. Remove the extra statements separated by semicolons.'+ : null,+ ],isSourceQueryLastRun: [(s) => [s.queryInput, s.lastRunQuery, s.sourceQuery, s.splitQueryRanges],(diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorPlaceholders.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorPlaceholders.tsnew file mode 100644index 000000000000..a72b87d4ec53--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorPlaceholders.ts@@ -0,0 +1,14 @@+/** A `{name}` placeholder that the scene embedding the editor fills in when it runs the query for real. */+export interface SQLEditorPlaceholder {+ name: string+ description: string+ /** Stands in for the real value whenever the editor runs or checks the query. */+ previewValue: string+}++export function placeholderPreviewValues(placeholders: SQLEditorPlaceholder[]): Record<string, string> | null {+ if (placeholders.length === 0) {+ return null+ }+ return Object.fromEntries(placeholders.map((placeholder) => [placeholder.name, placeholder.previewValue]))+}