Skip to content

refactor(sql-editor): extract pure SQL helpers + tighten safe-SQL boundary (decompose 2/6) - #47831

Merged
charislam merged 1 commit into
masterfrom
charislam/sql-editor-decompose-2-utils
Jul 10, 2026
Merged

charislam merged 1 commit into
masterfrom
charislam/sql-editor-decompose-2-utils

Conversation

@charislam

@charislam charislam commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  1. Extract pure logic out of the 1056-line SQLEditor.tsx monolith into unit-tested functions in SQLEditor.utils.ts.
  2. Remove rawSql() from the SQL editor and tighten the untrusted→safe boundary per the safe-sql-execution model.

Extracted functions (+ tests)

  • getEditorSql(editor, snippetContent?) — selection → full value → snippet fallback. Returns an UntrustedSqlFragment so editor/snippet SQL keeps its provenance.
  • computeErrorHighlightLine(error, startLineNumber) — parses the LINE n: marker + selection offset.
  • assembleCompletionDiff(meta, text) — before/selection/after assembly for the AI completion diff.
  • buildExplainSql(sql, impersonatedRoleState) — takes an already-safe fragment; EXPLAIN ANALYZE + role impersonation + rollback wrapping.
  • buildDebugPromptText(sql, errorMessage) — the assistant debug prompt string.

Safe-SQL boundary

  • rawSql() is no longer used anywhere in the SQL editor.
  • executeQuery / executeExplainQuery now require a SafeSqlFragment — safe by construction, so they can never auto-run untrusted SQL.
  • acceptUntrustedSql promotion happens only in the small run/explain gesture handlers (executeQueryFromButton, handleRunShortcut, handleRunExplain, and the warning-modal confirm handlers), never buried in the long helpers.

Verification

  • vitest — 156 pass (11 characterization + 145 utils, incl. new cases)
  • pnpm --filter studio typecheck — clean for all SQL editor files (two unrelated @sentry/tanstackstart-react module-resolution errors exist on current master pre-install; not touched by this PR)
  • eslint — 0 errors

Summary by CodeRabbit

  • Enhancements

    • Improved SQL execution and EXPLAIN workflows with safer handling at run and analysis actions.
    • Enhanced SQL selection and snippet handling in the editor.
    • Improved error highlighting to more accurately identify affected lines.
    • Refined completion previews and debugging prompts for clearer results.
    • EXPLAIN ANALYZE now supports rollback-wrapped execution and avoids duplicate wrapping.
  • Bug Fixes

    • Improved behavior when working with selected, empty, or missing SQL content.
    • Prevented existing EXPLAIN statements from being unnecessarily modified.

@charislam
charislam requested a review from a team as a code owner July 10, 2026 17:39
@supabase

supabase Bot commented Jul 10, 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 10, 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 10, 2026 5:57pm
studio-staging Ready Ready Preview, Comment Jul 10, 2026 5:57pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jul 10, 2026 5:57pm
design-system Skipped Skipped Jul 10, 2026 5:57pm
docs Skipped Skipped Jul 10, 2026 5:57pm
ui-library Skipped Skipped Jul 10, 2026 5:57pm
zone-www-dot-com Skipped Skipped Jul 10, 2026 5:57pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3c048e6a-4af2-42f0-9676-21596e73e561

📥 Commits

Reviewing files that changed from the base of the PR and between 972ddfa and 0a9430f.

📒 Files selected for processing (3)
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts

📝 Walkthrough

Walkthrough

The SQL editor now uses typed untrusted and safe SQL fragments, promotes SQL at execution boundaries, centralizes editor and EXPLAIN helpers, and adds utility coverage for extraction, diagnostics, completion, debugging, and execution formatting.

Changes

SQL editor execution and utility refactor

Layer / File(s) Summary
SQL extraction and helper utilities
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts, apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
Adds shared utilities for editor SQL selection, error-line calculation, completion diff assembly, EXPLAIN construction, and debug prompt formatting, with corresponding tests.
Typed execution and EXPLAIN flow
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
Moves untrusted-to-safe SQL promotion into run and confirmation handlers, updates query and EXPLAIN execution signatures, and rewires editor and warning-modal callbacks.
Editor behavior integration
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
Uses shared helpers for prettification, diagnostics, completion handling, debug prompts, and decoration cleanup.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MonacoEditor
  participant handleRunShortcut
  participant executeQuery
  MonacoEditor->>handleRunShortcut: editor SQL
  handleRunShortcut->>handleRunShortcut: acceptUntrustedSql(sql)
  handleRunShortcut->>executeQuery: SafeSqlFragment
Loading

Possibly related PRs

Suggested reviewers: awaseem, joshenlim, SaxonF

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is informative, but it does not follow the required template or include the mandated sections. Rewrite the PR description using the repository template, including the CONTRIBUTING.md acknowledgment, change type, current behavior, new behavior, and additional context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: SQL editor helper extraction and safe-SQL boundary tightening.
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-2-utils

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.

@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.

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 875-886: Update onConfirmWithRLS to resolve the base SQL through
readEditorSql(), matching onConfirm and the run path, instead of directly
calling getEditorSql(editor). Preserve the snippet unchecked_sql fallback before
passing the result to appendEnableRLSStatements.
🪄 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: 0c6ddfad-b85c-481e-a035-3c75581f36fb

📥 Commits

Reviewing files that changed from the base of the PR and between e5df232 and 972ddfa.

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

@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (tanstack)

passed  238 passed
skipped  5 skipped

Details

stats  243 tests across 28 suites
duration  5 minutes, 4 seconds
commit  0a9430f

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

@charislam
charislam force-pushed the charislam/sql-editor-decompose-2-utils branch from 972ddfa to d11dfe3 Compare July 10, 2026 17:51
…QL boundary

Extracts getEditorSql, computeErrorHighlightLine, assembleCompletionDiff, buildExplainSql, and buildDebugPromptText out of the SQLEditor monolith into SQLEditor.utils, with unit tests.

Also removes rawSql() from the SQL editor. getEditorSql now returns an UntrustedSqlFragment so editor/snippet SQL keeps its untrusted provenance through the destructive-query checks. The execute helpers (executeQuery/executeExplainQuery) now require a SafeSqlFragment, so they are safe by construction and can never auto-run untrusted SQL; acceptUntrustedSql promotion happens only in the small run/explain gesture handlers. Runtime-identical (identity casts); the characterization suite stays green.
@charislam
charislam force-pushed the charislam/sql-editor-decompose-2-utils branch from d11dfe3 to 0a9430f Compare July 10, 2026 17:53
@charislam
charislam merged commit b6cdd5c into master Jul 10, 2026
37 of 38 checks passed
@charislam
charislam deleted the charislam/sql-editor-decompose-2-utils branch July 10, 2026 19:01
@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1783710229)

Score Average Improvements Regressions
Knowledge Usage 92.1% (0pp) - -
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+3pp) 1 🟢 -
Tool Usage 71.4% (+3pp) 1 🟢 -
Time_to_first_token 3.65tok (-0.58tok) 23 🟢 6 🔴
Llm_calls 2.77 (-0.06) 8 🟢 12 🔴
Tool_calls 3.09 (+0.14) 10 🟢 11 🔴
Errors 5.32 (+0.02) 5 🟢 5 🔴
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 24314.62tok (+78.99tok) 13 🟢 12 🔴
Prompt_cached_tokens 6867.86tok (-906.3tok) 12 🟢 10 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 619.62tok (+39.57tok) 12 🟢 17 🔴
Completion_reasoning_tokens 99tok (+6.71tok) 16 🟢 12 🔴
Total_tokens 24934.24tok (+118.56tok) 15 🟢 14 🔴
Estimated_cost 0$ (+0$) 16 🟢 11 🔴
Duration 18.25s (-1.75s) 25 🟢 4 🔴
Llm_duration 12.04s (-1.21s) 21 🟢 8 🔴

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