useIndexInvalidation.ts54 lines · main
| 1 | import { useQueryClient } from '@tanstack/react-query' |
| 2 | import { useRouter } from 'next/router' |
| 3 | import { parseAsString, useQueryStates } from 'nuqs' |
| 4 | import { useCallback } from 'react' |
| 5 | |
| 6 | import { |
| 7 | QUERY_PERFORMANCE_PRESET_MAP, |
| 8 | QUERY_PERFORMANCE_REPORT_TYPES, |
| 9 | } from '../QueryPerformance.constants' |
| 10 | import { type QueryPerformanceSort } from '../QueryPerformance.types' |
| 11 | import { useQueryPerformanceQuery } from '../useQueryPerformanceQuery' |
| 12 | import { useIndexAdvisorStatus } from './useIsIndexAdvisorStatus' |
| 13 | import { useTableIndexAdvisor } from '@/components/grid/context/TableIndexAdvisorContext' |
| 14 | import { databaseIndexesKeys } from '@/data/database-indexes/keys' |
| 15 | import { databaseKeys } from '@/data/database/keys' |
| 16 | import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject' |
| 17 | |
| 18 | export function useIndexInvalidation() { |
| 19 | const router = useRouter() |
| 20 | const queryClient = useQueryClient() |
| 21 | const { data: project } = useSelectedProjectQuery() |
| 22 | const { isIndexAdvisorEnabled } = useIndexAdvisorStatus() |
| 23 | |
| 24 | const [{ preset: urlPreset, search: searchQuery, order, sort }] = useQueryStates({ |
| 25 | sort: parseAsString, |
| 26 | search: parseAsString.withDefault(''), |
| 27 | order: parseAsString, |
| 28 | preset: parseAsString.withDefault('unified'), |
| 29 | }) |
| 30 | |
| 31 | const { invalidate: invalidateTableIndexAdvisor } = useTableIndexAdvisor() |
| 32 | |
| 33 | const preset = QUERY_PERFORMANCE_PRESET_MAP[urlPreset as QUERY_PERFORMANCE_REPORT_TYPES] |
| 34 | const orderBy = !!sort ? ({ column: sort, order } as QueryPerformanceSort) : undefined |
| 35 | const roles = router?.query?.roles ?? [] |
| 36 | |
| 37 | const queryPerformanceQuery = useQueryPerformanceQuery({ |
| 38 | searchQuery, |
| 39 | orderBy, |
| 40 | preset, |
| 41 | roles: typeof roles === 'string' ? [roles] : roles, |
| 42 | runIndexAdvisor: isIndexAdvisorEnabled, |
| 43 | }) |
| 44 | |
| 45 | return useCallback(() => { |
| 46 | queryPerformanceQuery.runQuery() |
| 47 | queryClient.invalidateQueries({ |
| 48 | queryKey: databaseKeys.indexAdvisorFromQuery(project?.ref, ''), |
| 49 | }) |
| 50 | queryClient.invalidateQueries({ queryKey: databaseIndexesKeys.list(project?.ref) }) |
| 51 | |
| 52 | invalidateTableIndexAdvisor() |
| 53 | }, [queryPerformanceQuery, queryClient, project?.ref, invalidateTableIndexAdvisor]) |
| 54 | } |