Skip to content

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

feat(etl): Implement batch rollback (#41552)

Riccardo Busettic62cd07b8673
diff --git a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
index 749a3826ee8..0aaca58a6f2 100644
--- a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
@@ -19,7 +19,7 @@ import { InlineLink, InlineLinkClassName } from 'components/ui/InlineLink'
import { UpgradeToPro } from 'components/ui/UpgradeToPro'
import { useBranchCreateMutation } from 'data/branches/branch-create-mutation'
import { useBranchesQuery } from 'data/branches/branches-query'
-import { useDiskAttributesQuery } from 'data/config/disk-attributes-query'
+import { DiskAttributesData, useDiskAttributesQuery } from 'data/config/disk-attributes-query'
import { useCheckGithubBranchValidity } from 'data/integrations/github-branch-check-query'
import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'
import { projectKeys } from 'data/projects/keys'
@@ -172,7 +172,7 @@ export const CreateBranchModal = () => {
...projectDiskAttributes,
// [Joshen] JFYI for Qiao - this multiplier may eventually be dropped
size_gb: Math.round(projectDiskAttributes.size_gb * 1.5),
- }
+ } as DiskAttributesData['attributes']
const branchComputeSize = estimateComputeSize(projectDiskAttributes.size_gb, computeSize)
const estimatedDiskCost = estimateDiskCost(branchDiskAttributes)
diff --git a/apps/studio/components/interfaces/Database/Replication/BatchRestartDialog.tsx b/apps/studio/components/interfaces/Database/Replication/BatchRestartDialog.tsx
new file mode 100644
index 00000000000..13a11344b17
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Replication/BatchRestartDialog.tsx
@@ -0,0 +1,162 @@
+import { useMemo } from 'react'
+import { toast } from 'sonner'
+
+import { ReplicationPipelineTableStatus } from '@/data/replication/pipeline-replication-status-query'
+import { useParams } from 'common'
+import { useRollbackTablesMutation } from 'data/replication/rollback-tables-mutation'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from 'ui'
+
+interface BatchRestartDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ mode: 'all' | 'errored'
+ totalTables: number
+ erroredTablesCount: number
+ tables: ReplicationPipelineTableStatus[]
+ onRestartStart?: (tableIds: number[]) => void
+ onRestartComplete?: (tableIds: number[]) => void
+}
+
+export const BatchRestartDialog = ({
+ open,
+ onOpenChange,
+ mode,
+ totalTables,
+ erroredTablesCount,
+ tables,
+ onRestartStart,
+ onRestartComplete,
+}: BatchRestartDialogProps) => {
+ const { ref: projectRef, pipelineId: _pipelineId } = useParams()
+ const pipelineId = Number(_pipelineId)
+
+ // Calculate which table IDs will be restarted based on mode (memoized)
+ const affectedTableIds = useMemo(() => {
+ if (mode === 'all') {
+ return tables.map((t) => t.table_id)
+ } else {
+ return tables
+ .filter(
+ (t) =>
+ t.state.name === 'error' &&
+ 'retry_policy' in t.state &&
+ t.state.retry_policy?.policy === 'manual_retry'
+ )
+ .map((t) => t.table_id)
+ }
+ }, [mode, tables])
+
+ const { mutate: rollbackTables, isPending: isResetting } = useRollbackTablesMutation({
+ onSuccess: (data) => {
+ const count = data.tables.length
+ toast.success(
+ `Restarting replication for ${count} table${count > 1 ? 's' : ''}. Pipeline will restart automatically.`
+ )
+ onRestartComplete?.(affectedTableIds)
+ onOpenChange(false)
+ },
+ onError: (error) => {
+ toast.error(`Failed to restart replication: ${error.message}`)
+ onRestartComplete?.(affectedTableIds)
+ onOpenChange(false)
+ },
+ })
+
+ const handleReset = () => {
+ if (!projectRef) return toast.error('Project ref is required')
+
+ onRestartStart?.(affectedTableIds)
+
+ rollbackTables({
+ projectRef,
+ pipelineId,
+ target: mode === 'all' ? { type: 'all_tables' } : { type: 'all_errored_tables' },
+ rollbackType: 'full',
+ })
+ }
+
+ const dialogContent =
+ mode === 'all'
+ ? {
+ title: 'Restart all tables',
+ description: (
+ <div className="space-y-3 text-sm">
+ <p>
+ This will restart replication for <strong>all {totalTables} tables</strong> in this
+ pipeline from scratch:
+ </p>
+ <ul className="list-disc list-inside space-y-1.5 pl-2">
+ <li>
+ <strong>All table copies will be re-initialized.</strong> Every table will be
+ copied again from the source.
+ </li>
+ <li>
+ <strong>All downstream data will be deleted.</strong> All replicated data will be
+ removed.
+ </li>
+ <li>
+ <strong>The pipeline will restart automatically.</strong> This is required to
+ apply this change.
+ </li>
+ </ul>
+ </div>
+ ),
+ action: 'Restart all tables',
+ }
+ : {
+ title: 'Restart failed tables',
+ description: (
+ <div className="space-y-3 text-sm">
+ <p>
+ This will restart replication for{' '}
+ <strong>all {erroredTablesCount} failed tables</strong> from scratch:
+ </p>
+ <ul className="list-disc list-inside space-y-1.5 pl-2">
+ <li>
+ <strong>Failed table copies will be re-initialized.</strong> These tables will be
+ copied again from the source.
+ </li>
+ <li>
+ <strong>Existing downstream data will be deleted.</strong> Replicated data for
+ these tables will be removed.
+ </li>
+ <li>
+ <strong>All other tables remain untouched.</strong> Only failed tables are
+ affected.
+ </li>
+ <li>
+ <strong>The pipeline will restart automatically.</strong> This is required to
+ apply this change.
+ </li>
+ </ul>
+ </div>
+ ),
+ action: 'Restart failed tables',
+ }
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{dialogContent.title}</AlertDialogTitle>
+ <AlertDialogDescription asChild>{dialogContent.description}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={isResetting}>Cancel</AlertDialogCancel>
+ <AlertDialogAction disabled={isResetting} onClick={handleReset} variant="warning">
+ {isResetting ? 'Restarting replication...' : dialogContent.action}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx b/apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx
index 86bb4dbfbf1..7b5091a01b4 100644
--- a/apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/DestinationRow.tsx
@@ -1,4 +1,3 @@
-import { AlertCircle } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
@@ -17,7 +16,7 @@ import {
usePipelineRequestStatus,
} from 'state/replication-pipeline-request-status'
import type { ResponseError } from 'types'
-import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import { Button, Tooltip, TooltipContent, TooltipTrigger, WarningIcon } from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { DeleteDestination } from './DeleteDestination'
import { DestinationPanel } from './DestinationPanel/DestinationPanel'
@@ -178,22 +177,19 @@ export const DestinationRow = ({
</Table.td>
<Table.td>
<div className="flex items-center justify-end gap-x-2">
+ {hasTableErrors && (
+ <Tooltip>
+ <TooltipTrigger>
+ <WarningIcon />
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {errorCount} table{errorCount === 1 ? '' : 's'} encountered replication errors
+ </TooltipContent>
+ </Tooltip>
+ )}
<Button asChild type="default" className="relative">
<Link href={`/project/${projectRef}/database/replication/${pipeline?.id}`}>
- <span className="inline-flex items-center gap-2">
- <span>View status</span>
- {hasTableErrors && (
- <Tooltip>
- <TooltipTrigger>
- <AlertCircle size={14} />
- </TooltipTrigger>
- <TooltipContent side="bottom">
- {errorCount} table{errorCount === 1 ? '' : 's'} encountered replication
- errors
- </TooltipContent>
- </Tooltip>
- )}
- </span>
+ View replication
</Link>
</Button>
<RowMenu
diff --git a/apps/studio/components/interfaces/Database/Replication/ErrorDetailsButton.tsx b/apps/studio/components/interfaces/Database/Replication/ErrorDetailsButton.tsx
deleted file mode 100644
index 7ff4ce5205c..00000000000
--- a/apps/studio/components/interfaces/Database/Replication/ErrorDetailsButton.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { AlertCircle } from 'lucide-react'
-import {
- Button,
- cn,
- CodeBlock,
- Dialog,
- DialogClose,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogSection,
- DialogSectionSeparator,
- DialogTitle,
- DialogTrigger,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from 'ui'
-
-interface ErrorDetailsButtonProps {
- tableName: string
- reason: string
- solution?: string
-}
-
-export const ErrorDetailsButton = ({ tableName, reason, solution }: ErrorDetailsButtonProps) => {
- return (
- <Dialog>
- <DialogTrigger asChild>
- <Button size="tiny" type="default" className="w-min" aria-label="Show error details">
- Show error
- </Button>
- </DialogTrigger>
- <DialogContent size="xlarge" aria-describedby={undefined}>
- <DialogHeader>
- <DialogTitle>Replication error on "{tableName}"</DialogTitle>
- </DialogHeader>
- <DialogSectionSeparator />
- <DialogSection className="!p-0">
- <div className="px-4 py-3">
- <p className="text-sm text-foreground-light">
- The following error occurred during replication:
- </p>
- </div>
- <CodeBlock
- hideLineNumbers
- wrapLines={false}
- wrapperClassName={cn(
- '[&_pre]:px-4 [&_pre]:py-3 [&>pre]:border-x-0 [&>pre]:rounded-none'
- )}
- language="bash"
- value={reason}
- className="[&_code]:text-xs [&_code]:text-foreground [&_span]:!text-foreground"
- />
- {/* Solution if available */}
- {solution && (
- <div className="px-4 py-3">
- <p className="text-sm">{solution}</p>
- </div>
- )}
- </DialogSection>
- <DialogFooter>
- <DialogClose>
- <Button type="default">Close</Button>
- </DialogClose>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-
- return (
- <Tooltip delayDuration={0}>
- <TooltipTrigger asChild>
- <Button
- size="tiny"
- type="default"
- className="w-min"
- icon={<AlertCircle size={14} />}
- aria-label="Show error details"
- >
- Show Error
- </Button>
- </TooltipTrigger>
- <TooltipContent
- side="bottom"
- align="start"
- className="w-[500px] max-w-[90vw] max-h-[400px] p-0 overflow-hidden"
- >
- <div className="flex flex-col gap-y-3 p-4 max-h-[400px] overflow-y-auto">
- {/* Error message */}
- <div>
- <div className="text-xs font-medium mb-2">Error</div>
- <div className="bg-surface-100 rounded p-2 max-h-[250px] overflow-y-auto">
- <pre className="text-xs font-mono whitespace-pre-wrap break-words">{reason}</pre>
- </div>
- </div>
-
- {/* Solution if available */}
- {solution && (
- <div>
- <div className="text-xs font-medium mb-2">Solution</div>
- <p className="text-xs">{solution}</p>
- </div>
- )}
- </div>
- </TooltipContent>
- </Tooltip>
- )
-}
diff --git a/apps/studio/components/interfaces/Database/Replication/ErrorDetailsDialog.tsx b/apps/studio/components/interfaces/Database/Replication/ErrorDetailsDialog.tsx
new file mode 100644
index 00000000000..799f225e258
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Replication/ErrorDetailsDialog.tsx
@@ -0,0 +1,69 @@
+import {
+ Button,
+ cn,
+ CodeBlock,
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogSection,
+ DialogSectionSeparator,
+ DialogTitle,
+} from 'ui'
+
+interface ErrorDetailsDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ tableName: string
+ reason: string
+ solution?: string
+}
+
+export const ErrorDetailsDialog = ({
+ open,
+ onOpenChange,
+ tableName,
+ reason,
+ solution,
+}: ErrorDetailsDialogProps) => {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent size="xlarge" aria-describedby={undefined}>
+ <DialogHeader>
+ <DialogTitle>
+ Replication error on <code className="text-code-inline">{tableName}</code>
+ </DialogTitle>
+ </DialogHeader>
+ <DialogSectionSeparator />
+ <DialogSection className="!p-0">
+ <div className="px-4 py-3">
+ <p className="text-sm text-foreground-light">
+ The following error occurred during replication:
+ </p>
+ </div>
+ <CodeBlock
+ hideLineNumbers
+ wrapLines={false}
+ wrapperClassName={cn(
+ '[&_pre]:px-4 [&_pre]:py-3 [&>pre]:border-x-0 [&>pre]:rounded-none'
+ )}
+ language="bash"
+ value={reason}
+ className="[&_code]:text-xs [&_code]:text-foreground [&_span]:!text-foreground"
+ />
+ {solution && (
+ <div className="px-4 py-3">
+ <p className="text-sm">{solution}</p>
+ </div>
+ )}
+ </DialogSection>
+ <DialogFooter>
+ <DialogClose>
+ <Button type="default">Close</Button>
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Replication/ErroredTableDetails.tsx b/apps/studio/components/interfaces/Database/Replication/ErroredTableDetails.tsx
index 666766af7f2..e4f01c69bcb 100644
--- a/apps/studio/components/interfaces/Database/Replication/ErroredTableDetails.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/ErroredTableDetails.tsx
@@ -1,19 +1,19 @@
+import { ReplicationPipelineTableStatus } from '@/data/replication/pipeline-replication-status-query'
import { useParams } from 'common'
import { InlineLink } from 'components/ui/InlineLink'
-import { ErrorDetailsButton } from './ErrorDetailsButton'
-import { TableState } from './ReplicationPipelineStatus/ReplicationPipelineStatus.types'
+import { CriticalIcon } from 'ui'
import { isValidRetryPolicy } from './ReplicationPipelineStatus/ReplicationPipelineStatus.utils'
-import { ResetTableButton } from './ResetTableButton'
import { RetryCountdown } from './RetryCountdown'
interface ErroredTableDetailsProps {
- state: Extract<TableState['state'], { name: 'error' }>
- tableName: string
- tableId: number
+ table: ReplicationPipelineTableStatus
}
-export const ErroredTableDetails = ({ state, tableName, tableId }: ErroredTableDetailsProps) => {
+export const ErroredTableDetails = ({ table }: ErroredTableDetailsProps) => {
const { ref: projectRef } = useParams()
+
+ const state = table.state as Extract<ReplicationPipelineTableStatus['state'], { name: 'error' }>
+ const tableName = table.table_name
const retryPolicy = state.retry_policy.policy
if (!isValidRetryPolicy(state.retry_policy)) {
@@ -41,43 +41,35 @@ export const ErroredTableDetails = ({ state, tableName, tableId }: ErroredTableD
>
support
</InlineLink>
- . Alternatively, you may also recreate the pipeline.
+ . Alternatively, you may also recreate the pipeline. Use the table actions menu on the
+ right to view the full error details.
</p>
- <ErrorDetailsButton
- tableName={tableName}
- reason={state.reason}
- solution={state.solution}
- />
</div>
) : retryPolicy === 'manual_retry' ? (
- <div className="flex flex-col gap-y-3 text-foreground-lighter">
- <div>
- <p className="text-xs">
- {state.solution}
- {state.solution && !/[.!?]$/.test(state.solution.trim()) && '.'}
- </p>
- <p className="text-xs">You can reset the table to start replication from scratch.</p>
- </div>
- <div className="flex items-center gap-x-2">
- <ResetTableButton tableId={tableId} tableName={tableName} />
- <ErrorDetailsButton
- tableName={tableName}
- reason={state.reason}
- solution={state.solution}
- />
+ <div className="flex flex-col gap-y-3">
+ <div className="rounded-md border border-destructive-400 bg-destructive-100 px-3 py-3 space-y-2">
+ <div className="flex items-start gap-x-2">
+ <CriticalIcon />
+ <div className="flex-1 text-xs text-destructive-900">
+ <p className="font-semibold mb-1">Action required to continue replication</p>
+ <p className="text-foreground-light">
+ {state.solution}
+ {state.solution && !/[.!?]$/.test(state.solution.trim()) && '.'}
+ </p>
+ <p className="text-foreground-light mt-2">
+ Restart table replication from the table actions menu on the right. The pipeline
+ will restart automatically.
+ </p>
+ </div>
+ </div>
</div>
</div>
) : retryPolicy === 'timed_retry' ? (
<div className="flex flex-col text-foreground-lighter gap-y-3">
<p className="text-xs">
- A retry will be triggered automatically by restarting the pipeline on this table.
+ Replication will retry automatically. The pipeline will restart to apply the retry.
</p>
<RetryCountdown nextRetryTime={state.retry_policy.next_retry} />
- <ErrorDetailsButton
- tableName={tableName}
- reason={state.reason}
- solution={state.solution}
- />
</div>
) : null}
</div>
diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.tsx b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.tsx
index 2d50cdd14d7..203f867f277 100644
--- a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.tsx
+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/ReplicationPipelineStatus.tsx
@@ -2,8 +2,8 @@ import {
Activity,
ArrowUpCircle,
Ban,
+ ChevronDown,
ChevronLeft,
- ExternalLink,
Info,
Pause,
Play,
@@ -14,13 +14,11 @@ import {
} from 'lucide-react'
import Link from 'next/link'
import { parseAsString, useQueryState } from 'nuqs'
-import { useEffect, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
-import Table from 'components/to-be-cleaned/Table'
import AlertError from 'components/ui/AlertError'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useReplicationPipelineByIdQuery } from 'data/replication/pipeline-by-id-query'
import { useReplicationPipelineReplicationStatusQuery } from 'data/replication/pipeline-replication-status-query'
import { useReplicationPipelineStatusQuery } from 'data/replication/pipeline-status-query'
@@ -32,21 +30,37 @@ import {
PipelineStatusRequestStatus,
usePipelineRequestStatus,
} from 'state/replication-pipeline-request-status'
-import { Badge, Button, cn } from 'ui'
+import {
+ Button,
+ Card,
+ CardContent,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Table,
+ TableBody,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from 'ui'
import { GenericSkeletonLoader } from 'ui-patterns'
import { Input } from 'ui-patterns/DataInputs/Input'
-import { ErroredTableDetails } from '../ErroredTableDetails'
+import { BatchRestartDialog } from '../BatchRestartDialog'
+import { ErrorDetailsDialog } from '../ErrorDetailsDialog'
import {
+ getStatusName,
PIPELINE_ACTIONABLE_STATES,
PIPELINE_ERROR_MESSAGES,
- getStatusName,
} from '../Pipeline.utils'
import { PipelineStatus } from '../PipelineStatus'
import { PipelineStatusName, STATUS_REFRESH_FREQUENCY_MS } from '../Replication.constants'
+import { RestartTableDialog } from '../RestartTableDialog'
import { UpdateVersionModal } from '../UpdateVersionModal'
-import { SlotLagMetrics, TableState } from './ReplicationPipelineStatus.types'
-import { getDisabledStateConfig, getStatusConfig } from './ReplicationPipelineStatus.utils'
+import { SlotLagMetrics } from './ReplicationPipelineStatus.types'
+import { getDisabledStateConfig } from './ReplicationPipelineStatus.utils'
import { SlotLagMetricsInline, SlotLagMetricsList } from './SlotLagMetrics'
+import { TableReplicationRow } from './TableReplicationRow'
/**
* Component for displaying replication pipeline status and table replication details.
@@ -57,6 +71,20 @@ export const ReplicationPipelineStatus = () => {
const [searchString, setSearchString] = useQueryState('search', parseAsString.withDefault(''))
const [showUpdateVersionModal, setShowUpdateVersionModal] = useState(false)
+ const [showErrorDialog, setShowErrorDialog] = useState(false)
+ const [selectedTableError, setSelectedTableError] = useState<{
+ tableName: string
+ reason: string
+ solution?: string
+ } | null>(null)
+ const [showRestartDialog, setShowRestartDialog] = useState(false)
+ const [selectedTableForRestart, setSelectedTableForRestart] = useState<{
+ tableId: number
+ tableName: string
+ } | null>(null)
+ const [showBatchRestartDialog, setShowBatchRestartDialog] = useState(false)
+ const [batchRestartMode, setBatchRestartMode] = useState<'all' | 'errored' | null>(null)
+ const [restartingTableIds, setRestartingTableIds] = useState<Set<number>>(new Set())
const pipelineId = Number(_pipelineId)
const { getRequestStatus, updatePipelineStatus, setRequestStatus } = usePipelineRequestStatus()
@@ -112,15 +140,46 @@ export const ReplicationPipelineStatus = () => {
const statusName = getStatusName(pipelineStatusData?.status)
const config = getDisabledStateConfig({ requestStatus, statusName })
- const tableStatuses = replicationStatusData?.table_statuses || []
+ // Sort tables by name for consistent ordering (memoized)
+ const tableStatuses = useMemo(
+ () =>
+ (replicationStatusData?.table_statuses || []).sort((a, b) =>
+ a.table_name.localeCompare(b.table_name)
+ ),
+ [replicationStatusData?.table_statuses]
+ )
+
const applyLagMetrics = replicationStatusData?.apply_lag
- const filteredTableStatuses =
- searchString.length === 0
- ? tableStatuses
- : tableStatuses.filter((table) =>
- table.table_name.toLowerCase().includes(searchString.toLowerCase())
- )
- const tablesWithLag = tableStatuses.filter((table) => Boolean(table.table_sync_lag))
+
+ // Filter tables based on search (memoized)
+ const filteredTableStatuses = useMemo(
+ () =>
+ searchString.length === 0
+ ? tableStatuses
+ : tableStatuses.filter((table) =>
+ table.table_name.toLowerCase().includes(searchString.toLowerCase())
+ ),
+ [tableStatuses, searchString]
+ )
+
+ const tablesWithLag = useMemo(
+ () => tableStatuses.filter((table) => Boolean(table.table_sync_lag)),
+ [tableStatuses]
+ )
+
+ const erroredTables = useMemo(
+ () =>
+ tableStatuses.filter(
+ (table) =>
+ table.state.name === 'error' &&
+ 'retry_policy' in table.state &&
+ table.state.retry_policy?.policy === 'manual_retry'
+ ),
+ [tableStatuses]
+ )
+
+ const hasErroredTables = erroredTables.length > 0
+ const isAnyRestartInProgress = restartingTableIds.size > 0
const isPipelineRunning = statusName === 'started'
const hasTableData = tableStatuses.length > 0
@@ -145,7 +204,7 @@ export const ReplicationPipelineStatus = () => {
? 'Stop'
: statusName === 'failed'
? 'Restart'
- : 'Action unavailable'
+ : statusName
const icon =
statusName === 'stopped' ? (
@@ -184,7 +243,7 @@ export const ReplicationPipelineStatus = () => {
return (
<>
- <div className="space-y-4">
+ <div className="flex flex-col gap-y-4">
<div className="flex items-center justify-between">
<div className="flex items-center gap-x-3">
<Button asChild type="outline" icon={<ChevronLeft />} style={{ padding: '5px' }}>
@@ -214,27 +273,6 @@ export const ReplicationPipelineStatus = () => {
Update available
</Button>
)}
- <Input
- icon={<Search />}
- className="text-xs"
- placeholder="Search for tables"
- value={searchString}
- disabled={isPipelineError}
- onChange={(e) => setSearchString(e.target.value)}
- actions={
- searchString.length > 0
- ? [
- <X
- key="close"
- className="mx-2 cursor-pointer text-foreground"
- size={14}
- strokeWidth={1.5}
- onClick={() => setSearchString('')}
- />,
- ]
- : undefined
- }
- />
<Button asChild type="default">
<Link href={logsUrl}>View logs</Link>
@@ -249,6 +287,7 @@ export const ReplicationPipelineStatus = () => {
!PIPELINE_ACTIONABLE_STATES.includes(statusName as PipelineStatusName)
}
icon={icon}
+ className="capitalize"
>
{label}
</Button>
@@ -266,30 +305,6 @@ export const ReplicationPipelineStatus = () => {
</div>
)}
- {showDisabledState && (
- <div
- className={cn(
- 'p-4 border border-default rounded-lg flex items-center justify-between',
- config.colors.bg
- )}
- >
- <div className="flex items-center gap-x-3">
- <div
- className={cn(
- 'w-10 h-10 rounded-full flex items-center justify-center',
- config.colors.iconBg
- )}
- >
- <div className={config.colors.icon}>{config.icon}</div>
- </div>
- <div className="flex-1">
- <h4 className={`text-sm font-medium ${config.colors.text}`}>{config.title}</h4>
- <p className={`text-sm ${config.colors.subtext}`}>{config.message}</p>
- </div>
- </div>
- </div>
- )}
-
{(isPipelineLoading || isStatusLoading) && (
<div className="space-y-3">
<div className="flex items-center gap-x-3">
@@ -353,87 +368,119 @@ export const ReplicationPipelineStatus = () => {
{hasTableData && (
<div className="flex flex-col gap-y-3">
- <div className="w-full overflow-hidden overflow-x-auto">
- {/* [Joshen] Should update to use new Table components next time */}
- <Table
- head={[
- <Table.th key="table">Table</Table.th>,
- <Table.th key="status">Status</Table.th>,
- <Table.th key="details">Details</Table.th>,
- ]}
- body={
- <>
- {filteredTableStatuses.length === 0 && hasTableData && (
- <Table.tr>
- <Table.td colSpan={3}>
- <div className="space-y-1">
- <p className="text-sm text-foreground">No results found</p>
- <p className="text-sm text-foreground-light">
- Your search for "{searchString}" did not return any results
- </p>
- </div>
- </Table.td>
- </Table.tr>
- )}
- {filteredTableStatuses.map((table, index) => {
- const statusConfig = getStatusConfig(table.state as TableState['state'])
- return (
- <Table.tr key={`${table.table_name}-${index}`} className="border-t">
- <Table.td className="align-top">
- <div className="flex items-center gap-x-2">
- <p>{table.table_name}</p>
-
- <ButtonTooltip
- asChild
- type="text"
- className="px-1.5"
- icon={<ExternalLink />}
- tooltip={{
- content: { side: 'bottom', text: 'Open in Table Editor' },
- }}
- >
- <Link
- target="_blank"
- rel="noopener noreferrer"
- href={`/project/${projectRef}/editor/${table.table_id}`}
- />
- </ButtonTooltip>
- </div>
- </Table.td>
- <Table.td className="align-top">
- {showDisabledState ? (
- <Badge variant="default">Not Available</Badge>
- ) : (
- statusConfig.badge
- )}
- </Table.td>
- <Table.td className="align-top">
- {showDisabledState ? (
- <p className="text-sm text-foreground-lighter">
- Status unavailable while pipeline is {config.badge.toLowerCase()}
- </p>
- ) : (
- <div className="flex flex-col gap-y-2">
- <div className="text-sm text-foreground">
- {statusConfig.description}
- </div>
- {table.state.name === 'error' && (
- <ErroredTableDetails
- state={table.state}
- tableName={table.table_name}
- tableId={table.table_id}
- />
- )}
- </div>
- )}
- </Table.td>
- </Table.tr>
- )
- })}
- </>
+ <div className="flex items-center justify-between">
+ <Input
+ icon={<Search />}
+ size="tiny"
+ className="text-xs w-52"
+ placeholder="Search for tables"
+ value={searchString}
+ disabled={isPipelineError}
+ onChange={(e) => setSearchString(e.target.value)}
+ actions={
+ searchString.length > 0 && [
+ <X
+ key="close"
+ className="mx-2 cursor-pointer text-foreground"
+ size={14}
+ strokeWidth={1.5}
+ onClick={() => setSearchString('')}
+ />,
+ ]
}
/>
+ {!showDisabledState && (
+ <div className="flex items-center">
+ <Button
+ size="tiny"
+ type="default"
+ className="rounded-r-none hover:z-[2]"
+ icon={<RotateCcw />}
+ disabled={tableStatuses.length === 0 || isAnyRestartInProgress}
+ loading={isAnyRestartInProgress}
+ onClick={() => {
+ setBatchRestartMode('all')
+ setShowBatchRestartDialog(true)
+ }}
+ >
+ Restart all tables
+ </Button>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="default"
+ icon={<ChevronDown />}
+ className="w-7 rounded-l-none -ml-[1px]"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem
+ disabled={!hasErroredTables || isAnyRestartInProgress}
+ onClick={() => {
+ setBatchRestartMode('errored')
+ setShowBatchRestartDialog(true)
+ }}
+ >
+ Restart failed tables only
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
</div>
+
+ <Card>
+ <CardContent className="p-0">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead key="table">Table</TableHead>
+ <TableHead key="status">Status</TableHead>
+ <TableHead key="details">Details</TableHead>
+ <TableHead key="actions" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {filteredTableStatuses.map((table) => {
+ const isRestarting = restartingTableIds.has(table.table_id)
+ const isErrorState = table.state.name === 'error'
+ const errorReason =
+ isErrorState && 'reason' in table.state ? table.state.reason : undefined
+ const errorSolution =
+ isErrorState && 'solution' in table.state ? table.state.solution : undefined
+ return (
+ <TableReplicationRow
+ key={table.table_id}
+ table={table}
+ config={config}
+ isRestarting={isRestarting}
+ showDisabledState={showDisabledState}
+ onSelectRestart={() => {
+ setSelectedTableForRestart({
+ tableId: table.table_id,
+ tableName: table.table_name,
+ })
+ setShowRestartDialog(true)
+ }}
+ onSelectShowError={
+ isErrorState && errorReason
+ ? () => {
+ setSelectedTableError({
+ tableName: table.table_name,
+ reason: errorReason,
+ solution: errorSolution,
+ })
+ setShowErrorDialog(true)
+ }
+ : () => {}
+ }
+ />
+ )
+ })}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
</div>
)}
@@ -472,6 +519,59 @@ export const ReplicationPipelineStatus = () => {
: 'Update version'
}
/>
+
+ {/* Restart Table Confirmation Dialog */}
+ {selectedTableForRestart && (
+ <RestartTableDialog
+ open={showRestartDialog}
+ onOpenChange={setShowRestartDialog}
+ tableId={selectedTableForRestart.tableId}
+ tableName={selectedTableForRestart.tableName}
+ onRestartStart={() => {
+ setRestartingTableIds((prev) => new Set(prev).add(selectedTableForRestart.tableId))
+ }}
+ onRestartComplete={() => {
+ setRestartingTableIds((prev) => {
+ const next = new Set(prev)
+ next.delete(selectedTableForRestart.tableId)
+ return next
+ })
+ }}
+ />
+ )}
+
+ {/* Error Details Dialog */}
+ {selectedTableError && (
+ <ErrorDetailsDialog
+ open={showErrorDialog}
+ onOpenChange={setShowErrorDialog}
+ tableName={selectedTableError.tableName}
+ reason={selectedTableError.reason}
+ solution={selectedTableError.solution}
+ />
+ )}
+
+ {/* Batch Restart Dialog */}
+ {batchRestartMode && (
+ <BatchRestartDialog
+ open={showBatchRestartDialog}
+ onOpenChange={setShowBatchRestartDialog}
+ mode={batchRestartMode}
+ totalTables={tableStatuses.length}
+ erroredTablesCount={erroredTables.length}
+ tables={tableStatuses}
+ onRestartStart={(tableIds) => {
+ setRestartingTableIds((prev) => new Set([...prev, ...tableIds]))
+ }}
+ onRestartComplete={(tableIds) => {
+ setRestartingTableIds((prev) => {
+ const next = new Set(prev)
+ tableIds.forEach((id) => next.delete(id))
+ return next
+ })
+ }}
+ />
+ )}
</>
)
}
diff --git a/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/TableReplicationRow.tsx b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/TableReplicationRow.tsx
new file mode 100644
index 00000000000..d1d41159076
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Replication/ReplicationPipelineStatus/TableReplicationRow.tsx
@@ -0,0 +1,113 @@
+import { ExternalLink, RotateCcw } from 'lucide-react'
+import Link from 'next/link'
+
+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
+import { InlineLinkClassName } from '@/components/ui/InlineLink'
+import { ReplicationPipelineTableStatus } from '@/data/replication/pipeline-replication-status-query'
+import { useParams } from 'common'
+import { Badge, Button, cn, TableCell, TableRow, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import { ErroredTableDetails } from '../ErroredTableDetails'
+import { TableState } from './ReplicationPipelineStatus.types'
+import { getDisabledStateConfig, getStatusConfig } from './ReplicationPipelineStatus.utils'
+
+interface TableReplicationRowProps {
+ table: ReplicationPipelineTableStatus
+ config: ReturnType<typeof getDisabledStateConfig>
+ isRestarting: boolean
+ showDisabledState: boolean
+ onSelectRestart: () => void
+ onSelectShowError: () => void
+}
+
+export const TableReplicationRow = ({
+ table,
+ config,
+ isRestarting,
+ showDisabledState,
+ onSelectRestart,
+ onSelectShowError,
+}: TableReplicationRowProps) => {
+ const { ref } = useParams()
+ const isErrorState = table.state.name === 'error'
+ const statusConfig = getStatusConfig(table.state as TableState['state'])
+
+ return (
+ <TableRow>
+ <TableCell className="align-top">
+ <div className="flex items-center gap-x-2">
+ <p className={cn(isRestarting && 'text-foreground-light')}>{table.table_name}</p>
+
+ <ButtonTooltip
+ asChild
+ type="text"
+ className="px-1.5"
+ icon={<ExternalLink />}
+ tooltip={{
+ content: { side: 'bottom', text: 'Open in Table Editor' },
+ }}
+ >
+ <Link
+ target="_blank"
+ rel="noopener noreferrer"
+ href={`/project/${ref}/editor/${table.table_id}`}
+ />
+ </ButtonTooltip>
+ </div>
+ </TableCell>
+
+ <TableCell className="align-top">
+ {isRestarting ? (
+ <Badge variant="default">Restarting</Badge>
+ ) : showDisabledState ? (
+ <Badge variant="default">Not Available</Badge>
+ ) : (
+ statusConfig.badge
+ )}
+ </TableCell>
+
+ <TableCell className="align-top">
+ {isRestarting ? (
+ <p className="text-sm text-foreground-lighter">
+ Replication is being restarted for this table. The pipeline will restart automatically.
+ </p>
+ ) : showDisabledState ? (
+ <p className="text-sm text-foreground-lighter">
+ Status unavailable while pipeline is {config.badge.toLowerCase()}
+ </p>
+ ) : (
+ <div className="flex flex-col gap-y-3">
+ <div className="text-sm text-foreground">
+ {statusConfig.description}{' '}
+ {isErrorState && 'reason' in table.state && (
+ <button className={InlineLinkClassName} onClick={() => onSelectShowError()}>
+ View error.
+ </button>
+ )}
+ </div>
+ {table.state.name === 'error' && <ErroredTableDetails table={table} />}
+ </div>
+ )}
+ </TableCell>
+
+ <TableCell className="align-top">
+ <div className="flex items-center justify-end">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="default"
+ className="w-7"
+ icon={<RotateCcw />}
+ disabled={showDisabledState || isRestarting}
+ aria-label={`Restart replication for ${table.table_name}`}
+ onClick={onSelectRestart}
+ />
+ </TooltipTrigger>
+ <TooltipContent side="bottom" align="center">
+ Restart table replication
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </TableCell>
+ </TableRow>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Replication/ResetTableButton.tsx b/apps/studio/components/interfaces/Database/Replication/ResetTableButton.tsx
deleted file mode 100644
index 6c399ae2bf4..00000000000
--- a/apps/studio/components/interfaces/Database/Replication/ResetTableButton.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-import { RotateCcw } from 'lucide-react'
-import { useState } from 'react'
-import { toast } from 'sonner'
-
-import { useParams } from 'common'
-import { useTableReset } from 'data/replication/use-table-reset'
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- Button,
-} from 'ui'
-
-interface ResetTableButtonProps {
- tableId: number
- tableName: string
-}
-
-export const ResetTableButton = ({ tableId, tableName }: ResetTableButtonProps) => {
- const { ref: projectRef, pipelineId: _pipelineId } = useParams()
- const [isOpen, setIsOpen] = useState(false)
-
- const { resetTable, isRollingBack, isRestartingPipeline, isResetting } = useTableReset({
- tableName,
- onSuccess: () => setIsOpen(false),
- onError: () => setIsOpen(false),
- })
-
- const handleReset = () => {
- if (!projectRef) return toast.error('Project ref is required')
- if (!_pipelineId) return toast.error('Pipeline ID is required')
-
- const pipelineId = Number(_pipelineId)
-
- resetTable({
- projectRef,
- pipelineId,
- tableId,
- rollbackType: 'full',
- })
- }
-
- return (
- <AlertDialog open={isOpen} onOpenChange={setIsOpen}>
- <Button
- size="tiny"
- type="default"
- loading={isResetting}
- disabled={isResetting}
- className="w-min"
- icon={<RotateCcw />}
- aria-label={`Reset and restart table ${tableName}`}
- onClick={() => setIsOpen(true)}
- >
- Reset table and restart
- </Button>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Reset table and restart</AlertDialogTitle>
- <AlertDialogDescription>
- This will reset replication for <code className="text-code-inline">{tableName}</code>{' '}
- only. The table will be copied again from scratch, and any existing downstream data for
- it will be deleted. Other tables in the pipeline are not affected, but the pipeline will
- restart to apply this reset.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel disabled={isResetting}>Cancel</AlertDialogCancel>
- <AlertDialogAction disabled={isResetting} onClick={handleReset} variant="danger">
- {isRollingBack
- ? 'Resetting table...'
- : isRestartingPipeline
- ? 'Restarting pipeline...'
- : 'Reset and restart'}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- )
-}
diff --git a/apps/studio/components/interfaces/Database/Replication/RestartTableDialog.tsx b/apps/studio/components/interfaces/Database/Replication/RestartTableDialog.tsx
new file mode 100644
index 00000000000..9b886760791
--- /dev/null
+++ b/apps/studio/components/interfaces/Database/Replication/RestartTableDialog.tsx
@@ -0,0 +1,106 @@
+import { toast } from 'sonner'
+
+import { useParams } from 'common'
+import { useRollbackTablesMutation } from 'data/replication/rollback-tables-mutation'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from 'ui'
+
+interface RestartTableDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ tableId: number
+ tableName: string
+ onRestartStart?: () => void
+ onRestartComplete?: () => void
+}
+
+export const RestartTableDialog = ({
+ open,
+ onOpenChange,
+ tableId,
+ tableName,
+ onRestartStart,
+ onRestartComplete,
+}: RestartTableDialogProps) => {
+ const { ref: projectRef, pipelineId: _pipelineId } = useParams()
+ const pipelineId = Number(_pipelineId)
+
+ const { mutate: rollbackTables, isPending: isResetting } = useRollbackTablesMutation({
+ onSuccess: () => {
+ toast.success(
+ `Restarting replication for "${tableName}". Pipeline will restart automatically.`
+ )
+ onRestartComplete?.()
+ onOpenChange(false)
+ },
+ onError: (error) => {
+ toast.error(`Failed to restart replication: ${error.message}`)
+ onRestartComplete?.()
+ onOpenChange(false)
+ },
+ })
+
+ const handleReset = () => {
+ if (!projectRef) return toast.error('Project ref is required')
+ if (!pipelineId) return toast.error('Pipeline ID is required')
+
+ onRestartStart?.()
+ rollbackTables({
+ projectRef,
+ pipelineId,
+ target: { type: 'single_table', table_id: tableId },
+ rollbackType: 'full',
+ })
+ }
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ Restart replication for <code className="text-code-inline">{tableName}</code>
+ </AlertDialogTitle>
+ <AlertDialogDescription asChild>
+ <div className="space-y-3 text-sm">
+ <p>
+ This will restart replication for{' '}
+ <code className="text-code-inline">{tableName}</code> from scratch:
+ </p>
+ <ul className="list-disc list-inside space-y-1.5 pl-2">
+ <li>
+ <strong>The table copy will be re-initialized.</strong> All data will be copied
+ again from the source.
+ </li>
+ <li>
+ <strong>Existing downstream data will be deleted.</strong> Any replicated data for
+ this table will be removed.
+ </li>
+ <li>
+ <strong>All other tables remain untouched.</strong> Only this table is affected.
+ </li>
+ <li>
+ <strong>The pipeline will restart automatically.</strong> This is required to
+ apply this change.
+ </li>
+ </ul>
+ </div>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={isResetting}>Cancel</AlertDialogCancel>
+ <AlertDialogAction disabled={isResetting} onClick={handleReset} variant="warning">
+ {isResetting ? 'Restarting replication...' : 'Restart replication'}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/apps/studio/components/interfaces/Database/Replication/RetryOptionsDropdown.tsx b/apps/studio/components/interfaces/Database/Replication/RetryOptionsDropdown.tsx
deleted file mode 100644
index 06544c297e2..00000000000
--- a/apps/studio/components/interfaces/Database/Replication/RetryOptionsDropdown.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-import { ChevronDown, RotateCcw, Undo2 } from 'lucide-react'
-import { useState } from 'react'
-import { toast } from 'sonner'
-
-import { useParams } from 'common'
-import { useRestartPipelineHelper } from 'data/replication/restart-pipeline-helper'
-import { RollbackType, useRollbackTableMutation } from 'data/replication/rollback-table-mutation'
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from 'ui'
-
-const RETRY_OPTIONS = [
- {
- type: 'individual' as RollbackType,
- icon: <Undo2 className="w-3 h-3 mt-0.5" />,
- title: 'Rollback to previous state',
- description: 'Restart from the last working state (may not be enough in some cases)',
- },
- {
- type: 'full' as RollbackType,
- icon: <RotateCcw className="w-3 h-3 mt-0.5" />,
- title: 'Reset from scratch',
- description: 'Completely restart replicating this table',
- },
-] as const
-
-interface RetryOptionsDropdownProps {
- tableId: number
- tableName: string
-}
-
-export const RetryOptionsDropdown = ({ tableId, tableName }: RetryOptionsDropdownProps) => {
- const { ref: projectRef, pipelineId: _pipelineId } = useParams()
- const [isOpen, setIsOpen] = useState(false)
- const [isRestartingPipeline, setIsRestartingPipeline] = useState(false)
-
- const { restartPipeline } = useRestartPipelineHelper()
-
- const { mutate: rollbackTable, isPending: isRollingBack } = useRollbackTableMutation({
- onSuccess: async (_, vars) => {
- const { projectRef, pipelineId, rollbackType } = vars
- toast.success(
- `Table "${tableName}" ${rollbackType === 'full' ? 'reset' : 'rolled back'} successfully and pipeline is being restarted`
- )
-
- setIsRestartingPipeline(true)
- try {
- await restartPipeline({ projectRef, pipelineId })
- toast.success('Pipeline restarted successfully')
- } catch (error: any) {
- toast.error(`Failed to restart pipeline: ${error.message}`)
- } finally {
- setIsRestartingPipeline(false)
- setIsOpen(false)
- }
- },
- onError: (error, vars) => {
- const { rollbackType } = vars
- toast.error(
- `Failed to ${rollbackType === 'full' ? 'reset' : 'rollback'} table: ${error.message}`
- )
- },
- })
-
- const isLoading = isRollingBack || isRestartingPipeline
-
- const handleRollback = async (rollbackType: RollbackType) => {
- if (!projectRef) return toast.error('Project ref is required')
- if (!_pipelineId) return toast.error('Pipeline ID is required')
-
- const pipelineId = Number(_pipelineId)
-
- rollbackTable({
- projectRef,
- pipelineId,
- tableId,
- rollbackType,
- })
- }
-
- return (
- <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
- <DropdownMenuTrigger asChild>
- <Button
- size="tiny"
- type="default"
- loading={isLoading}
- disabled={isLoading}
- className="w-min"
- iconRight={<ChevronDown />}
- aria-label={`Rollback ${tableName}`}
- >
- Rollback
- </Button>
- </DropdownMenuTrigger>
-
- <DropdownMenuContent align="start" className="w-72" aria-label="Rollback options">
- {RETRY_OPTIONS.map((option) => (
- <DropdownMenuItem
- key={option.type}
- disabled={isLoading}
- className="flex flex-col items-start px-3 py-2 cursor-pointer disabled:cursor-not-allowed disabled:opacity-50"
- aria-describedby={`rollback-${option.type}-description`}
- onClick={() => handleRollback(option.type)}
- >
- <div className="flex items-start gap-x-2 w-full">
- <div className="min-w-4">{option.icon}</div>
- <div
- id={`rollback-${option.type}-description`}
- className="flex flex-col gap-y-1 text-xs"
- >
- <p>{option.title}</p>
- <p className="text-foreground-light">{option.description}</p>
- </div>
- </div>
- </DropdownMenuItem>
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
- )
-}
diff --git a/apps/studio/data/replication/pipeline-replication-status-query.ts b/apps/studio/data/replication/pipeline-replication-status-query.ts
index f4e164fc38f..3074d629090 100644
--- a/apps/studio/data/replication/pipeline-replication-status-query.ts
+++ b/apps/studio/data/replication/pipeline-replication-status-query.ts
@@ -1,11 +1,15 @@
import { useQuery } from '@tanstack/react-query'
+import { components } from 'api-types'
import { get, handleError } from 'data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from 'types'
import { replicationKeys } from './keys'
type ReplicationPipelineReplicationStatusParams = { projectRef?: string; pipelineId?: number }
+export type ReplicationPipelineTableStatus =
+ components['schemas']['ReplicationPipelineReplicationStatusResponse']['table_statuses'][number]
+
async function fetchReplicationPipelineReplicationStatus(
{ projectRef, pipelineId }: ReplicationPipelineReplicationStatusParams,
signal?: AbortSignal
diff --git a/apps/studio/data/replication/rollback-table-mutation.ts b/apps/studio/data/replication/rollback-tables-mutation.ts
similarity index 55%
rename from apps/studio/data/replication/rollback-table-mutation.ts
rename to apps/studio/data/replication/rollback-tables-mutation.ts
index d95b62b2e08..17407a3a1f1 100644
--- a/apps/studio/data/replication/rollback-table-mutation.ts
+++ b/apps/studio/data/replication/rollback-tables-mutation.ts
@@ -4,18 +4,23 @@ import { toast } from 'sonner'
import { handleError, post } from 'data/fetchers'
import type { ResponseError, UseCustomMutationOptions } from 'types'
import { replicationKeys } from './keys'
+import { useRestartPipelineHelper } from './restart-pipeline-helper'
export type RollbackType = 'individual' | 'full'
-type RollbackTableParams = {
+export type RollbackTablesTarget =
+ | { type: 'single_table'; table_id: number }
+ | { type: 'all_tables' }
+ | { type: 'all_errored_tables' }
+
+type RollbackTablesParams = {
projectRef: string
pipelineId: number
- tableId: number
+ target: RollbackTablesTarget
rollbackType: RollbackType
}
-type RollbackTableResponse = {
- pipeline_id: number
+type RolledBackTable = {
table_id: number
new_state: {
name: string
@@ -23,20 +28,24 @@ type RollbackTableResponse = {
}
}
-async function rollbackTableState(
- { projectRef, pipelineId, tableId, rollbackType }: RollbackTableParams,
+type RollbackTablesResponse = {
+ pipeline_id: number
+ tables: RolledBackTable[]
+}
+
+async function rollbackTables(
+ { projectRef, pipelineId, target, rollbackType }: RollbackTablesParams,
signal?: AbortSignal
-): Promise<RollbackTableResponse> {
+): Promise<RollbackTablesResponse> {
if (!projectRef) throw new Error('Project reference is required')
if (!pipelineId) throw new Error('Pipeline ID is required')
- if (!tableId) throw new Error('Table ID is required')
if (!rollbackType) throw new Error('Rollback type is required')
const { data, error } = await post(
- '/platform/replication/{ref}/pipelines/{pipeline_id}/rollback-table-state',
+ '/platform/replication/{ref}/pipelines/{pipeline_id}/rollback-tables',
{
params: { path: { ref: projectRef, pipeline_id: pipelineId } },
- body: { table_id: tableId, rollback_type: rollbackType },
+ body: { target, rollback_type: rollbackType },
signal,
}
)
@@ -45,22 +54,33 @@ async function rollbackTableState(
return data
}
-type RollbackTableData = Awaited<ReturnType<typeof rollbackTableState>>
+type RollbackTablesData = Awaited<ReturnType<typeof rollbackTables>>
-export const useRollbackTableMutation = ({
+export const useRollbackTablesMutation = ({
onSuccess,
onError,
...options
}: Omit<
- UseCustomMutationOptions<RollbackTableData, ResponseError, RollbackTableParams>,
+ UseCustomMutationOptions<RollbackTablesData, ResponseError, RollbackTablesParams>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
+ const { restartPipeline } = useRestartPipelineHelper()
- return useMutation<RollbackTableData, ResponseError, RollbackTableParams>({
- mutationFn: (vars) => rollbackTableState(vars),
+ return useMutation<RollbackTablesData, ResponseError, RollbackTablesParams>({
+ mutationFn: (vars) => rollbackTables(vars),
async onSuccess(data, variables, context) {
const { projectRef, pipelineId } = variables
+
+ // Restart the pipeline (stop + start)
+ try {
+ await restartPipeline({ projectRef, pipelineId })
+ } catch (error: any) {
+ toast.error(`Rollback succeeded but failed to restart pipeline: ${error.message}`)
+ throw error
+ }
+
+ // Invalidate queries after restart to get the latest state
await Promise.all([
queryClient.invalidateQueries({
queryKey: replicationKeys.pipelinesStatus(projectRef, pipelineId),
@@ -74,7 +94,7 @@ export const useRollbackTableMutation = ({
},
async onError(data, variables, context) {
if (onError === undefined) {
- toast.error(`Failed to rollback table: ${data.message}`)
+ toast.error(`Failed to rollback tables: ${data.message}`)
} else {
onError(data, variables, context)
}
diff --git a/apps/studio/data/replication/use-table-reset.ts b/apps/studio/data/replication/use-table-reset.ts
deleted file mode 100644
index bf401e89559..00000000000
--- a/apps/studio/data/replication/use-table-reset.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { useState } from 'react'
-import { toast } from 'sonner'
-import { useRestartPipelineHelper } from './restart-pipeline-helper'
-import { RollbackType, useRollbackTableMutation } from './rollback-table-mutation'
-
-interface UseTableResetParams {
- tableName: string
- onSuccess?: () => void
- onError?: (error: Error) => void
-}
-
-/**
- * Custom hook that encapsulates the logic for resetting a table and restarting the pipeline.
- * Provides unified error handling and loading states for table reset operations.
- */
-export const useTableReset = ({ tableName, onSuccess, onError }: UseTableResetParams) => {
- const [isRestartingPipeline, setIsRestartingPipeline] = useState(false)
- const { restartPipeline } = useRestartPipelineHelper()
-
- const { mutate: rollbackTable, isPending: isRollingBack } = useRollbackTableMutation({
- onSuccess: async (_, vars) => {
- const { projectRef, pipelineId } = vars
- toast.success(`Table "${tableName}" reset successfully and pipeline is being restarted`)
-
- setIsRestartingPipeline(true)
- try {
- await restartPipeline({ projectRef, pipelineId })
- toast.success('Pipeline restarted successfully')
- onSuccess?.()
- } catch (error: any) {
- const errorMessage = `Failed to restart pipeline: ${error.message}`
- toast.error(errorMessage)
- onError?.(new Error(errorMessage))
- } finally {
- setIsRestartingPipeline(false)
- }
- },
- onError: (error) => {
- const errorMessage = `Failed to reset table: ${error.message}`
- toast.error(errorMessage)
- onError?.(new Error(errorMessage))
- },
- })
-
- const resetTable = ({
- projectRef,
- pipelineId,
- tableId,
- rollbackType = 'full' as RollbackType,
- }: {
- projectRef: string
- pipelineId: number
- tableId: number
- rollbackType?: RollbackType
- }) => {
- rollbackTable({
- projectRef,
- pipelineId,
- tableId,
- rollbackType,
- })
- }
-
- return {
- resetTable,
- isRollingBack,
- isRestartingPipeline,
- isResetting: isRollingBack || isRestartingPipeline,
- }
-}
diff --git a/apps/studio/pages/api/platform/organizations/[slug]/billing/subscription.ts b/apps/studio/pages/api/platform/organizations/[slug]/billing/subscription.ts
index e5b946a8286..dfc1d786321 100644
--- a/apps/studio/pages/api/platform/organizations/[slug]/billing/subscription.ts
+++ b/apps/studio/pages/api/platform/organizations/[slug]/billing/subscription.ts
@@ -38,7 +38,6 @@ const handleGet = async (req: NextApiRequest, res: NextApiResponse<ResponseData>
billing_partner: 'fly',
scheduled_plan_change: null,
customer_balance: 0,
- cached_egress_enabled: false,
}
return res.status(200).json(response)
diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.ts
index 2f6368f3ca1..6908cefc155 100644
--- a/packages/api-types/types/api.d.ts
+++ b/packages/api-types/types/api.d.ts
@@ -287,7 +287,7 @@ export interface paths {
* Gets all projects for the given organization
* @description Returns a paginated list of projects for the specified organization.
*
- * This endpoint uses offset-based pagination. Use the `offset` parameter to skip a number of projects and the `limit` parameter to control the number of projects returned per page.
+ * This endpoint uses offset-based pagination. Use the `offset` parameter to skip a number of projects and the `limit` parameter to control the number of projects returned per page.
*/
get: operations['v1-get-all-projects-for-organization']
put?: never
@@ -308,6 +308,8 @@ export interface paths {
/**
* List all projects
* @description Returns a list of all projects you've previously created.
+ *
+ * Use `/v1/organizations/{slug}/projects` instead when possible to get more precise results and pagination support.
*/
get: operations['v1-list-all-projects']
put?: never
@@ -3287,6 +3289,10 @@ export interface components {
eligible: boolean
latest_app_version: string
legacy_auth_custom_roles: string[]
+ /**
+ * @deprecated
+ * @description Use validation_errors instead.
+ */
objects_to_be_dropped: string[]
target_upgrade_versions: {
app_version: string
@@ -3295,8 +3301,68 @@ export interface components {
/** @enum {string} */
release_channel: 'internal' | 'alpha' | 'beta' | 'ga' | 'withdrawn' | 'preview'
}[]
+ /**
+ * @deprecated
+ * @description Use validation_errors instead.
+ */
unsupported_extensions: string[]
+ /**
+ * @deprecated
+ * @description Use validation_errors instead.
+ */
user_defined_objects_in_internal_schemas: string[]
+ validation_errors: (
+ | {
+ dependents: string[]
+ /** @enum {string} */
+ type: 'objects_depending_on_pg_cron'
+ }
+ | {
+ index_name: string
+ schema_name: string
+ table_name: string
+ /** @enum {string} */
+ type: 'indexes_referencing_ll_to_earth'
+ }
+ | {
+ function_name: string
+ lang_name: string
+ schema_name: string
+ /** @enum {string} */
+ type: 'function_using_obsolete_lang'
+ }
+ | {
+ extension_name: string
+ /** @enum {string} */
+ type: 'unsupported_extension'
+ }
+ | {
+ fdw_handler_name: string
+ fdw_name: string
+ /** @enum {string} */
+ type: 'unsupported_fdw_handler'
+ }
+ | {
+ schema_name: string
+ sequence_name: string
+ table_name: string
+ /** @enum {string} */
+ type: 'unlogged_table_with_persistent_sequence'
+ }
+ | {
+ obj_name: string
+ /** @enum {string} */
+ obj_type: 'table' | 'function'
+ schema_name: string
+ /** @enum {string} */
+ type: 'user_defined_objects_in_internal_schemas'
+ }
+ | {
+ slot_name: string
+ /** @enum {string} */
+ type: 'active_replication_slot'
+ }
+ )[]
}
ProjectUpgradeInitiateResponse: {
tracking_id: string
diff --git a/packages/api-types/types/platform.d.ts b/packages/api-types/types/platform.d.ts
index ac52c0dbf5c..f9c6465edfa 100644
--- a/packages/api-types/types/platform.d.ts
+++ b/packages/api-types/types/platform.d.ts
@@ -1556,7 +1556,7 @@ export interface paths {
* Gets all projects for the given organization
* @description Returns a paginated list of projects for the specified organization.
*
- * This endpoint uses offset-based pagination. Use the `offset` parameter to skip a number of projects and the `limit` parameter to control the number of projects returned per page.
+ * This endpoint uses offset-based pagination. Use the `offset` parameter to skip a number of projects and the `limit` parameter to control the number of projects returned per page.
*/
get: operations['OrganizationProjectsController_getOrganizationProjects']
put?: never
@@ -2048,7 +2048,7 @@ export interface paths {
* Gets all projects that belong to the authenticated user
* @description Returns a paginated list of projects across all organizations the user has access to.
*
- * This endpoint uses offset-based pagination. Use the `offset` parameter to skip a number of projects and the `limit` parameter to control the number of projects returned per page.
+ * This endpoint uses offset-based pagination. Use the `offset` parameter to skip a number of projects and the `limit` parameter to control the number of projects returned per page.
*/
get: operations['ProjectsController_getProjects']
put?: never
@@ -3533,8 +3533,9 @@ export interface paths {
get?: never
put?: never
/**
- * Rollback pipeline table state
- * @description Rollback a table state for the pipeline. Requires bearer auth and an active, healthy project.
+ * Rollback pipeline table state (deprecated)
+ * @deprecated
+ * @description Deprecated: Use POST /pipelines/{pipeline_id}/rollback-tables instead. Rollback a table state for the pipeline. Requires bearer auth and an active, healthy project.
*/
post: operations['ReplicationPipelinesController_rollbackTableState']
delete?: never
@@ -3543,6 +3544,26 @@ export interface paths {
patch?: never
trace?: never
}
+ '/platform/replication/{ref}/pipelines/{pipeline_id}/rollback-tables': {
+ parameters: {
+ query?: never
+ header?: never
+ path?: never
+ cookie?: never
+ }
+ get?: never
+ put?: never
+ /**
+ * Rollback pipeline tables
+ * @description Rollback the replication state of tables in the pipeline. Supports rolling back a single table or all tables with manual retry errors. Requires bearer auth and an active, healthy project.
+ */
+ post: operations['ReplicationPipelinesController_rollbackTables']
+ delete?: never
+ options?: never
+ head?: never
+ patch?: never
+ trace?: never
+ }
'/platform/replication/{ref}/pipelines/{pipeline_id}/start': {
parameters: {
query?: never
@@ -4582,7 +4603,6 @@ export interface components {
}
pitr_enabled: boolean
region: string
- tierKey: string
walg_enabled: boolean
}
BillingCustomerUpdateBody: {
@@ -5399,7 +5419,6 @@ export interface components {
name: string
organization_slugs?: string[]
permissions: (
- | 'available_regions_read'
| 'organizations_read'
| 'organizations_create'
| 'projects_read'
@@ -5811,7 +5830,12 @@ export interface components {
| {
iops: number
size_gb: number
- throughput_mbps: number
+ /**
+ * @deprecated
+ * @description Use throughput_mibps instead. This field incorrectly uses `mbps` but the value is actually MiB/s.
+ */
+ throughput_mbps?: number
+ throughput_mibps?: number
/** @enum {string} */
type: 'gp3'
}
@@ -5827,7 +5851,12 @@ export interface components {
| {
iops: number
size_gb: number
+ /**
+ * @deprecated
+ * @description Use throughput_mibps instead. This field incorrectly uses `mbps` but the value is actually MiB/s.
+ */
throughput_mbps: number
+ throughput_mibps: number
/** @enum {string} */
type: 'gp3'
}
@@ -5842,7 +5871,12 @@ export interface components {
| {
iops: number
size_gb: number
+ /**
+ * @deprecated
+ * @description Use throughput_mibps instead. This field incorrectly uses `mbps` but the value is actually MiB/s.
+ */
throughput_mbps: number
+ throughput_mibps: number
/** @enum {string} */
type: 'gp3'
}
@@ -6328,7 +6362,6 @@ export interface components {
/** @enum {string} */
billing_partner?: 'fly' | 'aws_marketplace' | 'vercel_marketplace'
billing_via_partner: boolean
- cached_egress_enabled: boolean
current_period_end: number
current_period_start: number
customer_balance?: number
@@ -6935,6 +6968,8 @@ export interface components {
| 'storage.max_file_size'
| 'security.audit_logs_days'
| 'security.questionnaire'
+ | 'security.soc2_report'
+ | 'security.private_link'
| 'log.retention_days'
| 'custom_domain'
| 'vanity_subdomain'
@@ -6948,6 +6983,15 @@ export interface components {
| 'auth.hooks'
| 'auth.platform.sso'
| 'backup.retention_days'
+ | 'function.max_count'
+ | 'function.size_limit_mb'
+ | 'realtime.max_concurrent_users'
+ | 'realtime.max_events_per_second'
+ | 'realtime.max_joins_per_second'
+ | 'realtime.max_channels_per_client'
+ | 'realtime.max_bytes_per_second'
+ | 'realtime.max_presence_events_per_second'
+ | 'realtime.max_payload_size_in_kb'
/** @enum {string} */
type: 'boolean' | 'numeric' | 'set'
}
@@ -7850,14 +7894,14 @@ export interface components {
| 'billing:payment_methods'
| 'realtime:all'
)[]
- first_name: string | null
- free_project_limit: number | null
+ first_name: string
+ free_project_limit: number
gotrue_id: string
id: number
is_alpha_user: boolean
is_sso_user: boolean
- last_name: string | null
- mobile: string | null
+ last_name: string
+ mobile: string
primary_email: string
username: string
}
@@ -8797,6 +8841,90 @@ export interface components {
name: string
website: string
}
+ RollbackTablesBody: {
+ /**
+ * @description Rollback type
+ * @example individual
+ * @enum {string}
+ */
+ rollback_type: 'individual' | 'full'
+ /** @description Rollback target */
+ target:
+ | {
+ /**
+ * @description Table id (Postgres OID)
+ * @example 16408
+ */
+ table_id: number
+ /** @enum {string} */
+ type: 'single_table'
+ }
+ | {
+ /** @enum {string} */
+ type: 'all_errored_tables'
+ }
+ | {
+ /** @enum {string} */
+ type: 'all_tables'
+ }
+ }
+ RollbackTablesResponse: {
+ /**
+ * @description Pipeline id
+ * @example 1012
+ */
+ pipeline_id: number
+ /** @description Rolled back tables */
+ tables: {
+ /** @description Table replication state */
+ new_state:
+ | {
+ /** @enum {string} */
+ name: 'queued'
+ }
+ | {
+ /** @enum {string} */
+ name: 'copying_table'
+ }
+ | {
+ /** @enum {string} */
+ name: 'copied_table'
+ }
+ | {
+ /** @enum {string} */
+ name: 'following_wal'
+ }
+ | {
+ /** @enum {string} */
+ name: 'error'
+ reason: string
+ retry_policy:
+ | {
+ /** @enum {string} */
+ policy: 'no_retry'
+ }
+ | {
+ /** @enum {string} */
+ policy: 'manual_retry'
+ }
+ | {
+ /**
+ * @description Next retry time (RFC 3339 timestamp)
+ * @example 2025-01-02T03:04:05Z
+ */
+ next_retry: string
+ /** @enum {string} */
+ policy: 'timed_retry'
+ }
+ solution?: string
+ }
+ /**
+ * @description Table id (Postgres OID)
+ * @example 16408
+ */
+ table_id: number
+ }[]
+ }
RollbackTableStateBody: {
/**
* @description Rollback type
@@ -22924,6 +23052,63 @@ export interface operations {
}
}
}
+ ReplicationPipelinesController_rollbackTables: {
+ parameters: {
+ query?: never
+ header?: never
+ path: {
+ /** @description Pipeline id */
+ pipeline_id: number
+ /** @description Project ref */
+ ref: string
+ }
+ cookie?: never
+ }
+ requestBody: {
+ content: {
+ 'application/json': components['schemas']['RollbackTablesBody']
+ }
+ }
+ responses: {
+ /** @description New table states after rollback. */
+ 200: {
+ headers: {
+ [name: string]: unknown
+ }
+ content: {
+ 'application/json': components['schemas']['RollbackTablesResponse']
+ }
+ }
+ /** @description Unauthorized */
+ 401: {
+ headers: {
+ [name: string]: unknown
+ }
+ content?: never
+ }
+ /** @description Forbidden action */
+ 403: {
+ headers: {
+ [name: string]: unknown
+ }
+ content?: never
+ }
+ /** @description Rate limit exceeded */
+ 429: {
+ headers: {
+ [name: string]: unknown
+ }
+ content?: never
+ }
+ /** @description Unexpected error while rolling back tables. */
+ 500: {
+ headers: {
+ [name: string]: unknown
+ }
+ content?: never
+ }
+ }
+ }
ReplicationPipelinesController_startPipeline: {
parameters: {
query?: never