: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): stop re-rendering SQL editor chrome on every keystroke (#100300)
George Munyoro2a4f72028baf
diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex 9db0478e3688..342dfa903937 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -4,7 +4,7 @@ import MonacoEditor, { type EditorProps, Monaco, DiffEditor as MonacoDiffEditorimport { BuiltLogic, useActions, useMountedLogic, useValues } from 'kea'import * as monacoModule from 'monaco-editor'import { IDisposable, editor, editor as importedEditor } from 'monaco-editor'-import { useEffect, useRef, useState } from 'react'+import { useEffect, useMemo, useRef, useState } from 'react'import 'lib/monaco/monacoEnvironment'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'@@ -418,31 +418,45 @@ export function CodeEditor({}}, [editor, enableVimMode, vimCommandHistory, appendVimCommand])- const editorOptions: editor.IStandaloneEditorConstructionOptions = {- minimap: {- enabled: false,- },- scrollBeyondLastLine: false,- automaticLayout: true,- fixedOverflowWidgets: true,- glyphMargin: false,- folding: true,- wordWrap: 'off',- lineNumbers: 'on',- tabFocusMode: false,- overviewRulerBorder: true,- hideCursorInOverviewRuler: false,- overviewRulerLanes: 3,- overflowWidgetsDomNode: monacoRoot,- ...options,- padding: { bottom: enableVimMode ? 28 : 8, top: 8 },- scrollbar: {- vertical: scrollbarRendering,- horizontal: scrollbarRendering,- alwaysConsumeMouseWheel: false,- ...options?.scrollbar,- },- }+ // The wrapper calls `editor.updateOptions` whenever this object's identity changes, and+ // Monaco revalidates every option on each call, so only rebuild it when an input changes.+ const editorOptions = useMemo<editor.IStandaloneEditorConstructionOptions>(+ () => ({+ minimap: {+ enabled: false,+ },+ scrollBeyondLastLine: false,+ automaticLayout: true,+ fixedOverflowWidgets: true,+ glyphMargin: false,+ folding: true,+ wordWrap: 'off',+ lineNumbers: 'on',+ tabFocusMode: false,+ overviewRulerBorder: true,+ hideCursorInOverviewRuler: false,+ overviewRulerLanes: 3,+ overflowWidgetsDomNode: monacoRoot,+ ...options,+ padding: { bottom: enableVimMode ? 28 : 8, top: 8 },+ scrollbar: {+ vertical: scrollbarRendering,+ horizontal: scrollbarRendering,+ alwaysConsumeMouseWheel: false,+ ...options?.scrollbar,+ },+ }),+ [options, enableVimMode, scrollbarRendering, monacoRoot]+ )+ const diffEditorOptions = useMemo<editor.IStandaloneDiffEditorConstructionOptions>(+ () => ({+ ...editorOptions,+ renderSideBySide: false,+ acceptSuggestionOnEnter: 'on',+ renderGutterMenu: false,+ }),+ [editorOptions]+ )const editorOnMount = (editor: importedEditor.IStandaloneCodeEditor, monaco: Monaco): void => {// The lazy Suspense facade can resolve after the component has already@@ -631,12 +645,7 @@ export function CodeEditor({theme={isDarkModeOn ? 'vs-dark' : 'vs-light'}original={originalValue}modified={value}- options={{- ...editorOptions,- renderSideBySide: false,- acceptSuggestionOnEnter: 'on',- renderGutterMenu: false,- }}+ options={diffEditorOptions}onMount={diffEditorOnMount}{...editorProps}// Own model disposal ourselves via `disposeTrackedModels`. Left to the library,diff --git a/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsx b/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsxindex bb4072fcb881..53ea3167bd13 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryFiltersMenu.tsx@@ -1,5 +1,5 @@-import { useActions, useValues } from 'kea'-import { useState } from 'react'+import { useActions, useMountedLogic, useValues } from 'kea'+import { memo, useState } from 'react'import { IconFilter, IconWarning } from '@posthog/icons'import { LemonButton, LemonMenu, LemonMenuItems, Link } from '@posthog/lemon-ui'@@ -12,7 +12,6 @@ import { EventPropertyFilters } from '~/queries/nodes/EventsNode/EventPropertyFiimport type { HogQLFilters, HogQLQuery } from '~/queries/schema/schema-general'import { isHogQLQuery } from '~/queries/utils'-import { filtersPlaceholderBindings, queryUsesFiltersPlaceholder } from './sql-utils'import { sqlEditorLogic } from './sqlEditorLogic'const hasDateRange = (filters?: HogQLFilters): boolean => {@@ -48,9 +47,12 @@ const filtersTooltip = ({return undefined}-export function QueryFiltersMenu(): JSX.Element | null {- const { sourceQuery, queryInput } = useValues(sqlEditorLogic)+// QueryWindow subscribes to queryInput, so it renders on every keystroke. memo stops that render from+// reaching this menu, and the selectors below keep the menu's own subscriptions off the keystroke path.+export const QueryFiltersMenu = memo(function QueryFiltersMenu(): JSX.Element | null {+ const { sourceQuery, hasFiltersPlaceholder, filtersPlaceholderBindings } = useValues(sqlEditorLogic)const { setSourceQuery, runQuery, insertTextAtCursor } = useActions(sqlEditorLogic)+ const logic = useMountedLogic(sqlEditorLogic)const [isMenuOpen, setIsMenuOpen] = useState(false)if (!isHogQLQuery(sourceQuery.source)) {@@ -60,11 +62,10 @@ export function QueryFiltersMenu(): JSX.Element | null {const source = sourceQuery.sourceconst filters = source.filtersconst hasFilters = hasActiveFilters(filters)- const queryText = queryInput ?? source.query- const usesFiltersPlaceholder = queryUsesFiltersPlaceholder(queryText)+ const usesFiltersPlaceholder = hasFiltersPlaceholderconst filtersMissingPlaceholder = hasFilters && !usesFiltersPlaceholder- const bindings = filtersPlaceholderBindings(queryText)- const bindingsMissingTimestamp = bindings !== null && !bindings.includes('timestamp')+ const bindingsMissingTimestamp =+ filtersPlaceholderBindings !== null && !filtersPlaceholderBindings.includes('timestamp')const setHogQLQuery = (query: HogQLQuery): void => {const nextSourceQuery = {@@ -75,7 +76,7 @@ export function QueryFiltersMenu(): JSX.Element | null {setSourceQuery(nextSourceQuery)if (usesFiltersPlaceholder) {- runQuery(queryInput ?? query.query)+ runQuery(logic.values.queryInput ?? query.query)}}@@ -200,4 +201,4 @@ export function QueryFiltersMenu(): JSX.Element | null {</LemonButton></LemonMenu>)-}+})diff --git a/frontend/src/scenes/data-warehouse/editor/QueryPane.tsx b/frontend/src/scenes/data-warehouse/editor/QueryPane.tsxindex b11662eb7b8f..13d2d3b39b55 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryPane.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryPane.tsx@@ -1,4 +1,5 @@import { useActions, useValues } from 'kea'+import { useMemo } from 'react'import { IconCheck, IconX } from '@posthog/icons'@@ -28,6 +29,23 @@ export function QueryPane(props: QueryPaneProps): JSX.Element {const { queryPaneHeight, queryPaneDesiredSize, queryPaneResizerProps } = useValues(editorSizingLogic)const { onAcceptSuggestedQueryInput, onRejectSuggestedQueryInput } = useActions(sqlEditorLogic)const { acceptText, rejectText, diffShowRunButton } = useValues(sqlEditorLogic)+ const editorOptions = useMemo<CodeEditorProps['options']>(+ () => ({+ minimap: {+ enabled: false,+ },+ wordWrap: 'on',+ scrollBeyondLastLine: !!props.originalValue,+ automaticLayout: true,+ fixedOverflowWidgets: true,+ glyphMargin: true,+ suggest: {+ showInlineDetails: true,+ },+ quickSuggestionsDelay: 300,+ }),+ [props.originalValue]+ )// Without an output pane beneath it the editor owns its column, so it takes whatever height the// database tree gives the row rather than leaving dead space next to the schema list.const fillsColumn = props.constrainHeight === false@@ -71,20 +89,7 @@ export function QueryPane(props: QueryPaneProps): JSX.Element {enableVimMode={props.editorVimModeEnabled}autoFocus={true}{...props.codeEditorProps}- options={{- minimap: {- enabled: false,- },- wordWrap: 'on',- scrollBeyondLastLine: !!props.originalValue,- automaticLayout: true,- fixedOverflowWidgets: true,- glyphMargin: true,- suggest: {- showInlineDetails: true,- },- quickSuggestionsDelay: 300,- }}+ options={editorOptions}/>) : null}diff --git a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsxindex f33ffa423f9a..8c2f3fa6e495 100644--- a/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx+++ b/frontend/src/scenes/data-warehouse/editor/QueryWindow.tsx@@ -134,10 +134,13 @@ export function QueryWindow({[debouncedMaxToolQueryInput, debouncedMaxToolSourceQuery])- useAttachedContext(- [{ type: 'sql_editor_state', value: JSON.stringify(executeSqlToolContext), label: 'Current query' }],- { active: showQueryPanel }+ const attachedContextItems = useMemo(+ () => [+ { type: 'sql_editor_state' as const, value: JSON.stringify(executeSqlToolContext), label: 'Current query' },+ ],+ [executeSqlToolContext])+ useAttachedContext(attachedContextItems, { active: showQueryPanel })const executeSqlToolContextDescription = useMemo(() => ({diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex a7c7637acd45..9424dfd154a9 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -7,6 +7,7 @@ import { IconBook, IconChevronDown, IconDownload, IconNotebook, IconX } from '@pimport { LemonModal, Spinner } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'+import { useDebouncedValue } from 'lib/hooks/useDebouncedValue'import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'@@ -60,6 +61,7 @@ export enum SQLEditorPanel {}const VARIABLE_QUERY_SYNC_DEBOUNCE_MS = 150+const MAX_TOOL_CONTEXT_DEBOUNCE_MS = 150interface SQLEditorProps {tabId?: string@@ -478,13 +480,23 @@ function SQLEditorSceneTitle(): JSX.Element | null {const { response, responseError, responseLoading } = useValues(dataNodeLogic)const { updatingDataWarehouseSavedQuery } = useValues(dataWarehouseViewsLogic)- useAttachedContext([- {- type: 'sql_editor_state',- value: JSON.stringify(getExecuteSqlToolContext(queryInput, sourceQuery)),- label: 'Current query',- },- ])+ const debouncedQueryInput = useDebouncedValue(queryInput, MAX_TOOL_CONTEXT_DEBOUNCE_MS)+ const debouncedSourceQuery = useDebouncedValue(sourceQuery, MAX_TOOL_CONTEXT_DEBOUNCE_MS)+ const executeSqlToolContext = useMemo(+ () => getExecuteSqlToolContext(debouncedQueryInput, debouncedSourceQuery),+ [debouncedQueryInput, debouncedSourceQuery]+ )+ const attachedContextItems = useMemo(+ () => [+ {+ type: 'sql_editor_state' as const,+ value: JSON.stringify(executeSqlToolContext),+ label: 'Current query',+ },+ ],+ [executeSqlToolContext]+ )+ useAttachedContext(attachedContextItems)const saveAsViewAccessDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.WarehouseObjects,@@ -661,7 +673,7 @@ function SQLEditorSceneTitle(): JSX.Element | null {})}maxToolProps={{identifier: 'execute_sql',- context: getExecuteSqlToolContext(queryInput, sourceQuery),+ context: executeSqlToolContext,contextDescription: {text: 'Current query',icon: iconForType('sql_editor'),diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex e65d02447ee4..f1e863526da1 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -355,6 +355,23 @@ describe('sqlEditorLogic', () => {expect(logic.values.hasFiltersPlaceholder).toBe(false)})+ it('keeps the same bindings reference when an edit does not change the placeholder', () => {+ logic = sqlEditorLogic({+ tabId: TAB_ID,+ monaco: createMockMonaco(),+ editor: createMockEditor(),+ })+ logic.mount()++ logic.actions.setQueryInput('SELECT * FROM events WHERE {filters(created_at AS timestamp)}')+ const bindings = logic.values.filtersPlaceholderBindings++ logic.actions.setQueryInput('SELECT *, 1 FROM events WHERE {filters(created_at AS timestamp)}')++ expect(bindings).toEqual(['timestamp'])+ expect(logic.values.filtersPlaceholderBindings).toBe(bindings)+ })+it('restores filters from the URL hash', async () => {const filters: HogQLFilters = {dateRange: {diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 57044aebd800..a016c6f1c8da 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -48,7 +48,11 @@ import { lazyWithRetry } from 'lib/utils/retryImport'import { slugify } from 'lib/utils/strings'import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'-import { parseQueryTablesAndColumns, queryUsesFiltersPlaceholder } from 'scenes/data-warehouse/editor/sql-utils'+import {+ filtersPlaceholderBindings,+ parseQueryTablesAndColumns,+ queryUsesFiltersPlaceholder,+} from 'scenes/data-warehouse/editor/sql-utils'import { insightLogic } from 'scenes/insights/insightLogic'import { insightsApi } from 'scenes/insights/utils/api'import { urls } from 'scenes/urls'@@ -574,6 +578,7 @@ export interface sqlEditorLogicValues {editorSource: SqlEditorSourceerror: string | nullexportContext: ExportContext+ filtersPlaceholderBindings: string[] | nullfinishedLoading: booleanfixErrorsError: string | nullhasFiltersPlaceholder: boolean@@ -1148,6 +1153,7 @@ export interface sqlEditorLogicMeta {splitQueryRanges: QueryRange[]) => booleanhasFiltersPlaceholder: (queryInput: string | null) => boolean+ filtersPlaceholderBindings: (queryInput: string | null) => string[] | nullhasQueryInput: (queryInput: string | null) => booleanisEmbeddedMode: (arg: SQLEditorMode | undefined) => booleandataLogicKey: (tabId: string) => string@@ -3274,6 +3280,11 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([return queryUsesFiltersPlaceholder(queryInput)},],+ filtersPlaceholderBindings: [+ (s) => [s.queryInput],+ (queryInput: string | null): string[] | null => filtersPlaceholderBindings(queryInput),+ { resultEqualityCheck: objectsEqual },+ ],hasQueryInput: [(s) => [s.queryInput], (queryInput: string | null) => !!queryInput],isEmbeddedMode: [() => [(_, p: SqlEditorLogicProps) => p.mode],