Skip to content

refactor(sql-editor): extract execution + explain hooks (decompose 4/6) - #47923

Merged
charislam merged 1 commit into
masterfrom
charislam/sql-editor-decompose-4-execution
Jul 14, 2026
Merged

charislam merged 1 commit into
masterfrom
charislam/sql-editor-decompose-4-execution

Conversation

@charislam

@charislam charislam commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

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, the executeQuery pipeline (destructive-query gating, lazy title generation, connection resolution), and the potentialIssues warning-modal state.
  • useSqlEditorExplain — the execute-explain mutation and the executeExplainQuery pipeline.

Both pipelines accept an already-promoted SafeSqlFragment.

Safe-SQL boundary

Per review guidance, acceptUntrustedSql promotion 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 call acceptUntrustedSql; they only accept safe SQL. executeQuery lists its (now all-stable) dependencies directly rather than suppressing react-hooks/exhaustive-deps.

Verification

  • vitest — 11 characterization tests pass
  • pnpm --filter studio typecheck — clean for SQL editor files
  • eslint / lint:ratchet — pass (0 new violations)
  • prettier --check — clean

SQLEditorContent is 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

    • Improved SQL query execution safeguards for potentially destructive statements, unsafe updates, and missing row-level security coverage.
    • Improved EXPLAIN handling, including clearer validation for unsupported multi-statement queries.
    • Preserved query results, errors, and EXPLAIN output more reliably in the SQL editor.
  • Improvements

    • Added clearer execution status handling and more consistent editor focus, highlighting, and utility-tab behavior.
    • Improved connection selection and SQL execution reliability across supported database configurations.

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.
@charislam
charislam requested a review from a team as a code owner July 14, 2026 13:50
@supabase

supabase Bot commented Jul 14, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@vercel

vercel Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview, Comment Jul 14, 2026 1:53pm
studio-staging Ready Ready Preview, Comment Jul 14, 2026 1:53pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jul 14, 2026 1:53pm
design-system Skipped Skipped Jul 14, 2026 1:53pm
docs Skipped Skipped Open in v0 Jul 14, 2026 1:53pm
ui-library Skipped Skipped Jul 14, 2026 1:53pm
zone-www-dot-com Skipped Skipped Open in v0 Jul 14, 2026 1:53pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

SQL execution and EXPLAIN logic are extracted from SQLEditor.tsx into dedicated hooks. The hooks handle validation, SQL preparation, mutation execution, session persistence, utility-tab switching, and warning state management.

Changes

SQL editor execution flows

Layer / File(s) Summary
Query execution orchestration
apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
Centralizes execution guards, destructive-query and RLS checks, title generation, connection selection, SQL transformation, mutation dispatch, result persistence, and lint invalidation.
EXPLAIN execution flow
apps/studio/components/interfaces/SQLEditor/useSqlEditorExplain.ts
Adds EXPLAIN validation, connection resolution, rollback-wrapped SQL construction, mutation handling, session persistence, and utility-tab switching.
SQLEditor hook integration
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
Uses the new execution hooks, promotes untrusted shortcut SQL, removes local potential-issue state, and resets hook-owned warnings from modal handlers.

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
Loading

Possibly related PRs

Suggested reviewers: alaister, awaseem, myerekapan, joshenlim

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is informative, but it misses several required template sections, including the CONTRIBUTING confirmation and explicit current/new behavior headings. Add the missing template sections: CONTRIBUTING confirmation, change type, current behavior, new behavior, and any additional context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: extracting SQL editor execution and explain logic into hooks.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch charislam/sql-editor-decompose-4-execution

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (tanstack)

passed  238 passed
skipped  5 skipped

Details

stats  243 tests across 28 suites
duration  4 minutes, 10 seconds
commit  89599f4

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
apps/studio/components/interfaces/SQLEditor/useSqlEditorExplain.ts (1)

77-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate connection-resolution logic with useSqlEditorExecution.ts.

Same find-by-selectedDatabaseId + isValidConnString + toast pattern as useSqlEditorExecution.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 win

Duplicated 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 (plus useReadReplicasQuery/databaseSelectorState lookup) 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 win

Duplicate connection-resolution logic with useSqlEditorExplain.ts.

This block (find selected DB by databaseSelectorState.selectedDatabaseId, validate with isValidConnString, toast on failure) is duplicated almost verbatim in useSqlEditorExplain.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

📥 Commits

Reviewing files that changed from the base of the PR and between 4096267 and 89599f4.

📒 Files selected for processing (3)
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
  • apps/studio/components/interfaces/SQLEditor/useSqlEditorExecution.ts
  • apps/studio/components/interfaces/SQLEditor/useSqlEditorExplain.ts

@charislam
charislam merged commit 3fa7f08 into master Jul 14, 2026
37 checks passed
@charislam
charislam deleted the charislam/sql-editor-decompose-4-execution branch July 14, 2026 14:37
@github-actions

github-actions Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1784040023)

Score Average Improvements Regressions
Knowledge Usage 100% (+8pp) 2 🟢 -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Tool Usage 74.5% (+2pp) 1 🟢 1 🔴
Time_to_first_token 3.41tok (-0.32tok) 19 🟢 10 🔴
Llm_calls 2.95 (+0.02) 12 🟢 11 🔴
Tool_calls 3.31 (+0.14) 14 🟢 7 🔴
Errors 5.26 (-0.02) 6 🟢 4 🔴
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 25976.32tok (-2259.59tok) 16 🟢 9 🔴
Prompt_cached_tokens 7856.55tok (-1824.37tok) 14 🟢 12 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 616.17tok (-9.82tok) 15 🟢 14 🔴
Completion_reasoning_tokens 98.28tok (-0.4tok) 15 🟢 12 🔴
Total_tokens 26592.49tok (-2269.4tok) 19 🟢 10 🔴
Estimated_cost 0$ (0$) 15 🟢 10 🔴
Duration 18.4s (-0.73s) 17 🟢 12 🔴
Llm_duration 12.57s (-0.39s) 14 🟢 15 🔴

charislam added a commit that referenced this pull request Jul 14, 2026
…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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants