Files
supabase/apps/studio/state/sql-editor/sql-editor-state.test.ts
Charis fa5eb17277 feat(studio): discriminated snippet union + source-aware writes (#48313)
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.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## 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.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-07-28 12:28:36 -04:00

125 lines
3.9 KiB
TypeScript

import { untrustedSql } from '@supabase/pg-meta'
import { beforeEach, describe, expect, it } from 'vitest'
import { sqlEditorState } from './sql-editor-state'
import type { SnippetWithContent } from '@/data/content/sql-folders-query'
import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
function makeLogSnippet(id: string): SnippetWithContent {
return {
id,
name: 'My Logs Query',
description: '',
visibility: 'user',
project_id: 42,
owner_id: 7,
folder_id: null,
favorite: false,
status: 'saved',
inserted_at: '2024-01-01T00:00:00.000Z',
updated_at: '2024-01-01T00:00:00.000Z',
type: 'log_sql',
content: {
content_id: id,
schema_version: '1',
unchecked_sql: untrustedLogSql('select * from logs'),
},
}
}
function makeSnippet(
id: string,
overrides: Omit<Partial<SnippetWithContent>, 'content' | 'type'> = {}
): SnippetWithContent {
return {
id,
name: 'My Query',
description: 'A description',
visibility: 'user',
project_id: 42,
owner_id: 7,
folder_id: null,
favorite: false,
status: 'saved',
inserted_at: '2024-01-01T00:00:00.000Z',
updated_at: '2024-01-01T00:00:00.000Z',
...overrides,
type: 'sql',
content: {
content_id: id,
schema_version: '1',
unchecked_sql: untrustedSql('SELECT * FROM users;'),
},
}
}
describe('addFavorite / removeFavorite', () => {
beforeEach(() => {
// sqlEditorState is a module-level singleton, so reset the state these tests touch
for (const id of Object.keys(sqlEditorState.snippets)) {
delete sqlEditorState.snippets[id]
}
sqlEditorState.needsSaving.clear()
})
it('marks a loaded snippet as favorite and queues it for saving', () => {
sqlEditorState.addSnippet({ projectRef: 'ref', snippet: makeSnippet('snippet-1') })
sqlEditorState.addFavorite('snippet-1')
expect(sqlEditorState.snippets['snippet-1'].snippet.favorite).toBe(true)
expect(sqlEditorState.needsSaving.get('snippet-1')).toBe(true)
})
it('unmarks a favorited snippet and queues it for saving', () => {
sqlEditorState.addSnippet({
projectRef: 'ref',
snippet: makeSnippet('snippet-1', { favorite: true }),
})
sqlEditorState.removeFavorite('snippet-1')
expect(sqlEditorState.snippets['snippet-1'].snippet.favorite).toBe(false)
expect(sqlEditorState.needsSaving.get('snippet-1')).toBe(true)
})
it('ignores addFavorite for a snippet that is not in the store', () => {
expect(() => sqlEditorState.addFavorite('missing')).not.toThrow()
expect(sqlEditorState.needsSaving.has('missing')).toBe(false)
})
it('ignores removeFavorite for a snippet that is not in the store', () => {
expect(() => sqlEditorState.removeFavorite('missing')).not.toThrow()
expect(sqlEditorState.needsSaving.has('missing')).toBe(false)
})
})
describe('setSql — source-aware branding', () => {
beforeEach(() => {
for (const id of Object.keys(sqlEditorState.snippets)) {
delete sqlEditorState.snippets[id]
}
sqlEditorState.needsSaving.clear()
})
it('updates the SQL of a database snippet and marks it for saving', () => {
sqlEditorState.addSnippet({ projectRef: 'ref', snippet: makeSnippet('db-1') })
sqlEditorState.setSql({ id: 'db-1', sql: 'select 2' })
expect(sqlEditorState.snippets['db-1'].snippet.content?.unchecked_sql).toBe('select 2')
expect(sqlEditorState.needsSaving.has('db-1')).toBe(true)
})
it('updates the SQL of a logs snippet and marks it for saving', () => {
sqlEditorState.addSnippet({ projectRef: 'ref', snippet: makeLogSnippet('logs-1') })
sqlEditorState.setSql({ id: 'logs-1', sql: 'select count(*) from logs' })
expect(sqlEditorState.snippets['logs-1'].snippet.content?.unchecked_sql).toBe(
'select count(*) from logs'
)
expect(sqlEditorState.needsSaving.has('logs-1')).toBe(true)
})
})