import { replicationLagSql } from '@supabase/pg-meta' import { useQuery } from '@tanstack/react-query' import { replicaKeys } 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 ReplicationLagVariables = { id: string projectRef?: string connectionString?: string | null } export async function getReplicationLag( { projectRef, connectionString, id }: ReplicationLagVariables, signal?: AbortSignal ) { const sql = replicationLagSql() const { result } = await executeSql( { projectRef, connectionString, sqlOrigin: 'studio', queryName: 'replica-lag', sql, queryKey: ['replica-lag', id], grant: unguarded.migrating, }, signal ) return Number((result[0] ?? null)?.physical_replica_lag_second ?? 0) } export type ReplicationLagData = Awaited> export type ReplicationLagError = StudioError export const useReplicationLagQuery = ( { projectRef, connectionString, id }: ReplicationLagVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => useQuery({ queryKey: replicaKeys.replicaLag(projectRef, id), queryFn: ({ signal }) => getReplicationLag({ projectRef, connectionString, id }, signal), enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined', ...options, })