The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): add backup cli instructions (#44621)
Jordi Enric21584fe51244
diff --git a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsxindex 4e96189765a..40ad7cf88e7 100644--- a/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx+++ b/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx@@ -5,6 +5,7 @@ import { toast } from 'sonner'import { Input } from 'ui'import { CANCELLATION_REASONS } from '@/components/interfaces/Billing/Billing.constants'+import { LogicalBackupCliInstructions } from '@/components/layouts/ProjectLayout/LogicalBackupCliInstructions'import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'import { useSendDowngradeFeedbackMutation } from '@/data/feedback/exit-survey-send'import type { OrgProject } from '@/data/projects/org-projects-infinite-query'@@ -116,7 +117,7 @@ export const DeleteProjectModal = ({<TextConfirmModalvisible={visible}loading={isSubmitting}- size={isFree ? 'small' : 'xlarge'}+ size={isFree ? 'medium' : 'xlarge'}title={`Confirm deletion of ${project?.name}`}variant="destructive"alert={{@@ -138,58 +139,61 @@ export const DeleteProjectModal = ({if (!isSubmitting) onClose()}}>- {/*+ <div className="space-y-6">+ <LogicalBackupCliInstructions enabled={visible} showResetPassword={false} />+ {/*[Joshen] This is basically ExitSurvey.tsx, ideally we have one shared component but the onein ExitSurvey has a Form wrapped around it already. Will probably need some effort to refactorbut leaving that for the future.*/}- {!isFree && (- <>- <div className="space-y-1">- <h4 className="text-base">What made you decide to delete your project?</h4>- </div>- <div className="space-y-4 pt-4">- <div className="flex flex-wrap gap-2" data-toggle="buttons">- {shuffledReasons.map((option) => {- const active = selectedReason[0] === option.value- return (- <label- key={option.value}- className={[- 'flex cursor-pointer items-center space-x-2 rounded-md py-1',- 'pl-2 pr-3 text-center text-sm shadow-sm transition-all duration-100',- `${- active- ? ` bg-foreground text-background opacity-100 hover:bg-opacity-75`- : ` bg-border-strong text-foreground opacity-50 hover:opacity-75`- }`,- ].join(' ')}- >- <input- type="radio"- name="options"- value={option.value}- className="hidden"- checked={active}- onChange={() => onSelectCancellationReason(option.value)}- />- <div>{option.value}</div>- </label>- )- })}+ {!isFree && (+ <>+ <div className="space-y-1">+ <h4 className="text-base">What made you decide to delete your project?</h4></div>- <div className="text-area-text-sm flex flex-col gap-y-2">- <label className="text-sm whitespace-pre-line break-words">{textareaLabel}</label>- <Input.TextArea- name="message"- rows={3}- value={message}- onChange={(event) => setMessage(event.target.value)}- />+ <div className="space-y-4 pt-4">+ <div className="flex flex-wrap gap-2" data-toggle="buttons">+ {shuffledReasons.map((option) => {+ const active = selectedReason[0] === option.value+ return (+ <label+ key={option.value}+ className={[+ 'flex cursor-pointer items-center space-x-2 rounded-md py-1',+ 'pl-2 pr-3 text-center text-sm shadow-sm transition-all duration-100',+ `${+ active+ ? ` bg-foreground text-background opacity-100 hover:bg-opacity-75`+ : ` bg-border-strong text-foreground opacity-50 hover:opacity-75`+ }`,+ ].join(' ')}+ >+ <input+ type="radio"+ name="options"+ value={option.value}+ className="hidden"+ checked={active}+ onChange={() => onSelectCancellationReason(option.value)}+ />+ <div>{option.value}</div>+ </label>+ )+ })}+ </div>+ <div className="text-area-text-sm flex flex-col gap-y-2">+ <label className="text-sm whitespace-pre-line break-words">{textareaLabel}</label>+ <Input.TextArea+ name="message"+ rows={3}+ value={message}+ onChange={(event) => setMessage(event.target.value)}+ />+ </div></div>- </div>- </>- )}+ </>+ )}+ </div></TextConfirmModal>)}diff --git a/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsx b/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsxnew file mode 100644index 00000000000..5ea4f163c61--- /dev/null+++ b/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.tsx@@ -0,0 +1,130 @@+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> → <code>%40</code>, <code>:</code> → <code>%3A</code>,{' '}+ <code>/</code> → <code>%2F</code>, <code>#</code> → <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>+ )+}diff --git a/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.utils.ts b/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.utils.tsnew file mode 100644index 00000000000..15bd2d604bc--- /dev/null+++ b/apps/studio/components/layouts/ProjectLayout/LogicalBackupCliInstructions.utils.ts@@ -0,0 +1,18 @@+export const DB_PASSWORD_PLACEHOLDER = '[YOUR-PASSWORD]'++export function buildDirectPostgresConnectionUri(settings: {+ db_user: string+ db_host: string+ db_port: number+ db_name: string+}): string {+ return `postgresql://${settings.db_user}:${DB_PASSWORD_PLACEHOLDER}@${settings.db_host}:${settings.db_port}/${settings.db_name}`+}++export function buildLogicalBackupShellScript(connectionUri: string): string {+ return [+ `npx supabase db dump --db-url '${connectionUri}' -f roles.sql --role-only`,+ `npx supabase db dump --db-url '${connectionUri}' -f schema.sql`,+ `npx supabase db dump --db-url '${connectionUri}' -f data.sql --use-copy --data-only -x "storage.buckets_vectors" -x "storage.vector_indexes"`,+ ].join('\n')+}diff --git a/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsx b/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsxindex d5317135612..2a6c4c42aec 100644--- a/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/PauseFailedState.tsx@@ -2,10 +2,22 @@ import { PermissionAction, SupportCategories } from '@supabase/shared-types/out/import { useParams } from 'common'import { Download, MoreVertical, Trash } from 'lucide-react'import { useState } from 'react'-import { Button, CriticalIcon, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'ui'+import {+ Button,+ CriticalIcon,+ Dialog,+ DialogContent,+ DialogHeader,+ DialogSection,+ DialogTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from 'ui'import { DeleteProjectModal } from '@/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal'import { SupportLink } from '@/components/interfaces/Support/SupportLink'+import { LogicalBackupCliInstructions } from '@/components/layouts/ProjectLayout/LogicalBackupCliInstructions'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { DropdownMenuItemTooltip } from '@/components/ui/DropdownMenuItemTooltip'import { InlineLink } from '@/components/ui/InlineLink'@@ -18,12 +30,13 @@ export const PauseFailedState = () => {const { ref } = useParams()const { data: project } = useSelectedProjectQuery()const [visible, setVisible] = useState(false)+ const [showCliBackup, setShowCliBackup] = useState(false)const { can: canDeleteProject } = useAsyncCheckPermissions(PermissionAction.UPDATE, 'projects', {resource: { project_id: project?.id },})- const { data } = useDownloadableBackupQuery({ projectRef: ref })+ const { data, isPending: isLoadingBackups } = useDownloadableBackupQuery({ projectRef: ref })const backups = data?.backups ?? []const { mutate: downloadBackup, isPending: isDownloading } = useBackupDownloadMutation({@@ -41,10 +54,19 @@ export const PauseFailedState = () => {const onClickDownloadBackup = () => {if (!ref) return console.error('Project ref is required')- if (backups.length === 0) return console.error('No available backups to download')+ if (backups.length === 0 || data?.status === 'physical-backups-enabled')+ return setShowCliBackup(true)downloadBackup({ ref, backup: backups[0] })}+ const downloadBackupTooltipText = isLoadingBackups+ ? undefined+ : data?.status === 'physical-backups-enabled'+ ? 'Project uses physical backups — click to see CLI backup instructions'+ : backups.length === 0+ ? 'No downloadable backup available — click to see CLI backup instructions'+ : undefined+return (<><div className="flex items-center justify-center h-full">@@ -82,17 +104,12 @@ export const PauseFailedState = () => {<ButtonTooltiptype="default"icon={<Download />}- loading={isDownloading}- disabled={backups.length === 0}+ disabled={isLoadingBackups}+ loading={isDownloading || isLoadingBackups}tooltip={{content: {side: 'bottom',- text:- data?.status === 'physical-backups-enabled'- ? 'No available backups to download as project is on physical backups'- : backups.length === 0- ? 'No available backups to download'- : undefined,+ text: downloadBackupTooltipText,},}}onClick={onClickDownloadBackup}@@ -133,6 +150,18 @@ export const PauseFailedState = () => {</div></div></div>++ <Dialog open={showCliBackup} onOpenChange={setShowCliBackup}>+ <DialogContent size="medium">+ <DialogHeader>+ <DialogTitle>Back up your database</DialogTitle>+ </DialogHeader>+ <DialogSection>+ <LogicalBackupCliInstructions showResetPassword={false} />+ </DialogSection>+ </DialogContent>+ </Dialog>+<DeleteProjectModal visible={visible} onClose={() => setVisible(false)} /></>)diff --git a/apps/studio/components/layouts/ProjectLayout/PausedState/ProjectPausedState.tsx b/apps/studio/components/layouts/ProjectLayout/PausedState/ProjectPausedState.tsxindex ea4787ca574..e4a3ffc1852 100644--- a/apps/studio/components/layouts/ProjectLayout/PausedState/ProjectPausedState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/PausedState/ProjectPausedState.tsx@@ -36,6 +36,7 @@ import {extractPostgresVersionDetails,PostgresVersionSelector,} from '@/components/interfaces/ProjectCreation/PostgresVersionSelector'+import { LogicalBackupCliInstructions } from '@/components/layouts/ProjectLayout/LogicalBackupCliInstructions'import AlertError from '@/components/ui/AlertError'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { InlineLinkClassName } from '@/components/ui/InlineLink'@@ -226,6 +227,12 @@ export const ProjectPausedState = ({ product }: ProjectPausedStateProps) => {</div></CardContent>+ {!isRestoreDisabled && (+ <div className="border-t px-6 py-4">+ <LogicalBackupCliInstructions note="Your project must be resumed before running these commands." />+ </div>+ )}+{isError && (<AlertErrorclassName="rounded-none border-0"diff --git a/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsx b/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsxindex 3d986811a11..9de26db616a 100644--- a/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsx+++ b/apps/studio/components/layouts/ProjectLayout/RestoreFailedState.tsx@@ -2,10 +2,22 @@ import { PermissionAction, SupportCategories } from '@supabase/shared-types/out/import { useParams } from 'common'import { Download, MoreVertical, Trash } from 'lucide-react'import { useState } from 'react'-import { Button, CriticalIcon, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'ui'+import {+ Button,+ CriticalIcon,+ Dialog,+ DialogContent,+ DialogHeader,+ DialogSection,+ DialogTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+} from 'ui'import { DeleteProjectModal } from '@/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal'import { SupportLink } from '@/components/interfaces/Support/SupportLink'+import { LogicalBackupCliInstructions } from '@/components/layouts/ProjectLayout/LogicalBackupCliInstructions'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { DropdownMenuItemTooltip } from '@/components/ui/DropdownMenuItemTooltip'import { InlineLink } from '@/components/ui/InlineLink'@@ -18,12 +30,13 @@ export const RestoreFailedState = () => {const { ref } = useParams()const { data: project } = useSelectedProjectQuery()const [visible, setVisible] = useState(false)+ const [showCliBackup, setShowCliBackup] = useState(false)const { can: canDeleteProject } = useAsyncCheckPermissions(PermissionAction.UPDATE, 'projects', {resource: { project_id: project?.id },})- const { data } = useDownloadableBackupQuery({ projectRef: ref })+ const { data, isPending: isLoadingBackups } = useDownloadableBackupQuery({ projectRef: ref })const backups = data?.backups ?? []const { mutate: downloadBackup, isPending: isDownloading } = useBackupDownloadMutation({@@ -41,10 +54,19 @@ export const RestoreFailedState = () => {const onClickDownloadBackup = () => {if (!ref) return console.error('Project ref is required')- if (backups.length === 0) return console.error('No available backups to download')+ if (backups.length === 0 || data?.status === 'physical-backups-enabled')+ return setShowCliBackup(true)downloadBackup({ ref, backup: backups[0] })}+ const downloadBackupTooltipText = isLoadingBackups+ ? undefined+ : data?.status === 'physical-backups-enabled'+ ? 'Project uses physical backups — click to see CLI backup instructions'+ : backups.length === 0+ ? 'No downloadable backup available — click to see CLI backup instructions'+ : undefined+return (<><div className="flex items-center justify-center h-full">@@ -83,17 +105,12 @@ export const RestoreFailedState = () => {<ButtonTooltiptype="default"icon={<Download />}- loading={isDownloading}- disabled={backups.length === 0}+ disabled={isLoadingBackups}+ loading={isDownloading || isLoadingBackups}tooltip={{content: {side: 'bottom',- text:- data?.status === 'physical-backups-enabled'- ? 'No available backups to download as project is on physical backups'- : backups.length === 0- ? 'No available backups to download'- : undefined,+ text: downloadBackupTooltipText,},}}onClick={onClickDownloadBackup}@@ -135,6 +152,18 @@ export const RestoreFailedState = () => {</div></div></div>++ <Dialog open={showCliBackup} onOpenChange={setShowCliBackup}>+ <DialogContent size="medium">+ <DialogHeader>+ <DialogTitle>Back up your database</DialogTitle>+ </DialogHeader>+ <DialogSection>+ <LogicalBackupCliInstructions showResetPassword={false} />+ </DialogSection>+ </DialogContent>+ </Dialog>+<DeleteProjectModal visible={visible} onClose={() => setVisible(false)} /></>)diff --git a/apps/studio/tests/unit/LogicalBackupCliInstructions.test.ts b/apps/studio/tests/unit/LogicalBackupCliInstructions.test.tsnew file mode 100644index 00000000000..e2f0444f007--- /dev/null+++ b/apps/studio/tests/unit/LogicalBackupCliInstructions.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest'++import {+ buildDirectPostgresConnectionUri,+ buildLogicalBackupShellScript,+ DB_PASSWORD_PLACEHOLDER,+} from '../../components/layouts/ProjectLayout/LogicalBackupCliInstructions.utils'++describe('buildDirectPostgresConnectionUri', () => {+ it('builds a valid postgresql URI from settings', () => {+ const uri = buildDirectPostgresConnectionUri({+ db_user: 'postgres',+ db_host: 'db.abcdef.supabase.co',+ db_port: 5432,+ db_name: 'postgres',+ })+ expect(uri).toBe(+ `postgresql://postgres:${DB_PASSWORD_PLACEHOLDER}@db.abcdef.supabase.co:5432/postgres`+ )+ })++ it('uses the password placeholder, never a real password', () => {+ const uri = buildDirectPostgresConnectionUri({+ db_user: 'postgres',+ db_host: 'db.abcdef.supabase.co',+ db_port: 5432,+ db_name: 'postgres',+ })+ expect(uri).toContain(DB_PASSWORD_PLACEHOLDER)+ expect(uri).not.toContain('secret')+ })++ it('includes a non-default port', () => {+ const uri = buildDirectPostgresConnectionUri({+ db_user: 'postgres',+ db_host: 'db.abcdef.supabase.co',+ db_port: 6543,+ db_name: 'postgres',+ })+ expect(uri).toContain(':6543/')+ })+})++describe('buildLogicalBackupShellScript', () => {+ const testUri = `postgresql://postgres:${DB_PASSWORD_PLACEHOLDER}@db.abcdef.supabase.co:5432/postgres`++ it('produces exactly three commands', () => {+ const script = buildLogicalBackupShellScript(testUri)+ expect(script.split('\n')).toHaveLength(3)+ })++ it('wraps the connection URI in single quotes to prevent shell expansion', () => {+ const script = buildLogicalBackupShellScript(testUri)+ for (const line of script.split('\n')) {+ expect(line).toContain(`'${testUri}'`)+ }+ })++ it('dumps roles, schema, and data in that order', () => {+ const [roles, schema, data] = buildLogicalBackupShellScript(testUri).split('\n')+ expect(roles).toContain('--role-only')+ expect(roles).toContain('-f roles.sql')+ expect(schema).toContain('-f schema.sql')+ expect(data).toContain('--data-only')+ expect(data).toContain('-f data.sql')+ })++ it('excludes storage vector tables from the data dump', () => {+ const [, , data] = buildLogicalBackupShellScript(testUri).split('\n')+ expect(data).toContain('-x "storage.buckets_vectors"')+ expect(data).toContain('-x "storage.vector_indexes"')+ })++ it('does not include npx supabase login', () => {+ const script = buildLogicalBackupShellScript(testUri)+ expect(script).not.toContain('supabase login')+ })+})