Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

1.4 KB
Raw Blame
import { replicationLagSql } from '@supabase/pg-meta'
import { useQuery } from '@tanstack/react-query'

import { replicaKeys } from './keys'
import { executeSql } from '@/data/sql/execute-sql-mutation'
import { ResponseError, 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, sql, queryKey: ['replica-lag', id] },
    signal
  )

  return Number((result[0] ?? null)?.physical_replica_lag_second ?? 0)
}

export type ReplicationLagData = Awaited<ReturnType<typeof getReplicationLag>>
export type ReplicationLagError = ResponseError

export const useReplicationLagQuery = <TData = ReplicationLagData>(
  { projectRef, connectionString, id }: ReplicationLagVariables,
  {
    enabled = true,
    ...options
  }: UseCustomQueryOptions<ReplicationLagData, ReplicationLagError, TData> = {}
) =>
  useQuery<ReplicationLagData, ReplicationLagError, TData>({
    queryKey: replicaKeys.replicaLag(projectRef, id),
    queryFn: ({ signal }) => getReplicationLag({ projectRef, connectionString, id }, signal),
    enabled: enabled && typeof projectRef !== 'undefined' && typeof id !== 'undefined',
    ...options,
  })