import { getMaxConnectionsSql } from '@supabase/pg-meta' import { useQuery } from '@tanstack/react-query' import { databaseKeys } from './keys' 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' export type MaxConnectionsVariables = { projectRef?: string connectionString?: string | null table?: string schema?: string } export async function getMaxConnections( { projectRef, connectionString }: MaxConnectionsVariables, signal?: AbortSignal ) { const sql = getMaxConnectionsSql() const { result } = await executeSql( { projectRef, connectionString, sqlOrigin: 'studio', queryName: 'max-connections', sql, queryKey: ['max-connections'], grant: unguarded.migrating, }, signal ) const connections = parseInt(result[0].max_connections) return { maxConnections: connections } } export type MaxConnectionsData = Awaited> export type MaxConnectionsError = StudioError export const useMaxConnectionsQuery = ( { projectRef, connectionString }: MaxConnectionsVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => useQuery({ queryKey: databaseKeys.maxConnections(projectRef), queryFn: ({ signal }) => getMaxConnections({ projectRef, connectionString }, signal), enabled: enabled && typeof projectRef !== 'undefined', ...options, })