import { getTableEditorSql } from '@supabase/pg-meta' import { QueryClient, queryOptions, useQuery } from '@tanstack/react-query' import { tableEditorKeys } from './keys' import { Entity } from './table-editor-types' import { unguarded } from '@/data/fetchers' import { executeSql } from '@/data/sql/execute-sql-mutation' import type { StudioError } from '@/lib/errors/studio-errors' import { UseCustomQueryOptions } from '@/types' type TableEditorArgs = { id?: number } export type TableEditorVariables = TableEditorArgs & { projectRef?: string connectionString?: string | null } export async function getTableEditor( { projectRef, connectionString, id }: TableEditorVariables, signal?: AbortSignal ) { if (!id) { throw new Error('id is required') } const sql = getTableEditorSql({ id }) const { result } = await executeSql( { projectRef, connectionString, sqlOrigin: 'studio', queryName: 'table-editor', sql, queryKey: ['table-editor', id], grant: unguarded.migrating, }, signal ) return (result[0]?.entity ?? null) as Entity | undefined } export type TableEditorData = Awaited> export type TableEditorError = StudioError export const useTableEditorQuery = ( { projectRef, connectionString, id }: TableEditorVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => { return useQuery({ ...tableEditorQueryOptions({ projectRef, connectionString, id }), enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined' && !isNaN(id), refetchOnWindowFocus: false, refetchOnMount: false, staleTime: 5 * 60 * 1000, ...options, }) } export function prefetchTableEditor( client: QueryClient, { projectRef, connectionString, id }: TableEditorVariables ) { return client.fetchQuery(tableEditorQueryOptions({ projectRef, connectionString, id })) } export const tableEditorQueryOptions = ({ projectRef, connectionString, id, }: TableEditorVariables) => { return queryOptions({ queryKey: tableEditorKeys.tableEditor(projectRef, id), queryFn: ({ signal }) => getTableEditor({ projectRef, connectionString, id }, signal), }) }