import { getExposedTableCountsSql } 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 ExposedTableCountsVariables = { projectRef?: string connectionString?: string | null selectedSchemas: string[] } export type ExposedTableCountsResponse = { total_count: number grants_count: number } export async function getExposedTableCounts( { projectRef, connectionString, selectedSchemas }: ExposedTableCountsVariables, signal?: AbortSignal ): Promise { if (!projectRef) throw new Error('projectRef is required') if (!selectedSchemas) throw new Error('selectedSchemas is required') const sql = getExposedTableCountsSql({ selectedSchemas, ignoredSchemas: IGNORED_SCHEMAS }) const { result } = await executeSql( { projectRef, connectionString, sqlOrigin: 'studio', queryName: 'exposed-table-counts', sql, queryKey: ['exposed-table-counts', selectedSchemas], grant: unguarded.migrating, }, signal ) return result[0] as ExposedTableCountsResponse } export type ExposedTableCountsData = Awaited> export type ExposedTableCountsError = StudioError export const exposedTableCountsQueryOptions = ( { projectRef, connectionString, selectedSchemas }: ExposedTableCountsVariables, { enabled = true }: { enabled?: boolean } = {} ) => { return queryOptions({ queryKey: privilegeKeys.exposedTableCounts(projectRef, selectedSchemas), queryFn: ({ signal }) => getExposedTableCounts( { projectRef, connectionString, selectedSchemas, }, signal ), enabled: enabled && typeof projectRef !== 'undefined', }) }