import pgMeta, { type PGView } from '@supabase/pg-meta' import { useQuery } from '@tanstack/react-query' import { executeSql } from '../sql/execute-sql-mutation' import { viewKeys } from './keys' import { unguarded } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomQueryOptions } from '@/types' export type ViewsVariables = { projectRef?: string connectionString?: string | null schemas?: string[] } export async function getViews( { projectRef, connectionString, schemas }: ViewsVariables, signal?: AbortSignal ) { if (!projectRef) throw new Error('projectRef is required') const { sql } = pgMeta.views.list({ includedSchemas: schemas }) const { result } = await executeSql( { projectRef, connectionString, sqlOrigin: 'studio', queryName: 'views', sql, queryKey: ['views', schemas].filter(Boolean), grant: unguarded.migrating, }, signal ) return result as PGView[] } export type ViewsData = Awaited> export type ViewsError = StudioError export const useViewsQuery = ( { projectRef, connectionString, schemas }: ViewsVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => useQuery({ queryKey: schemas ? viewKeys.listBySchema(projectRef, schemas) : viewKeys.list(projectRef), queryFn: ({ signal }) => getViews({ projectRef, connectionString, schemas }, signal), enabled: enabled && typeof projectRef !== 'undefined', staleTime: 0, ...options, })