mirror of
https://github.com/supabase/supabase.git
synced 2026-09-07 02:20:52 +08:00
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 -->
117 lines
4.2 KiB
TypeScript
117 lines
4.2 KiB
TypeScript
import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query'
|
|
import { components } from 'api-types'
|
|
|
|
import { contentKeys } from './keys'
|
|
import type { SnippetStatus } from './snippet-status'
|
|
import { get, handleError } from '@/data/fetchers'
|
|
import type {
|
|
LogSqlSnippets,
|
|
ResponseError,
|
|
SqlSnippets,
|
|
UseCustomInfiniteQueryOptions,
|
|
} from '@/types'
|
|
|
|
export type SnippetFolderResponse = components['schemas']['GetUserContentFolderResponse']['data']
|
|
export type SnippetFolder =
|
|
components['schemas']['GetUserContentFolderResponse']['data']['folders'][number]
|
|
export type Snippet =
|
|
components['schemas']['GetUserContentFolderResponse']['data']['contents'][number]
|
|
|
|
// The SQL editor's loaded-snippet type. Discriminated on `type` so database SQL
|
|
// (`SqlSnippets.Content`, Postgres brand) and logs SQL (`LogSqlSnippets.Content`,
|
|
// logs brand) can never cross execution paths: reading `snippet.content.unchecked_sql`
|
|
// on the union yields the widened brand, forcing callers that need one specific
|
|
// brand to narrow on `type` first. The shared field names (`content_id`,
|
|
// `unchecked_sql`, `schema_version`) keep the many read sites that only need the
|
|
// SQL text compiling unchanged.
|
|
//
|
|
// `report` is included because the content endpoints' wire type carries it, but
|
|
// it deliberately has NO SQL content (`content?: never`): report bodies are
|
|
// `Dashboards.Content` and are loaded through the separate `Content` union
|
|
// (data/content/content-query.ts), never with SQL here. Modelling it as `never`
|
|
// (rather than reusing `SqlSnippets.Content`) keeps that honest while letting the
|
|
// broadly-typed rows the content/folder queries return assign without a cast.
|
|
export type SnippetWithContent = Omit<Snippet, 'type'> & { status: SnippetStatus } & (
|
|
| { type: 'sql'; content?: SqlSnippets.Content }
|
|
| { type: 'log_sql'; content?: LogSqlSnippets.Content }
|
|
| { type: 'report'; content?: never }
|
|
)
|
|
|
|
// Attaches the 'saved' lifecycle status to a snippet as it crosses from the
|
|
// database into the app. Generic so it preserves any loaded content on the
|
|
// snippet, and types `status` as the full SnippetStatus (not the 'saved'
|
|
// literal) so the result is a regular SnippetWithContent.
|
|
export function withSavedStatus<T extends Snippet>(snippet: T): T & { status: SnippetStatus } {
|
|
return { ...snippet, status: 'saved' }
|
|
}
|
|
|
|
export type SQLSnippetFolderVariables = {
|
|
projectRef?: string
|
|
cursor?: string
|
|
name?: string
|
|
sort?: 'name' | 'inserted_at'
|
|
}
|
|
|
|
export const SNIPPET_PAGE_LIMIT = 100
|
|
|
|
export async function getSQLSnippetFolders(
|
|
{ projectRef, cursor, sort, name }: SQLSnippetFolderVariables,
|
|
signal?: AbortSignal
|
|
) {
|
|
if (typeof projectRef === 'undefined') throw new Error('projectRef is required')
|
|
|
|
const sortOrder = sort === 'name' ? 'asc' : 'desc'
|
|
|
|
const { data, error } = await get('/platform/projects/{ref}/content/folders', {
|
|
params: {
|
|
path: { ref: projectRef },
|
|
query: {
|
|
type: 'sql',
|
|
cursor,
|
|
limit: SNIPPET_PAGE_LIMIT.toString(),
|
|
sort_by: sort,
|
|
sort_order: sortOrder,
|
|
name,
|
|
// [Alaister] Hard coding visibility to 'user' as folders are only supported for user content
|
|
visibility: 'user',
|
|
},
|
|
},
|
|
signal,
|
|
})
|
|
|
|
if (error) handleError(error)
|
|
return {
|
|
...data.data,
|
|
contents: (data.data.contents ?? []).map(withSavedStatus),
|
|
cursor: data.cursor,
|
|
}
|
|
}
|
|
|
|
export type SQLSnippetFoldersData = Awaited<ReturnType<typeof getSQLSnippetFolders>>
|
|
export type SQLSnippetFoldersError = ResponseError
|
|
|
|
export const useSQLSnippetFoldersQuery = <TData = SQLSnippetFoldersData>(
|
|
{ projectRef, name, sort }: Omit<SQLSnippetFolderVariables, 'cursor'>,
|
|
{
|
|
enabled = true,
|
|
...options
|
|
}: UseCustomInfiniteQueryOptions<
|
|
SQLSnippetFoldersData,
|
|
SQLSnippetFoldersError,
|
|
InfiniteData<TData>,
|
|
readonly unknown[],
|
|
string | undefined
|
|
> = {}
|
|
) =>
|
|
useInfiniteQuery({
|
|
queryKey: contentKeys.folders(projectRef, { name, sort }),
|
|
queryFn: ({ signal, pageParam }) =>
|
|
getSQLSnippetFolders({ projectRef, cursor: pageParam, name, sort }, signal),
|
|
enabled: enabled && typeof projectRef !== 'undefined',
|
|
initialPageParam: undefined,
|
|
getNextPageParam(lastPage) {
|
|
return lastPage.cursor
|
|
},
|
|
...options,
|
|
})
|