Skip to content

feat(studio): discriminated snippet union + source-aware writes - #48313

Merged
charislam merged 1 commit into
masterfrom
charislam/discriminated-snippet-union-source-aware-writes
Jul 28, 2026
Merged

charislam merged 1 commit into
masterfrom
charislam/discriminated-snippet-union-source-aware-writes

Conversation

@charislam

@charislam charislam commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #48305.

What

PR 3 of the stacked SQL-editor query-source series (Database vs Logs). Stacked on the PR 2 branch charislam/log-sql-content-shape.

Turns SnippetWithContent into a discriminated union on type and makes all snippet writes source-aware:

  • data/content/sql-folders-query.ts: SnippetWithContent is now { type: 'sql'; content?: SqlSnippets.Content } | { type: 'log_sql'; content?: LogSqlSnippets.Content } | { type: 'report'; content?: never }. report is kept (the content endpoints' wire type carries it) but has no SQL content — its body is Dashboards.Content, loaded through the separate Content union.
  • setSql brands per type (untrustedLogSql vs untrustedSql).
  • buildUpsertPayload persists snippet.type (no longer hardcoded 'sql').
  • createSqlSnippetSkeletonV2({ source }) emits the matching type + content shape with the as any cast removed.
  • New components/interfaces/SQLEditor/querySource.ts: SqlSnippetSource + getSnippetSource.
  • seedSnippet test helper gains a source arg.
  • New remapWireSnippet boundary helper in content-remap.ts concentrates the single wire->domain assertion, so content-id-query / content-upsert-mutation call sites are cast-free (no as unknown as).
  • Collateral: query result types aligned to the union; updateSnippet no longer accepts type (source is immutable); db-only editor read paths narrow away log_sql.

Why

Impossible-states-impossible typing: a snippet's brand follows its content type, so logs SQL and database SQL can never cross execution paths. No behavior change for existing database snippets.

Testing

  • `pnpm typecheck` — clean
  • `pnpm --filter studio run lint:ratchet` — no new warnings
  • `pnpm test:studio` (data/content, SQLEditor, state/sql-editor) — passing, including new tests for `getSnippetSource`, source-aware `setSql`, type-aware `buildUpsertPayload`, and both skeleton shapes.

Summary by CodeRabbit

  • New Features
    • Added source-aware creation for SQL editor snippets, including log-based SQL snippets.
    • Introduced backend source mapping so log snippets are treated as log_sql.
  • Bug Fixes
    • Improved SQL retrieval/prettification so log snippets no longer use the wrong fallback content.
    • Ensured log snippets are sanitized and preserve correct type, content, identifiers, and statuses during save/upsert flows.
  • Tests
    • Expanded unit and integration coverage for log snippet creation, source mapping, editing, prettification, and upsert payloads.

@charislam
charislam requested a review from a team as a code owner July 24, 2026 18:06
@vercel

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

Request Review

@supabase

supabase Bot commented Jul 24, 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 ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

SQL editor snippets now support database and logs sources. Source-specific types, sanitization, persistence remapping, state updates, fixture creation, and editor SQL retrieval were updated, with tests covering both sql and log_sql behavior.

Changes

Source-aware snippet creation

Layer / File(s) Summary
Source contract and snippet skeletons
apps/studio/components/interfaces/SQLEditor/querySource.*, apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.*, apps/studio/tests/lib/sql-editor-test-utils.tsx
Adds source mapping and creates database or logs snippets with corresponding branded SQL content and status defaults.
Typed payloads and wire remapping
apps/studio/data/content/content-remap.ts, apps/studio/data/content/content-id-query.ts, apps/studio/data/content/content-upsert-mutation.ts, apps/studio/data/content/sql-folders-query.ts, apps/studio/data/content/sql-snippets-query.ts
Uses discriminated snippet content types and shared wire-to-domain remapping for fetched and upserted snippets.
State updates and upsert payloads
apps/studio/state/sql-editor/sql-editor-state.ts, apps/studio/state/sql-editor/sql-editor-rules.ts, apps/studio/state/sql-editor/*test.ts
Applies log-specific sanitization, preserves snippet types in upsert payloads, and tests database and logs snippets.
Editor SQL retrieval
apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx, apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts
Avoids using stored unchecked SQL as the editor fallback for log_sql snippets.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Suggested labels: frontend, self-hosted

Suggested reviewers: awaseem, joshenlim, djhi

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is relevant but does not follow the required template sections or include the requested current/new behavior fields. Fill in the template sections: CONTRIBUTING acknowledgment, change type, current behavior, new behavior, and additional context, using the required headings.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: discriminated snippet typing and source-aware writes.
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/discriminated-snippet-union-source-aware-writes

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.

@charislam

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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 (1)
apps/studio/data/content/content-remap.ts (1)

33-42: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Keep wire payloads separate from the domain union at both boundaries.

Both changes assert API rows as SnippetWithContent before content.sql is converted and/or status is added.

  • apps/studio/data/content/content-remap.ts#L33-L42: validate or type the wire row before remapping.
  • apps/studio/data/content/sql-snippets-query.ts#L52-L52: pass the wire list type to the remapper and produce SnippetWithContent[] only after withSavedStatus.

As per coding guidelines, avoid as casts and parse external data with Zod.

🤖 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/data/content/content-remap.ts` around lines 33 - 42, Keep wire
payloads separate from the domain union at both boundaries: in
apps/studio/data/content/content-remap.ts lines 33-42, replace the
SnippetWithContent assertion in remapWireSnippet with Zod validation or an
appropriate wire-row type before remapping; in
apps/studio/data/content/sql-snippets-query.ts line 52, pass the wire list type
to the remapper and only produce SnippetWithContent[] after withSavedStatus,
avoiding `as` casts throughout.

Source: Coding guidelines

🤖 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/data/content/content-remap.ts`:
- Around line 33-42: Keep wire payloads separate from the domain union at both
boundaries: in apps/studio/data/content/content-remap.ts lines 33-42, replace
the SnippetWithContent assertion in remapWireSnippet with Zod validation or an
appropriate wire-row type before remapping; in
apps/studio/data/content/sql-snippets-query.ts line 52, pass the wire list type
to the remapper and only produce SnippetWithContent[] after withSavedStatus,
avoiding `as` casts throughout.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 18f64415-6295-47b3-9c29-ba33799ca96f

📥 Commits

Reviewing files that changed from the base of the PR and between c939c88 and 0db771a.

📒 Files selected for processing (18)
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
  • apps/studio/components/interfaces/SQLEditor/querySource.test.ts
  • apps/studio/components/interfaces/SQLEditor/querySource.ts
  • apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts
  • apps/studio/data/content/content-id-query.ts
  • apps/studio/data/content/content-remap.ts
  • apps/studio/data/content/content-upsert-mutation.ts
  • apps/studio/data/content/sql-folders-query.ts
  • apps/studio/data/content/sql-snippets-query.ts
  • apps/studio/state/sql-editor/sql-editor-rules.test.ts
  • apps/studio/state/sql-editor/sql-editor-rules.ts
  • apps/studio/state/sql-editor/sql-editor-save-scheduler.test.ts
  • apps/studio/state/sql-editor/sql-editor-save.test.ts
  • apps/studio/state/sql-editor/sql-editor-state.test.ts
  • apps/studio/state/sql-editor/sql-editor-state.ts
  • apps/studio/tests/lib/sql-editor-test-utils.tsx

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  240 passed
flaky  3 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  6 minutes, 27 seconds
commit  66b10a8

Flaky tests

Features › database.spec.ts › Database Enumerated Types › CRUD operations works as expected
Features › table-editor.spec.ts › table editor › should show rls accordingly
Features › table-editor.spec.ts › table editor › add enums and show enums on table

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/log-sql-content-shape branch from c939c88 to e987da5 Compare July 28, 2026 14:34
Base automatically changed from charislam/log-sql-content-shape to master July 28, 2026 14:47
Make SnippetWithContent a discriminated union on `type` (sql →
SqlSnippets.Content, log_sql → LogSqlSnippets.Content, report →
content?: never) so database and logs SQL brands can never cross execution
paths. Source-aware writes: `setSql` brands per snippet type,
`buildUpsertPayload` persists the snippet's own type, and
`createSqlSnippetSkeletonV2({ source })` emits the matching type + content
shape cast-free. New `querySource.ts` exposes `SqlSnippetSource` +
`getSnippetSource`; `seedSnippet` gains a `source` arg. Concentrate the
wire->domain assertion in a single `remapWireSnippet` boundary helper so the
content query/mutation call sites are cast-free.

PR 3 of the SQL-editor query-source stack. No user-visible change (no entry
points yet). Green on typecheck, lint:ratchet, and test:studio.
@charislam
charislam force-pushed the charislam/discriminated-snippet-union-source-aware-writes branch from 0db771a to 66b10a8 Compare July 28, 2026 16:11

@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/data/content/sql-snippets-query.ts`:
- Line 52: Validate the API payload before remapping in the query flow
containing remapSqlContentFields. Replace the unsafe data.data cast with the
appropriate Zod wire-schema parse, or use an existing validating fetcher, and
pass the parsed SnippetWithContent[] result to remapSqlContentFields.
🪄 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 Plus

Run ID: 972fe4cc-5329-4f59-9abe-eed9811b4a06

📥 Commits

Reviewing files that changed from the base of the PR and between 0db771a and 66b10a8.

📒 Files selected for processing (18)
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
  • apps/studio/components/interfaces/SQLEditor/querySource.test.ts
  • apps/studio/components/interfaces/SQLEditor/querySource.ts
  • apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts
  • apps/studio/data/content/content-id-query.ts
  • apps/studio/data/content/content-remap.ts
  • apps/studio/data/content/content-upsert-mutation.ts
  • apps/studio/data/content/sql-folders-query.ts
  • apps/studio/data/content/sql-snippets-query.ts
  • apps/studio/state/sql-editor/sql-editor-rules.test.ts
  • apps/studio/state/sql-editor/sql-editor-rules.ts
  • apps/studio/state/sql-editor/sql-editor-save-scheduler.test.ts
  • apps/studio/state/sql-editor/sql-editor-save.test.ts
  • apps/studio/state/sql-editor/sql-editor-state.test.ts
  • apps/studio/state/sql-editor/sql-editor-state.ts
  • apps/studio/tests/lib/sql-editor-test-utils.tsx
🚧 Files skipped from review as they are similar to previous changes (15)
  • apps/studio/components/interfaces/SQLEditor/usePrettifyQuery.ts
  • apps/studio/state/sql-editor/sql-editor-save.test.ts
  • apps/studio/components/interfaces/SQLEditor/querySource.ts
  • apps/studio/state/sql-editor/sql-editor-save-scheduler.test.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
  • apps/studio/data/content/content-upsert-mutation.ts
  • apps/studio/data/content/content-id-query.ts
  • apps/studio/state/sql-editor/sql-editor-state.test.ts
  • apps/studio/state/sql-editor/sql-editor-rules.test.ts
  • apps/studio/data/content/content-remap.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
  • apps/studio/tests/lib/sql-editor-test-utils.tsx
  • apps/studio/data/content/sql-folders-query.ts
  • apps/studio/state/sql-editor/sql-editor-state.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts

const snippets = remapSqlContentFields(
data.data as unknown as Array<Snippet & { content?: SqlSnippets.Content }>
)
const snippets = remapSqlContentFields(data.data as unknown as SnippetWithContent[])

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Validate the wire response before remapping.

Line 52 uses as unknown as SnippetWithContent[], so the discriminated union is only enforced at compile time. Parse the API payload with the appropriate Zod wire schema before calling remapSqlContentFields, or use a fetcher that performs this validation.

As per coding guidelines, external data should be parsed with Zod instead of bypassed with TypeScript casts.

🤖 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/data/content/sql-snippets-query.ts` at line 52, Validate the API
payload before remapping in the query flow containing remapSqlContentFields.
Replace the unsafe data.data cast with the appropriate Zod wire-schema parse, or
use an existing validating fetcher, and pass the parsed SnippetWithContent[]
result to remapSqlContentFields.

Source: Coding guidelines

@charislam
charislam merged commit fa5eb17 into master Jul 28, 2026
37 checks passed
@charislam
charislam deleted the charislam/discriminated-snippet-union-source-aware-writes branch July 28, 2026 16:28
@github-actions

github-actions Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1785256312)

Score Average Improvements Regressions
Knowledge Usage 94.9% (+10pp) 4 🟢 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Tool Usage 72.5% (+12pp) 7 🟢 -
Completeness 100% (+8pp) 7 🟢 -
Conciseness 38.4% (-3pp) 8 🟢 10 🔴
Docs Faithfulness 58.1% (-9pp) 1 🟢 4 🔴
Goal Completion 80.8% (+8pp) 11 🟢 1 🔴
Correctness 73.3% (+2pp) 4 🟢 2 🔴
Safety 100% (+21pp) 4 🟢 -
URL Validity 100% - -
Time_to_first_token 3.73tok (+0.38tok) 9 🟢 20 🔴
Llm_calls 7.08 (-0.13) 7 🟢 11 🔴
Tool_calls 3.09 (+0.55) 20 🟢 3 🔴
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 23047.11tok (+1206.61tok) 8 🟢 17 🔴
Prompt_cached_tokens 7515.22tok (+435.49tok) 15 🟢 11 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 627.63tok (+81.59tok) 3 🟢 26 🔴
Completion_reasoning_tokens 91.61tok (-2.79tok) 12 🟢 14 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 23674.75tok (+1288.2tok) 8 🟢 21 🔴
Estimated_cost 0$ (+0$) 8 🟢 20 🔴
Duration 21.04s (+3.68s) 8 🟢 21 🔴
Llm_duration 13.86s (+1.15s) 7 🟢 22 🔴

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