Repository navigation
refactor(sql-editor): extract execution + explain hooks (decompose 4/6) - #47923
Conversation
Moves the execute mutation + executeQuery pipeline (destructive-query gating, title gen, connection resolution, potentialIssues state) into useSqlEditorExecution, and the explain mutation + pipeline into useSqlEditorExplain. Both pipelines accept an already-promoted SafeSqlFragment; acceptUntrustedSql promotion stays in the composition root's run/explain gesture + warning-modal handlers so it remains auditable next to the explicit user action. executeQuery lists its (now all-stable) deps directly instead of suppressing exhaustive-deps. Behavior-preserving. PR 4/6 of the SQLEditor decomposition stack.
|
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
|
📝 WalkthroughWalkthroughSQL execution and EXPLAIN logic are extracted from ChangesSQL editor execution flows
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant SQLEditor
participant SQLExecutionHook
participant SQLMutation
participant SessionSnapshot
User->>SQLEditor: Run or EXPLAIN SQL
SQLEditor->>SQLExecutionHook: executeQuery or executeExplainQuery
SQLExecutionHook->>SQLMutation: Execute prepared SQL
SQLMutation->>SessionSnapshot: Store result or error
SessionSnapshot-->>SQLEditor: Update results or EXPLAIN tab
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 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 Results (tanstack)Details
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.
🧹 Nitpick comments (3)
apps/studio/components/interfaces/SQLEditor/useSqlEditorExplain.ts (1)
77-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate connection-resolution logic with
useSqlEditorExecution.ts.Same find-by-
selectedDatabaseId+isValidConnString+ toast pattern asuseSqlEditorExecution.ts(Lines 166-172). Worth factoring into a shared helper to avoid the two copies drifting apart.🤖 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/useSqlEditorExplain.ts` around lines 77 - 82, Factor the duplicated connection-resolution and validation flow out of useSqlEditorExplain and useSqlEditorExecution into a shared helper. The helper should find the database by selectedDatabaseId, validate its connectionString with isValidConnString, and preserve the existing missing-connection toast behavior; update both call sites to use it.apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts (2)
1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicated connection-string resolution/validation across both new hooks. Both hooks independently re-implement "find the connection string for the selected database, validate it, toast on failure" — one root cause (no shared resolver), two copies to keep in sync.
apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts#L166-172: extract this block (plususeReadReplicasQuery/databaseSelectorStatelookup) into a shared helper, e.g.useResolveConnectionString(project), and call it here.apps/studio/components/interfaces/SQLEditor/useSqlEditorExplain.ts#L77-82: call the same shared helper instead of re-implementing the find/validate/toast logic.🤖 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/useSqlEditorExecution.ts` at line 1, Extract the duplicated selected-database connection-string lookup, validation, and failure toast from the execution and explain hooks into a shared useResolveConnectionString(project) helper, including the useReadReplicasQuery and databaseSelectorState lookup. Update both useSqlEditorExecution and useSqlEditorExplain to call the helper and remove their local implementations, preserving the existing failure behavior.
166-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate connection-resolution logic with
useSqlEditorExplain.ts.This block (find selected DB by
databaseSelectorState.selectedDatabaseId, validate withisValidConnString, toast on failure) is duplicated almost verbatim inuseSqlEditorExplain.ts(Lines 77-82). Consider extracting a small shared helper (e.g.useResolveConnectionString) so the resolution/validation rule lives in one place.🤖 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/useSqlEditorExecution.ts` around lines 166 - 172, Extract the selected-database lookup and connection-string validation currently used in the execution flow into a shared helper such as useResolveConnectionString, then reuse it from both useSqlEditorExecution and useSqlEditorExplain. Preserve the existing missing-connection behavior, including clearing pending refocus where applicable and showing the current error toast, while centralizing only the resolution and validation rule.
🤖 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.
Nitpick comments:
In `@apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts`:
- Line 1: Extract the duplicated selected-database connection-string lookup,
validation, and failure toast from the execution and explain hooks into a shared
useResolveConnectionString(project) helper, including the useReadReplicasQuery
and databaseSelectorState lookup. Update both useSqlEditorExecution and
useSqlEditorExplain to call the helper and remove their local implementations,
preserving the existing failure behavior.
- Around line 166-172: Extract the selected-database lookup and
connection-string validation currently used in the execution flow into a shared
helper such as useResolveConnectionString, then reuse it from both
useSqlEditorExecution and useSqlEditorExplain. Preserve the existing
missing-connection behavior, including clearing pending refocus where applicable
and showing the current error toast, while centralizing only the resolution and
validation rule.
In `@apps/studio/components/interfaces/SQLEditor/useSqlEditorExplain.ts`:
- Around line 77-82: Factor the duplicated connection-resolution and validation
flow out of useSqlEditorExplain and useSqlEditorExecution into a shared helper.
The helper should find the database by selectedDatabaseId, validate its
connectionString with isValidConnString, and preserve the existing
missing-connection toast behavior; update both call sites to use it.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: aafb6780-46dc-4369-97ed-69f76e2d6673
📒 Files selected for processing (3)
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsxapps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.tsapps/studio/components/interfaces/SQLEditor/useSqlEditorExplain.ts
Braintrust eval report
|
…6) (#47935) ## What Decompose step **5 of 6** for `SQLEditor.tsx`. Extracts the Assistant / diff cluster and the keyboard-shortcut wiring out of the `SQLEditorContent` monolith into two focused, individually-testable hooks: - **`useSqlEditorAi`** — SQL completion (`complete`), the ask-AI prompt flow (`handlePrompt`), accept/discard diff handlers, `onDebug` / `buildDebugPrompt` helpers, `handleDiffEditorMount`, and the fragile diff lifecycle effects (one-shot diff-request drain, diff-editor value sync, ask-AI widget visibility). - **`useSqlEditorShortcuts`** — the registered shortcuts (focus editor, new snippet, format, explain) plus the accept/discard/escape keydown handling. `SQLEditorContent` now composes these hooks alongside the execution/explain hooks landed in decompose 4. ## Behavior-preserving This is a pure extraction. The moved function bodies, effect logic, dependency arrays, and JSX are unchanged from the previous monolith (verified via `git diff` against the pre-decomposition source). In particular: - `useEffectEvent` is preserved for `drainDiffRequest` / `resetDiff`. - `editorMountCount` remains single-owner (passed into the AI hook to drive the one-shot drain). - The untrusted→safe SQL promotion (`acceptUntrustedSql`) continues to happen in the run/explain gesture and warning-modal handlers in `SQLEditorContent`, as close to the explicit user action as possible. The Phase-1 characterization suite (`SQLEditor.test.tsx`, 11 tests) remains green. ## Stack Part of the SQLEditor decomposition stack (1/6 … 6/6). Builds on decompose 4 (execution + explain hooks, #47923). Next: PR6 splits the JSX into panes + final cleanup. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved SQL editor AI assistance, including completion prompts, debugging support, and diff review controls. * Added keyboard shortcuts for accepting or discarding AI-generated SQL changes. * Added shortcuts for focusing the editor, creating snippets, formatting queries, and explaining SQL. * **Bug Fixes** * Prevented SQL execution while reviewing AI-generated differences. * Improved handling of AI diff state during editor loading and interaction. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Summary
PR 4 of 6 in the SQLEditor decomposition stack. Extracts the two query-run concerns out of the composition root into cohesive hooks. Behavior-preserving — the characterization suite stays green.
New hooks
useSqlEditorExecution— the execute mutation, theexecuteQuerypipeline (destructive-query gating, lazy title generation, connection resolution), and thepotentialIssueswarning-modal state.useSqlEditorExplain— the execute-explain mutation and theexecuteExplainQuerypipeline.Both pipelines accept an already-promoted
SafeSqlFragment.Safe-SQL boundary
Per review guidance,
acceptUntrustedSqlpromotion stays in the composition root's run/explain gesture handlers and warning-modal confirm handlers — as close to the explicit user action as possible, so it's auditable. The hooks never callacceptUntrustedSql; they only accept safe SQL.executeQuerylists its (now all-stable) dependencies directly rather than suppressingreact-hooks/exhaustive-deps.Verification
vitest— 11 characterization tests passpnpm --filter studio typecheck— clean for SQL editor fileseslint/lint:ratchet— pass (0 new violations)prettier --check— cleanSQLEditorContentis down to ~530 lines (from 1056 at the start of the stack). Remaining: PR5 (AI/diff + shortcuts), PR6 (JSX pane split + cleanup).Summary by CodeRabbit
Bug Fixes
Improvements