Files
supabase/apps/studio/data/database-indexes/indexes-query.ts
Ivan Vasilov 8b657165b5 chore: Migrate to use custom type for ReactQuery queries and mutations (#40073)
* Add custom types for queries, mutations and infinite queries.

* Migrate all queries to use the new type.

* Migrate all infinite queries to useCustomInfiniteQueryOptions.

* Migrate all mutations to use useCustomMutationOptions.

* Add type to all imports in `types` folder.
2025-11-03 13:18:13 +01:00

67 lines
1.7 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { executeSql, ExecuteSqlError } from '../sql/execute-sql-query'
import { databaseIndexesKeys } from './keys'
import { UseCustomQueryOptions } from 'types'
type GetIndexesArgs = {
schema?: string
}
export const getIndexesSql = ({ schema }: GetIndexesArgs) => {
const sql = /* SQL */ `
SELECT schemaname as "schema",
tablename as "table",
indexname as "name",
indexdef as "definition"
FROM pg_indexes
WHERE schemaname = '${schema}';
`.trim()
return sql
}
export type DatabaseIndex = {
name: string
schema: string
table: string
definition: string
enabled: boolean
}
export type IndexesVariables = GetIndexesArgs & {
projectRef?: string
connectionString?: string | null
}
export async function getIndexes(
{ schema, projectRef, connectionString }: IndexesVariables,
signal?: AbortSignal
) {
if (!schema) {
throw new Error('schema is required')
}
const sql = getIndexesSql({ schema })
const { result } = await executeSql(
{ projectRef, connectionString, sql, queryKey: ['indexes', schema] },
signal
)
return result as DatabaseIndex[]
}
export type IndexesData = Awaited<ReturnType<typeof getIndexes>>
export type IndexesError = ExecuteSqlError
export const useIndexesQuery = <TData = IndexesData>(
{ projectRef, connectionString, schema }: IndexesVariables,
{ enabled = true, ...options }: UseCustomQueryOptions<IndexesData, IndexesError, TData> = {}
) =>
useQuery<IndexesData, IndexesError, TData>({
queryKey: databaseIndexesKeys.list(projectRef, schema),
queryFn: ({ signal }) => getIndexes({ projectRef, connectionString, schema }, signal),
enabled: enabled && typeof projectRef !== 'undefined' && typeof schema !== 'undefined',
...options,
})