import pgMeta from '@supabase/pg-meta' import { useQuery } from '@tanstack/react-query' import { z } from 'zod' import { executeSql } from '../sql/execute-sql-mutation' import { privilegeKeys } from './keys' import type { components } from '@/data/api' import { unguarded } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomQueryOptions } from '@/types' export type ColumnPrivilegesVariables = { projectRef?: string connectionString?: string | null /** * Required to keep this off the whole-catalog path: without it the query * aclexplodes every relation in the database across every one of its columns. */ schema: string /** * Restricts to a single relation. The UI only ever renders one table at a * time, so this keeps the query scoped to what's on screen -- without it the * whole schema's columns are fetched and all but one table discarded. The * query stays disabled until a table is selected. */ table?: string } export type ColumnPrivilege = components['schemas']['PostgresColumnPrivileges'] const pgMetaColumnPrivilegesList = pgMeta.columnPrivileges.list() type ColumnPrivilegesData = z.infer export async function getColumnPrivileges( { projectRef, connectionString, schema, table }: ColumnPrivilegesVariables, signal?: AbortSignal ) { if (!projectRef) throw new Error('projectRef is required') const sql = pgMeta.columnPrivileges.list({ includedSchemas: [schema], relationName: table, }).sql const queryKey = ['column-privileges', schema, table] const { result } = await executeSql( { projectRef, connectionString, sql, sqlOrigin: 'studio', queryName: 'column-privileges', queryKey, grant: unguarded.migrating, }, signal ) return result as ColumnPrivilegesData } export type ColumnPrivilegesError = StudioError export const useColumnPrivilegesQuery = ( vars: ColumnPrivilegesVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => { const { projectRef, schema, table } = vars return useQuery({ queryKey: privilegeKeys.columnPrivilegesList(projectRef, schema, table), queryFn: ({ signal }) => getColumnPrivileges(vars, signal), enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined' && typeof table !== 'undefined', ...options, }) }