Files
Alaister YoungandAlaister Young e0635f2f38 [FE-5108] (part 3) refactor(studio): migrate database, editors & storage off next/link (#54306)
Part 3 of a 6-PR stack migrating all `next/link` imports in
`apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known
external URLs) and removing `compat/next/link.tsx`.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54304 | `data/prefetchers/PrefetchableLink.tsx` and
`components/ui/**` |
| 2 | #54305 | `components/layouts/**` and top-level shell components |
| **3** | **#54306 ← this PR** | **Database, TableGridEditor, Storage,
SQLEditor, BranchManagement, Branching, Functions, Realtime** |
| 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues,
Linter, Reports, QueryPerformance, QuerySources, ConfigDrift,
DiskManagement, Compute |
| 5 | #54308 | Remaining `components/interfaces/**` (Org, Billing, Auth,
Support, Home, SignIn, ConnectSheet, etc.) |
| 6 | #54309 | Remove `compat/next/link.tsx` shim, Vite alias, and
update basePath tests/docs |

Migrates
`components/interfaces/{Database,TableGridEditor,Storage,SQLEditor,BranchManagement,Branching,Functions,Realtime}/`
off `next/link`.

**Changed:**

- Replaced `next/link` across all 60 importing files in Database,
TableGridEditor, Storage, SQLEditor, BranchManagement, Branching,
Functions, and Realtime interfaces
- Updated legacy permanent-redirect hrefs (`/reports` →
`/observability`, `/database/schema` → `/database/schemas`) to their
canonical TanStack routes
- Dropped legacy `passHref` in `GridHeaderActions.tsx`, removed
duplicate `RouterLink` alias in `ChooseFunctionForm.tsx`, and removed
`vi.mock('next/link', ...)` in `ReplicationPipelineLayout.test.tsx`

Addresses
[FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link)

## To test

- [ ] Check Table Editor, SQL Editor, Database (tables, policies,
functions, triggers, replication, backups), Storage
(files/analytics/vector buckets), Edge Functions, Branching, and
Realtime links
- [ ] Verify SQL Editor and Table Editor links with query parameters
(`schema`, `content`, `search`) do not double-encode values

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 16:43:56 +08:00

593 lines
21 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { ExternalLinkIcon } from 'lucide-react'
import { toast } from 'sonner'
import { Alert, AlertDescription, AlertTitle, Button, Checkbox } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { useTableFilter } from '@/components/grid/hooks/useTableFilter'
import type { SupaRow } from '@/components/grid/types'
import { useDatabaseColumnDeleteMutation } from '@/data/database-columns/database-column-delete-mutation'
import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'
import { partitionCountQueryOptions } from '@/data/entity-types/partition-count-query'
import { useMaterializedViewDeleteMutation } from '@/data/materialized-views/materialized-view-delete-mutation'
import { useTableEditorQuery } from '@/data/table-editor/table-editor-query'
import type { Entity } from '@/data/table-editor/table-editor-types'
import { useTableRowDeleteAllMutation } from '@/data/table-rows/table-row-delete-all-mutation'
import { useTableRowDeleteMutation } from '@/data/table-rows/table-row-delete-mutation'
import { useTableRowTruncateMutation } from '@/data/table-rows/table-row-truncate-mutation'
import { useTableDeleteMutation } from '@/data/tables/table-delete-mutation'
import { useViewDeleteMutation } from '@/data/views/view-delete-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { pluralize } from '@/lib/helpers'
import { useGetImpersonatedRoleState } from '@/state/role-impersonation-state'
import { useTableEditorStateSnapshot } from '@/state/table-editor'
export type DeleteConfirmationDialogsProps = {
/** The table open in the grid. Row and column deletes act on this table */
selectedTable?: Entity
onTableDeleted?: (table: Entity) => void
}
export const DeleteConfirmationDialogs = ({
selectedTable,
onTableDeleted,
}: DeleteConfirmationDialogsProps) => {
const { data: project } = useSelectedProjectQuery()
const snap = useTableEditorStateSnapshot()
const { filters, setFilters } = useTableFilter()
const entityDialog =
snap.confirmationDialog?.type === 'table' ||
snap.confirmationDialog?.type === 'view' ||
snap.confirmationDialog?.type === 'materialized-view'
? snap.confirmationDialog
: undefined
const { data: targetEntity } = useTableEditorQuery({
projectRef: project?.ref,
connectionString: project?.connectionString,
id: entityDialog?.tableId,
})
const targetTable = targetEntity ?? undefined
const isAwaitingTargetTable = entityDialog !== undefined && targetTable === undefined
const removeDeletedColumnFromFiltersAndSorts = ({
columnName,
}: {
ref?: string
tableName?: string
schema?: string
columnName: string
}) => {
setFilters(filters.filter((filter) => filter.column !== columnName))
}
const { mutate: deleteColumn } = useDatabaseColumnDeleteMutation({
onSuccess: () => {
if (!(snap.confirmationDialog?.type === 'column')) return
const selectedColumnToDelete = snap.confirmationDialog.column
removeDeletedColumnFromFiltersAndSorts({ columnName: selectedColumnToDelete.name })
toast.success(`Successfully deleted column "${selectedColumnToDelete.name}"`)
},
onError: (error) => {
if (!(snap.confirmationDialog?.type === 'column')) return
const selectedColumnToDelete = snap.confirmationDialog.column
toast.error(`Failed to delete ${selectedColumnToDelete!.name}: ${error.message}`)
},
onSettled: () => {
snap.closeConfirmationDialog()
},
})
const { mutateAsync: deleteTable } = useTableDeleteMutation({
onSuccess: async (_, variables) => {
toast.success(`Successfully deleted table "${variables.name}"`)
},
onError: (error, variables) => {
toast.error(`Failed to delete ${variables.name}: ${error.message}`)
},
onSettled: () => {
snap.closeConfirmationDialog()
},
})
const { mutateAsync: deleteView } = useViewDeleteMutation({
onSuccess: async (_, variables) => {
toast.success(`Successfully deleted view "${variables.name}"`)
},
onError: (error, variables) => {
toast.error(`Failed to delete ${variables.name}: ${error.message}`)
},
onSettled: () => {
snap.closeConfirmationDialog()
},
})
const { mutateAsync: deleteMaterializedView } = useMaterializedViewDeleteMutation({
onSuccess: async (_, variables) => {
toast.success(`Successfully deleted materialized view "${variables.name}"`)
},
onError: (error, variables) => {
toast.error(`Failed to delete ${variables.name}: ${error.message}`)
},
onSettled: () => {
snap.closeConfirmationDialog()
},
})
const { mutate: deleteRows, isPending: isDeletingRows } = useTableRowDeleteMutation({
onSuccess: () => {
if (snap.confirmationDialog?.type === 'row') {
snap.confirmationDialog.callback?.()
}
toast.success(`Successfully deleted selected row(s)`)
},
onSettled: () => {
snap.closeConfirmationDialog()
},
})
const { mutate: deleteAllRows, isPending: isDeletingAllRows } = useTableRowDeleteAllMutation({
onSuccess: () => {
if (snap.confirmationDialog?.type === 'row') {
snap.confirmationDialog.callback?.()
}
toast.success(`Successfully deleted selected rows`)
},
onError: (error) => {
toast.error(`Failed to delete rows: ${error.message}`)
},
onSettled: () => {
snap.closeConfirmationDialog()
},
})
const { mutate: truncateRows, isPending: isTruncatingRows } = useTableRowTruncateMutation({
onSuccess: () => {
if (snap.confirmationDialog?.type === 'row') {
snap.confirmationDialog.callback?.()
}
toast.success(`Successfully deleted all rows from table`)
},
onError: (error) => {
toast.error(`Failed to delete rows: ${error.message}`)
},
onSettled: () => {
snap.closeConfirmationDialog()
},
})
const isAllRowsSelected =
snap.confirmationDialog?.type === 'row' ? snap.confirmationDialog.allRowsSelected : false
const numRows =
snap.confirmationDialog?.type === 'row'
? snap.confirmationDialog.allRowsSelected
? (snap.confirmationDialog.numRows ?? 0)
: snap.confirmationDialog.rows.length
: 0
const isDeleteWithCascade =
snap.confirmationDialog?.type === 'column' ||
snap.confirmationDialog?.type === 'table' ||
snap.confirmationDialog?.type === 'view' ||
snap.confirmationDialog?.type === 'materialized-view'
? snap.confirmationDialog.isDeleteWithCascade
: false
const onConfirmDeleteColumn = async () => {
if (!(snap.confirmationDialog?.type === 'column')) return
if (project === undefined) return
const selectedColumnToDelete = snap.confirmationDialog.column
if (selectedColumnToDelete === undefined) return
deleteColumn({
column: selectedColumnToDelete,
cascade: isDeleteWithCascade,
projectRef: project.ref,
connectionString: project?.connectionString,
})
}
const onConfirmDeleteTable = async () => {
if (snap.confirmationDialog?.type !== 'table') return
if (!project || !targetTable) return
// Not read from `targetTable` after the delete: once the table is gone its query empties it
const deletedEntity = targetTable
try {
await deleteTable({
projectRef: project.ref,
connectionString: project.connectionString,
id: deletedEntity.id,
name: deletedEntity.name,
schema: deletedEntity.schema,
cascade: isDeleteWithCascade,
})
} catch {
return // Reported by the mutation's onError
}
onTableDeleted?.(deletedEntity)
}
const onConfirmDeleteView = async () => {
if (snap.confirmationDialog?.type !== 'view') return
if (!project || !targetTable) return
// Not read from `targetTable` after the delete: once the table is gone its query empties it
const deletedEntity = targetTable
try {
await deleteView({
projectRef: project.ref,
connectionString: project.connectionString,
id: deletedEntity.id,
name: deletedEntity.name,
schema: deletedEntity.schema,
cascade: isDeleteWithCascade,
})
} catch {
return // Reported by the mutation's onError
}
onTableDeleted?.(deletedEntity)
}
const onConfirmDeleteMaterializedView = async () => {
if (snap.confirmationDialog?.type !== 'materialized-view') return
if (!project || !targetTable) return
// Not read from `targetTable` after the delete: once the table is gone its query empties it
const deletedEntity = targetTable
try {
await deleteMaterializedView({
projectRef: project.ref,
connectionString: project.connectionString,
id: deletedEntity.id,
name: deletedEntity.name,
schema: deletedEntity.schema,
cascade: isDeleteWithCascade,
})
} catch {
return // Reported by the mutation's onError
}
onTableDeleted?.(deletedEntity)
}
const isPartitionedTableDialogOpen =
snap.confirmationDialog?.type === 'table' &&
targetTable?.entity_type === ENTITY_TYPE.PARTITIONED_TABLE
const {
data: partitionCount,
isError: isPartitionCountError,
isFetching: isFetchingPartitionCount,
refetch: refetchPartitionCount,
} = useQuery({
...partitionCountQueryOptions({
projectRef: project?.ref,
connectionString: project?.connectionString,
id: targetTable?.id,
}),
enabled: isPartitionedTableDialogOpen && !!project?.ref,
})
const isAwaitingPartitionCount = isPartitionedTableDialogOpen && partitionCount === undefined
const getImpersonatedRoleState = useGetImpersonatedRoleState()
const onConfirmDeleteRow = async () => {
if (!project) return console.error('Project ref is required')
if (!selectedTable) return console.error('Selected table required')
if (snap.confirmationDialog?.type !== 'row') return
const selectedRowsToDelete = snap.confirmationDialog.rows
if (snap.confirmationDialog.allRowsSelected) {
if (filters.length === 0) {
if (getImpersonatedRoleState().role !== undefined) {
snap.closeConfirmationDialog()
return toast.error('Table truncation is not supported when impersonating a role')
}
truncateRows({
projectRef: project.ref,
connectionString: project.connectionString,
table: selectedTable,
})
} else {
deleteAllRows({
projectRef: project.ref,
connectionString: project.connectionString,
table: selectedTable,
filters,
roleImpersonationState: getImpersonatedRoleState(),
})
}
} else {
deleteRows({
projectRef: project.ref,
connectionString: project.connectionString,
table: selectedTable,
rows: selectedRowsToDelete as SupaRow[],
roleImpersonationState: getImpersonatedRoleState(),
})
}
}
return (
<>
<ConfirmationModal
variant="destructive"
size="small"
visible={snap.confirmationDialog?.type === 'column'}
title={`Confirm deletion of column "${
snap.confirmationDialog?.type === 'column' && snap.confirmationDialog.column.name
}"`}
confirmLabel="Delete"
confirmLabelLoading="Deleting"
onCancel={() => {
snap.closeConfirmationDialog()
}}
onConfirm={onConfirmDeleteColumn}
>
<div className="space-y-4">
<p className="text-sm text-foreground-light">
Are you sure you want to delete the selected column? This action cannot be undone.
</p>
<div className="items-start flex space-x-2">
<Checkbox
id="checkbox-cascade"
checked={isDeleteWithCascade}
onCheckedChange={() => snap.toggleConfirmationIsWithCascade()}
/>
<div className="grid gap-1.5 leading-none">
<label
htmlFor="checkbox-cascade"
className="text-sm text-foreground-light leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Drop column with cascade?
</label>
<p className="text-sm text-foreground-muted">
Deletes the column and its dependent objects
</p>
</div>
</div>
{isDeleteWithCascade && (
<Alert
variant="warning"
title="Warning: Dropping with cascade may result in unintended consequences"
>
<AlertTitle>
All dependent objects will be removed, as will any objects that depend on them,
recursively.
</AlertTitle>
<AlertDescription>
<Button asChild size="tiny" icon={<ExternalLinkIcon />}>
<a
href="https://www.postgresql.org/docs/current/ddl-depend.html"
target="_blank"
rel="noreferrer"
>
About dependency tracking
</a>
</Button>
</AlertDescription>
</Alert>
)}
</div>
</ConfirmationModal>
<ConfirmationModal
variant={'destructive'}
size="small"
visible={snap.confirmationDialog?.type === 'table'}
title={
<span className="wrap-break-word">{`Confirm deletion of table "${targetTable?.name ?? ''}"`}</span>
}
confirmLabel="Delete"
confirmLabelLoading="Deleting"
disabled={isAwaitingTargetTable || isAwaitingPartitionCount}
onCancel={() => {
snap.closeConfirmationDialog()
}}
onConfirm={onConfirmDeleteTable}
>
<div data-testid="confirm-delete-table-modal" className="space-y-4">
{isAwaitingPartitionCount && isPartitionCountError && (
<Alert variant="warning">
<AlertTitle>Failed to check this table's partitions</AlertTitle>
<AlertDescription>
Deleting a partitioned table also deletes its partitions. Retry to see how many will
be deleted.
</AlertDescription>
<AlertDescription className="mt-4">
<Button
size="tiny"
loading={isFetchingPartitionCount}
onClick={() => refetchPartitionCount()}
>
Retry
</Button>
</AlertDescription>
</Alert>
)}
{isPartitionedTableDialogOpen && partitionCount !== undefined && partitionCount > 0 && (
<p className="text-sm text-foreground-light">
This will also delete its {partitionCount} {pluralize(partitionCount, 'partition')},
any nested partitions, and all of their data.
</p>
)}
<p className="text-sm text-foreground-light">
Are you sure you want to delete the selected table? This action cannot be undone.
</p>
<div className="items-start flex space-x-2">
<Checkbox
id="checkbox-cascade"
checked={isDeleteWithCascade}
onCheckedChange={() => snap.toggleConfirmationIsWithCascade(!isDeleteWithCascade)}
/>
<div className="grid gap-1.5 leading-none">
<label
htmlFor="checkbox-cascade"
className="text-sm text-foreground-light leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Drop table with cascade?
</label>
<p className="text-sm text-foreground-muted">
Deletes the table and its dependent objects
</p>
</div>
</div>
{isDeleteWithCascade && (
<Alert variant="warning">
<AlertTitle>
Warning: Dropping with cascade may result in unintended consequences
</AlertTitle>
<AlertDescription>
All dependent objects will be removed, as will any objects that depend on them,
recursively.
</AlertDescription>
<AlertDescription className="mt-4">
<Button asChild size="tiny" icon={<ExternalLinkIcon />}>
<a
href="https://www.postgresql.org/docs/current/ddl-depend.html"
target="_blank"
rel="noreferrer"
>
About dependency tracking
</a>
</Button>
</AlertDescription>
</Alert>
)}
</div>
</ConfirmationModal>
<DropEntityConfirmationModal
visible={snap.confirmationDialog?.type === 'view'}
entityLabel="view"
entityName={targetTable?.name}
isDeleteWithCascade={isDeleteWithCascade}
onToggleCascade={() => snap.toggleConfirmationIsWithCascade(!isDeleteWithCascade)}
onCancel={() => snap.closeConfirmationDialog()}
onConfirm={onConfirmDeleteView}
/>
<DropEntityConfirmationModal
visible={snap.confirmationDialog?.type === 'materialized-view'}
entityLabel="materialized view"
entityName={targetTable?.name}
isDeleteWithCascade={isDeleteWithCascade}
onToggleCascade={() => snap.toggleConfirmationIsWithCascade(!isDeleteWithCascade)}
onCancel={() => snap.closeConfirmationDialog()}
onConfirm={onConfirmDeleteMaterializedView}
/>
<ConfirmationModal
variant={'destructive'}
size="small"
visible={snap.confirmationDialog?.type === 'row'}
title={
<p className="wrap-break-word">
<span>Confirm to delete the selected row</span>
<span>{numRows > 1 && 's'}</span>
</p>
}
confirmLabel="Delete"
confirmLabelLoading="Deleting"
onCancel={() => snap.closeConfirmationDialog()}
onConfirm={() => onConfirmDeleteRow()}
loading={isTruncatingRows || isDeletingRows || isDeletingAllRows}
>
<div className="space-y-4">
<p className="text-sm text-foreground-light">
<span>Are you sure you want to delete </span>
<span>{isAllRowsSelected ? 'all' : 'the selected'} </span>
<span>{numRows > 1 && `${numRows} `}</span>
<span>row</span>
<span>{numRows > 1 && 's'}</span>
<span>? This action cannot be undone.</span>
</p>
</div>
</ConfirmationModal>
</>
)
}
type DropEntityConfirmationModalProps = {
visible: boolean
entityLabel: 'view' | 'materialized view'
entityName?: string
isDeleteWithCascade: boolean
onToggleCascade: () => void
onCancel: () => void
onConfirm: () => void
}
const DropEntityConfirmationModal = ({
visible,
entityLabel,
entityName,
isDeleteWithCascade,
onToggleCascade,
onCancel,
onConfirm,
}: DropEntityConfirmationModalProps) => {
const checkboxId = `checkbox-cascade-${entityLabel.replace(/\s+/g, '-')}`
return (
<ConfirmationModal
variant="destructive"
size="small"
visible={visible}
title={
<span className="wrap-break-word">{`Confirm deletion of ${entityLabel} "${entityName ?? ''}"`}</span>
}
confirmLabel="Delete"
confirmLabelLoading="Deleting"
onCancel={onCancel}
onConfirm={onConfirm}
>
<div className="space-y-4">
<p className="text-sm text-foreground-light">
Are you sure you want to delete this {entityLabel}? This action cannot be undone.
</p>
<div className="items-start flex space-x-2">
<Checkbox
id={checkboxId}
checked={isDeleteWithCascade}
onCheckedChange={onToggleCascade}
/>
<div className="grid gap-1.5 leading-none">
<label
htmlFor={checkboxId}
className="text-sm text-foreground-light leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Drop {entityLabel} with cascade?
</label>
<p className="text-sm text-foreground-muted">
Deletes the {entityLabel} and its dependent objects
</p>
</div>
</div>
{isDeleteWithCascade && (
<Alert variant="warning">
<AlertTitle>
Warning: Dropping with cascade may result in unintended consequences
</AlertTitle>
<AlertDescription>
All dependent objects will be removed, as will any objects that depend on them,
recursively.
</AlertDescription>
<AlertDescription className="mt-4">
<Button asChild size="tiny" icon={<ExternalLinkIcon />}>
<a
href="https://www.postgresql.org/docs/current/ddl-depend.html"
target="_blank"
rel="noreferrer"
>
About dependency tracking
</a>
</Button>
</AlertDescription>
</Alert>
)}
</div>
</ConfirmationModal>
)
}