backupdrill 2.12.0 → 2.14.0

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/restore.js CHANGED
@@ -19,6 +19,7 @@ import { describeTarget, restoreRecordKey } from "./restore-record.js";
19
19
  import { primaryAuthRestoreError, AUTH_TABLE_KEYS, authRestoreFailureMessage, authRestoreNotes, targetIdentity, transactionOutcome, authRestorePreflight, largeObjectEntries, psqlProblem, readAuthArchive, restoreWithAuth, } from "./auth-restore.js";
20
20
  import { parsePgDumpMajor } from "./backup.js";
21
21
  import { log } from "./log.js";
22
+ import { schemaNamesText } from "./schema-patterns.js";
22
23
  /** 归档可读性要求:pg_restore 必须 ≥ max(写入工具版本, 源服务端版本)——格式跟随写入工具。 */
23
24
  export function requiredRestoreToolMajor(manifest) {
24
25
  return Math.max(parsePgDumpMajor(manifest.database.pgDumpVersion) ?? 0, parseInt(manifest.database.serverVersion, 10) || 0);
@@ -181,7 +182,7 @@ export function assertConfirmedTarget(confirmTarget, targetDatabaseUrl, targetSu
181
182
  * 用户会以为自己漏了一步,其实只需要换一个空项目。
182
183
  */
183
184
  export function nonEmptyTargetMessage(schemas, objectCount, alsoRestoringStorage) {
184
- 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) — ` +
185
186
  `restore only writes into an empty target. Create a fresh Supabase project ` +
186
187
  `(or empty these schemas) and retry.`;
187
188
  if (!alsoRestoringStorage)
@@ -235,14 +236,14 @@ async function targetStateAfterFailure(targetUrl, schemas) {
235
236
  return (" It ran in one transaction and was rolled back, so nothing from the snapshot is on the target and " +
236
237
  "you can run restore again on the same project once the cause is fixed.");
237
238
  }
238
- 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} ` +
239
240
  `object(s), so it may have committed before pg_restore lost its connection. Check the target before ` +
240
241
  `doing anything else; restore won't write into it again while those objects are there.`);
241
242
  }
242
243
  /** README 里讲怎么先把 Auth 用户搬过去的那一节;报错和 dry-run 都指向它。 */
243
244
  const AUTH_USERS_GUIDE = "https://github.com/backupdrill/cli#tables-that-reference-authusers";
244
245
  function referencesHint(schemas) {
245
- 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 ` +
246
247
  `the restore. Copy them over first (Supabase Auth users: ${AUTH_USERS_GUIDE}), then run restore again.`);
247
248
  }
248
249
  /**
@@ -268,7 +269,7 @@ function logExternalReferences(check, schemas, printProblems) {
268
269
  }
269
270
  }
270
271
  else if (!check.unchecked.length) {
271
- 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)}`);
272
273
  }
273
274
  return [];
274
275
  }
@@ -282,7 +283,7 @@ async function dryRunPreflight(config, manifest, targetUrl, storageTarget, alsoR
282
283
  const blockers = [];
283
284
  const db = manifest.database;
284
285
  const mb = (n) => (n / 1024 / 1024).toFixed(1);
285
- log.ok(`coverage: schemas ${db.schemas.join(", ")} — ${db.tableCount} tables, ` +
286
+ log.ok(`coverage: schemas ${schemaNamesText(db.schemas)} — ${db.tableCount} tables, ` +
286
287
  `~${db.estimatedRowTotal.toLocaleString()} rows, dump ${mb(manifest.dump.bytes)} MB`);
287
288
  log.ok(manifest.storage
288
289
  ? `storage: ${manifest.storage.fileCount} files, ${mb(manifest.storage.totalBytes)} MB` +
@@ -320,7 +321,7 @@ async function dryRunPreflight(config, manifest, targetUrl, storageTarget, alsoR
320
321
  }
321
322
  try {
322
323
  await assertEmptyTarget(targetUrl, db.schemas, alsoRestoringStorage);
323
- log.ok(`target schemas (${db.schemas.join(", ")}) are empty`);
324
+ log.ok(`target schemas (${schemaNamesText(db.schemas)}) are empty`);
324
325
  }
325
326
  catch (error) {
326
327
  blockers.push(error.message);
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backupdrill",
3
- "version": "2.12.0",
3
+ "version": "2.14.0",
4
4
  "description": "Open-source CLI to back up a Supabase project to your own S3/R2/B2 bucket (the Postgres database, Auth users when your role can read them, and Storage files once you add the project's Storage S3 keys), then run a restore drill that proves the backup restores.",
5
5
  "type": "module",
6
6
  "bin": {