Skip to content

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

Convert PITR restore to RQ mutation and refactor PITRSelection to use it

Joshen Lim6f5ece0f0386
diff --git a/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx b/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
index 85ba4eed382..50379e93744 100644
--- a/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
+++ b/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
@@ -1,5 +1,6 @@
import * as Tooltip from '@radix-ui/react-tooltip'
import { useQueryClient } from '@tanstack/react-query'
+import { useParams } from 'common'
import { format } from 'date-fns'
import dayjs from 'dayjs'
import { useRouter } from 'next/router'
@@ -7,13 +8,12 @@ import { useState } from 'react'
import DatePicker from 'react-datepicker'
import { Alert, Button, IconChevronLeft, IconChevronRight, IconHelpCircle, Modal } from 'ui'
-import { useParams } from 'common'
import { FormHeader, FormPanel } from 'components/ui/Forms'
import InformationBox from 'components/ui/InformationBox'
+import { usePitrRestoreMutation } from 'data/database/pitr-restore-mutation'
import { setProjectStatus } from 'data/projects/projects-query'
import { useStore } from 'hooks'
-import { post } from 'lib/common/fetch'
-import { API_URL, PROJECT_STATUS } from 'lib/constants'
+import { PROJECT_STATUS } from 'lib/constants'
import BackupsEmpty from '../BackupsEmpty'
import { Timezone } from './PITR.types'
import {
@@ -27,14 +27,25 @@ import TimeInput from './TimeInput'
import TimezoneSelection from './TimezoneSelection'
const PITRSelection = () => {
- const queryClient = useQueryClient()
const router = useRouter()
const { ref } = useParams()
+ const { backups } = useStore()
+ const queryClient = useQueryClient()
- const { ui, backups } = useStore()
-
+ const [showConfiguration, setShowConfiguration] = useState(false)
+ const [showConfirmation, setShowConfirmation] = useState(false)
const [selectedTimezone, setSelectedTimezone] = useState<Timezone>(getClientTimezone())
+ const { mutate: restoreFromPitr, isLoading: isRestoring } = usePitrRestoreMutation({
+ onSuccess: (res, variables) => {
+ setTimeout(() => {
+ setShowConfirmation(false)
+ setProjectStatus(queryClient, variables.ref, PROJECT_STATUS.RESTORING)
+ router.push(`/project/${variables.ref}`)
+ }, 3000)
+ },
+ })
+
const { earliestPhysicalBackupDateUnix, latestPhysicalBackupDateUnix } =
backups?.configuration?.physicalBackupData ?? {}
const hasNoBackupsAvailable = !earliestPhysicalBackupDateUnix || !latestPhysicalBackupDateUnix
@@ -46,10 +57,6 @@ const PITRSelection = () => {
const [selectedDateRaw, setSelectedDateRaw] = useState<Date>(latestAvailableBackup.toDate())
const selectedDate = dayjs(selectedDateRaw).tz(selectedTimezone.utc[0], true) // true to keep local time and just change +whatever
- const [showConfiguration, setShowConfiguration] = useState(false)
- const [showConfirmation, setShowConfirmation] = useState(false)
- const [isRestoring, setIsRestoring] = useState(false)
-
const isSelectedOnEarliestDay = selectedDate.isSame(earliestAvailableBackup, 'day')
const isSelectedOnLatestDay = selectedDate.isSame(latestAvailableBackup, 'day')
const availableDates = getDatesBetweenRange(earliestAvailableBackup, latestAvailableBackup)
@@ -98,28 +105,9 @@ const PITRSelection = () => {
}
const onConfirmRestore = async () => {
- if (!recoveryTimeTargetUnix) return
-
- setIsRestoring(true)
- const projectRef = ref as string
- const { error } = await post(`${API_URL}/database/${projectRef}/backups/pitr`, {
- recovery_time_target_unix: recoveryTimeTargetUnix,
- })
-
- if (error) {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to start restoration: ${error.message}`,
- })
- setIsRestoring(false)
- } else {
- setTimeout(() => {
- setShowConfirmation(false)
- setProjectStatus(queryClient, projectRef, PROJECT_STATUS.RESTORING)
- router.push(`/project/${projectRef}`)
- }, 3000)
- }
+ if (!ref) return console.error('Project ref is required')
+ if (!recoveryTimeTargetUnix) return console.error('Recovery time target unix is required')
+ restoreFromPitr({ ref, recovery_time_target_unix: recoveryTimeTargetUnix })
}
return (
diff --git a/studio/data/database/pitr-restore-mutation.ts b/studio/data/database/pitr-restore-mutation.ts
new file mode 100644
index 00000000000..b94c070e0ad
--- /dev/null
+++ b/studio/data/database/pitr-restore-mutation.ts
@@ -0,0 +1,47 @@
+import { useMutation, UseMutationOptions } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { post } from 'data/fetchers'
+import { ResponseError } from 'types'
+
+export type PitrRestoreVariables = {
+ ref: string
+ recovery_time_target_unix: number
+}
+
+export async function restoreFromPitr({ ref, recovery_time_target_unix }: PitrRestoreVariables) {
+ const { data, error } = await post('/platform/database/{ref}/backups/pitr', {
+ params: { path: { ref } },
+ body: { recovery_time_target_unix },
+ })
+ if (error) throw error
+ return data
+}
+
+type PitrRestoreData = Awaited<ReturnType<typeof restoreFromPitr>>
+
+export const usePitrRestoreMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<PitrRestoreData, ResponseError, PitrRestoreVariables>,
+ 'mutationFn'
+> = {}) => {
+ return useMutation<PitrRestoreData, ResponseError, PitrRestoreVariables>(
+ (vars) => restoreFromPitr(vars),
+ {
+ async onSuccess(data, variables, context) {
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to start PITR restoration: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}