Files
supabase/apps/studio/data/content/sql-folders-query.ts
Charis d5653f1f92 refactor(studio): unify snippet save + persistence into SnippetStatus (3/9) (#47251)
## What

PR 3 of a stacked refactor of the SQL editor snippet state. Replaces the
two overlapping pieces of snippet lifecycle state — the `savingStates`
map (`IDLE|UPDATING|UPDATING_FAILED`) and the `isNotSavedInDatabaseYet`
boolean — with a single `SnippetStatus` enum.

## Status is attached at the data layer (never absent)

- `SnippetStatus` + `SnippetWithContent` now live in `data/content`. The
snippet queries attach `status: 'saved'` via a typed `withSavedStatus()`
helper, and `upsertContent` returns `SnippetWithContent` so move/rename
responses carry status too.
- A SQL-typed `getSqlSnippetById`/`useSqlSnippetByIdQuery` returns
`SnippetWithContent` (the generic `useContentIdQuery` stays for Reports,
which use it). `[id].tsx` loads content with **no casting**.
- `'new'` is attached on local creation (`createSqlSnippetSkeletonV2`).

## Behavior

Behavior-preserving for the existing auto-save flow (faithful mapping of
both old fields, including the replication-lag swallow). One incidental
fix: the read-only/saving indicator now also covers a brand-new
snippet's first save (previously only re-saves of persisted snippets had
distinct saving/failed states in some paths).

## Tests

New `sql-editor-lifecycle.test.ts` (29 tests) covering every predicate
and transition; existing rules tests updated. `pnpm --filter studio
typecheck` clean; 52 state/sql-editor unit tests pass.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **Refactor**
* Restructured SQL snippet persistence tracking, replacing boolean flags
with a comprehensive status system for clearer visibility into save
progress.
* Enhanced saving indicator UI to reflect accurate snippet save states.

* **Tests**
* Added test coverage for snippet persistence state transitions and
lifecycle scenarios.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-06-24 08:56:39 -04:00

97 lines
3.1 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 { 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]
export interface SnippetWithContent extends Snippet {
content?: SqlSnippets.Content
status: SnippetStatus
}
// 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,
})