Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Add support for running only selected query in QueryEditor (#49651)

Joshen Lim8d59e69da4f7
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
index ccafb2762fd..3e46de3d5c5 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/index.tsx
@@ -2,7 +2,7 @@ import { useMonaco } from '@monaco-editor/react'
import { acceptUntrustedSql, untrustedSql, type UntrustedSqlFragment } from '@supabase/pg-meta'
import { useFlag } from 'common'
import { CodeSquare, Eye, EyeOff, Play } from 'lucide-react'
-import type { editor as monacoEditor } from 'monaco-editor'
+import type { editor as monacoEditor, Selection } from 'monaco-editor'
import {
forwardRef,
useEffect,
@@ -46,6 +46,7 @@ import { useAddDefinitions } from '@/components/interfaces/SQLEditor/useAddDefin
import { ResizableAIWidget } from '@/components/ui/AIEditor/ResizableAIWidget'
import { getEditorSelectionParts, type EditorSelection } from '@/components/ui/AIEditor/utils'
import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'
+import { getEditorValueOrSelection } from '@/components/ui/CodeEditor/CodeEditor.utils'
import { DiffEditor } from '@/components/ui/DiffEditor'
import {
type DatabaseSourceParameters,
@@ -195,6 +196,7 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
const [promptState, setPromptState] = useState<(EditorSelection & { isOpen: boolean }) | null>(
null
)
+ const [hasSelection, setHasSelection] = useState(false)
const dialect = query._tag === 'logs' ? 'clickhouse' : 'postgres'
const { requestCompletion, isCompletionLoading } = useQueryEditorAi({ dialect })
@@ -237,13 +239,6 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
const isExecuting = isExecutingSql || isExecutingLogs
const isBusy = isLoadingProject || isResolvingDatabase || isExecuting
- /**
- * The user's run gesture, and therefore the promotion point for this query's SQL. The
- * raw text comes straight off the editor, so it is (re)branded untrusted here — the
- * editor boundary — and promoted in the same handler. Which pair of helpers applies is
- * decided by `query._tag`, the same discriminant that picks the execution endpoint, so
- * Postgres SQL cannot reach the analytics wire or vice versa.
- */
const handleRunQuery = async ({
rawSql = sql,
shouldForce = false,
@@ -409,13 +404,17 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
<ExplorerToolbarAction
loading={isExecuting}
icon={<Play />}
- tooltip="Run query"
+ tooltip={hasSelection ? 'Run selected query' : 'Run query'}
disabled={
isBusy || pendingProposal !== null || isRunDisabled || sql.trim().length === 0
}
- onClick={() => handleRunQuery()}
+ onClick={() => {
+ const editorInstance = editorInstanceRef.current
+ const rawSql = editorInstance ? getEditorValueOrSelection(editorInstance) : sql
+ handleRunQuery({ rawSql })
+ }}
>
- Run
+ {hasSelection ? 'Run selected' : 'Run'}
</ExplorerToolbarAction>
</ExplorerToolbarActions>
</ExplorerToolbar>
@@ -447,7 +446,10 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
placeholderClassName="top-[13px]"
className={variant === 'embedded' ? 'h-44' : undefined}
actions={{
- runQuery: { enabled: !isRunDisabled, callback: handleRunQuery },
+ runQuery: {
+ enabled: !isRunDisabled,
+ callback: (rawSql: string) => handleRunQuery({ rawSql }),
+ },
}}
options={{
minimap: { enabled: false },
@@ -458,6 +460,23 @@ export const QueryEditor = forwardRef<QueryEditorHandle, QueryEditorProps>(funct
editor.onDidBlurEditorWidget(() => onSqlCommitRef.current?.(sqlRef.current))
editorInstanceRef.current = editor
+ const updateHasSelection = (selection: Selection | null | undefined) => {
+ const noSelection =
+ !selection ||
+ (selection.startLineNumber === selection.endLineNumber &&
+ selection.startColumn === selection.endColumn)
+ setHasSelection(!noSelection)
+ }
+
+ // A remount (e.g. toggling "Show query" off then on) creates a fresh
+ // editor with no listener history, so `hasSelection` must be read from
+ // this instance directly rather than left at whatever the previous
+ // editor instance last reported.
+ updateHasSelection(editor.getSelection())
+ editor.onDidChangeCursorSelection(({ selection }) =>
+ updateHasSelection(selection)
+ )
+
editor.addAction({
id: 'generate-sql',
label: 'Generate SQL',
diff --git a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
index 70224e3f4ff..a7ddb608be2 100644
--- a/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
+++ b/apps/studio/components/interfaces/Explorer/__tests__/QueryTab.test.tsx
@@ -1,6 +1,7 @@
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { HttpResponse } from 'msw'
+import { useEffect, useRef } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ExplorerQueryTab } from '../ExplorerQueryTab'
@@ -14,6 +15,8 @@ import { setupSqlEditorMocks } from '@/tests/lib/sql-editor-test-utils'
const testContext = vi.hoisted(() => ({
flags: { otelLegacyLogs: true } as Record<string, boolean>,
params: { ref: 'default', id: 'query-test' } as { ref?: string; id?: string },
+ /** Simulated editor selection — the mocked CodeEditor's fake editor reads this. */
+ selectedText: undefined as string | undefined,
}))
vi.mock('common', async (importOriginal) => {
@@ -30,16 +33,51 @@ vi.mock('@/components/ui/CodeEditor/CodeEditor', () => ({
CodeEditor: ({
value,
onInputChange,
+ onMount,
}: {
value: string
onInputChange?: (value: string | undefined) => void
- }) => (
- <textarea
- aria-label="SQL editor"
- value={value}
- onChange={(e) => onInputChange?.(e.target.value)}
- />
- ),
+ onMount?: (editor: any, monaco: any) => void
+ }) => {
+ // Kept fresh via a ref (rather than closed over) so the fake editor's
+ // `getValue` reflects edits made after mount, same as the real editor would.
+ const valueRef = useRef(value)
+ valueRef.current = value
+
+ useEffect(() => {
+ const hasSelection = testContext.selectedText !== undefined
+ // Matches this instance's selection at the moment it mounts — a fresh editor
+ // instance (e.g. after "Show query" remounts it) has no memory of a prior
+ // instance's selection, so this must be read fresh rather than carried over.
+ const selection = hasSelection
+ ? { startLineNumber: 1, endLineNumber: 2, startColumn: 1, endColumn: 5 }
+ : null
+
+ onMount?.(
+ {
+ getValue: () => valueRef.current,
+ getSelection: () => selection,
+ getModel: () => ({ getValueInRange: () => testContext.selectedText }),
+ onDidBlurEditorWidget: () => () => {},
+ // Intentionally never invoked here — the real editor only fires this on a
+ // subsequent user-driven selection change, not eagerly on mount. Tests that
+ // need to simulate a live selection change should call this directly.
+ onDidChangeCursorSelection: () => ({ dispose: () => {} }),
+ addAction: () => {},
+ },
+ { KeyMod: { CtrlCmd: 1, Shift: 2 }, KeyCode: { KeyK: 3, Enter: 4 } }
+ )
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
+ return (
+ <textarea
+ aria-label="SQL editor"
+ value={value}
+ onChange={(e) => onInputChange?.(e.target.value)}
+ />
+ )
+ },
}))
vi.mock('../QueryEditor/QuerySourceMenu', () => ({
@@ -132,6 +170,7 @@ beforeEach(() => {
setupSqlEditorMocks()
testContext.flags.otelLegacyLogs = true
testContext.params = { ref: 'default', id: 'query-test' }
+ testContext.selectedText = undefined
explorerQueryState.removeDraft({ id: 'query-test', projectRef: 'default' })
})
@@ -389,4 +428,75 @@ describe('QueryTab execution', () => {
expect(executedQueries[0]).toContain('create table foo (id int)')
expect(executedQueries[0]).toContain('ALTER TABLE foo ENABLE ROW LEVEL SECURITY;')
})
+
+ it('runs only the selected text, not the full editor content, when there is an active selection', async () => {
+ createDraft({ _tag: 'database' }, 'select 1;\nselect 2;')
+ testContext.selectedText = 'select 2;'
+
+ // Background prefetches (intellisense keywords/functions/schemas/table-columns, event
+ // triggers) hit this same generic pg-meta query endpoint, distinguished from an actual
+ // run by their non-empty `key` search param — an executed query's `key` is `''`.
+ const executedQueries: string[] = []
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: async ({ request }) => {
+ const key = new URL(request.url).searchParams.get('key')
+ if (key !== '') return HttpResponse.json([])
+ const { query } = (await request.json()) as { query: string }
+ executedQueries.push(query)
+ return HttpResponse.json([])
+ },
+ })
+
+ renderQueryTab()
+ const runButton = await screen.findByRole('button', { name: 'Run selected' })
+ await waitFor(() => expect(runButton).toBeEnabled())
+ await userEvent.click(runButton)
+
+ await waitFor(() => expect(executedQueries).toHaveLength(1))
+ expect(executedQueries[0]).toContain('select 2')
+ expect(executedQueries[0]).not.toContain('select 1')
+ })
+
+ it('drops the stale "Run selected" state once the query panel is hidden and shown again', async () => {
+ createDraft({ _tag: 'database' }, 'select 1;\nselect 2;')
+ testContext.selectedText = 'select 2;'
+
+ const executedQueries: string[] = []
+ addAPIMock({
+ method: 'post',
+ path: '/platform/pg-meta/:ref/query',
+ response: async ({ request }) => {
+ const key = new URL(request.url).searchParams.get('key')
+ if (key !== '') return HttpResponse.json([])
+ const { query } = (await request.json()) as { query: string }
+ executedQueries.push(query)
+ return HttpResponse.json([])
+ },
+ })
+
+ renderQueryTab()
+ expect(await screen.findByRole('button', { name: 'Run selected' })).toBeInTheDocument()
+
+ // Hiding the query panel unmounts CodeEditor entirely. Simulate the selection being
+ // gone by the time it's shown again (a fresh editor instance has no selection yet).
+ const hideQueryButton = document.querySelector('.lucide-eye-off')?.closest('button')
+ expect(hideQueryButton).toBeInstanceOf(HTMLButtonElement)
+ await userEvent.click(hideQueryButton as HTMLButtonElement)
+ testContext.selectedText = undefined
+
+ const showQueryButton = document.querySelector('.lucide-eye')?.closest('button')
+ expect(showQueryButton).toBeInstanceOf(HTMLButtonElement)
+ await userEvent.click(showQueryButton as HTMLButtonElement)
+
+ const runButton = await screen.findByRole('button', { name: 'Run' })
+ expect(screen.queryByRole('button', { name: 'Run selected' })).not.toBeInTheDocument()
+
+ await userEvent.click(runButton)
+
+ await waitFor(() => expect(executedQueries).toHaveLength(1))
+ expect(executedQueries[0]).toContain('select 1')
+ expect(executedQueries[0]).toContain('select 2')
+ })
})
diff --git a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
index ffd6e738af7..cf36124858a 100644
--- a/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
+++ b/apps/studio/components/ui/CodeEditor/CodeEditor.tsx
@@ -6,7 +6,11 @@ import { RefObject, useEffect, useRef, useState } from 'react'
import { cn } from 'ui'
import { useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
-import { alignEditor, BASE_MONACO_EDITOR_OPTIONS } from './CodeEditor.utils'
+import {
+ alignEditor,
+ BASE_MONACO_EDITOR_OPTIONS,
+ getEditorValueOrSelection,
+} from './CodeEditor.utils'
import { Markdown } from '@/components/interfaces/Markdown'
import { useLatest } from '@/hooks/misc/useLatest'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
@@ -162,13 +166,8 @@ export const CodeEditor = ({
contextMenuGroupId: 'operation',
contextMenuOrder: 0,
run: () => {
- const selection = editorRef?.current?.getSelection()
- if (!selection) return
-
- const selectedValue = editorRef?.current?.getModel()?.getValueInRange(selection)
- const editorValue = editorRef?.current?.getValue()
-
- runQueryCallbackRef.current(selectedValue || editorValue)
+ if (!editorRef.current) return
+ runQueryCallbackRef.current(getEditorValueOrSelection(editorRef.current))
},
})
}
diff --git a/apps/studio/components/ui/CodeEditor/CodeEditor.utils.test.ts b/apps/studio/components/ui/CodeEditor/CodeEditor.utils.test.ts
new file mode 100644
index 00000000000..0a032c5c044
--- /dev/null
+++ b/apps/studio/components/ui/CodeEditor/CodeEditor.utils.test.ts
@@ -0,0 +1,51 @@
+import type { editor } from 'monaco-editor'
+import { describe, expect, it } from 'vitest'
+
+import { getEditorValueOrSelection } from './CodeEditor.utils'
+
+const buildEditor = ({
+ value,
+ selectedValue,
+ hasSelection,
+}: {
+ value: string
+ selectedValue?: string
+ hasSelection: boolean
+}): editor.IStandaloneCodeEditor => {
+ return {
+ getValue: () => value,
+ getSelection: () => (hasSelection ? {} : null),
+ getModel: () => ({ getValueInRange: () => selectedValue }),
+ } as unknown as editor.IStandaloneCodeEditor
+}
+
+describe('getEditorValueOrSelection', () => {
+ it('returns the selected text when there is a non-empty selection', () => {
+ const editorInstance = buildEditor({
+ value: 'select * from a;\nselect * from b;',
+ selectedValue: 'select * from b;',
+ hasSelection: true,
+ })
+
+ expect(getEditorValueOrSelection(editorInstance)).toBe('select * from b;')
+ })
+
+ it('falls back to the full value when there is no selection', () => {
+ const editorInstance = buildEditor({
+ value: 'select * from a;',
+ hasSelection: false,
+ })
+
+ expect(getEditorValueOrSelection(editorInstance)).toBe('select * from a;')
+ })
+
+ it('falls back to the full value when the selection is collapsed (empty range)', () => {
+ const editorInstance = buildEditor({
+ value: 'select * from a;',
+ selectedValue: '',
+ hasSelection: true,
+ })
+
+ expect(getEditorValueOrSelection(editorInstance)).toBe('select * from a;')
+ })
+})
diff --git a/apps/studio/components/ui/CodeEditor/CodeEditor.utils.ts b/apps/studio/components/ui/CodeEditor/CodeEditor.utils.ts
index 8f3b0c5aab6..a64c6c0866b 100644
--- a/apps/studio/components/ui/CodeEditor/CodeEditor.utils.ts
+++ b/apps/studio/components/ui/CodeEditor/CodeEditor.utils.ts
@@ -28,3 +28,16 @@ export const alignEditor = (editor: editor.IStandaloneCodeEditor) => {
})
})
}
+
+/**
+ * The text a "run" gesture should act on: the current selection if there is one
+ * (a collapsed cursor has an empty range, so `getValueInRange` returns `''` and
+ * this falls through), otherwise the full editor value.
+ */
+export const getEditorValueOrSelection = (
+ editor: editor.IStandaloneCodeEditor
+): string | undefined => {
+ const selection = editor.getSelection()
+ const selectedValue = selection ? editor.getModel()?.getValueInRange(selection) : undefined
+ return selectedValue || editor.getValue()
+}