Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/error-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ A database operation was blocked because the workspace has used up the operation

### POSTGRES.USAGE_ERROR

A `prisma postgres` subcommand was called with missing or invalid arguments: `create` without a name, `connection delete`/`connection rotate` without a connection id, `backup restore` without `--backup`, or `usage` with `--from` later than `--to`. The nextActions show the corrected command form. Meta: none.
A `prisma postgres` subcommand was called with missing or invalid arguments: `create` without a name, `connection delete`/`connection rotate` without a connection id, `backup restore` without `--backup`, `pitr restore` without `--name` or without a `--to` time that has a time zone, or `usage` with `--from` later than `--to`. The nextActions show the corrected command form. Meta: none.

## PROJECT

Expand Down
12 changes: 12 additions & 0 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ import { postgresConnectionRotateCommand } from "./commands/postgres/connection-
import { postgresCreateCommand } from "./commands/postgres/create";
import { postgresDeleteCommand } from "./commands/postgres/delete";
import { postgresListCommand } from "./commands/postgres/list";
import { postgresPitrRestoreCommand } from "./commands/postgres/pitr-restore";
import { postgresPitrShowCommand } from "./commands/postgres/pitr-show";
import { postgresShowCommand } from "./commands/postgres/show";
import { postgresUsageCommand } from "./commands/postgres/usage";
import { projectCreateCommand } from "./commands/project/create";
Expand Down Expand Up @@ -96,6 +98,8 @@ export const platformCommandFamily: CommandFamily = defineCommandFamily({
postgresCreate: postgresCreateCommand,
postgresUsage: postgresUsageCommand,
postgresBackupRestore: postgresBackupRestoreCommand,
postgresPitrShow: postgresPitrShowCommand,
postgresPitrRestore: postgresPitrRestoreCommand,
postgresDelete: postgresDeleteCommand,
postgresBackupList: postgresBackupListCommand,
postgresConnectionList: postgresConnectionListCommand,
Expand Down Expand Up @@ -231,6 +235,12 @@ export const cliGroups: Readonly<
description:
"The platform takes backups automatically; there is no backup-create command. Restore replaces a database's current state with a backup's contents after exact confirmation of the database's id, or its address when you name it by one.",
},
"postgres pitr": {
brief:
"Restore a database, as it was at a chosen time, into a new database. Show the available times and restore",
description:
"Point in time recovery (PITR) creates a new database from a database's data at a chosen time; the source database does not change. 'show' prints the oldest and newest available time, and 'restore' creates the new database.",
},
"postgres connection": {
brief:
"Manage database connection credentials. Create, rotate, and revoke per-consumer connection URLs",
Expand Down Expand Up @@ -395,6 +405,8 @@ export const mountedCommands: Readonly<Record<string, AnyCommand>> = {
"postgres delete": postgresDeleteCommand,
"postgres backup list": postgresBackupListCommand,
"postgres backup restore": postgresBackupRestoreCommand,
"postgres pitr show": postgresPitrShowCommand,
"postgres pitr restore": postgresPitrRestoreCommand,
"postgres connection list": postgresConnectionListCommand,
"postgres connection create": postgresConnectionCreateCommand,
"postgres connection rotate": postgresConnectionRotateCommand,
Expand Down
107 changes: 107 additions & 0 deletions packages/cli/src/commands/postgres/pitr-restore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/** The `postgres pitr restore` command. */
import { defineCommand, flag } from "@prisma/cli-engine";
import { CliStructuredError, ok } from "@prisma/cli-engine/protocol";
import { CLI_NAME } from "../../cli-name";
import { ensureProjectId } from "../../controllers/database";
import type { DatabasePointInTimeRestoreResult } from "../../types/database";
import {
branchFlag,
databasePositional,
projectFlag,
resolvePostgresDatabase,
} from "./context";
import { postgresTargetLabel, secretBlocks } from "./presentation";

const TIME_ZONE_SUFFIX = /(?:Z|[+-]\d{2}:?\d{2})$/i;

export const postgresPitrRestoreCommand = defineCommand({
args: {
positionals: { database: databasePositional },
flags: {
to: flag.string({
brief:
"Time to restore to, with a time zone, such as 2026-11-30T12:00:00Z; list the range with 'postgres pitr show'",
placeholder: "time",
}),
name: flag.string({
brief: "Name of the new database",
placeholder: "name",
}),
project: projectFlag,
branch: branchFlag,
},
},
help: {
summary:
"Restore a database, as it was at a chosen time, into a new database",
description:
"Creates a new database from the source database's data at the given time and prints its connection URL exactly once; store it now, nothing prints it again. The source database keeps running and does not change. The new database is in the same project, Branch, and region as the source.",
examples: [
"postgres pitr restore db_123 --to 2026-11-30T12:00:00Z --name orders-restored",
],
},
needs: { credentials: true },
handler: async (args, ctx) => {
const name = args.flags.name?.trim();
const to = args.flags.to?.trim() ?? "";
const hasTimeZone = TIME_ZONE_SUFFIX.test(to);
const time = Date.parse(to);
if (!name || !hasTimeZone || Number.isNaN(time)) {
const command = `${CLI_NAME} postgres pitr show <database>`;
throw new CliStructuredError(
"POSTGRES.USAGE_ERROR",
name ? "Restore time required" : "Database name required",
{
why: name
? "A restore needs --to with a date, a time, and a time zone, such as 2026-11-30T12:00:00Z."
: "A restore creates a new database, which needs --name.",
nextActions: [{ kind: "run-command", label: command, command }],
},
);
}

const { provider, projectId, projectName, branchName, database } =
await resolvePostgresDatabase(
ctx,
args.flags,
args.positionals.database,
"postgres pitr restore",
);
const targetTime = new Date(time).toISOString();
const created = await provider.createDatabase({
projectId,
name,
branchName: branchName ?? database.branchName ?? undefined,
region: database.region ?? undefined,
pointInTime: { databaseId: database.id, targetTime },
signal: ctx.signal,
});

const result: DatabasePointInTimeRestoreResult = {
projectId,
projectName,
database: ensureProjectId(created.database, projectId),
connection: created.connection,
connectionString: created.connectionString,
source: { databaseId: database.id, targetTime },
};
return ok(
ctx.present(
{ data: result },
{
human: () =>
secretBlocks(
`Restoring ${database.name} at ${targetTime} to new database "${result.database.name}" in ${postgresTargetLabel(projectName, result.database.branchName)}.`,
result.connectionString,
),
stdout: () => [result.connectionString],
json: () => result,
next: () => {
const command = `${CLI_NAME} postgres show ${result.database.id}`;
return [{ kind: "run-command", label: command, command }];
},
},
),
);
},
});
88 changes: 88 additions & 0 deletions packages/cli/src/commands/postgres/pitr-show.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/** The `postgres pitr show` command. */
import { defineCommand, noDataLines } from "@prisma/cli-engine";
import { ok } from "@prisma/cli-engine/protocol";
import { CLI_NAME } from "../../cli-name";
import type { DatabasePointInTimeResult } from "../../types/database";
import {
branchFlag,
databasePositional,
projectFlag,
resolvePostgresDatabase,
} from "./context";

export const postgresPitrShowCommand = defineCommand({
args: {
positionals: { database: databasePositional },
flags: { project: projectFlag, branch: branchFlag },
},
help: {
summary: "Show the oldest and newest time a database can be restored to",
description:
"Restore to any time in this range with 'postgres pitr restore'. The range is empty until the platform has taken the database's first backup. Needs the Pro plan or higher.",
examples: ["postgres pitr show db_123"],
},
needs: { credentials: true },
handler: async (args, ctx) => {
const { provider, projectId, projectName, database } =
await resolvePostgresDatabase(
ctx,
args.flags,
args.positionals.database,
"postgres pitr show",
);
const { window, retentionDays, availableOnPlan } =
await provider.getPointInTime(database.id, { signal: ctx.signal });
const unavailable = availableOnPlan
? "The database has no time that can be restored yet."
: "Point in time recovery requires the Pro plan or higher.";

const result: DatabasePointInTimeResult = {
projectId,
projectName,
database,
window,
retentionDays,
availableOnPlan,
};
return ok(
ctx.present(
{ data: result },
{
human: () => [
{
kind: "summary",
status: "info",
text: window
? "The database can be restored to any time in this range."
: unavailable,
},
{
kind: "fields",
rows: [
{ label: "database", value: database.name },
...(window
? [
{ label: "oldest", value: window.oldest },
{ label: "newest", value: window.newest },
]
: []),
],
},
],
stdout: window
? () => [`${window.oldest}\t${window.newest}`]
: noDataLines(unavailable),
json: () => result,
next: () => {
if (!window) {
return [];
}

const command = `${CLI_NAME} postgres pitr restore ${database.id} --to ${window.newest} --name <name>`;
return [{ kind: "run-command", label: command, command }];
},
},
),
);
},
});
51 changes: 50 additions & 1 deletion packages/cli/src/lib/database/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export interface DatabaseCreateInput {
name: string;
branchName?: string;
region?: string;
/** Creates the database from another one's data at a time, instead of empty. */
pointInTime?: { databaseId: string; targetTime: string };
signal?: AbortSignal;
}

Expand Down Expand Up @@ -64,6 +66,12 @@ export interface DatabaseBackupListRecord {
hasMore: boolean;
}

export interface DatabasePointInTimeRecord {
window: { oldest: string; newest: string } | null;
retentionDays: number | null;
availableOnPlan: boolean;
}

export interface DatabaseRestoreInput {
targetDatabaseId: string;
sourceDatabaseId: string;
Expand Down Expand Up @@ -122,6 +130,10 @@ export interface DatabaseProvider {
signal?: AbortSignal;
},
): Promise<DatabaseBackupListRecord>;
getPointInTime(
databaseId: string,
options?: { signal?: AbortSignal },
): Promise<DatabasePointInTimeRecord>;
restoreDatabase(options: DatabaseRestoreInput): Promise<DatabaseSummary>;
rotateConnection(
connectionId: string,
Expand Down Expand Up @@ -311,7 +323,9 @@ export function createManagementDatabaseProvider(
body: {
projectId: options.projectId,
name: options.name,
source: { type: "empty" },
source: options.pointInTime
? { type: "pitr", ...options.pointInTime }
: { type: "empty" },
...(options.branchName ? { branchGitName: options.branchName } : {}),
...(options.region ? { region: options.region } : {}),
} as never,
Expand Down Expand Up @@ -469,6 +483,41 @@ export function createManagementDatabaseProvider(
return normalizeBackupList(result.data as RawDatabaseBackupListBody);
},

async getPointInTime(databaseId, options) {
// The published SDK types gain this path when the Management API ships it.
const result = (await client.GET(
"/v1/databases/{databaseId}/backups/pitr" as never,
{
params: { path: { databaseId } },
signal: options?.signal,
} as never,
)) as {
data?: {
data: { window: DatabasePointInTimeRecord["window"] };
meta?: {
backupRetentionDays?: number | null;
availableOnPlan?: boolean;
} | null;
};
error?: ApiErrorBody;
response: Response;
};
if (result.error || !result.data) {
throw await toDatabaseApiError(
"Failed to read the restorable times",
result.response,
result.error,
options?.signal,
);
}

return {
window: result.data.data.window,
retentionDays: result.data.meta?.backupRetentionDays ?? null,
availableOnPlan: result.data.meta?.availableOnPlan ?? true,
};
},

async restoreDatabase(options) {
const result = await client.POST(
"/v1/databases/{targetDatabaseId}/restore",
Expand Down
16 changes: 16 additions & 0 deletions packages/cli/src/types/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,22 @@ export interface DatabaseBackupListResult {
hasMore: boolean;
}

export interface DatabasePointInTimeResult {
projectId: string;
projectName: string;
database: DatabaseSummary;
window: { oldest: string; newest: string } | null;
retentionDays: number | null;
availableOnPlan: boolean;
}

export interface DatabasePointInTimeRestoreResult extends DatabaseCreateResult {
source: {
databaseId: string;
targetTime: string;
};
}

export interface DatabaseRestoreResult {
projectId: string;
projectName: string;
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/tests/e2e-coverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ const EXCLUSIONS: Readonly<Record<string, string>> = {
"Irreversibly moves a project to another workspace, and needs a second workspace plus a recipient who accepts. Not safe to run unattended.",
"postgres backup restore":
"Needs an existing backup. Backups are created on the platform's own schedule, so a database made during the run never has one.",
"postgres pitr show":
"The Management API does not serve it yet. Replace this entry with an e2e test once prisma/pdp-control-plane#6260 is deployed.",
"postgres pitr restore":
"Needs an existing backup. Backups are created on the platform's own schedule, so a database made during the run never has one.",
"git connect":
"Needs a GitHub App installation on the account under test, which CI cannot provision.",
"git disconnect":
Expand Down
2 changes: 2 additions & 0 deletions packages/cli/tests/mount-coverage.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ const EXPECTED_MOUNT_PATHS: readonly string[] = [
"postgres create",
"postgres delete",
"postgres list",
"postgres pitr restore",
"postgres pitr show",
"postgres show",
"postgres usage",
"project create",
Expand Down
Loading
Loading