Skip to content

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

refactor(studio): extract SQL editor session store from god store (#47349)

Charisd153bab8498b
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index c3f736f8caf..6d1f261f253 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -12,7 +12,7 @@ import { IS_PLATFORM, LOCAL_STORAGE_KEYS, useFlag, useParams } from 'common'
import { ChevronUp, Loader2 } from 'lucide-react'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/router'
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react'
import { toast } from 'sonner'
import {
Button,
@@ -93,6 +93,8 @@ import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
import { getSqlEditorV2StateSnapshot, useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { useSqlEditorDiffRequestSnapshot } from '@/state/sql-editor/sql-editor-diff-request'
+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
// Load the monaco editor client-side only (does not behave well server-side)
@@ -119,6 +121,8 @@ export const SQLEditor = () => {
const aiSnap = useAiAssistantStateSnapshot()
const { openSidebar } = useSidebarManagerSnapshot()
const snapV2 = useSqlEditorV2StateSnapshot()
+ const sessionSnap = useSqlEditorSessionSnapshot()
+ const diffRequest = useSqlEditorDiffRequestSnapshot()
const getImpersonatedRoleState = useGetImpersonatedRoleState()
const databaseSelectorState = useDatabaseSelectorStateSnapshot()
const { aiOptInLevel } = useOrgAiOptInLevel()
@@ -152,6 +156,9 @@ export const SQLEditor = () => {
const [potentialIssues, setPotentialIssues] = useState<PotentialIssues>()
const [showWidget, setShowWidget] = useState(false)
+ // Bumped on every editor mount (including the keyed remount on snippet switch)
+ // so a diff request that arrived before the editor was ready gets re-processed.
+ const [editorMountCount, setEditorMountCount] = useState(0)
const [activeUtilityTab, setActiveUtilityTab] = useState<string>('results')
const refocusEditor = useCallback(() => {
@@ -197,8 +204,8 @@ export const SQLEditor = () => {
// the id is stable across renders - it depends either on the url or on the memoized generated id
const id = !urlId || urlId === 'new' ? generatedId : urlId
- const limit = snapV2.limit
- const results = snapV2.results[id]?.[0]
+ const limit = sessionSnap.limit
+ const results = sessionSnap.results[id]?.[0]
const snippetIsLoading = !(
id in snapV2.snippets && snapV2.snippets[id].snippet.content !== undefined
)
@@ -227,10 +234,10 @@ export const SQLEditor = () => {
const { mutate: execute, isPending: isExecuting } = useExecuteSqlMutation({
onSuccess(data, vars) {
if (id) {
- snapV2.addResult(id, data.result, vars.autoLimit)
+ sessionSnap.addResult(id, data.result, vars.autoLimit)
if (!disablePrettyExplain && showPrettyExplain && isExplainQuery(data.result)) {
- snapV2.addExplainResult(id, data.result)
+ sessionSnap.addExplainResult(id, data.result)
setActiveUtilityTab('explain')
} else if (activeUtilityTab === 'explain') {
// If on Explain tab but ran a non-EXPLAIN query, switch to Results tab
@@ -275,7 +282,7 @@ export const SQLEditor = () => {
}
}
- snapV2.addResultError(id, error, vars.autoLimit)
+ sessionSnap.addResultError(id, error, vars.autoLimit)
}
refocusEditorAfterRunIfNeeded()
@@ -285,13 +292,13 @@ export const SQLEditor = () => {
const { mutate: executeExplain, isPending: isExplainExecuting } = useExecuteSqlMutation({
onSuccess(data) {
if (id) {
- snapV2.addExplainResult(id, data.result)
+ sessionSnap.addExplainResult(id, data.result)
setActiveUtilityTab('explain')
}
},
onError(error) {
if (id) {
- snapV2.addExplainResultError(id, error)
+ sessionSnap.addExplainResultError(id, error)
setActiveUtilityTab('explain')
}
},
@@ -486,7 +493,7 @@ export const SQLEditor = () => {
// Check for multiple statements - EXPLAIN only works on a single statement
const statements = splitSqlStatements(sql)
if (statements.length > 1) {
- snapV2.addExplainResultError(id, {
+ sessionSnap.addExplainResultError(id, {
message:
'EXPLAIN only works on a single SQL statement. Please select just one query to analyze.',
})
@@ -537,7 +544,7 @@ export const SQLEditor = () => {
databaseSelectorState.selectedDatabaseId,
databases,
lineHighlights,
- snapV2,
+ sessionSnap,
])
useShortcut(SHORTCUT_IDS.SQL_EDITOR_EXPLAIN, executeExplainQuery, {
@@ -570,6 +577,8 @@ export const SQLEditor = () => {
)
const onMount = (editor: IStandaloneCodeEditor) => {
+ setEditorMountCount((count) => count + 1)
+
const tabId = createTabId('sql', { id })
const tabData = tabs.tabsMap[tabId]
@@ -584,7 +593,7 @@ export const SQLEditor = () => {
const buildDebugPrompt = useCallback(() => {
const snippet = snapV2.snippets[id]
- const result = snapV2.results[id]?.[0]
+ const result = sessionSnap.results[id]?.[0]
const sql = (snippet?.snippet.content?.unchecked_sql ?? '')
.replace(sqlAiDisclaimerComment, '')
.trim()
@@ -592,12 +601,12 @@ export const SQLEditor = () => {
const prompt = `Help me to debug the attached sql snippet which gives the following error: \n\n${errorMessage}`
return `${prompt}\n\nSQL Query:\n\`\`\`sql\n${sql}\n\`\`\``
- }, [id, snapV2.results, snapV2.snippets])
+ }, [id, sessionSnap.results, snapV2.snippets])
const onDebug = useCallback(async () => {
try {
const snippet = snapV2.snippets[id]
- const result = snapV2.results[id]?.[0]
+ const result = sessionSnap.results[id]?.[0]
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
aiSnap.newChat({
name: 'Debug SQL snippet',
@@ -617,7 +626,7 @@ export const SQLEditor = () => {
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [id, snapV2.results, snapV2.snippets])
+ }, [id, sessionSnap.results, snapV2.snippets])
const acceptAiHandler = useCallback(async () => {
try {
@@ -825,30 +834,40 @@ export const SQLEditor = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isSuccessReadReplicas, databases, ref])
- useEffect(() => {
- if (snapV2.diffContent !== undefined) {
- const { diffType, sql }: { diffType: DiffType; sql: string } = snapV2.diffContent
- const editorModel = editorRef.current?.getModel()
- if (!editorModel) return
-
- const existingValue = editorRef.current?.getValue() ?? ''
- if (existingValue.length === 0) {
- // if the editor is empty, just copy over the code
- editorRef.current?.executeEdits('apply-ai-message', [
- {
- text: `${sql}`,
- range: editorModel.getFullModelRange(),
- },
- ])
- } else {
- const currentSql = editorRef.current?.getValue()
- const diff = { original: currentSql || '', modified: sql }
- setSourceSqlDiff(diff)
- setSelectedDiffType(diffType)
- }
+ const drainDiffRequest = useEffectEvent(() => {
+ const request = diffRequest.pending
+ if (request === undefined) return
+
+ const editorModel = editorRef.current?.getModel()
+ // Editor isn't ready yet; leave the request pending. editorMountCount bumps
+ // on mount and re-runs this effect, so the request applies once mounted.
+ if (!editorModel) return
+
+ const { diffType, sql } = request
+ const existingValue = editorRef.current?.getValue() ?? ''
+ if (existingValue.length === 0) {
+ // if the editor is empty, just copy over the code
+ editorRef.current?.executeEdits('apply-ai-message', [
+ {
+ text: `${sql}`,
+ range: editorModel.getFullModelRange(),
+ },
+ ])
+ } else {
+ const currentSql = editorRef.current?.getValue()
+ const diff = { original: currentSql || '', modified: sql }
+ setSourceSqlDiff(diff)
+ setSelectedDiffType(diffType)
}
+
+ // One-shot: drain the request so it can't re-apply to a later editor or session.
+ diffRequest.consumeDiffRequest()
+ })
+ useEffect(() => {
+ drainDiffRequest()
+ // until we can upgrade eslint to ignore useEffectEvent
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [snapV2.diffContent])
+ }, [diffRequest.pending, editorMountCount])
// We want to check if the diff editor is mounted and if it is, we want to show the widget
// We also want to cleanup the widget when the diff editor is closed
@@ -1072,13 +1091,16 @@ export const SQLEditor = () => {
<DropdownMenuTrigger asChild>
<Button variant="default" iconRight={<ChevronUp size={14} />}>
Limit results to:{' '}
- {ROWS_PER_PAGE_OPTIONS.find((opt) => opt.value === snapV2.limit)?.label}
+ {
+ ROWS_PER_PAGE_OPTIONS.find((opt) => opt.value === sessionSnap.limit)
+ ?.label
+ }
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-40" align="end">
<DropdownMenuRadioGroup
- value={snapV2.limit.toString()}
- onValueChange={(val) => snapV2.setLimit(Number(val))}
+ value={sessionSnap.limit.toString()}
+ onValueChange={(val) => sessionSnap.setLimit(Number(val))}
>
{ROWS_PER_PAGE_OPTIONS.map((option) => (
<DropdownMenuRadioItem key={option.label} value={option.value.toString()}>
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
index 65a95230725..58b7f93131f 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -25,6 +25,7 @@ import { IS_PLATFORM } from '@/lib/constants'
import { hotkeyToKeys } from '@/state/shortcuts/formatShortcut'
import { SHORTCUT_DEFINITIONS, SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
export type UtilityActionsProps = {
id: string
@@ -45,6 +46,7 @@ export const UtilityActions = ({
}: UtilityActionsProps) => {
const { ref } = useParams()
const snapV2 = useSqlEditorV2StateSnapshot()
+ const sessionSnap = useSqlEditorSessionSnapshot()
const [isAiOpen] = useLocalStorageQuery(LOCAL_STORAGE_KEYS.SQL_EDITOR_AI_OPEN, true)
const [intellisenseEnabled, setIntellisenseEnabled] = useLocalStorageQuery(
@@ -75,7 +77,7 @@ export const UtilityActions = ({
const removeFavorite = () => snapV2.removeFavorite(id)
const onSelectDatabase = (databaseId: string) => {
- snapV2.resetResults(id)
+ sessionSnap.resetResults(id)
setLastSelectedDb(databaseId)
}
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
index d8ab07d67c4..98af2875443 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
@@ -11,6 +11,7 @@ import { useContentUpsertMutation } from '@/data/content/content-upsert-mutation
import { Snippet } from '@/data/content/sql-folders-query'
import { useTrack } from '@/lib/telemetry/track'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
export type UtilityPanelProps = {
id: string
@@ -57,9 +58,10 @@ export const UtilityPanel = ({
const { ref } = useParams()
const track = useTrack()
const snapV2 = useSqlEditorV2StateSnapshot()
+ const sessionSnap = useSqlEditorSessionSnapshot()
const snippet = snapV2.snippets[id]?.snippet
- const result = snapV2.results[id]?.[0]
+ const result = sessionSnap.results[id]?.[0]
const handleTabChange = (tab: string) => {
// When switching to the explain tab, trigger the explain query
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabExplain.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabExplain.tsx
index 6417e9ba734..f7d2e1c2267 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabExplain.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabExplain.tsx
@@ -10,7 +10,7 @@ import {
isTextFormatExplain,
} from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.utils'
import CopyButton from '@/components/ui/CopyButton'
-import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
export type UtilityTabExplainProps = {
id: string
@@ -18,8 +18,8 @@ export type UtilityTabExplainProps = {
}
export function UtilityTabExplain({ id, isExecuting }: UtilityTabExplainProps) {
- const snapV2 = useSqlEditorV2StateSnapshot()
- const explainResult = snapV2.explainResults[id]
+ const sessionSnap = useSqlEditorSessionSnapshot()
+ const explainResult = sessionSnap.explainResults[id]
const [mode, setMode] = useState<'visual' | 'raw'>('visual')
if (isExecuting) {
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
index 7a8b79dbcae..37ac910923d 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
@@ -15,7 +15,7 @@ import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-q
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { DOCS_URL } from '@/lib/constants'
import { useDatabaseSelectorStateSnapshot } from '@/state/database-selector'
-import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { useSqlEditorSessionSnapshot } from '@/state/sql-editor/sql-editor-session-state'
export type UtilityTabResultsProps = {
id: string
@@ -31,10 +31,10 @@ export const UtilityTabResults = forwardRef<HTMLDivElement, UtilityTabResultsPro
const { ref } = useParams()
const state = useDatabaseSelectorStateSnapshot()
const { data: organization } = useSelectedOrganizationQuery()
- const snapV2 = useSqlEditorV2StateSnapshot()
+ const sessionSnap = useSqlEditorSessionSnapshot()
const [, setShowConnect] = useQueryState('showConnect', parseAsBoolean.withDefault(false))
- const result = snapV2.results[id]?.[0]
+ const result = sessionSnap.results[id]?.[0]
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
// Customers on HIPAA plans should not have access to Supabase AI
@@ -139,7 +139,7 @@ export const UtilityTabResults = forwardRef<HTMLDivElement, UtilityTabResultsPro
variant="default"
onClick={() => {
state.setSelectedDatabaseId(ref)
- snapV2.resetResults(id)
+ sessionSnap.resetResults(id)
}}
>
Switch to primary database
diff --git a/apps/studio/components/ui/DiffEditor.tsx b/apps/studio/components/ui/DiffEditor.tsx
index d348ae2d0f8..a8777fd034d 100644
--- a/apps/studio/components/ui/DiffEditor.tsx
+++ b/apps/studio/components/ui/DiffEditor.tsx
@@ -25,6 +25,7 @@ const DEFAULT_OPTIONS: monacoEditor.IStandaloneDiffEditorConstructionOptions = {
lineNumbersMinChars: 3,
scrollBeyondLastLine: false,
renderSideBySide: false,
+ renderGutterMenu: false,
padding: { top: 4 },
}
diff --git a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
index 6b80fd72779..2f620af18ec 100644
--- a/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
+++ b/apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
@@ -18,7 +18,7 @@ import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/L
import { useTrack } from '@/lib/telemetry/track'
import { editorPanelState } from '@/state/editor-panel-state'
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
-import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor-v2'
+import { useSqlEditorDiffRequestSnapshot } from '@/state/sql-editor/sql-editor-diff-request'
interface EditQueryButtonProps {
id?: string
@@ -38,7 +38,7 @@ export const EditQueryButton = ({
const router = useRouter()
const { newQuery } = useNewQuery()
- const sqlEditorSnap = useSqlEditorV2StateSnapshot()
+ const diffRequest = useSqlEditorDiffRequestSnapshot()
const { closeSidebar, openSidebar } = useSidebarManagerSnapshot()
const isInSQLEditor = router.pathname.includes('/sql')
@@ -102,12 +102,10 @@ export const EditQueryButton = ({
</DropdownMenuTrigger>
{!!sql && (
<DropdownMenuContent className="w-36">
- <DropdownMenuItem onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.Addition)}>
+ <DropdownMenuItem onClick={() => diffRequest.requestDiff(sql, DiffType.Addition)}>
Insert code
</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() => sqlEditorSnap.setDiffContent(sql, DiffType.Modification)}
- >
+ <DropdownMenuItem onClick={() => diffRequest.requestDiff(sql, DiffType.Modification)}>
Replace code
</DropdownMenuItem>
<DropdownMenuItem onClick={() => newQuery(sql, title)}>
diff --git a/apps/studio/state/sql-editor/sql-editor-diff-request.test.ts b/apps/studio/state/sql-editor/sql-editor-diff-request.test.ts
new file mode 100644
index 00000000000..eef93ebc072
--- /dev/null
+++ b/apps/studio/state/sql-editor/sql-editor-diff-request.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { sqlEditorDiffRequestState } from './sql-editor-diff-request'
+import { DiffType } from '@/components/interfaces/SQLEditor/SQLEditor.types'
+
+// Module singleton — clear any pending request before each test.
+beforeEach(() => {
+ sqlEditorDiffRequestState.pending = undefined
+})
+
+describe('sqlEditorDiffRequestState', () => {
+ it('is empty by default', () => {
+ expect(sqlEditorDiffRequestState.pending).toBeUndefined()
+ })
+
+ it('requestDiff queues a pending request', () => {
+ sqlEditorDiffRequestState.requestDiff('select 1', DiffType.Addition)
+
+ expect(sqlEditorDiffRequestState.pending).toEqual({
+ sql: 'select 1',
+ diffType: DiffType.Addition,
+ })
+ })
+
+ it('consumeDiffRequest returns the pending request and clears it', () => {
+ sqlEditorDiffRequestState.requestDiff('select 1', DiffType.Modification)
+
+ const consumed = sqlEditorDiffRequestState.consumeDiffRequest()
+
+ expect(consumed).toEqual({ sql: 'select 1', diffType: DiffType.Modification })
+ expect(sqlEditorDiffRequestState.pending).toBeUndefined()
+ })
+
+ it('consumeDiffRequest returns undefined when nothing is pending', () => {
+ expect(sqlEditorDiffRequestState.consumeDiffRequest()).toBeUndefined()
+ })
+
+ it('a later request replaces an unconsumed one (queue of one)', () => {
+ sqlEditorDiffRequestState.requestDiff('select 1', DiffType.Addition)
+ sqlEditorDiffRequestState.requestDiff('select 2', DiffType.Modification)
+
+ expect(sqlEditorDiffRequestState.consumeDiffRequest()).toEqual({
+ sql: 'select 2',
+ diffType: DiffType.Modification,
+ })
+ })
+})
diff --git a/apps/studio/state/sql-editor/sql-editor-diff-request.ts b/apps/studio/state/sql-editor/sql-editor-diff-request.ts
new file mode 100644
index 00000000000..ee4f47f6084
--- /dev/null
+++ b/apps/studio/state/sql-editor/sql-editor-diff-request.ts
@@ -0,0 +1,32 @@
+import { proxy, useSnapshot } from 'valtio'
+
+import { DiffType } from '@/components/interfaces/SQLEditor/SQLEditor.types'
+
+/**
+ * A one-shot request to render a SQL diff in the active SQL editor.
+ *
+ * Unlike the session store (per-snippet results that many components read
+ * repeatedly), this is a transient command: it is produced outside the editor
+ * — e.g. the Assistant's "Insert code" / "Replace code" actions — and consumed
+ * exactly once by the editor. It targets whichever editor is active, not a
+ * particular snippet. It is drained on consumption rather than stored, so a
+ * stale request can never leak into a later editor or editing session.
+ */
+export const sqlEditorDiffRequestState = proxy({
+ pending: undefined as undefined | { sql: string; diffType: DiffType },
+
+ /** Queue a diff to be applied to the active editor. */
+ requestDiff: (sql: string, diffType: DiffType) => {
+ sqlEditorDiffRequestState.pending = { sql, diffType }
+ },
+
+ /** Read and clear the pending request, returning it (or undefined if none). */
+ consumeDiffRequest: () => {
+ const request = sqlEditorDiffRequestState.pending
+ sqlEditorDiffRequestState.pending = undefined
+ return request
+ },
+})
+
+export const useSqlEditorDiffRequestSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
+ useSnapshot(sqlEditorDiffRequestState, options)
diff --git a/apps/studio/state/sql-editor/sql-editor-session-state.test.ts b/apps/studio/state/sql-editor/sql-editor-session-state.test.ts
new file mode 100644
index 00000000000..46768b2a979
--- /dev/null
+++ b/apps/studio/state/sql-editor/sql-editor-session-state.test.ts
@@ -0,0 +1,94 @@
+import { snapshot } from 'valtio'
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { sqlEditorSessionState } from './sql-editor-session-state'
+
+// The session store is a module singleton, so reset its mutable fields before
+// each test to keep cases independent.
+beforeEach(() => {
+ sqlEditorSessionState.results = {}
+ sqlEditorSessionState.explainResults = {}
+ sqlEditorSessionState.limit = 100
+})
+
+describe('sqlEditorSessionState', () => {
+ describe('results', () => {
+ it('addResult stores rows (and optional autoLimit) keyed by snippet id', () => {
+ sqlEditorSessionState.addResult('a', [{ x: 1 }], 50)
+
+ const result = sqlEditorSessionState.results['a']?.[0]
+ expect(result?.rows).toEqual([{ x: 1 }])
+ expect(result?.autoLimit).toBe(50)
+ expect(result?.error).toBeUndefined()
+ })
+
+ it('addResultError stores the error with empty rows', () => {
+ sqlEditorSessionState.addResultError('a', { message: 'boom' }, 25)
+
+ const result = sqlEditorSessionState.results['a']?.[0]
+ expect(result?.rows).toEqual([])
+ expect(result?.error).toEqual({ message: 'boom' })
+ expect(result?.autoLimit).toBe(25)
+ })
+
+ it('resetResult clears the rows for a snippet', () => {
+ sqlEditorSessionState.addResult('a', [{ x: 1 }])
+ sqlEditorSessionState.resetResult('a')
+
+ expect(sqlEditorSessionState.results['a']).toEqual([])
+ })
+ })
+
+ describe('explain results', () => {
+ it('addExplainResult stores rows keyed by snippet id', () => {
+ const rows = [{ 'QUERY PLAN': 'Seq Scan' }]
+ sqlEditorSessionState.addExplainResult('a', rows)
+
+ expect(sqlEditorSessionState.explainResults['a']?.rows).toEqual(rows)
+ expect(sqlEditorSessionState.explainResults['a']?.error).toBeUndefined()
+ })
+
+ it('addExplainResultError stores the error with empty rows', () => {
+ sqlEditorSessionState.addExplainResultError('a', { message: 'bad plan' })
+
+ expect(sqlEditorSessionState.explainResults['a']?.rows).toEqual([])
+ expect(sqlEditorSessionState.explainResults['a']?.error).toEqual({ message: 'bad plan' })
+ })
+ })
+
+ describe('resetResults', () => {
+ it('clears both the query result and the explain result for a snippet', () => {
+ sqlEditorSessionState.addResult('a', [{ x: 1 }])
+ sqlEditorSessionState.addExplainResult('a', [{ 'QUERY PLAN': 'Seq Scan' }])
+
+ sqlEditorSessionState.resetResults('a')
+
+ expect(sqlEditorSessionState.results['a']).toEqual([])
+ expect(sqlEditorSessionState.explainResults['a']).toEqual({ rows: [] })
+ })
+ })
+
+ describe('clearForSnippet', () => {
+ it('deletes both results and explain results for a snippet, leaving others intact', () => {
+ sqlEditorSessionState.addResult('a', [{ x: 1 }])
+ sqlEditorSessionState.addExplainResult('a', [{ 'QUERY PLAN': 'Seq Scan' }])
+ sqlEditorSessionState.addResult('b', [{ y: 2 }])
+
+ sqlEditorSessionState.clearForSnippet('a')
+
+ expect(sqlEditorSessionState.results['a']).toBeUndefined()
+ expect(sqlEditorSessionState.explainResults['a']).toBeUndefined()
+ expect(sqlEditorSessionState.results['b']?.[0]?.rows).toEqual([{ y: 2 }])
+ })
+ })
+
+ describe('limit', () => {
+ it('defaults to 100 and is updated by setLimit', () => {
+ expect(snapshot(sqlEditorSessionState).limit).toBe(100)
+
+ sqlEditorSessionState.setLimit(500)
+
+ expect(snapshot(sqlEditorSessionState).limit).toBe(500)
+ })
+ })
+})
diff --git a/apps/studio/state/sql-editor/sql-editor-session-state.ts b/apps/studio/state/sql-editor/sql-editor-session-state.ts
new file mode 100644
index 00000000000..8cb9618c4fa
--- /dev/null
+++ b/apps/studio/state/sql-editor/sql-editor-session-state.ts
@@ -0,0 +1,87 @@
+import { proxy, ref, snapshot, useSnapshot } from 'valtio'
+
+import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'
+
+/**
+ * Ephemeral, per-session SQL editor state that is NOT persisted: query results,
+ * EXPLAIN results, and the row limit. Kept separate from the snippet/folder
+ * store (which deals with persistence) because none of this is saved — it lives
+ * only for the current editing session.
+ */
+export const sqlEditorSessionState = proxy({
+ /**
+ * Query results, if any, keyed by snippet id. An array per id as we once
+ * experimented with a notebook-style multi-result UI; the shape is kept since
+ * a single query with multiple statements can return multiple results.
+ */
+ results: {} as {
+ [snippetId: string]: {
+ rows: any[]
+ error?: any
+ autoLimit?: number
+ }[]
+ },
+
+ /** EXPLAIN results, if any, keyed by snippet id. */
+ explainResults: {} as {
+ [snippetId: string]: {
+ rows: QueryPlanRow[]
+ error?: { message: string; formattedError?: string }
+ }
+ },
+
+ /**
+ * UI-imposed limit for the number of rows a query can return (a safeguard
+ * against accidentally taking down the database with a huge SELECT). Related
+ * to `autoLimit` in `results`; see `checkIfAppendLimitRequired`/`suffixWithLimit`.
+ */
+ limit: 100,
+
+ setLimit: (value: number) => (sqlEditorSessionState.limit = value),
+
+ addResult: (id: string, results: any[], autoLimit?: number) => {
+ // Use ref() to prevent Valtio from creating proxies for each row object.
+ // This is critical for large result sets - without ref(), Valtio wraps every
+ // row and nested property in a Proxy, causing massive memory overhead.
+ // Alright to use ref() in this case as the data is meant to be read-only and we
+ // don't need to track changes to the underlying data
+ sqlEditorSessionState.results[id] = [{ rows: ref(results), autoLimit }]
+ },
+
+ addResultError: (id: string, error: any, autoLimit?: number) => {
+ sqlEditorSessionState.results[id] = [{ rows: ref([]), error, autoLimit }]
+ },
+
+ resetResult: (id: string) => {
+ sqlEditorSessionState.results[id] = []
+ },
+
+ addExplainResult: (id: string, results: QueryPlanRow[]) => {
+ // Use ref() to prevent Valtio from creating proxies for each row object
+ sqlEditorSessionState.explainResults[id] = { rows: ref(results) }
+ },
+
+ addExplainResultError: (id: string, error: { message: string; formattedError?: string }) => {
+ sqlEditorSessionState.explainResults[id] = { rows: ref([]), error }
+ },
+
+ resetExplainResult: (id: string) => {
+ sqlEditorSessionState.explainResults[id] = { rows: [] }
+ },
+
+ resetResults: (id: string) => {
+ sqlEditorSessionState.resetResult(id)
+ sqlEditorSessionState.resetExplainResult(id)
+ },
+
+ /** Drop all session state for a snippet (called when the snippet is removed). */
+ clearForSnippet: (id: string) => {
+ delete sqlEditorSessionState.results[id]
+ delete sqlEditorSessionState.explainResults[id]
+ },
+})
+
+export const getSqlEditorSessionSnapshot = () => snapshot(sqlEditorSessionState)
+
+export const useSqlEditorSessionSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
+ useSnapshot(sqlEditorSessionState, options)
diff --git a/apps/studio/state/sql-editor/sql-editor-state.ts b/apps/studio/state/sql-editor/sql-editor-state.ts
index 93c785d2e16..56c527876a0 100644
--- a/apps/studio/state/sql-editor/sql-editor-state.ts
+++ b/apps/studio/state/sql-editor/sql-editor-state.ts
@@ -1,13 +1,12 @@
import { untrustedSql } from '@supabase/pg-meta'
import { useMemo } from 'react'
import { toast } from 'sonner'
-import { proxy, ref, snapshot, useSnapshot } from 'valtio'
+import { proxy, snapshot, useSnapshot } from 'valtio'
import { devtools, proxyMap } from 'valtio/utils'
import { folderStatusOnSaveStart, isNewFolder } from './sql-editor-lifecycle'
+import { sqlEditorSessionState } from './sql-editor-session-state'
import type { StateSnippet, StateSnippetFolder } from './types'
-import type { QueryPlanRow } from '@/components/interfaces/ExplainVisualizer/ExplainVisualizer.types'
-import { DiffType } from '@/components/interfaces/SQLEditor/SQLEditor.types'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
import { Snippet, SnippetFolder } from '@/data/content/sql-folders-query'
@@ -30,29 +29,6 @@ export const sqlEditorState = proxy({
[snippetId: string]: StateSnippet
},
- /**
- * Query results, if any, for a snippet. Set as an array per snippetId as we were previously experimenting
- * with having a Jupyter notebook like UI but it never took off. Nonetheless kept this data structure as
- * we'd also want to support returning multiple results from a single query (e.g From a query that contains
- * multiple select statements), and this will allow us to do quite easily.
- */
- results: {} as {
- [snippetId: string]: {
- rows: any[]
- error?: any
- autoLimit?: number
- }[]
- },
-
- /**
- * Explain results, if any, for a snippet
- */
- explainResults: {} as {
- [snippetId: string]: {
- rows: QueryPlanRow[]
- error?: { message: string; formattedError?: string }
- }
- },
/**
* Snippets queued for saving. Key is the snippet id, value is whether saving
* it should also invalidate the snippet/folder lists.
@@ -63,17 +39,6 @@ export const sqlEditorState = proxy({
* `needsSaving` so snippet and folder saves are scheduled independently.
*/
pendingFolderSaves: proxyMap<string, boolean>([]),
- /**
- * UI-imposed limit for the number of results a query can return (applied to the SQL query being run if applicable).
- * Acts as a safeguard to prevent accidentally taking down the database from a really large SELECT query.
- * Related to `autoLimit` in `results`. Refer to `checkIfAppendLimitRequired` and `suffixWithLimit` for usage.
- */
- limit: 100,
-
- /**
- * For Assistant to render diffing into the editor
- */
- diffContent: undefined as undefined | { sql: string; diffType: DiffType },
get allFolderNames() {
return Object.values(sqlEditorState.folders).map((x) => x.folder.name)
@@ -83,9 +48,6 @@ export const sqlEditorState = proxy({
// ## Methods to interact the store with
// ========================================================================
- setDiffContent: (sql: string, diffType: DiffType) =>
- (sqlEditorState.diffContent = { sql, diffType }),
-
/**
* Load snippet into SQL Editor Valtio store
*/
@@ -93,8 +55,6 @@ export const sqlEditorState = proxy({
if (sqlEditorState.snippets[snippet.id]) return
sqlEditorState.snippets[snippet.id] = { projectRef, splitSizes: [50, 50], snippet }
- sqlEditorState.results[snippet.id] = []
- sqlEditorState.explainResults[snippet.id] = { rows: [] }
},
/**
@@ -182,11 +142,8 @@ export const sqlEditorState = proxy({
const { [id]: snippet, ...otherSnippets } = sqlEditorState.snippets
sqlEditorState.snippets = otherSnippets
- const { [id]: result, ...otherResults } = sqlEditorState.results
- sqlEditorState.results = otherResults
-
- const { [id]: explainResult, ...otherExplainResults } = sqlEditorState.explainResults
- sqlEditorState.explainResults = otherExplainResults
+ // Results/explain live in the session store; drop this snippet's entries.
+ sqlEditorSessionState.clearForSnippet(id)
if (!skipSave) sqlEditorState.needsSaving.delete(id)
},
@@ -266,11 +223,6 @@ export const sqlEditorState = proxy({
sqlEditorState.folders = otherFolders
},
- /**
- * Set the value for the auto limit for SELECT based SQL queries
- */
- setLimit: (value: number) => (sqlEditorState.limit = value),
-
addNeedsSaving: (id: string) => sqlEditorState.needsSaving.set(id, true),
addFavorite: (id: string) => {
@@ -288,47 +240,6 @@ export const sqlEditorState = proxy({
sqlEditorState.needsSaving.set(id, true)
}
},
-
- addResult: (id: string, results: any[], autoLimit?: number) => {
- if (sqlEditorState.results[id]) {
- // Use ref() to prevent Valtio from creating proxies for each row object.
- // This is critical for large result sets - without ref(), Valtio wraps every
- // row and nested property in a Proxy, causing massive memory overhead.
- // Alright to use ref() in this case as the data is meant to be read-only and we
- // don't need to track changes to the underlying data
- sqlEditorState.results[id] = [{ rows: ref(results), autoLimit }]
- }
- },
-
- addResultError: (id: string, error: any, autoLimit?: number) => {
- if (sqlEditorState.results[id]) {
- sqlEditorState.results[id] = [{ rows: ref([]), error, autoLimit }]
- }
- },
-
- resetResult: (id: string) => {
- if (sqlEditorState.results[id]) {
- sqlEditorState.results[id] = []
- }
- },
-
- addExplainResult: (id: string, results: QueryPlanRow[]) => {
- // Use ref() to prevent Valtio from creating proxies for each row object
- sqlEditorState.explainResults[id] = { rows: ref(results) }
- },
-
- addExplainResultError: (id: string, error: { message: string; formattedError?: string }) => {
- sqlEditorState.explainResults[id] = { rows: ref([]), error }
- },
-
- resetExplainResult: (id: string) => {
- sqlEditorState.explainResults[id] = { rows: [] }
- },
-
- resetResults: (id: string) => {
- sqlEditorState.resetResult(id)
- sqlEditorState.resetExplainResult(id)
- },
})
// ========================================================================