Files
supabase/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsx
Jordi EnricandClaude Opus 4.6 21584fe512 feat(studio): add backup cli instructions (#44621)
## Problem

When a project is paused, in a failed state, or about to be deleted,
users have no obvious way to take a logical backup of their data before
proceeding. This is particularly risky at deletion time — once deleted,
data is gone.

## Solution

Introduce a new `LogicalBackupCliInstructions` component that surfaces
ready-to-run `supabase db dump` commands pre-filled with the project's
direct connection details.

### Where it appears

| State | How |
|---|---|
| Project paused (restorable) | Inline in `ProjectPausedState` with a
note to resume first |
| Pause failed | Dialog via "Download backup" button when no backup is
available |
| Restore failed | Dialog via "Download backup" button when no backup is
available |
| Delete project modal | Inline in `DeleteProjectModal` for all plans |

Not shown in `PauseDisabledState` (project paused 90+ days, compute
stopped — `pg_dump` would fail anyway).

### What the component does

- Fetches the project's direct connection settings via
`useProjectSettingsV2Query`
- Builds a connection URI with a `[YOUR-PASSWORD]` placeholder (password
is never stored or displayed)
- Shows three shell commands to dump roles, schema, and data separately
— mirroring the [logical backup
docs](https://supabase.com/docs/guides/platform/backups)
- Optionally shows a **Reset database password** button (gated on
`UPDATE projects` permission); shown in the paused state, hidden
elsewhere via `showResetPassword={false}`
- Includes inline guidance to percent-encode special characters in the
password

### Shell safety

The generated `--db-url` values are wrapped in single quotes to prevent
shell metacharacter expansion when users paste and run the commands.
`npx supabase login` is intentionally omitted — the `--db-url` flag
authenticates directly against Postgres and does not require a Supabase
account.

### Backup button behaviour in failed states

The "Download backup" button in `PauseFailedState` and
`RestoreFailedState` now always stays enabled:
- **Backup available** — downloads immediately (unchanged)
- **No backup / physical backups** — opens a dialog with CLI
instructions instead of silently failing

## How to test

**Delete project flow**
1. Open any project → Settings → General → Delete project
2. Verify the CLI backup section appears with the project's host, port,
user, and db name pre-filled
3. Verify no Reset database password button is shown

**Paused project**
1. Open a paused project (`ProjectPausedState`) — verify CLI
instructions appear with the "Your project must be resumed before
running these commands." note
2. Open a project paused for 90+ days (`PauseDisabledState`) — verify
CLI instructions do not appear

**Failed states**
1. Simulate a pause-failed or restore-failed state
2. If a downloadable backup exists — "Download backup" downloads it
directly
3. Block the backup API or use a project with physical backups —
"Download backup" should open the CLI instructions dialog

**Error state**
1. Block the project settings API call (DevTools → Network → block
request)
2. Verify an error message appears with a link to Database settings
3. Verify a loading skeleton shows while the request is in flight

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-15 16:39:32 +02:00

131 lines
4.3 KiB
TypeScript

import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { useRouter } from 'next/router'
import { cn } from 'ui'
import { CodeBlock } from 'ui-patterns/CodeBlock'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import {
buildDirectPostgresConnectionUri,
buildLogicalBackupShellScript,
DB_PASSWORD_PLACEHOLDER,
} from './LogicalBackupCliInstructions.utils'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { InlineLink } from '@/components/ui/InlineLink'
import { useProjectSettingsV2Query } from '@/data/config/project-settings-v2-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { DOCS_URL } from '@/lib/constants'
export type LogicalBackupCliInstructionsProps = {
enabled?: boolean
className?: string
showResetPassword?: boolean
note?: string
}
export const LogicalBackupCliInstructions = ({
enabled = true,
className,
showResetPassword = true,
note,
}: LogicalBackupCliInstructionsProps) => {
const router = useRouter()
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
const { can: canResetDbPassword } = useAsyncCheckPermissions(
PermissionAction.UPDATE,
'projects',
{
resource: {
project_id: project?.id,
},
}
)
const {
data: settings,
isSuccess,
isError,
} = useProjectSettingsV2Query({ projectRef: ref }, { enabled: enabled && Boolean(ref) })
const connectionUri =
isSuccess && settings
? buildDirectPostgresConnectionUri({
db_user: settings.db_user,
db_host: settings.db_host,
db_port: settings.db_port,
db_name: settings.db_name,
})
: null
const shellScript = connectionUri ? buildLogicalBackupShellScript(connectionUri) : ''
const resetPasswordHref = ref ? `/project/${ref}/database/settings#database-password` : '#'
const resetDisabled = !canResetDbPassword
return (
<div className={cn('space-y-3', className)}>
<div className="space-y-1">
<h4 className="text-sm font-medium">Back up your database with the Supabase CLI</h4>
<p className="text-sm text-foreground-light">
Use your direct connection string — replace {DB_PASSWORD_PLACEHOLDER} with your database
password.{' '}
<InlineLink href={`${DOCS_URL}/guides/platform/backups`}>Backup documentation</InlineLink>
.
</p>
<p className="text-sm text-foreground-light">
Any reserved character in your password must be percent-encoded in the URL (e.g.{' '}
<code>@</code>&nbsp;→&nbsp;<code>%40</code>, <code>:</code>&nbsp;→&nbsp;<code>%3A</code>,{' '}
<code>/</code>&nbsp;→&nbsp;<code>%2F</code>, <code>#</code>&nbsp;→&nbsp;<code>%23</code>).
Encode <code>%</code> as <code>%25</code> first.
</p>
</div>
{showResetPassword && (
<ButtonTooltip
type="default"
disabled={resetDisabled}
onClick={() => {
if (!resetDisabled && ref) {
void router.push(`/project/${ref}/database/settings#database-password`)
}
}}
tooltip={{
content: {
side: 'bottom',
text: !canResetDbPassword
? 'You need additional permissions to reset the database password'
: undefined,
},
}}
>
Reset database password
</ButtonTooltip>
)}
{note && <p className="text-sm text-foreground-light">{note}</p>}
{isError && (
<p className="text-sm text-foreground-light">
Could not load connection details. Open{' '}
<InlineLink href={resetPasswordHref}>Database settings</InlineLink> to copy your
connection string manually.
</p>
)}
{!isError && !connectionUri && <ShimmeringLoader className="py-4" />}
{connectionUri ? (
<CodeBlock
language="bash"
value={shellScript}
hideLineNumbers
className="[&_code]:text-[12px] [&_code]:text-foreground"
wrapperClassName="[&_pre]:px-4 [&_pre]:py-3"
/>
) : null}
</div>
)
}