Files
supabase/apps/studio/state/sql-editor/sql-editor-session-state.ts
T
CharisandJoshen Lim d153bab849 refactor(studio): extract SQL editor session store from god store (#47349)
## What

PR 6 of the SQL editor state re-layering stack. Moves ephemeral,
never-persisted SQL editor state out of the snippet/folder "god store".

**Session store** — `state/sql-editor/sql-editor-session-state.ts` holds
per-snippet, read-by-many session state:
- query `results`
- `explainResults`
- the row `limit`

…with their mutators (`addResult`/`addResultError`/`resetResult`,
`addExplainResult`/`addExplainResultError`/`resetExplainResult`,
`resetResults`, `setLimit`). `removeSnippet` drops a snippet's session
entries via `clearForSnippet(id)`.

**Diff-request slice** — `state/sql-editor/sql-editor-diff-request.ts`.
The Assistant's "Insert code" / "Replace code" diff is *not* per-snippet
session state: it's a transient, fire-and-forget command produced
outside the editor (e.g. query blocks / assistant) and consumed exactly
once by whichever editor is active. It's modeled as a consume-once
request (`requestDiff` / `consumeDiffRequest`) rather than durable state
— the editor drains it on apply, so a stale diff can't leak into a later
editor or session. (Previously this was `diffContent` in the god store:
never cleared and triggered by object-reference identity.)

Consumers read session state from `useSqlEditorSessionSnapshot` and the
diff channel from `useSqlEditorDiffRequestSnapshot`, keeping
`useSqlEditorV2StateSnapshot` only for snippets/folders.

### Why not the TanStack Query cache for results/explain?

Editor execution is a **mutation**, not a keyed query — `mutation.data`
is per-hook-instance and not keyed by snippet id, and there's no caching
value to capture (re-running SQL must return *fresh* data, never a
cached result). `EXPLAIN ANALYZE` actually executes the statement, so a
declarative/auto-refetching `useQuery` is semantically wrong.
Results/explain are imperative mutation outputs, scoped to the session,
read by several decoupled consumers keyed by snippet id — exactly what a
small in-memory keyed store models honestly.

## Consumers migrated

- `SQLEditor.tsx` — results/explain/limit reads +
`addResult`/`addResultError`/`addExplainResult`/`addExplainResultError`/`setLimit`;
diff-apply effect now drains a consume-once request
- `UtilityPanel.tsx`, `UtilityTabResults.tsx`, `UtilityTabExplain.tsx`,
`UtilityActions.tsx`
- `QueryBlock/EditQueryButton.tsx` — produces via `requestDiff`

## Notes

- Result/explain types are kept verbatim from the god store
(pre-existing `any` row/error types come along unchanged; tightening
them is out of scope for this move).
- `ref()` on result rows is preserved to avoid Valtio proxying large row
sets.

## Tests

- `sql-editor-session-state.test.ts` — result/explain mutators,
`resetResults`, `clearForSnippet`, `limit`
- `sql-editor-diff-request.test.ts` — `requestDiff`,
`consumeDiffRequest` (drain + queue-of-one)

Validation:
- `pnpm --filter studio typecheck` ✅
- `pnpm exec vitest --run state/sql-editor/` ✅ (110 passed)
- lint ✅ (no new errors)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* SQL editor query results, EXPLAIN output, and the “Limit results to”
setting now persist more reliably across a session.
* AI-assisted SQL insert/replace actions now use a pending diff workflow
to apply updates more consistently.

* **Bug Fixes**
* Results/EXPLAIN rendering and downloads stay in sync with the latest
executed data.
* Switching databases/snippets now clears the correct temporary results.
* Diff application is more resilient when an editor is still loading,
including empty-vs-non-empty editor cases.

* **Tests**
  * Added coverage for the session and diff-request state logic.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
2026-06-30 11:24:48 -04:00

88 lines
3.2 KiB
TypeScript

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)