import { getExposedFunctionCountsSql } from '@supabase/pg-meta' import { queryOptions } from '@tanstack/react-query' import { privilegeKeys } from './keys' import { unguarded } from '@/data/fetchers' import { executeSql } from '@/data/sql/execute-sql-mutation' import { INTERNAL_SCHEMAS } from '@/hooks/useProtectedSchemas' import type { StudioError } from '@/lib/errors/studio-errors' const IGNORED_SCHEMAS = [...INTERNAL_SCHEMAS, 'pg_catalog'] export type ExposedFunctionCountsVariables = { projectRef?: string connectionString?: string | null selectedSchemas: string[] } export type ExposedFunctionCountsResponse = { total_count: number grants_count: number } export async function getExposedFunctionCounts( { projectRef, connectionString, selectedSchemas }: ExposedFunctionCountsVariables, signal?: AbortSignal ): Promise { if (!projectRef) throw new Error('projectRef is required') if (!selectedSchemas) throw new Error('selectedSchemas is required') const sql = getExposedFunctionCountsSql({ selectedSchemas, ignoredSchemas: IGNORED_SCHEMAS }) const { result } = await executeSql( { projectRef, connectionString, sqlOrigin: 'studio', queryName: 'exposed-function-counts', sql, queryKey: ['exposed-function-counts', selectedSchemas], grant: unguarded.migrating, }, signal ) return result[0] as ExposedFunctionCountsResponse } export type ExposedFunctionCountsData = Awaited> export type ExposedFunctionCountsError = StudioError export const exposedFunctionCountsQueryOptions = ( { projectRef, connectionString, selectedSchemas }: ExposedFunctionCountsVariables, { enabled = true }: { enabled?: boolean } = {} ) => { return queryOptions({ queryKey: privilegeKeys.exposedFunctionCounts(projectRef, selectedSchemas), queryFn: ({ signal }) => getExposedFunctionCounts( { projectRef, connectionString, selectedSchemas, }, signal ), enabled: enabled && typeof projectRef !== 'undefined', }) }