Repository navigation
refactor(studio): extract SQL editor session store from god store - #47349
Conversation
Move ephemeral, never-persisted SQL editor state (query results, EXPLAIN results, the Assistant diff content, and the row limit) out of the snippet/ folder store into a dedicated session store at state/sql-editor/sql-editor-session-state.ts. The snippet store now deals only with persistence; the session store holds state that lives only for the current editing session. removeSnippet drops a snippet's session entries via clearForSnippet. Consumers read session state directly from useSqlEditorSessionSnapshot rather than the god-store snapshot. Behavior-preserving; the moved result/explain types are kept verbatim. Adds sql-editor-session-state.test.ts covering result/explain mutators, resetResults, clearForSnippet, limit, and diffContent.
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
5 Skipped Deployments
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughSQL editor query, EXPLAIN, limit, and diff request state now live in session-scoped stores. The editor and utility panel components read and write that session state, while the persistent editor store keeps snippet metadata and clears session data on removal. ChangesSQL editor session-state split
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
🎭 Playwright Test ResultsDetails
Flaky testsFeatures › queue-table-operations.spec.ts › Queue Table Operations › reverted cell edit clears the pending change Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx (1)
831-853: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winConsume
diffContentexactly once.This effect reads a session-global
diffContentvalue but never clears it after applying/opening the diff. Since the effect also runs on mount, reopening the editor or navigating to another snippet can replay the previous “Insert/Replace code” action into the next editor instance. Clear the queued diff after handling it, or scope it to the target snippet so stale payloads are ignored.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx` around lines 831 - 853, The SQLEditor effect that handles sessionSnap.diffContent is consuming a queued diff without clearing or scoping it, so stale “Insert/Replace code” actions can replay in later editor instances. Update the useEffect in SQLEditor.tsx to consume diffContent exactly once by clearing it after handling, or by validating it against the current target snippet before applying it; use the existing editorRef, sessionSnap.diffContent, setSourceSqlDiff, and setSelectedDiffType flow to locate the fix.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/state/sql-editor/sql-editor-session-state.ts`:
- Around line 41-45: The session-scoped SQL diff state is not being
cleared/guarded when a snippet is removed, so stale assistant diffs can leak
into the next editor. Update clearForSnippet in sql-editor-session-state.ts to
also clear diffContent when the removed snippet is the one that produced it, and
update SQLEditor.tsx to only apply sessionSnap.diffContent when it matches the
active snippet id. Use the existing setDiffContent and diffContent handling
paths to locate the fix.
---
Outside diff comments:
In `@apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx`:
- Around line 831-853: The SQLEditor effect that handles sessionSnap.diffContent
is consuming a queued diff without clearing or scoping it, so stale
“Insert/Replace code” actions can replay in later editor instances. Update the
useEffect in SQLEditor.tsx to consume diffContent exactly once by clearing it
after handling, or by validating it against the current target snippet before
applying it; use the existing editorRef, sessionSnap.diffContent,
setSourceSqlDiff, and setSelectedDiffType flow to locate the fix.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: e420f321-de2c-45d5-a4ad-e41ea307be62
📒 Files selected for processing (9)
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxapps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsxapps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsxapps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabExplain.tsxapps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsxapps/studio/components/ui/QueryBlock/EditQueryButton.tsxapps/studio/state/sql-editor/sql-editor-session-state.test.tsapps/studio/state/sql-editor/sql-editor-session-state.tsapps/studio/state/sql-editor/sql-editor-state.ts
The Assistant's Insert/Replace code diff is not per-snippet session state — it is a transient, fire-and-forget command produced outside the editor and consumed exactly once by the active editor. Modelling it as durable state in the session store (never cleared, triggered by object-reference identity) was a poor fit. Extract it into a dedicated sql-editor-diff-request slice with requestDiff and consumeDiffRequest. The editor drains the request on apply, so a stale diff can never leak into a later editor or editing session. EditQueryButton produces via requestDiff; SQLEditor consumes and clears. Adds sql-editor-diff-request.test.ts; drops the diffContent coverage from the session-store test.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx`:
- Around line 835-863: The pending diff handling in SQLEditor can get stuck
because the effect only watches diffRequest.pending and returns early when
editorRef.current?.getModel() is not ready. Add an explicit editor-ready state
(for example in the editor onMount handler where editorRef.current is set) and
include that readiness flag in the useEffect dependencies so the pending request
is re-processed once the editor mounts. Keep the one-shot consumeDiffRequest
behavior in the same effect after applying the diff so the request still drains
correctly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: ba0f9556-6dba-43f0-bc97-5ebd8c8b96db
📒 Files selected for processing (6)
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxapps/studio/components/ui/QueryBlock/EditQueryButton.tsxapps/studio/state/sql-editor/sql-editor-diff-request.test.tsapps/studio/state/sql-editor/sql-editor-diff-request.tsapps/studio/state/sql-editor/sql-editor-session-state.test.tsapps/studio/state/sql-editor/sql-editor-session-state.ts
💤 Files with no reviewable changes (1)
- apps/studio/state/sql-editor/sql-editor-session-state.test.ts
✅ Files skipped from review due to trivial changes (1)
- apps/studio/state/sql-editor/sql-editor-diff-request.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/studio/state/sql-editor/sql-editor-session-state.ts
The diff-apply effect early-returns when the Monaco editor model isn't ready, but it only depended on diffRequest.pending, so a request issued before the editor mounted was dropped despite the comment claiming otherwise. Track an editorMountCount that bumps on every onMount (including the keyed remount on snippet switch) and add it to the effect deps, so a pending request is re-applied once the editor is ready. The one-shot consumeDiffRequest drain stays in the same effect.
| 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) |
There was a problem hiding this comment.
nit: hmm just wondering if this could be a simple boolean to see if the editor has been mounted? (to decide when to apply the diff)
Or why do we need to keep setting the count each time onMount is called?
There was a problem hiding this comment.
Monaco editor remounts on snippet switch, so we need to also check on remount, not just once per SQL editor render
joshenlim
left a comment
There was a problem hiding this comment.
just a tiny nit comment but changes generally LGTM! verified changes on staging preview just to make sure the results + diff behaviour works as expected
| } | ||
|
|
||
| // One-shot: drain the request so it can't re-apply to a later editor or session. | ||
| sqlEditorDiffRequestState.consumeDiffRequest() |
There was a problem hiding this comment.
Shouldn't this be diffRequest.consumeDiffRequest()?
executeExplainQuery now uses sessionSnap.addExplainResultError but its dependency array still listed snapV2, adding a new react-hooks/exhaustive-deps violation (the rule is ratcheted; baseline for this file is 2). Swap snapV2 for sessionSnap in the deps — the body no longer references snapV2. Also drop the now-unused sqlEditorDiffRequestState import (the drain effect calls consumeDiffRequest via the snapshot).
Braintrust eval report
|
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.tsholds per-snippet, read-by-many session state:resultsexplainResultslimit…with their mutators (
addResult/addResultError/resetResult,addExplainResult/addExplainResultError/resetExplainResult,resetResults,setLimit).removeSnippetdrops a snippet's session entries viaclearForSnippet(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 wasdiffContentin the god store: never cleared and triggered by object-reference identity.)Consumers read session state from
useSqlEditorSessionSnapshotand the diff channel fromuseSqlEditorDiffRequestSnapshot, keepinguseSqlEditorV2StateSnapshotonly for snippets/folders.Why not the TanStack Query cache for results/explain?
Editor execution is a mutation, not a keyed query —
mutation.datais 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 ANALYZEactually executes the statement, so a declarative/auto-refetchinguseQueryis 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 requestUtilityPanel.tsx,UtilityTabResults.tsx,UtilityTabExplain.tsx,UtilityActions.tsxQueryBlock/EditQueryButton.tsx— produces viarequestDiffNotes
anyrow/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,limitsql-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)Summary by CodeRabbit
New Features
Bug Fixes
Tests