: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(sql-editor): insert column at cursor and fix diff editor disposal (#72709)
posthog[bot]5b1ffebbc047
diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex 390509020d17..f1f7a7e9b100 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -290,6 +290,14 @@ export function CodeEditor({const disposeEditor = (): void => {try {if (diffEditorRef.current) {+ // Detach the models from the DiffEditorWidget before disposing it, so Monaco's+ // internal onWillDispose listeners don't fire against models that are torn down+ // right after ("TextModel got disposed before DiffEditorWidget model got reset").+ try {+ diffEditorRef.current.setModel(null)+ } catch {+ // already detached or disposed+ }diffEditorRef.current.dispose()} else {editorRef.current?.dispose()@@ -312,12 +320,14 @@ export function CodeEditor({disposeMonacoDisposables()disconnectMutationObserver()- // Dispose the editor BEFORE @monaco-editor/react's own cleanup- // runs: Monaco's services (HoverService, ContextView,- // DomListener) keep refs to the editor's container DOM that- // survive the library's dispose. Disposing while we still hold- // a strong reference lets Monaco tear down its services in an- // order that releases those DOM refs.+ // Dispose the editor while we still hold a strong reference: Monaco's+ // services (HoverService, ContextView, DomListener) keep refs to the+ // editor's container DOM that survive the library's dispose, so tearing+ // it down here lets Monaco release those DOM refs in the right order.+ // For the diff editor the library's own child cleanup has usually already+ // disposed the widget by now, so this is mostly a no-op guarded by the+ // try/catch in `disposeEditor`; model disposal is owned by+ // `disposeTrackedModels` below (see the `keepCurrent*` props on the widget).disposeEditor()// Now that our editor is disposed, dispose every model this@@ -612,6 +622,13 @@ export function CodeEditor({}}onMount={diffEditorOnMount}{...editorProps}+ // Own model disposal ourselves via `disposeTrackedModels`. Left to the library,+ // its unmount disposes the models before resetting the widget's own reference to+ // them ("TextModel got disposed before DiffEditorWidget model got reset"), and it+ // fires on teardown paths that don't unmount CodeEditor (diff dismissed, `key`+ // change), where our `disposeEditor` cleanup never runs.+ keepCurrentOriginalModel+ keepCurrentModifiedModel/></div>)diff --git a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsxindex 2811f3bcc47d..d80cb776e3bd 100644--- a/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sidebar/QueryDatabase.tsx@@ -40,13 +40,12 @@ import { cn } from 'lib/utils/css-classes'import { newInternalTab } from 'lib/utils/newInternalTab'import { POSTHOG_WAREHOUSE } from 'scenes/data-warehouse/editor/connectionSelectorLogic'import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'-import { buildQueryForColumnClick } from 'scenes/data-warehouse/editor/sql-utils'import { sqlEditorLogic } from 'scenes/data-warehouse/editor/sqlEditorLogic'import { urls } from 'scenes/urls'import { SearchHighlightMultiple } from '~/layout/navigation-3000/components/SearchHighlight'import { DatabaseSerializedFieldType, externalDataSources } from '~/queries/schema/schema-general'-import { escapePropertyAsHogQLIdentifier } from '~/queries/utils'+import { escapeDottedHogQLIdentifier, escapePropertyAsHogQLIdentifier } from '~/queries/utils'import { AccessControlLevel, AccessControlResourceType } from '~/types'import { sourceManagementLogic } from 'products/data_warehouse/frontend/shared/logics/sourceManagementLogic'@@ -139,10 +138,17 @@ export const QueryDatabase = ({} = useActions(dataWarehouseViewsLogic)const { deleteJoin } = useActions(sourceManagementLogic)const { deleteDraft } = useActions(draftsLogic)- const { openMaterializationModal, openAccessControlModal, runQuery, setActiveTab, setQueryInput, setSourceQuery } =- useActions(sqlEditorLogic)+ const {+ openMaterializationModal,+ openAccessControlModal,+ runQuery,+ setActiveTab,+ setQueryInput,+ setSourceQuery,+ insertTextAtCursor,+ } = useActions(sqlEditorLogic)const { isEmbeddedMode, sourceQuery } = useValues(sqlEditorLogic)- const builtTabLogic = useMountedLogic(sqlEditorLogic)+ useMountedLogic(sqlEditorLogic)// Project-wide warehouse write actions (Add join, Materialization) — gated at the// resource level regardless of per-object creator bypass. Per-object actions like// Edit view use the view's own user_access_level inline below.@@ -392,14 +398,9 @@ export const QueryDatabase = ({router.actions.push(urls.sqlEditor({ draftId: item.record.draft.id }))}- // Copy column name when clicking on a column+ // Insert the column at the cursor, preserving the rest of the query the user has typedif (item && item.record?.type === 'column') {- const currentQueryInput = builtTabLogic.values.queryInput- void buildQueryForColumnClick(currentQueryInput, item.record.table, item.record.columnName)- .then(setQueryInput)- .catch(() => {- // Parsing can fail (e.g. parser init errors) — keep the editor untouched instead of raising.- })+ insertTextAtCursor(escapeDottedHogQLIdentifier(item.record.columnName))}if (item && item.record?.type === 'unsaved-query') {diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.tsindex 34ece5e65cea..f7fdb413137d 100644--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.test.ts@@ -1,9 +1,4 @@-import {- buildQueryForColumnClick,- normalizeIdentifier,- parseQueryTablesAndColumns,- queryUsesFiltersPlaceholder,-} from './sql-utils'+import { normalizeIdentifier, parseQueryTablesAndColumns, queryUsesFiltersPlaceholder } from './sql-utils'describe('sql-utils', () => {describe('normalizeIdentifier', () => {@@ -36,91 +31,6 @@ describe('sql-utils', () => {})})- describe('buildQueryForColumnClick', () => {- it('returns fallback query when currentQuery is null', async () => {- const result = await buildQueryForColumnClick(null, 'events', 'id')- expect(result).toEqual('SELECT id FROM events LIMIT 100')- })-- it('replaces star with clicked column when select is star-only', async () => {- const result = await buildQueryForColumnClick('SELECT * FROM events LIMIT 100', 'events', 'id')- expect(result).toEqual('SELECT id FROM events LIMIT 100')- })-- it('removes column that is already in the select list (toggle off)', async () => {- const result = await buildQueryForColumnClick('SELECT id, name FROM events LIMIT 100', 'events', 'id')- expect(result).toEqual('SELECT name FROM events LIMIT 100')- })-- it('appends new column to existing columns', async () => {- const result = await buildQueryForColumnClick('SELECT id FROM events LIMIT 100', 'events', 'name')- expect(result).toEqual('SELECT id, name FROM events LIMIT 100')- })-- it('falls back to star when removing the only remaining column', async () => {- const result = await buildQueryForColumnClick('SELECT id FROM events LIMIT 100', 'events', 'id')- expect(result).toEqual('SELECT * FROM events LIMIT 100')- })-- it('returns fallback query when table in query differs from clicked table', async () => {- const result = await buildQueryForColumnClick('SELECT * FROM persons LIMIT 100', 'events', 'id')- expect(result).toEqual('SELECT id FROM events LIMIT 100')- })-- it('preserves LIMIT from the existing query', async () => {- const result = await buildQueryForColumnClick('SELECT * FROM events LIMIT 50', 'events', 'id')- expect(result).toEqual('SELECT id FROM events LIMIT 50')- })-- it('preserves LIMIT and OFFSET from the existing query', async () => {- const result = await buildQueryForColumnClick('SELECT * FROM events LIMIT 100 OFFSET 20', 'events', 'id')- expect(result).toEqual('SELECT id FROM events LIMIT 100 OFFSET 20')- })-- it('handles a JOIN query and matches against the first table', async () => {- const result = await buildQueryForColumnClick(- 'SELECT * FROM events JOIN persons ON events.id = persons.id LIMIT 100',- 'events',- 'id'- )- expect(result).toEqual('SELECT id FROM events LIMIT 100')- })-- it('returns fallback query for invalid SQL', async () => {- const result = await buildQueryForColumnClick('NOT VALID SQL', 'events', 'id')- expect(result).toEqual('SELECT id FROM events LIMIT 100')- })-- it('uses default LIMIT 100 when query has no LIMIT', async () => {- const result = await buildQueryForColumnClick('SELECT * FROM events', 'events', 'id')- expect(result).toEqual('SELECT id FROM events LIMIT 100')- })-- it('keeps dotted table names unquoted when building a new column query', async () => {- const result = await buildQueryForColumnClick(null, 'demo.orders', 'id')- expect(result).toEqual('SELECT id FROM demo.orders LIMIT 100')- })-- it('keeps dotted table names unquoted when toggling columns in an existing query', async () => {- const result = await buildQueryForColumnClick('SELECT * FROM demo.orders LIMIT 100', 'demo.orders', 'id')- expect(result).toEqual('SELECT id FROM demo.orders LIMIT 100')- })-- it('quotes dotted field paths by segment instead of as a single identifier', async () => {- const result = await buildQueryForColumnClick(null, 'demo.orders', 'orders.item count')- expect(result).toEqual('SELECT orders."item count" FROM demo.orders LIMIT 100')- })-- it('matches dotted field paths even when an existing query already quotes a segment', async () => {- const result = await buildQueryForColumnClick(- 'SELECT orders."item count" FROM demo.orders LIMIT 100',- 'demo.orders',- 'orders.item count'- )- expect(result).toEqual('SELECT * FROM demo.orders LIMIT 100')- })- })-describe('parseQueryTablesAndColumns', () => {it('returns empty object for null queryInput', async () => {expect(await parseQueryTablesAndColumns(null)).toEqual({})diff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.tsindex 7fc6cf9193e9..a6f426d1bf5e 100644--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts@@ -1,14 +1,7 @@import type { ASTNode } from '@posthog/hogql-parser'-import { escapePropertyAsHogQLIdentifier } from '~/queries/utils'-import { parseSelect } from './hogqlParserSingleton'-/** Escape a possibly qualified (dot-separated) name, escaping each segment individually. */-const escapeQualifiedIdentifier = (name: string): string => {- return name.split('.').map(escapePropertyAsHogQLIdentifier).join('.')-}-export const normalizeIdentifier = (identifier: string): string => {return identifier.replace(/[`"']/g, '').toLowerCase()}@@ -86,14 +79,6 @@ const tryParseSelect = async (query: string): Promise<ASTNode | null> => {}}-/** Extract the field name string from a select column AST node, or null for non-Field expressions. */-const fieldChainToString = (node: ASTNode): string | null => {- if (node.node === 'Field') {- return (node.chain as string[]).join('.')- }- return null-}-/** Collect all table names from a JoinExpr chain. */const collectTablesFromJoinExpr = (joinExpr: ASTNode | null): string[] => {const tables: string[] = []@@ -107,76 +92,6 @@ const collectTablesFromJoinExpr = (joinExpr: ASTNode | null): string[] => {return tables}-/** Extract the LIMIT/OFFSET clause string from an AST, or null if absent. */-const extractLimitOffsetFromAST = (ast: ASTNode): string | null => {- const parts: string[] = []- if (ast.limit != null && ast.limit.node === 'Constant' && ast.limit.value != null) {- parts.push(`LIMIT ${ast.limit.value}`)- }- if (ast.offset != null && ast.offset.node === 'Constant' && ast.offset.value != null) {- parts.push(`OFFSET ${ast.offset.value}`)- }- return parts.length > 0 ? parts.join(' ') : null-}--export const buildQueryForColumnClick = async (- currentQuery: string | null,- tableName: string,- columnName: string-): Promise<string> => {- const ast = currentQuery ? await tryParseSelect(currentQuery) : null- const limitOffsetClause = ast ? extractLimitOffsetFromAST(ast) : null- const baseQuery = `SELECT ${escapeQualifiedIdentifier(columnName)} FROM ${escapeQualifiedIdentifier(tableName)} ${limitOffsetClause ?? 'LIMIT 100'}`-- if (!ast || !currentQuery) {- return baseQuery- }-- const tables = collectTablesFromJoinExpr(ast.select_from)- if (tables.length === 0) {- return baseQuery- }-- const selectedTable = tables[0]- if (normalizeIdentifier(selectedTable) !== normalizeIdentifier(tableName)) {- return baseQuery- }-- const selectNodes: ASTNode[] = ast.select ?? []- const fieldNames = selectNodes.map(fieldChainToString)- const hasNonFieldExpressions = fieldNames.some((name) => name === null)-- // If the query contains non-Field expressions (e.g. COUNT(*), SUM(x)),- // we can't safely rewrite the SELECT list — fall back to a simple query.- if (hasNonFieldExpressions) {- return baseQuery- }-- let columns = fieldNames as string[]- const normalizedColumnName = normalizeIdentifier(columnName)- const isStarOnly = columns.length === 1 && columns[0] === '*'-- if (isStarOnly) {- columns = []- } else {- columns = columns.filter((column) => column !== '*')- }-- const existingIndex = columns.findIndex((column) => normalizeIdentifier(column) === normalizedColumnName)-- if (existingIndex >= 0) {- columns.splice(existingIndex, 1)- } else {- columns.push(columnName)- }-- if (columns.length === 0) {- columns = ['*']- }-- return `SELECT ${columns.map((column) => (column === '*' ? column : escapeQualifiedIdentifier(column))).join(', ')} FROM ${escapeQualifiedIdentifier(tableName)} ${limitOffsetClause ?? 'LIMIT 100'}`-}-export const parseQueryTablesAndColumns = async (queryInput: string | null): Promise<Record<string, Record<string, boolean>>> => {