backupdrill 2.11.2 → 2.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/manifest.js CHANGED
@@ -16,12 +16,16 @@ import { GRANT_PRIVILEGES, GRANT_ROLES, GRANTED_OBJECT_KINDS } from "./grants.js
16
16
  * - (仍是 2)2.9.0 加 database.grants:可加字段,旧读取端忽略它、照旧恢复,不升版本,
17
17
  * 免得还没升级的 CLI 和 worker 拒读新快照。
18
18
  * - (仍是 2)2.10.0 加 auth:同样是可加字段。旧读取端忽略它和 auth.dump,演练和恢复与之前完全一样。
19
+ * - (仍是 2)2.12.0 加 storage.vanished / storage.partial / storageFailure:可加字段。旧读取端把部分
20
+ * 复制的快照当成"文件清单就是这些",恢复与演练照旧只处理清单里的文件。
19
21
  */
20
22
  export const MANIFEST_SCHEMA_VERSION = 2;
21
23
  /**
22
24
  * Auth 用户备份的结果。只有 included 的快照带 dump 和统计;其余状态说明为什么没备上。
23
25
  * - included:auth.dump 在快照里,行数可以合法为 0
24
- * - skipped:默认开启但做不了(无权读取、没有 auth schema、存储不支持、schemas 可能已含 auth、太大),不算失败
26
+ * - skipped:默认开启但做不了(无权读取、没有 auth 表、存储不支持、主 dump 已含 auth、schema 名字不是普通名字、太大),不算失败。
27
+ * schemas_not_plain 是 2.12.1 之前的"用了模式写法";2.12.1 起按解析出的名字判断,记 schema_names_not_plain。
28
+ * server_too_old(2.12.1 起):源库是 PostgreSQL 11,数据库照常备,auth.dump 要 12
25
29
  * - failed:权限够、却在导出或上传时出错;只有显式要求时备份才因此失败
26
30
  */
27
31
  export const AUTH_STATUSES = ["included", "skipped", "failed"];
@@ -31,8 +35,10 @@ export const AUTH_SKIP_REASONS = [
31
35
  "unsupported_destination",
32
36
  "schemas_include_auth",
33
37
  "schemas_not_plain",
38
+ "schema_names_not_plain",
34
39
  "too_large",
35
40
  "snapshot_unavailable",
41
+ "server_too_old",
36
42
  ];
37
43
  /** 结构断言失败时的统一出错口径:说清哪个字段坏了,让"桶里的 manifest 被篡改/截断"可定位。 */
38
44
  function malformed(what) {
@@ -259,8 +265,45 @@ function assertManifestShape(m) {
259
265
  }
260
266
  }
261
267
  }
268
+ if (m.storage.vanished !== undefined) {
269
+ if (!Array.isArray(m.storage.vanished))
270
+ malformed("storage.vanished");
271
+ for (const v of m.storage.vanished) {
272
+ if (typeof v?.bucket !== "string" || typeof v?.key !== "string")
273
+ malformed("storage.vanished[]");
274
+ }
275
+ }
276
+ if (m.storage.partial !== undefined) {
277
+ const p = m.storage.partial;
278
+ if (typeof p !== "object" || p === null)
279
+ malformed("storage.partial");
280
+ // copied 必须就是 files 的条数,total = copied + 各原因没复制的个数:不然"备了 N 个"的说法和清单对不上
281
+ if (!Number.isSafeInteger(p.copied) || p.copied !== m.storage.files.length || !Number.isSafeInteger(p.total)) {
282
+ malformed("storage.partial.copied/total");
283
+ }
284
+ if (!Array.isArray(p.notCopied) || p.notCopied.length === 0)
285
+ malformed("storage.partial.notCopied");
286
+ for (const n of p.notCopied) {
287
+ if (!STORAGE_NOT_COPIED_REASONS.includes(n?.reason) || !Number.isSafeInteger(n.count) || n.count <= 0) {
288
+ malformed("storage.partial.notCopied[]");
289
+ }
290
+ }
291
+ if (p.total !== p.copied + p.notCopied.reduce((sum, n) => sum + n.count, 0)) {
292
+ malformed("storage.partial.total does not match copied + notCopied");
293
+ }
294
+ }
295
+ }
296
+ if (m.storageFailure !== undefined) {
297
+ if (typeof m.storageFailure !== "object" || m.storageFailure === null || typeof m.storageFailure.reason !== "string") {
298
+ malformed("storageFailure");
299
+ }
300
+ // 失败的那次 Storage 一个文件也不算进快照:两者同时出现说明 manifest 被拼错了
301
+ if (m.storage !== null)
302
+ malformed("storageFailure with a storage section");
262
303
  }
263
304
  }
305
+ /** manifest.storage.partial.notCopied[].reason 的取值 */
306
+ export const STORAGE_NOT_COPIED_REASONS = ["time_budget", "read_stalled", "key_too_long"];
264
307
  /**
265
308
  * 解析桶里的 manifest.json,并做**向前兼容**校验:比本程序更新的格式一律拒绝,
266
309
  * 明确告诉用户升级,绝不按旧结构硬解析(那会静默产出错误的演练/恢复结果)。
@@ -74,8 +74,15 @@ export function describeOrphanedForeignKey(orphaned) {
74
74
  // 不说"指向不存在的行":MATCH FULL 下部分为空的行也算违反,它们未必缺对应的行(文案审查)
75
75
  return `${rows} in ${orphaned.table} break foreign key ${orphaned.constraint}, which references ${orphaned.referencedTable}`;
76
76
  }
77
- /** 外键两端的键列里有没有生成列(attgenerated:存储型 's',PostgreSQL 18 起还有虚拟型 'v') */
77
+ /**
78
+ * 外键两端的键列里有没有生成列(attgenerated:存储型 's',PostgreSQL 18 起还有虚拟型 'v')。
79
+ * 生成列和 attgenerated 都是 12 才有的:恢复目标是 11 时没有生成列,也不能去查这一列——
80
+ * 查了会报 "column does not exist",把整个恢复事务弄坏
81
+ */
78
82
  async function hasGeneratedKeyColumn(client, fk) {
83
+ const version = await client.query("show server_version_num");
84
+ if (Number(version.rows[0].server_version_num) < 120000)
85
+ return false;
79
86
  const qualified = (table) => `${quoteIdent(table.schema)}.${quoteIdent(table.name)}`;
80
87
  const { rows } = await client.query(`select exists (
81
88
  select 1 from pg_attribute
package/dist/ping.d.ts CHANGED
@@ -14,6 +14,11 @@ export declare function createPinger(rawUrl: string | undefined, opts?: {
14
14
  }): Pinger;
15
15
  /** backup 成功时发给监控的一行。快照名取对象键里的目录名(和 drill --snapshot 认的是同一个) */
16
16
  export declare function backupSummary(manifest: Manifest): string;
17
+ /**
18
+ * 备份完成、但有要处理的部分没备全时(退出码 3)的通知:先说哪部分出了问题、为什么,再说数据库存在了哪个快照。
19
+ * Storage 和 Auth 同时出问题时两样都写。
20
+ */
21
+ export declare function incompleteBackupSummary(manifest: Manifest, authRequiredButMissing: boolean): string;
17
22
  /** drill 跑完(没抛错)后发哪种 ping、带什么:通过 = 成功;没通过 = 失败,列出没过的检查 */
18
23
  export declare function drillOutcome(report: DrillReport): {
19
24
  pass: boolean;
package/dist/ping.js CHANGED
@@ -128,6 +128,26 @@ export function backupSummary(manifest) {
128
128
  (manifest.auth?.status === "included" ? ` + ${manifest.auth.rows.users} Auth users` : "") +
129
129
  `, snapshot ${manifest.dump.key.split("/").at(-2) ?? manifest.createdAt}`);
130
130
  }
131
+ /**
132
+ * 备份完成、但有要处理的部分没备全时(退出码 3)的通知:先说哪部分出了问题、为什么,再说数据库存在了哪个快照。
133
+ * Storage 和 Auth 同时出问题时两样都写。
134
+ */
135
+ export function incompleteBackupSummary(manifest, authRequiredButMissing) {
136
+ const problems = [];
137
+ const partial = manifest.storage?.partial;
138
+ if (manifest.storageFailure)
139
+ problems.push(`Storage backup failed (${manifest.storageFailure.reason}).`);
140
+ else if (partial)
141
+ problems.push(`Storage backup incomplete. Copied ${partial.copied} of ${partial.total} files.`);
142
+ if (authRequiredButMissing) {
143
+ problems.push(`Auth users were required but not backed up (${manifest.auth?.reason ?? "unknown reason"}).`);
144
+ }
145
+ const saved = `Database saved in snapshot ${manifest.dump.key.split("/").at(-2) ?? manifest.createdAt} ` +
146
+ `(${manifest.database.tableCount} tables` +
147
+ (manifest.auth?.status === "included" ? `, ${manifest.auth.rows.users} Auth users` : "") +
148
+ `).`;
149
+ return `backupdrill ${TOOL_VERSION}. ${problems.join(" ")} ${saved}`;
150
+ }
131
151
  /** drill 跑完(没抛错)后发哪种 ping、带什么:通过 = 成功;没通过 = 失败,列出没过的检查 */
132
152
  export function drillOutcome(report) {
133
153
  const outcome = `snapshot ${report.snapshot}, ${report.restoredTableCount} tables / ` +
@@ -37,7 +37,12 @@ export interface AuthRecoveryText {
37
37
  /**
38
38
  * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版(renderRecoveryDoc)和托管 worker 的
39
39
  * Google Drive 版共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,两边不能各写各的。
40
- * 没有 auth 字段的快照:contentsLine 为空、included 为 null,手册和 2.10.0 之前一样
40
+ * 没有 auth 字段的快照:included 为 null;contentsLine 只在备份范围选了 auth 时有一行(见 authMaybeInMainDump),否则为空,手册和 2.10.0 之前一样
41
41
  */
42
+ /**
43
+ * 没有 auth.dump、备份范围却选了 auth 的快照:Auth 用户可能在主 dump 里。manifest 的表清单是转储前查的,
44
+ * 证明不了归档里有(表归扩展所有、分区落在范围外、转储期间被删都会让归档里没有),手册只告诉读者怎么查,不担保
45
+ */
46
+ export declare function authMaybeInMainDump(manifest: Manifest): boolean;
42
47
  export declare function authRecoveryText(manifest: Manifest, place: RecoveryDocPlace): AuthRecoveryText;
43
48
  export declare function renderRecoveryDoc(manifest: Manifest, ctx: RecoveryDocContext): string;
@@ -13,6 +13,13 @@ export function markdownCode(text) {
13
13
  const fence = "`".repeat(longestRun + 1);
14
14
  return `${fence} ${visible} ${fence}`;
15
15
  }
16
+ /**
17
+ * 手册里列出的 schema 名字。2.12.1 起它们取自源库本身,可能带反引号、换行、Markdown 符号:
18
+ * 小写普通名字原样写(和以前的手册一样),其余放进行内代码,控制字符转义、反引号用更长的围栏挡住
19
+ */
20
+ function markdownSchemaName(name) {
21
+ return /^[a-z_][a-z0-9_]*$/.test(name) ? name : markdownCode(name);
22
+ }
16
23
  function quoteSqlIdent(name) {
17
24
  return `"${name.replace(/"/g, '""')}"`;
18
25
  }
@@ -21,10 +28,12 @@ const AUTH_NOT_INCLUDED_TEXT = {
21
28
  no_permission: "the backup role couldn't read every row of the Auth tables",
22
29
  no_auth_schema: "the source database has no Supabase auth schema",
23
30
  unsupported_destination: "this destination couldn't hold the Auth archive",
24
- schemas_include_auth: "the auth schema is part of the database dump",
31
+ // 2.12.1 之前的快照:用了模式写法,算不清选中了哪些 schema
25
32
  schemas_not_plain: "the schema list used a pattern or a quoted name; the Auth users are in the database dump only if one of those patterns matched auth",
33
+ schema_names_not_plain: "one of the selected schema names blocks `auth.dump`. Each name must start with `a`–`z` or `_` and use only `a`–`z`, `0`–`9` and `_`. The database dump excludes `auth`",
26
34
  too_large: "the Auth archive was larger than 2 GiB",
27
35
  snapshot_unavailable: "a consistent snapshot for the Auth export couldn't be set up",
36
+ server_too_old: "the source database runs PostgreSQL 11, and a separate `auth.dump` requires PostgreSQL 12 or newer",
28
37
  };
29
38
  /** POSIX 安全的 shell 值引用:项目名/前缀里合法的空格与元字符不得拆散或改写命令。 */
30
39
  function shellQuote(value) {
@@ -33,8 +42,17 @@ function shellQuote(value) {
33
42
  /**
34
43
  * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版(renderRecoveryDoc)和托管 worker 的
35
44
  * Google Drive 版共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,两边不能各写各的。
36
- * 没有 auth 字段的快照:contentsLine 为空、included 为 null,手册和 2.10.0 之前一样
45
+ * 没有 auth 字段的快照:included 为 null;contentsLine 只在备份范围选了 auth 时有一行(见 authMaybeInMainDump),否则为空,手册和 2.10.0 之前一样
46
+ */
47
+ /**
48
+ * 没有 auth.dump、备份范围却选了 auth 的快照:Auth 用户可能在主 dump 里。manifest 的表清单是转储前查的,
49
+ * 证明不了归档里有(表归扩展所有、分区落在范围外、转储期间被删都会让归档里没有),手册只告诉读者怎么查,不担保
37
50
  */
51
+ export function authMaybeInMainDump(manifest) {
52
+ if (manifest.auth?.status === "included")
53
+ return false;
54
+ return manifest.database.schemas.includes("auth") || manifest.auth?.reason === "schemas_include_auth";
55
+ }
38
56
  export function authRecoveryText(manifest, place) {
39
57
  const db = manifest.database;
40
58
  const mb = (bytes) => (bytes / 1024 / 1024).toFixed(1);
@@ -48,12 +66,15 @@ export function authRecoveryText(manifest, place) {
48
66
  ? `- **Supabase Auth users**: ${authListing}
49
67
  (pg_dump custom format, ${mb(auth.dump.bytes)} MB, sha256 \`${auth.dump.sha256}\`) — ${auth.rows.users.toLocaleString("en-US")} users, ${auth.rows.identities.toLocaleString("en-US")} sign-in identities
50
68
  `
51
- : manifest.auth
52
- ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? markdownCode(manifest.auth.reason ?? "not captured")})
69
+ : authMaybeInMainDump(manifest)
70
+ ? `- **Supabase Auth users**: this snapshot has no separate \`auth.dump\`. The schema list selected \`auth\`, so the database dump may hold them. Before restoring Auth users, run \`pg_restore --list dump.pgcustom\` and look for \`TABLE DATA\` entries for \`auth.users\` and \`auth.identities\`.
71
+ `
72
+ : manifest.auth
73
+ ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? markdownCode(manifest.auth.reason ?? "not captured")})
53
74
  `
54
- : "";
75
+ : "";
55
76
  // 空目标检查用的 schema 列表(SQL 字符串字面量,单引号按 SQL 规则加倍)
56
- // 含 Auth 的快照里 schemas 全是普通名字(见 authInSchemas),按 pg_dump 的规则规范化后逐个比较
77
+ // 含 Auth 的快照里 schemas 全是普通名字(备份端 planAuth 保证),按 pg_dump 的规则规范化后逐个比较
57
78
  // plainSchemaName 只放行 [a-z0-9_],拼进 SQL 字面量是安全的;万一出现别的(不该发生),整项不放进去
58
79
  const schemaListSql = db.schemas
59
80
  .map((name) => plainSchemaName(name))
@@ -170,6 +191,12 @@ export function renderRecoveryDoc(manifest, ctx) {
170
191
  const db = manifest.database;
171
192
  const extensions = db.extensions ?? [];
172
193
  const storage = manifest.storage;
194
+ // 授权 SQL 里有取自源库的 schema 和对象名,可能带反引号:围栏比 SQL 里最长的一串反引号还长,名字关不掉它
195
+ const grantsSql = recoveryGrantsSql(db);
196
+ let longestBacktickRun = 0;
197
+ for (const run of grantsSql.matchAll(/`+/g))
198
+ longestBacktickRun = Math.max(longestBacktickRun, run[0].length);
199
+ const sqlFence = "`".repeat(Math.max(3, longestBacktickRun + 1));
173
200
  const mb = (bytes) => (bytes / 1024 / 1024).toFixed(1);
174
201
  // 归档格式跟随 dump 工具版本(允许比服务端新):pg_restore 必须 ≥ 两者较大值,
175
202
  // 只按服务端版本指引会让 PG17 的 pg_restore 读不了 PG18 pg_dump 写的归档。
@@ -204,15 +231,20 @@ export function renderRecoveryDoc(manifest, ctx) {
204
231
  ...(storage ? [` --target-supabase-url https://<target-ref>.supabase.co \\`] : []),
205
232
  ` --confirm-target <target-ref>`,
206
233
  ].join("\n");
207
- // 没有 Auth 的快照:以下两段与 2.10.0 之前逐字一致
234
+ // 没有 Auth 的快照:以下两段与 2.10.0 之前逐字一致。备份范围选了 auth 的快照另说:Auth 用户可能在主 dump 里,
235
+ // 这里只列确实缺的东西,怎么查写在清单那一行
208
236
  const notCovered = auth
209
237
  ? auth.notCovered
210
- : `Supabase **Auth users/sessions, secret values, Edge Function code and most
238
+ : authMaybeInMainDump(manifest)
239
+ ? `Secret values, Edge Function code and most platform settings are **NOT in this
240
+ snapshot**. After restoring, reconfigure them by hand.
241
+ `
242
+ : `Supabase **Auth users/sessions, secret values, Edge Function code and most
211
243
  platform settings are NOT in this snapshot**. After restoring, reconfigure them
212
244
  by hand. This is a database + Storage snapshot, not a full project image.
213
245
  ${db.schemas.includes("auth")
214
- ? ""
215
- : `
246
+ ? ""
247
+ : `
216
248
  If a table in this snapshot has a foreign key into \`auth.users\` (a \`profiles.id\`
217
249
  that references it, for example), copy the Auth users into the new project
218
250
  **before** restoring, or that foreign key can't be created and the restore fails.
@@ -292,14 +324,19 @@ works with standard PostgreSQL tools against this bucket alone.
292
324
 
293
325
  - **Database dump**: \`${manifest.dump.key}\`
294
326
  (pg_dump custom format, ${mb(manifest.dump.bytes)} MB, sha256 \`${manifest.dump.sha256}\`)
295
- - schemas: ${db.schemas.join(", ")} — ${db.tableCount} tables, ~${db.estimatedRowTotal.toLocaleString("en-US")} rows at backup time
327
+ - schemas: ${db.schemas.map(markdownSchemaName).join(", ")} — ${db.tableCount} tables, ~${db.estimatedRowTotal.toLocaleString("en-US")} rows at backup time
296
328
  - source PostgreSQL ${db.serverVersion}, archive written by ${db.pgDumpVersion} — restore with pg_restore ${requiredRestoreMajor} or newer (the archive format follows the dump tool, not the server)
297
329
  ${extensions.length
298
330
  ? ` - extensions required: ${extensions.map((e) => `${e.name} (schema "${e.schema}")`).join(", ")}`
299
331
  : " - no extensions recorded"}
300
332
  - **Storage files**: ${storage
301
- ? `${storage.fileCount} files, ${mb(storage.totalBytes)} MB under \`${base}/storage/<bucket>/<key>\` — per-file sha256 in manifest.json`
302
- : "none (database-only snapshot)"}
333
+ ? storage.partial
334
+ ? `copied ${storage.partial.copied} of ${storage.partial.total} files (${mb(storage.totalBytes)} MB) to \`${base}/storage/<bucket>/<key>\`. ` +
335
+ `See manifest.json for file checksums and \`storage.partial\` for skip counts by reason`
336
+ : `${storage.fileCount} files, ${mb(storage.totalBytes)} MB under \`${base}/storage/<bucket>/<key>\` — per-file sha256 in manifest.json`
337
+ : manifest.storageFailure
338
+ ? `not in this snapshot — copying them failed (${manifest.storageFailure.reason}); the database part is complete`
339
+ : "none (database-only snapshot)"}
303
340
  ${authText.contentsLine}- **Machine-readable inventory**: \`${base}/manifest.json\`
304
341
 
305
342
  ## Not covered — plan for these separately
@@ -327,9 +364,9 @@ ${restoreSteps}
327
364
  give the three roles Supabase's old default access to everything in \`public\`;
328
365
  afterwards, revoke it on any table you had kept private:`}
329
366
 
330
- \`\`\`sql
331
- ${recoveryGrantsSql(db)}
332
- \`\`\`
367
+ ${sqlFence}sql
368
+ ${grantsSql}
369
+ ${sqlFence}
333
370
 
334
371
  ## Restore Storage files
335
372
 
package/dist/restore.js CHANGED
@@ -4,9 +4,8 @@ import { createWriteStream } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join, dirname, resolve, sep } from "node:path";
6
6
  import { pipeline } from "node:stream/promises";
7
- import { GetObjectCommand } from "@aws-sdk/client-s3";
8
7
  import { parseManifest } from "./manifest.js";
9
- import { s3SnapshotStore } from "./snapshot-store.js";
8
+ import { s3SnapshotStore, s3StorageSource } from "./snapshot-store.js";
10
9
  import { afterCommit, deferredForeignKeysOf, restoreDatabaseArtifact, userObjectCountSql, installExtensions, projectRefOf, refFromStorageEndpoint, assertNoHostOverride, normalizeHost, } from "./restore-engine.js";
11
10
  import { checkExternalReferences, describe } from "./external-refs.js";
12
11
  import { verifyRestored } from "./drill.js";
@@ -20,6 +19,7 @@ import { describeTarget, restoreRecordKey } from "./restore-record.js";
20
19
  import { primaryAuthRestoreError, AUTH_TABLE_KEYS, authRestoreFailureMessage, authRestoreNotes, targetIdentity, transactionOutcome, authRestorePreflight, largeObjectEntries, psqlProblem, readAuthArchive, restoreWithAuth, } from "./auth-restore.js";
21
20
  import { parsePgDumpMajor } from "./backup.js";
22
21
  import { log } from "./log.js";
22
+ import { schemaNamesText } from "./schema-patterns.js";
23
23
  /** 归档可读性要求:pg_restore 必须 ≥ max(写入工具版本, 源服务端版本)——格式跟随写入工具。 */
24
24
  export function requiredRestoreToolMajor(manifest) {
25
25
  return Math.max(parsePgDumpMajor(manifest.database.pgDumpVersion) ?? 0, parseInt(manifest.database.serverVersion, 10) || 0);
@@ -128,6 +128,17 @@ export function assertRequestApplies(manifest, wantsDatabase, wantsStorageUpload
128
128
  throw new Error("nothing to do: no database restore was requested (--database) and this snapshot has no " +
129
129
  "Storage files to download.");
130
130
  }
131
+ // 部分复制、一个文件也没复制进来的快照:本地下载无事可做;上传到目标时,没记下 bucket 设置也无事可做
132
+ // (没文件也能建 bucket)。不能把空操作报成一次成功恢复。Storage 本来就是空的完整快照不在此列
133
+ const nothingCopied = Boolean(manifest.storage?.partial) && manifest.storage.files.length === 0;
134
+ if (!wantsDatabase && !wantsStorageUpload && nothingCopied) {
135
+ throw new Error("nothing to do: no database restore was requested (--database) and none of this snapshot's " +
136
+ "Storage files were copied when it was taken.");
137
+ }
138
+ if (!wantsDatabase && wantsStorageUpload && nothingCopied && !manifest.storage.buckets?.length) {
139
+ throw new Error("nothing to do: this snapshot has no Storage files or bucket settings to restore. " +
140
+ "To restore its database, add --database.");
141
+ }
131
142
  }
132
143
  /**
133
144
  * 正式执行的确认门(PRD §5.3.3):用户必须键入目标 project ref(或非 Supabase 目标的
@@ -171,7 +182,7 @@ export function assertConfirmedTarget(confirmTarget, targetDatabaseUrl, targetSu
171
182
  * 用户会以为自己漏了一步,其实只需要换一个空项目。
172
183
  */
173
184
  export function nonEmptyTargetMessage(schemas, objectCount, alsoRestoringStorage) {
174
- const message = `target schema(s) ${schemas.join(", ")} contain ${objectCount} existing object(s) — ` +
185
+ const message = `target schema(s) ${schemaNamesText(schemas)} contain ${objectCount} existing object(s) — ` +
175
186
  `restore only writes into an empty target. Create a fresh Supabase project ` +
176
187
  `(or empty these schemas) and retry.`;
177
188
  if (!alsoRestoringStorage)
@@ -225,14 +236,14 @@ async function targetStateAfterFailure(targetUrl, schemas) {
225
236
  return (" It ran in one transaction and was rolled back, so nothing from the snapshot is on the target and " +
226
237
  "you can run restore again on the same project once the cause is fixed.");
227
238
  }
228
- return (` The restore runs in one transaction, yet schema(s) ${schemas.join(", ")} now hold ${objectCount} ` +
239
+ return (` The restore runs in one transaction, yet schema(s) ${schemaNamesText(schemas)} now hold ${objectCount} ` +
229
240
  `object(s), so it may have committed before pg_restore lost its connection. Check the target before ` +
230
241
  `doing anything else; restore won't write into it again while those objects are there.`);
231
242
  }
232
243
  /** README 里讲怎么先把 Auth 用户搬过去的那一节;报错和 dry-run 都指向它。 */
233
244
  const AUTH_USERS_GUIDE = "https://github.com/backupdrill/cli#tables-that-reference-authusers";
234
245
  function referencesHint(schemas) {
235
- return (`This backup only holds schema(s) ${schemas.join(", ")}, so those rows have to be on the target before ` +
246
+ return (`This backup only holds schema(s) ${schemaNamesText(schemas)}, so those rows have to be on the target before ` +
236
247
  `the restore. Copy them over first (Supabase Auth users: ${AUTH_USERS_GUIDE}), then run restore again.`);
237
248
  }
238
249
  /**
@@ -258,7 +269,7 @@ function logExternalReferences(check, schemas, printProblems) {
258
269
  }
259
270
  }
260
271
  else if (!check.unchecked.length) {
261
- log.ok(`references outside the backup: no foreign key points outside ${schemas.join(", ")}`);
272
+ log.ok(`references outside the backup: no foreign key points outside ${schemaNamesText(schemas)}`);
262
273
  }
263
274
  return [];
264
275
  }
@@ -272,7 +283,7 @@ async function dryRunPreflight(config, manifest, targetUrl, storageTarget, alsoR
272
283
  const blockers = [];
273
284
  const db = manifest.database;
274
285
  const mb = (n) => (n / 1024 / 1024).toFixed(1);
275
- log.ok(`coverage: schemas ${db.schemas.join(", ")} — ${db.tableCount} tables, ` +
286
+ log.ok(`coverage: schemas ${schemaNamesText(db.schemas)} — ${db.tableCount} tables, ` +
276
287
  `~${db.estimatedRowTotal.toLocaleString()} rows, dump ${mb(manifest.dump.bytes)} MB`);
277
288
  log.ok(manifest.storage
278
289
  ? `storage: ${manifest.storage.fileCount} files, ${mb(manifest.storage.totalBytes)} MB` +
@@ -310,7 +321,7 @@ async function dryRunPreflight(config, manifest, targetUrl, storageTarget, alsoR
310
321
  }
311
322
  try {
312
323
  await assertEmptyTarget(targetUrl, db.schemas, alsoRestoringStorage);
313
- log.ok(`target schemas (${db.schemas.join(", ")}) are empty`);
324
+ log.ok(`target schemas (${schemaNamesText(db.schemas)}) are empty`);
314
325
  }
315
326
  catch (error) {
316
327
  blockers.push(error.message);
@@ -606,10 +617,22 @@ export async function runRestore(config, opts) {
606
617
  storageFilesWritten: 0,
607
618
  };
608
619
  assertRequestApplies(manifest, !!opts.targetDatabaseUrl, !!storageTarget);
620
+ // 2.12.0:这份快照里 Storage 只复制了一部分,或这次没备上 —— 恢复前说清楚,别让人以为文件齐了
621
+ if (manifest.storage?.partial) {
622
+ const p = manifest.storage.partial;
623
+ log.warn(`This snapshot holds ${p.copied} of ${p.total} Storage files; the others were not copied when it was taken.`);
624
+ }
625
+ else if (manifest.storageFailure) {
626
+ log.warn(`Storage files are not in this snapshot (copying them failed: ${manifest.storageFailure.reason}).`);
627
+ }
609
628
  // 这次运行会不会碰 Storage(回传到目标,或下载到本地)。只有会碰时,空目标门才该
610
629
  // 提示"库已恢复、只重试 Storage";skipStorage 的纯数据库运行(托管恢复)不该看到这句。
611
630
  const alsoRestoringStorage = !!manifest.storage && !opts.skipStorage;
612
- const storageSource = manifest.storage ? reader.storageFiles(manifest) : null;
631
+ // 本地目录(restore --from-dir)只提供 storageSource;桶里的快照按 storageFiles 的位置读
632
+ const storageLocation = manifest.storage && !reader.storageSource ? reader.storageFiles(manifest) : null;
633
+ const storageSource = manifest.storage
634
+ ? (reader.storageSource?.(manifest) ?? (storageLocation ? s3StorageSource(storageLocation) : null))
635
+ : null;
613
636
  if (alsoRestoringStorage && !storageSource) {
614
637
  throw new Error("the manifest lists Storage files, but this snapshot location cannot hold them — " +
615
638
  "restore the database only (skip Storage).");
@@ -982,11 +1005,7 @@ export async function runRestore(config, opts) {
982
1005
  throw new Error(`unsafe storage path escapes output directory: ${f.bucket}/${f.key}`);
983
1006
  }
984
1007
  await mkdir(dirname(dest), { recursive: true });
985
- const res = await storageSource.s3.send(new GetObjectCommand({
986
- Bucket: storageSource.bucket,
987
- Key: `${storageSource.base}/storage/${f.bucket}/${f.key}`,
988
- }));
989
- await pipeline(res.Body, createWriteStream(dest));
1008
+ await pipeline(await storageSource.open(f.bucket, f.key), createWriteStream(dest));
990
1009
  result.storageFilesWritten += 1;
991
1010
  }
992
1011
  result.storageDir = outDir;
@@ -0,0 +1,38 @@
1
+ import type { Client } from "pg";
2
+ /**
3
+ * 备份范围(BACKUPDRILL_SCHEMAS / --schema)的每一项都是 pg_dump 的 --schema 模式,不是 schema 名字:
4
+ * 不加引号的字母折成小写,* 和 ? 是通配,双引号里按字面,双引号外别的正则字符原样交给 PostgreSQL。
5
+ * manifest 的表清单、授权记录、体积估算以前直接拿这些字符串去比 pg_namespace.nspname,
6
+ * 写了 "Public"、"app_*" 或 "\"Sales\"" 时就和 pg_dump 实际导出的对不上,漏表、漏授权。
7
+ * 现在先在源库上把模式解析成 schema 名字,manifest、授权、Auth 判断都用这份名字。
8
+ * pg_dump 自己仍拿用户写的模式:换成解析出的名字的话,解析和转储之间改了名的 schema 会整个漏掉,
9
+ * 客户端编码不是 UTF-8 时名字也可能对不上;转储前后各解析一次、不一致就让备份失败(见 runBackup)。
10
+ */
11
+ /** 数据库名.schema 这种写法:pg_dump 有自己的一套规则,我们不跟着猜,直接拒绝 */
12
+ export declare class SchemaPatternError extends Error {
13
+ }
14
+ /**
15
+ * 把一个 --schema 模式转成 pg_dump 在服务端拿来匹配 nspname 的正则。
16
+ * 逐字照搬 PostgreSQL 的 patternToSQLRegex(src/fe_utils/string_utils.c,force_escape = false):
17
+ * - 双引号切换"按字面"状态,引号里的 "" 是一个双引号;
18
+ * - 引号外的 ASCII 大写字母折成小写,* → .*,? → .;
19
+ * - $ 不管在不在引号里都按字面(它在标识符里合法,模式又自动加了首尾锚点);
20
+ * - 引号里的正则特殊字符加反斜杠;引号外的原样传过去(可以写正则),只有紧跟 ] 的 [ 转义;
21
+ * - 结果包在 ^( … )$ 里。
22
+ * 引号外的点在 pg_dump 里是"数据库名.schema"的分隔符,这里不支持,抛 SchemaPatternError。
23
+ */
24
+ export declare function schemaPatternRegex(pattern: string): string;
25
+ /**
26
+ * 在源库上解析备份范围,返回 pg_dump 会导出的 schema 名字(按模式的顺序,每个模式内按名字排序,去重)。
27
+ * 和 pg_dump 一样逐个模式查 pg_namespace、用库的默认排序规则做正则匹配。
28
+ * 一个都没匹配到就报错,pg_dump 这时也会拒绝导出。
29
+ * 匹配到 pg_catalog、information_schema 这些系统 schema 也报错:pg_dump 会把它们导出来,
30
+ * 可任何目标库里它们都已经有内容,恢复的空库检查一定不过,等于备了一份恢复不了的快照
31
+ */
32
+ export declare function resolveSchemaPatterns(client: Client, patterns: string[]): Promise<string[]>;
33
+ /**
34
+ * 把 schema 名字列给人看(终端、报错)。2.12.1 起 manifest 里的名字取自源库本身,建 schema 的人
35
+ * 可以在名字里放换行、引号、控制字符;小写普通名字原样显示,其余一律加引号并把控制字符转义,
36
+ * 不让一个名字改写终端里的其他内容或伪造出另一行输出
37
+ */
38
+ export declare function schemaNamesText(names: string[]): string;
@@ -0,0 +1,115 @@
1
+ import { quotedName } from "./auth-backup.js";
2
+ /**
3
+ * 备份范围(BACKUPDRILL_SCHEMAS / --schema)的每一项都是 pg_dump 的 --schema 模式,不是 schema 名字:
4
+ * 不加引号的字母折成小写,* 和 ? 是通配,双引号里按字面,双引号外别的正则字符原样交给 PostgreSQL。
5
+ * manifest 的表清单、授权记录、体积估算以前直接拿这些字符串去比 pg_namespace.nspname,
6
+ * 写了 "Public"、"app_*" 或 "\"Sales\"" 时就和 pg_dump 实际导出的对不上,漏表、漏授权。
7
+ * 现在先在源库上把模式解析成 schema 名字,manifest、授权、Auth 判断都用这份名字。
8
+ * pg_dump 自己仍拿用户写的模式:换成解析出的名字的话,解析和转储之间改了名的 schema 会整个漏掉,
9
+ * 客户端编码不是 UTF-8 时名字也可能对不上;转储前后各解析一次、不一致就让备份失败(见 runBackup)。
10
+ */
11
+ /** 数据库名.schema 这种写法:pg_dump 有自己的一套规则,我们不跟着猜,直接拒绝 */
12
+ export class SchemaPatternError extends Error {
13
+ }
14
+ /**
15
+ * 把一个 --schema 模式转成 pg_dump 在服务端拿来匹配 nspname 的正则。
16
+ * 逐字照搬 PostgreSQL 的 patternToSQLRegex(src/fe_utils/string_utils.c,force_escape = false):
17
+ * - 双引号切换"按字面"状态,引号里的 "" 是一个双引号;
18
+ * - 引号外的 ASCII 大写字母折成小写,* → .*,? → .;
19
+ * - $ 不管在不在引号里都按字面(它在标识符里合法,模式又自动加了首尾锚点);
20
+ * - 引号里的正则特殊字符加反斜杠;引号外的原样传过去(可以写正则),只有紧跟 ] 的 [ 转义;
21
+ * - 结果包在 ^( … )$ 里。
22
+ * 引号外的点在 pg_dump 里是"数据库名.schema"的分隔符,这里不支持,抛 SchemaPatternError。
23
+ */
24
+ export function schemaPatternRegex(pattern) {
25
+ let re = "^(";
26
+ let quoted = false;
27
+ for (let i = 0; i < pattern.length; i++) {
28
+ const ch = pattern[i];
29
+ if (ch === '"') {
30
+ if (quoted && pattern[i + 1] === '"') {
31
+ re += '"';
32
+ i++;
33
+ }
34
+ else {
35
+ quoted = !quoted;
36
+ }
37
+ }
38
+ else if (!quoted && ch >= "A" && ch <= "Z") {
39
+ re += ch.toLowerCase();
40
+ }
41
+ else if (!quoted && ch === "*") {
42
+ re += ".*";
43
+ }
44
+ else if (!quoted && ch === "?") {
45
+ re += ".";
46
+ }
47
+ else if (!quoted && ch === ".") {
48
+ throw new SchemaPatternError(`The schema entry ${JSON.stringify(pattern)} has a dot outside double quotes, which pg_dump reads as ` +
49
+ `database.schema. BackupDrill doesn't support that form: list the schema on its own, ` +
50
+ `or put the name in double quotes if the dot is part of it.`);
51
+ }
52
+ else if (ch === "$") {
53
+ re += "\\$";
54
+ }
55
+ else {
56
+ if (quoted && "|*+?()[]{}.^$\\".includes(ch))
57
+ re += "\\";
58
+ else if (ch === "[" && pattern[i + 1] === "]")
59
+ re += "\\";
60
+ re += ch;
61
+ }
62
+ }
63
+ return `${re})$`;
64
+ }
65
+ /** PostgreSQL 自己的 schema:pg_dump 遇到能匹配它们的模式会照样导出,但这样的归档恢复不到任何库里 */
66
+ function isSystemSchema(name) {
67
+ return name.startsWith("pg_") || name === "information_schema";
68
+ }
69
+ /**
70
+ * 在源库上解析备份范围,返回 pg_dump 会导出的 schema 名字(按模式的顺序,每个模式内按名字排序,去重)。
71
+ * 和 pg_dump 一样逐个模式查 pg_namespace、用库的默认排序规则做正则匹配。
72
+ * 一个都没匹配到就报错,pg_dump 这时也会拒绝导出。
73
+ * 匹配到 pg_catalog、information_schema 这些系统 schema 也报错:pg_dump 会把它们导出来,
74
+ * 可任何目标库里它们都已经有内容,恢复的空库检查一定不过,等于备了一份恢复不了的快照
75
+ */
76
+ export async function resolveSchemaPatterns(client, patterns) {
77
+ const names = [];
78
+ for (const pattern of patterns) {
79
+ const regex = schemaPatternRegex(pattern);
80
+ let rows;
81
+ try {
82
+ ({ rows } = await client.query(`select n.nspname::text as name
83
+ from pg_catalog.pg_namespace n
84
+ where n.nspname operator(pg_catalog.~) ($1::text collate pg_catalog."default")
85
+ order by 1`, [regex]));
86
+ }
87
+ catch (error) {
88
+ // 2201B = invalid_regular_expression:模式本身写错了(比如括号不配对),pg_dump 也会拒绝。连接断了这类照原样抛
89
+ if (error.code !== "2201B")
90
+ throw error;
91
+ throw new Error(`The schema entry ${JSON.stringify(pattern)} isn't a valid pattern: ${error.message}`);
92
+ }
93
+ for (const { name } of rows)
94
+ if (!names.includes(name))
95
+ names.push(name);
96
+ }
97
+ const system = names.filter(isSystemSchema);
98
+ if (system.length) {
99
+ throw new Error(`Your schema patterns match PostgreSQL system schemas (${schemaNamesText(system)}). ` +
100
+ `List the schemas you want by name or narrow your patterns to leave these out.`);
101
+ }
102
+ if (names.length === 0) {
103
+ throw new Error(`No schema matches ${patterns.map((p) => JSON.stringify(p)).join(", ")}. ` +
104
+ `Check the patterns in BACKUPDRILL_SCHEMAS or --schema.`);
105
+ }
106
+ return names;
107
+ }
108
+ /**
109
+ * 把 schema 名字列给人看(终端、报错)。2.12.1 起 manifest 里的名字取自源库本身,建 schema 的人
110
+ * 可以在名字里放换行、引号、控制字符;小写普通名字原样显示,其余一律加引号并把控制字符转义,
111
+ * 不让一个名字改写终端里的其他内容或伪造出另一行输出
112
+ */
113
+ export function schemaNamesText(names) {
114
+ return names.map((name) => (/^[a-z_][a-z0-9_]*$/.test(name) ? name : quotedName(name))).join(", ");
115
+ }
@@ -19,6 +19,19 @@ export interface StorageFilesLocation {
19
19
  bucket: string;
20
20
  base: string;
21
21
  }
22
+ /**
23
+ * 读快照里的 Storage 文件(恢复回传、本地下载用)。range 为闭区间字节范围。
24
+ * S3 兼容桶经 s3StorageSource 包一层;下载到本地的快照(restore --from-dir)读本地文件。
25
+ */
26
+ export interface StorageObjectSource {
27
+ open(bucket: string, key: string, range?: {
28
+ start: number;
29
+ end: number;
30
+ }): Promise<Readable>;
31
+ }
32
+ export declare function s3StorageSource(location: StorageFilesLocation): StorageObjectSource;
33
+ /** 两种形态都收:老调用方传桶位置,新的传 StorageObjectSource */
34
+ export declare function asStorageSource(source: StorageObjectSource | StorageFilesLocation): StorageObjectSource;
22
35
  export interface DumpUpload {
23
36
  /** 转储全部写完才 resolve;任何失败都 reject */
24
37
  done: Promise<void>;
@@ -60,8 +73,13 @@ export interface SnapshotReader {
60
73
  bytes: number;
61
74
  sha256: string;
62
75
  }>;
63
- /** 这份快照的 Storage 文件从哪读;实现不支持 Storage 文件时为 null */
76
+ /** 这份快照的 Storage 文件在哪个桶位置(演练按它抽样);实现不支持 Storage 文件时为 null */
64
77
  storageFiles(manifest: Manifest): StorageFilesLocation | null;
78
+ /**
79
+ * 可选(2.12.0 起):恢复时从哪读 Storage 文件。没实现时由 storageFiles 的桶位置读;
80
+ * 本地目录(restore --from-dir)没有桶,只实现这一个。
81
+ */
82
+ storageSource?(manifest: Manifest): StorageObjectSource | null;
65
83
  }
66
84
  /** S3 兼容桶(S3 / R2 / B2 / Wasabi)。行为与抽出这层之前逐字一致。 */
67
85
  export declare function s3SnapshotStore(config: BackupConfig): SnapshotStore;
@@ -1,9 +1,25 @@
1
- import { PutObjectCommand } from "@aws-sdk/client-s3";
1
+ import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
2
2
  import { Upload } from "@aws-sdk/lib-storage";
3
3
  import { requireBucket } from "./config.js";
4
4
  import { targetClient, resolveSnapshot, getObjectText, downloadToFile } from "./snapshots.js";
5
5
  import { renderRecoveryDoc } from "./recovery-doc.js";
6
6
  import { dumpPartSizeFor } from "./part-size.js";
7
+ export function s3StorageSource(location) {
8
+ return {
9
+ async open(bucket, key, range) {
10
+ const got = await location.s3.send(new GetObjectCommand({
11
+ Bucket: location.bucket,
12
+ Key: `${location.base}/storage/${bucket}/${key}`,
13
+ ...(range ? { Range: `bytes=${range.start}-${range.end}` } : {}),
14
+ }));
15
+ return got.Body;
16
+ },
17
+ };
18
+ }
19
+ /** 两种形态都收:老调用方传桶位置,新的传 StorageObjectSource */
20
+ export function asStorageSource(source) {
21
+ return "open" in source ? source : s3StorageSource(source);
22
+ }
7
23
  /** 写入时的键都在 <prefix>/<projectName>/<快照名>/ 下;读取时 Storage 文件的 base 从 dump.key 反推。 */
8
24
  function storageBaseOf(manifest) {
9
25
  return manifest.dump.key.replace(/\/dump\.pgcustom$/, "");