backupdrill 2.12.0 → 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/README.md +16 -2
- package/dist/auth-backup.d.ts +5 -14
- package/dist/auth-backup.js +6 -69
- package/dist/auth-restore.js +1 -1
- package/dist/backup.d.ts +12 -2
- package/dist/backup.js +93 -30
- package/dist/estimate.js +7 -4
- package/dist/grants.js +4 -0
- package/dist/index.js +4 -3
- package/dist/manifest.d.ts +4 -2
- package/dist/manifest.js +5 -1
- package/dist/orphaned-foreign-keys.js +8 -1
- package/dist/recovery-doc.d.ts +6 -1
- package/dist/recovery-doc.js +46 -14
- package/dist/restore.js +7 -6
- package/dist/schema-patterns.d.ts +38 -0
- package/dist/schema-patterns.js +115 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -21,6 +21,7 @@ This CLI gets your database into a bucket **you** control, with a manifest you c
|
|
|
21
21
|
## Requirements
|
|
22
22
|
|
|
23
23
|
- Node.js ≥ 20
|
|
24
|
+
- A source database on PostgreSQL 11 or newer (12 or newer for a separate `auth.dump`, see `BACKUPDRILL_AUTH` below). `backup` checks the version before it creates a snapshot.
|
|
24
25
|
- `pg_dump` whose **major version ≥ your Supabase Postgres version** (Supabase runs PG 15–17). On macOS: `brew install libpq` then add it to `PATH`, or point `BACKUPDRILL_PG_DUMP` at the binary. The CLI checks this and refuses to run a mismatched dump.
|
|
25
26
|
|
|
26
27
|
## Install
|
|
@@ -76,8 +77,8 @@ All recognized variables:
|
|
|
76
77
|
|---|---|---|
|
|
77
78
|
| `BACKUPDRILL_DATABASE_URL` | Source connection string (falls back to `DATABASE_URL`) | — (required) |
|
|
78
79
|
| `BACKUPDRILL_PROJECT_NAME` | Readable name used in object keys and the manifest | `supabase` |
|
|
79
|
-
| `BACKUPDRILL_SCHEMAS` | Comma-separated
|
|
80
|
-
| `BACKUPDRILL_AUTH` | Supabase Auth users
|
|
80
|
+
| `BACKUPDRILL_SCHEMAS` | Comma-separated `pg_dump --schema` patterns, such as `public,app_*`. See [Choosing schemas](#choosing-schemas) | `public` |
|
|
81
|
+
| `BACKUPDRILL_AUTH` | On PostgreSQL 12+, BackupDrill tries to write Supabase Auth users to `auth.dump` beside `dump.pgcustom` if the backup role can read every row in `auth.users` and `auth.identities`. `off` skips only `auth.dump`. `on` saves the database backup and exits with code 3 if neither archive contains both tables. Also set with `--auth`, `--no-auth` or `"auth": true/false`. See [Choosing schemas](#choosing-schemas). | on when possible |
|
|
81
82
|
| `BACKUPDRILL_S3_ENDPOINT` | S3-compatible endpoint (R2/B2/self-hosted; omit for AWS S3) | — |
|
|
82
83
|
| `BACKUPDRILL_S3_REGION` | Destination bucket region | `auto` |
|
|
83
84
|
| `BACKUPDRILL_S3_BUCKET` | Destination bucket | — (required) |
|
|
@@ -91,6 +92,19 @@ All recognized variables:
|
|
|
91
92
|
| `BACKUPDRILL_STATE_DIR` | Where `restore` keeps its record of restores with Auth users, for `--status` and `--finish` | `~/.backupdrill/restores` |
|
|
92
93
|
| `BACKUPDRILL_PING_URL` | Healthchecks.io ping URL for `backup` and `drill` — see [Alerts with Healthchecks.io](#alerts-with-healthchecksio) | — |
|
|
93
94
|
|
|
95
|
+
### Choosing schemas
|
|
96
|
+
|
|
97
|
+
`BACKUPDRILL_SCHEMAS` and `--schema` take `pg_dump --schema` patterns. Outside double quotes, ASCII letters become lowercase and `*` and `?` act as wildcards, so `app_*` matches every schema whose name starts with `app_`. To match `Sales` exactly, quote it: `export BACKUPDRILL_SCHEMAS='"Sales"'`. Leave out the database name. A name containing a comma can't go in the variable; use `--schema` or the config file's `schemas` array.
|
|
98
|
+
|
|
99
|
+
`manifest.json` lists the schemas the patterns matched, with their tables and grants. Before it creates a snapshot, BackupDrill checks that at least one schema matches and that none of them are PostgreSQL system schemas such as `pg_catalog` or `information_schema`. After the dump it matches the patterns again and fails the backup if a different set of schemas matches.
|
|
100
|
+
|
|
101
|
+
If your patterns select `auth`, BackupDrill skips `auth.dump` and lets `pg_dump` export the `auth` schema. If `dump.pgcustom` includes `auth.users`, any pending password-reset and confirmation tokens stay intact. BackupDrill also skips `auth.dump` unless every matched schema name starts with a lowercase ASCII letter or `_` and contains only lowercase ASCII letters, digits and `_`. When BackupDrill writes a separate `auth.dump`, it clears those tokens before upload.
|
|
102
|
+
|
|
103
|
+
Two known limits, until a later release checks the dump's own table list:
|
|
104
|
+
|
|
105
|
+
- If a schema name has non-ASCII characters and the client encoding isn't UTF-8, `manifest.json` can list a schema that `pg_dump` didn't dump. Run the backup with `PGCLIENTENCODING=UTF8` and leave `client_encoding` out of the connection string.
|
|
106
|
+
- A schema renamed and renamed back, or an Auth table dropped, while the backup runs can go unnoticed. Don't change the database structure during a backup.
|
|
107
|
+
|
|
94
108
|
### Config file
|
|
95
109
|
|
|
96
110
|
Copy `backupdrill.config.example.json` → `backupdrill.config.json` (it's gitignored) and fill it in. Keep secrets in env vars even when using a file. To also back up Storage files, start from `backupdrill.config.with-storage.example.json` instead — only copy the `supabaseStorage` block once you actually have S3 access keys for your project's Storage.
|
package/dist/auth-backup.d.ts
CHANGED
|
@@ -19,22 +19,13 @@ export declare const AUTH_TABLES: readonly ["users", "identities"];
|
|
|
19
19
|
/** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
|
|
20
20
|
export declare const AUTH_DUMP_MAX_BYTES: number;
|
|
21
21
|
/**
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* - "no":全是普通名字,且没有 auth。
|
|
28
|
-
*/
|
|
29
|
-
export declare function authInSchemas(schemas: string[]): "yes" | "maybe" | "no";
|
|
30
|
-
/**
|
|
31
|
-
* 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
|
|
32
|
-
* 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
33
|
-
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
|
|
22
|
+
* 小写的普通 schema 名字:按 pg_dump 的规则,不加引号的名字折成小写;只有字母数字和下划线的才返回,其余返回 null。
|
|
23
|
+
* 名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
24
|
+
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会。
|
|
25
|
+
* 2.12.1 起 manifest.database.schemas 记的是解析好的真实名字(见 schema-patterns.ts),单独的 auth.dump 只在
|
|
26
|
+
* 每个名字都满足 plainSchemaName(name) === name 时才做;更早的快照记的是用户写的模式,带 Auth 的那些也全是普通名字
|
|
34
27
|
*/
|
|
35
28
|
export declare function plainSchemaName(pattern: string): string | null;
|
|
36
|
-
/** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
|
|
37
|
-
export declare function schemasMayIncludeAuth(schemas: string[]): boolean;
|
|
38
29
|
/**
|
|
39
30
|
* 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
|
|
40
31
|
* Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
|
package/dist/auth-backup.js
CHANGED
|
@@ -5,78 +5,15 @@ export const AUTH_TABLES = ["users", "identities"];
|
|
|
5
5
|
/** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
|
|
6
6
|
export const AUTH_DUMP_MAX_BYTES = 2 * 1024 * 1024 * 1024;
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*/
|
|
14
|
-
function schemaPatternRegex(pattern) {
|
|
15
|
-
let re = "";
|
|
16
|
-
let quoted = false;
|
|
17
|
-
for (let i = 0; i < pattern.length; i++) {
|
|
18
|
-
const ch = pattern[i];
|
|
19
|
-
if (ch === '"') {
|
|
20
|
-
if (quoted && pattern[i + 1] === '"') {
|
|
21
|
-
re += '"';
|
|
22
|
-
i++;
|
|
23
|
-
}
|
|
24
|
-
else {
|
|
25
|
-
quoted = !quoted;
|
|
26
|
-
}
|
|
27
|
-
continue;
|
|
28
|
-
}
|
|
29
|
-
if (quoted) {
|
|
30
|
-
re += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
31
|
-
continue;
|
|
32
|
-
}
|
|
33
|
-
if (ch === "*")
|
|
34
|
-
re += ".*";
|
|
35
|
-
else if (ch === "?")
|
|
36
|
-
re += ".";
|
|
37
|
-
else if (ch === "$")
|
|
38
|
-
re += "\\$";
|
|
39
|
-
else if (/[A-Za-z0-9_]/.test(ch))
|
|
40
|
-
re += ch.toLowerCase();
|
|
41
|
-
else
|
|
42
|
-
return null;
|
|
43
|
-
}
|
|
44
|
-
return new RegExp(`^(?:${re})$`);
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* schemas 配置和 Auth 备份的关系。单独的 Auth 备份只在每一项都是普通 schema 名字时才做:
|
|
48
|
-
* 模式写法(通配、正则、"库.schema")由 PostgreSQL 自己解析,我们在这里算不准它最终选中哪些 schema,
|
|
49
|
-
* 也就没法可靠地判断"会不会重复导出"和"恢复时目标里哪些 schema 该是空的"——干脆不做。
|
|
50
|
-
* - "yes":明写了 auth(主 dump 里已经有),或某个模式确定匹配得到 auth(例如 "*");
|
|
51
|
-
* - "maybe":有模式写法,而又不能确定它包含 auth;
|
|
52
|
-
* - "no":全是普通名字,且没有 auth。
|
|
53
|
-
*/
|
|
54
|
-
export function authInSchemas(schemas) {
|
|
55
|
-
let maybe = false;
|
|
56
|
-
for (const pattern of schemas) {
|
|
57
|
-
const plain = plainSchemaName(pattern);
|
|
58
|
-
if (plain === "auth")
|
|
59
|
-
return "yes";
|
|
60
|
-
if (plain !== null)
|
|
61
|
-
continue;
|
|
62
|
-
if (schemaPatternRegex(pattern)?.test("auth"))
|
|
63
|
-
return "yes";
|
|
64
|
-
maybe = true;
|
|
65
|
-
}
|
|
66
|
-
return maybe ? "maybe" : "no";
|
|
67
|
-
}
|
|
68
|
-
/**
|
|
69
|
-
* 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
|
|
70
|
-
* 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
71
|
-
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
|
|
8
|
+
* 小写的普通 schema 名字:按 pg_dump 的规则,不加引号的名字折成小写;只有字母数字和下划线的才返回,其余返回 null。
|
|
9
|
+
* 名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
|
|
10
|
+
* 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会。
|
|
11
|
+
* 2.12.1 起 manifest.database.schemas 记的是解析好的真实名字(见 schema-patterns.ts),单独的 auth.dump 只在
|
|
12
|
+
* 每个名字都满足 plainSchemaName(name) === name 时才做;更早的快照记的是用户写的模式,带 Auth 的那些也全是普通名字
|
|
72
13
|
*/
|
|
73
14
|
export function plainSchemaName(pattern) {
|
|
74
15
|
return /^[A-Za-z_][A-Za-z0-9_]*$/.test(pattern) ? pattern.toLowerCase() : null;
|
|
75
16
|
}
|
|
76
|
-
/** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
|
|
77
|
-
export function schemasMayIncludeAuth(schemas) {
|
|
78
|
-
return authInSchemas(schemas) !== "no";
|
|
79
|
-
}
|
|
80
17
|
/**
|
|
81
18
|
* 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
|
|
82
19
|
* Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
|
|
@@ -444,7 +381,7 @@ async function firstNonStockObject(client) {
|
|
|
444
381
|
* 用户自己建在 extensions 之类里的函数不在任何一份归档里,新项目里也没有。
|
|
445
382
|
*/
|
|
446
383
|
function schemaCovered(schema, backedUpSchemas) {
|
|
447
|
-
//
|
|
384
|
+
// 带 Auth 的快照里 schemas 都是普通名字(见 plainSchemaName)
|
|
448
385
|
return backedUpSchemas.some((name) => plainSchemaName(name) === schema);
|
|
449
386
|
}
|
|
450
387
|
/** 触发器依赖的函数所在的全部 schema(触发函数 + WHEN 里调用的);旧记录没有 dependencySchemas 时只看触发函数 */
|
package/dist/auth-restore.js
CHANGED
|
@@ -461,7 +461,7 @@ export async function restoreWithAuth(opts) {
|
|
|
461
461
|
return null;
|
|
462
462
|
return `pg_restore stopped while writing out ${what} (${code === null ? "killed by a signal" : `exit code ${code}`}): ${firstRestoreError(genStderr)}`;
|
|
463
463
|
};
|
|
464
|
-
// 带 Auth 的快照里 schemas 全是普通名字(备份端
|
|
464
|
+
// 带 Auth 的快照里 schemas 全是普通名字(备份端 planAuth 保证),按 pg_dump 的规则规范化后才是真正的 schema 名;
|
|
465
465
|
// plainSchemaName 只放行 [a-z0-9_],拼进 SQL 字面量是安全的
|
|
466
466
|
const schemaNames = opts.schemas.map((name) => plainSchemaName(name)).filter((name) => name !== null);
|
|
467
467
|
const schemaArray = `array[${schemaNames.map((name) => `'${name}'`).join(", ")}]::text[]`;
|
package/dist/backup.d.ts
CHANGED
|
@@ -4,8 +4,18 @@ import type { Manifest } from "./manifest.js";
|
|
|
4
4
|
import { type StorageSyncOptions } from "./storage.js";
|
|
5
5
|
import { parsePgDumpMajor } from "./pgbin.js";
|
|
6
6
|
export { parsePgDumpMajor };
|
|
7
|
-
/**
|
|
8
|
-
|
|
7
|
+
/**
|
|
8
|
+
* 能备份的最老服务端:PostgreSQL 11,读授权要 pg_proc.prokind(11 起才有)。再老的库以前会在备份半途报一句
|
|
9
|
+
* "column does not exist",现在动手之前就挡。Supabase 的项目都在 15 以上,这条只挡自建的老库
|
|
10
|
+
*/
|
|
11
|
+
export declare const MIN_SERVER_VERSION_NUM = 110000;
|
|
12
|
+
/** 另备 Auth 用户(auth.dump)要 12:检查 auth.users 用到 pg_attribute.attgenerated(12 起才有) */
|
|
13
|
+
export declare const MIN_AUTH_SERVER_VERSION_NUM = 120000;
|
|
14
|
+
/**
|
|
15
|
+
* 主 dump 的 pg_dump 参数。patterns 是用户写的 --schema 模式,原样交给 pg_dump(为什么不换成解析出的名字见
|
|
16
|
+
* schema-patterns.ts)。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样)
|
|
17
|
+
*/
|
|
18
|
+
export declare function mainDumpArgs(patterns: string[], snapshotId?: string): string[];
|
|
9
19
|
/**
|
|
10
20
|
* Auth 一侧的两个时限(导出供测试调短,产品里不改):
|
|
11
21
|
* - waitAfterMainMs:主 dump 完成后还肯等 Auth 导出多久
|
package/dist/backup.js
CHANGED
|
@@ -4,7 +4,7 @@ import { Transform } from "node:stream";
|
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
5
|
import { s3SnapshotStore } from "./snapshot-store.js";
|
|
6
6
|
import { MANIFEST_SCHEMA_VERSION } from "./manifest.js";
|
|
7
|
-
import { AUTH_DUMP_MAX_BYTES, authDumpArgs, exportSharedSnapshot, inspectAuth,
|
|
7
|
+
import { AUTH_DUMP_MAX_BYTES, AUTH_TABLES, authDumpArgs, exportSharedSnapshot, inspectAuth, manualAuthObjects, plainSchemaName, redactValues, } from "./auth-backup.js";
|
|
8
8
|
import { scrubPendingAuthTokens } from "./auth-archive.js";
|
|
9
9
|
import { syncStorage, StorageSyncError } from "./storage.js";
|
|
10
10
|
import { inspectBucketAttrs } from "./storage-catalog.js";
|
|
@@ -14,6 +14,7 @@ import { TOOL_VERSION } from "./version.js";
|
|
|
14
14
|
import { parsePgDumpMajor } from "./pgbin.js";
|
|
15
15
|
import { relationBytes } from "./estimate.js";
|
|
16
16
|
import { captureIdentifiedGrants, grantsHeldThroughout } from "./grants.js";
|
|
17
|
+
import { resolveSchemaPatterns, schemaNamesText } from "./schema-patterns.js";
|
|
17
18
|
// 解析函数搬到了 pgbin(演练与恢复都要读 pg_restore 版本,放这里会成环);保留旧出口
|
|
18
19
|
export { parsePgDumpMajor };
|
|
19
20
|
import { dumpUrlFor, connectPg, isSupabaseHost } from "./supabase-ca.js";
|
|
@@ -23,6 +24,13 @@ function majorOf(serverVersionNum) {
|
|
|
23
24
|
// server_version_num: 150004 → 15, 170002 → 17
|
|
24
25
|
return Math.floor(serverVersionNum / 10000);
|
|
25
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* 能备份的最老服务端:PostgreSQL 11,读授权要 pg_proc.prokind(11 起才有)。再老的库以前会在备份半途报一句
|
|
29
|
+
* "column does not exist",现在动手之前就挡。Supabase 的项目都在 15 以上,这条只挡自建的老库
|
|
30
|
+
*/
|
|
31
|
+
export const MIN_SERVER_VERSION_NUM = 110000;
|
|
32
|
+
/** 另备 Auth 用户(auth.dump)要 12:检查 auth.users 用到 pg_attribute.attgenerated(12 起才有) */
|
|
33
|
+
export const MIN_AUTH_SERVER_VERSION_NUM = 120000;
|
|
26
34
|
async function pgDumpVersion(bin) {
|
|
27
35
|
try {
|
|
28
36
|
const { stdout } = await execFileAsync(bin, ["--version"]);
|
|
@@ -41,13 +49,18 @@ async function pgDumpVersion(bin) {
|
|
|
41
49
|
throw error;
|
|
42
50
|
}
|
|
43
51
|
}
|
|
44
|
-
async function inspectDatabase(databaseUrl,
|
|
52
|
+
async function inspectDatabase(databaseUrl, patterns) {
|
|
45
53
|
// Supabase 主机 → 用打包的根 CA 做 verify-full(pooler 证书自签、不在系统信任库);
|
|
46
54
|
// 非 Supabase(本 CLI 不限制目标)→ 保持默认,别把开源用户挡在门外
|
|
47
55
|
const client = await connectPg(databaseUrl);
|
|
48
56
|
try {
|
|
49
57
|
const version = await client.query("show server_version");
|
|
50
58
|
const versionNum = await client.query("show server_version_num");
|
|
59
|
+
if (Number(versionNum.rows[0].server_version_num) < MIN_SERVER_VERSION_NUM) {
|
|
60
|
+
throw new Error(`This database runs PostgreSQL ${version.rows[0].server_version}. BackupDrill backs up PostgreSQL 11 or newer ` +
|
|
61
|
+
`(12 or newer for a separate auth.dump).`);
|
|
62
|
+
}
|
|
63
|
+
const schemas = await resolveSchemaPatterns(client, patterns);
|
|
51
64
|
// 只统计将被 dump 的 schema,manifest 才与转储内容一致。
|
|
52
65
|
// 口径 = pg_class relkind in ('r','p','m'):普通表 + 分区父表 + 物化视图,
|
|
53
66
|
// 与 pg_dump 实际转储的关系集合一致,且必须与 drill 校验端(verifyRestored)
|
|
@@ -61,6 +74,17 @@ async function inspectDatabase(databaseUrl, schemas) {
|
|
|
61
74
|
where c.relkind in ('r', 'p', 'm')
|
|
62
75
|
and n.nspname = any($1::text[])
|
|
63
76
|
order by 1, 2`, [schemas]);
|
|
77
|
+
// 备份范围带上 auth 时,两张 Auth 表会不会进主 dump 决定这次算不算备了 Auth 用户(见 planAuth)。
|
|
78
|
+
// 只算普通表:分区表的行在各个分区里,分区可以建在备份范围之外的 schema,pg_dump 只按 schema 导出;
|
|
79
|
+
// 扩展自己的表 pg_dump 不导出,也不算。Supabase 的这两张表都是普通表
|
|
80
|
+
const authTablesDumped = schemas.includes("auth")
|
|
81
|
+
? (await client.query(`select c.relname as name
|
|
82
|
+
from pg_class c
|
|
83
|
+
join pg_namespace n on n.oid = c.relnamespace
|
|
84
|
+
where n.nspname = 'auth' and c.relname = any($1::text[]) and c.relkind = 'r'
|
|
85
|
+
and not exists (select 1 from pg_depend d
|
|
86
|
+
where d.classid = 'pg_catalog.pg_class'::regclass and d.objid = c.oid and d.deptype = 'e')`, [[...AUTH_TABLES]])).rows.map((r) => r.name)
|
|
87
|
+
: [];
|
|
64
88
|
// 非内置扩展清单(排除必装的 plpgsql):--schema 转储不含 CREATE EXTENSION,
|
|
65
89
|
// 演练沙箱要靠它在恢复前把扩展类型(如 vector)装回来
|
|
66
90
|
const extensions = await client.query(`select e.extname as name, e.extversion as version, n.nspname as schema
|
|
@@ -80,6 +104,8 @@ async function inspectDatabase(databaseUrl, schemas) {
|
|
|
80
104
|
return {
|
|
81
105
|
serverVersion: version.rows[0].server_version,
|
|
82
106
|
serverVersionNum: Number(versionNum.rows[0].server_version_num),
|
|
107
|
+
schemas,
|
|
108
|
+
authTablesDumped,
|
|
83
109
|
tables: tables.rows.map((r) => ({
|
|
84
110
|
schema: r.schema,
|
|
85
111
|
name: r.name,
|
|
@@ -93,6 +119,15 @@ async function inspectDatabase(databaseUrl, schemas) {
|
|
|
93
119
|
await client.end();
|
|
94
120
|
}
|
|
95
121
|
}
|
|
122
|
+
async function readSchemaNames(databaseUrl, patterns) {
|
|
123
|
+
const client = await connectPg(databaseUrl);
|
|
124
|
+
try {
|
|
125
|
+
return await resolveSchemaPatterns(client, patterns);
|
|
126
|
+
}
|
|
127
|
+
finally {
|
|
128
|
+
await client.end();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
96
131
|
async function readGrants(databaseUrl, schemas) {
|
|
97
132
|
const client = await connectPg(databaseUrl);
|
|
98
133
|
try {
|
|
@@ -102,14 +137,17 @@ async function readGrants(databaseUrl, schemas) {
|
|
|
102
137
|
await client.end();
|
|
103
138
|
}
|
|
104
139
|
}
|
|
105
|
-
/**
|
|
106
|
-
|
|
140
|
+
/**
|
|
141
|
+
* 主 dump 的 pg_dump 参数。patterns 是用户写的 --schema 模式,原样交给 pg_dump(为什么不换成解析出的名字见
|
|
142
|
+
* schema-patterns.ts)。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样)
|
|
143
|
+
*/
|
|
144
|
+
export function mainDumpArgs(patterns, snapshotId) {
|
|
107
145
|
return [
|
|
108
146
|
"--format=custom",
|
|
109
147
|
"--no-owner",
|
|
110
148
|
"--no-privileges",
|
|
111
149
|
...(snapshotId ? [`--snapshot=${snapshotId}`] : []),
|
|
112
|
-
...
|
|
150
|
+
...patterns.map((s) => `--schema=${s}`),
|
|
113
151
|
];
|
|
114
152
|
}
|
|
115
153
|
class AuthDumpTooLarge extends Error {
|
|
@@ -277,11 +315,16 @@ const AUTH_SKIP_TEXT = {
|
|
|
277
315
|
no_permission: "the backup role can't read every row of auth.users and auth.identities (it needs BYPASSRLS or superuser, plus read access)",
|
|
278
316
|
no_auth_schema: "this database has no Supabase auth schema",
|
|
279
317
|
unsupported_destination: "this backup destination can't hold the Auth archive yet",
|
|
280
|
-
schemas_include_auth: "
|
|
318
|
+
schemas_include_auth: "the selected schemas include auth, so the Auth users are in the database dump",
|
|
319
|
+
// 2.12.1 之前:模式写法算不清选中哪些 schema。新快照不再记这个原因,旧快照的说法照旧
|
|
281
320
|
schemas_not_plain: "your schema list uses a pattern or a quoted name, so the Auth users aren't backed up separately " +
|
|
282
321
|
"(they are in the database dump only if one of those patterns matches auth)",
|
|
322
|
+
schema_names_not_plain: "one of the selected schema names blocks auth.dump, and the database dump excludes auth. " +
|
|
323
|
+
"Each name must start with a–z or _ and use only a–z, 0–9 and _",
|
|
283
324
|
too_large: "the Auth archive is larger than 2 GiB",
|
|
284
325
|
snapshot_unavailable: "a consistent snapshot for the Auth export couldn't be set up",
|
|
326
|
+
server_too_old: "the source database runs PostgreSQL 11, and a separate auth.dump requires PostgreSQL 12 or newer " +
|
|
327
|
+
"(BackupDrill checks auth.users with a column added in 12); the database itself is backed up",
|
|
285
328
|
};
|
|
286
329
|
/** 报错只留第一行、截短:pg_dump / 上传的错误不该把大段原文(更不能是行值)带进 manifest 和告警 */
|
|
287
330
|
function shortReason(error) {
|
|
@@ -291,33 +334,44 @@ function shortReason(error) {
|
|
|
291
334
|
* 决定这次要不要、能不能另外备 Auth。任何"不能"都在这里落成 skipped/failed,不抛错——
|
|
292
335
|
* 主 dump 永远不因 Auth 受影响。返回 dump 时,共享快照已经导出,调用方负责释放。
|
|
293
336
|
*/
|
|
294
|
-
async function planAuth(
|
|
295
|
-
//
|
|
296
|
-
|
|
297
|
-
|
|
337
|
+
async function planAuth(writer, mode, db, databaseUrl) {
|
|
338
|
+
// db.schemas 是备份范围在源库上解析出来的 schema 名字,和主 dump 导出的一致(见 schema-patterns.ts)
|
|
339
|
+
const authDumped = db.schemas.includes("auth");
|
|
340
|
+
const authTablesDumped = AUTH_TABLES.every((name) => db.authTablesDumped.includes(name));
|
|
341
|
+
// 2.11.1 起只有 auth.dump 抹掉待处理 token;主 dump 带着 auth.users 时,里面的 token 还是原样,
|
|
342
|
+
// 每次备份提醒一句(只看 auth.users,token 都在这张表里)。不管 Auth 备份开没开都提醒:主 dump 的内容和它无关
|
|
343
|
+
if (db.authTablesDumped.includes("users")) {
|
|
298
344
|
log.warn("Your schema list includes auth, so dump.pgcustom holds the Auth tables as they are, " +
|
|
299
345
|
"including pending password-reset and confirmation tokens. Only auth.dump has them cleared.");
|
|
300
346
|
}
|
|
301
347
|
if (mode === "off")
|
|
302
348
|
return { kind: "none" };
|
|
303
|
-
//
|
|
304
|
-
//
|
|
305
|
-
//
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
349
|
+
// 主 dump 已经带上 auth:今天怎样以后还怎样,不另备一份。两张 Auth 表都会进主 dump 才算备上了(skipped,数据在主 dump 里);
|
|
350
|
+
// auth 这个 schema 在、表缺了一张(不是 Supabase 的库,或表归扩展所有、pg_dump 不导出),
|
|
351
|
+
// 显式要求时记 failed——不能在 Auth 用户哪份归档都不在时报成功
|
|
352
|
+
if (authDumped) {
|
|
353
|
+
return {
|
|
354
|
+
kind: "settled",
|
|
355
|
+
section: authTablesDumped ? { status: "skipped", reason: "schemas_include_auth" } : authNotDone(mode, "no_auth_schema"),
|
|
356
|
+
};
|
|
309
357
|
}
|
|
310
|
-
|
|
311
|
-
|
|
358
|
+
// 单独的 auth.dump 只在每个 schema 名字都是小写普通名字时才做:名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,
|
|
359
|
+
// 恢复端也按这个规则读(plainSchemaName)。带大写、$ 这类字符的名字(加引号建的 schema)不给拼接出错的机会
|
|
360
|
+
if (!db.schemas.every((name) => plainSchemaName(name) === name)) {
|
|
361
|
+
return { kind: "settled", section: authNotDone(mode, "schema_names_not_plain") };
|
|
312
362
|
}
|
|
313
363
|
if (!writer.uploadAuthDump || !writer.authDumpKey) {
|
|
314
364
|
return { kind: "settled", section: authNotDone(mode, "unsupported_destination") };
|
|
315
365
|
}
|
|
366
|
+
// PostgreSQL 11 的库照常备数据库,只是做不了 auth.dump(见 MIN_AUTH_SERVER_VERSION_NUM)
|
|
367
|
+
if (db.serverVersionNum < MIN_AUTH_SERVER_VERSION_NUM) {
|
|
368
|
+
return { kind: "settled", section: authNotDone(mode, "server_too_old") };
|
|
369
|
+
}
|
|
316
370
|
// 导出快照和统计都发生在主 dump 之前,必须有总时限:连接池满时新连接会一直排队,
|
|
317
371
|
// 不能让数据库备份陪着等。到点就按"快照不可用"放弃,并立刻断开 Auth 的两条连接
|
|
318
372
|
// (不管它们还在排队还是在跑查询),把连接让给主 dump
|
|
319
373
|
const stop = new AbortController();
|
|
320
|
-
const prepared = prepareAuthDump(
|
|
374
|
+
const prepared = prepareAuthDump(databaseUrl, writer, mode, stop.signal);
|
|
321
375
|
prepared.catch(() => { });
|
|
322
376
|
let deadline;
|
|
323
377
|
const timedOut = new Promise((resolve) => {
|
|
@@ -331,13 +385,13 @@ async function planAuth(config, writer, mode) {
|
|
|
331
385
|
clearTimeout(deadline);
|
|
332
386
|
return plan;
|
|
333
387
|
}
|
|
334
|
-
async function prepareAuthDump(
|
|
335
|
-
const shared = await exportSharedSnapshot(
|
|
388
|
+
async function prepareAuthDump(databaseUrl, writer, mode, signal) {
|
|
389
|
+
const shared = await exportSharedSnapshot(databaseUrl, signal);
|
|
336
390
|
if (!shared)
|
|
337
391
|
return { kind: "settled", section: authNotDone(mode, "snapshot_unavailable") };
|
|
338
392
|
let inspection;
|
|
339
393
|
try {
|
|
340
|
-
inspection = await inspectAuth(
|
|
394
|
+
inspection = await inspectAuth(databaseUrl, shared.id, signal);
|
|
341
395
|
}
|
|
342
396
|
catch (error) {
|
|
343
397
|
await shared.release();
|
|
@@ -557,8 +611,9 @@ export async function runBackup(config, opts = {}) {
|
|
|
557
611
|
const pgDumpBin = process.env.BACKUPDRILL_PG_DUMP || "pg_dump";
|
|
558
612
|
log.step("Inspecting database…");
|
|
559
613
|
const db = await inspectDatabase(config.databaseUrl, config.schemas);
|
|
614
|
+
// 授权、Auth 判断、manifest 用解析出来的 schema 名字;pg_dump 拿原样的模式(见 schema-patterns.ts)
|
|
560
615
|
const serverMajor = majorOf(db.serverVersionNum);
|
|
561
|
-
log.ok(`Postgres ${db.serverVersion} — schema(s) ${
|
|
616
|
+
log.ok(`Postgres ${db.serverVersion} — schema(s) ${schemaNamesText(db.schemas)}: ` +
|
|
562
617
|
`${db.tables.length} tables, ` +
|
|
563
618
|
`~${db.tables.reduce((n, t) => n + t.estimatedRows, 0).toLocaleString()} rows`);
|
|
564
619
|
// pg_dump 主版本必须 ≥ 服务端,否则转储会失败或不完整(PRD §4.2)
|
|
@@ -580,11 +635,11 @@ export async function runBackup(config, opts = {}) {
|
|
|
580
635
|
// 授权在转储前后各读一次,只记两次都有的(为什么见 grantsHeldThroughout)。
|
|
581
636
|
// 哪次读不到都让备份失败,不留一份缺授权记录的快照:恢复端把"没有记录"当成 2.9.0 之前的旧快照,
|
|
582
637
|
// 按 Supabase 以前的默认授权开放 public,会把源库关着的表打开
|
|
583
|
-
const grantsBeforeDump = await readGrants(config.databaseUrl,
|
|
584
|
-
// Auth 用户另备一份(2.10.0 起,见 auth-backup.ts)。库调用方没传 =
|
|
585
|
-
//
|
|
638
|
+
const grantsBeforeDump = await readGrants(config.databaseUrl, db.schemas);
|
|
639
|
+
// Auth 用户另备一份(2.10.0 起,见 auth-backup.ts)。库调用方没传 = 关闭:不另导 auth.dump、pg_dump 不带 --snapshot,
|
|
640
|
+
// manifest 里没有 auth 段。共享快照在转储前一刻才导出,尽量少占连接
|
|
586
641
|
const authMode = config.auth ?? "off";
|
|
587
|
-
const authPlan = await planAuth(
|
|
642
|
+
const authPlan = await planAuth(writer, authMode, db, config.databaseUrl);
|
|
588
643
|
let auth = authPlan.kind === "settled" ? authPlan.section : undefined;
|
|
589
644
|
log.step(`Dumping → ${writer.describe("dump.pgcustom")}`);
|
|
590
645
|
let bytes;
|
|
@@ -604,8 +659,16 @@ export async function runBackup(config, opts = {}) {
|
|
|
604
659
|
}
|
|
605
660
|
log.ok(`Database dumped (${(bytes / 1024 / 1024).toFixed(1)} MB, sha256 ${sha256.slice(0, 12)}…)`);
|
|
606
661
|
if (auth)
|
|
607
|
-
logAuthOutcome(auth,
|
|
608
|
-
|
|
662
|
+
logAuthOutcome(auth, db.schemas);
|
|
663
|
+
// 转储前解析的 schema 名字要在转储后还是同一份:中间有人建、删、改名了 schema,pg_dump 按它那一刻的样子导出,
|
|
664
|
+
// manifest 却记着之前的名字,两边对不上。pg_dump 的快照落在这两次解析之间,两次一样就说明它看到的也一样
|
|
665
|
+
const schemasAfterDump = await readSchemaNames(config.databaseUrl, config.schemas);
|
|
666
|
+
if (schemasAfterDump.join("\u0000") !== db.schemas.join("\u0000")) {
|
|
667
|
+
throw new Error(`The schemas matching your patterns changed while the backup ran ` +
|
|
668
|
+
`(before: ${schemaNamesText(db.schemas)}; after: ${schemaNamesText(schemasAfterDump)}), ` +
|
|
669
|
+
`so this snapshot's manifest might not match its dump. Run the backup again.`);
|
|
670
|
+
}
|
|
671
|
+
const grants = grantsHeldThroughout(grantsBeforeDump, await readGrants(config.databaseUrl, db.schemas));
|
|
609
672
|
// Storage 文件同步(源配置存在才做;否则只备数据库)。2.12.0 起 Storage 失败不拖累数据库:
|
|
610
673
|
// 列不出来、读不了、写不进目标时这份快照照常完成,manifest 记 storageFailure,storage 为 null
|
|
611
674
|
let storageResult = null;
|
|
@@ -669,7 +732,7 @@ export async function runBackup(config, opts = {}) {
|
|
|
669
732
|
database: {
|
|
670
733
|
serverVersion: db.serverVersion,
|
|
671
734
|
pgDumpVersion: pgd.raw,
|
|
672
|
-
schemas:
|
|
735
|
+
schemas: db.schemas,
|
|
673
736
|
tableCount: db.tables.length,
|
|
674
737
|
estimatedRowTotal: db.tables.reduce((n, t) => n + t.estimatedRows, 0),
|
|
675
738
|
tables: db.tables,
|
package/dist/estimate.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { measureStorage } from "./storage.js";
|
|
2
2
|
import { log } from "./log.js";
|
|
3
3
|
import { connectPg } from "./supabase-ca.js";
|
|
4
|
+
import { resolveSchemaPatterns, schemaNamesText } from "./schema-patterns.js";
|
|
4
5
|
// 超出这个月度成本就该提醒用户"备份的 egress 账单快赶上订阅费了"
|
|
5
6
|
const SUBSCRIPTION_FLOOR_USD = 19;
|
|
6
7
|
const GB = 1024 * 1024 * 1024;
|
|
@@ -16,10 +17,12 @@ export async function relationBytes(client, schemas) {
|
|
|
16
17
|
where schemaname = any($1::text[])`, [schemas]);
|
|
17
18
|
return Number(res.rows[0].bytes);
|
|
18
19
|
}
|
|
19
|
-
|
|
20
|
+
/** schemas 是 pg_dump 的 --schema 模式,先在库上解析成名字(和 backup 一样,见 schema-patterns.ts)再量 */
|
|
21
|
+
async function measureDbBytes(databaseUrl, patterns) {
|
|
20
22
|
const client = await connectPg(databaseUrl);
|
|
21
23
|
try {
|
|
22
|
-
|
|
24
|
+
const schemas = await resolveSchemaPatterns(client, patterns);
|
|
25
|
+
return { bytes: await relationBytes(client, schemas), schemas };
|
|
23
26
|
}
|
|
24
27
|
finally {
|
|
25
28
|
await client.end();
|
|
@@ -62,8 +65,8 @@ export function overageNote(pricing) {
|
|
|
62
65
|
}
|
|
63
66
|
export async function runEstimate(config, pricing) {
|
|
64
67
|
log.step("Measuring database size…");
|
|
65
|
-
const dbBytes = await measureDbBytes(config.databaseUrl, config.schemas);
|
|
66
|
-
log.ok(`Database (schema ${
|
|
68
|
+
const { bytes: dbBytes, schemas } = await measureDbBytes(config.databaseUrl, config.schemas);
|
|
69
|
+
log.ok(`Database (schema ${schemaNamesText(schemas)}): ${(dbBytes / GB).toFixed(2)} GB (upper bound)`);
|
|
67
70
|
let storageBytes = 0;
|
|
68
71
|
if (config.supabaseStorage) {
|
|
69
72
|
log.step("Measuring Storage size (listing only, no download)…");
|
package/dist/grants.js
CHANGED
|
@@ -328,6 +328,10 @@ function dollarQuoteTag(base, contents) {
|
|
|
328
328
|
}
|
|
329
329
|
}
|
|
330
330
|
function sqlLiteral(value) {
|
|
331
|
+
// 名字可能取自源库(schema 名),什么字符都可能有。有反斜杠时用 E'' 写法并把反斜杠加倍:
|
|
332
|
+
// 它的含义不随会话的 standard_conforming_strings 变,不会被读成转义序列
|
|
333
|
+
if (value.includes("\\"))
|
|
334
|
+
return `E'${value.replace(/\\/g, "\\\\").replace(/'/g, "''")}'`;
|
|
331
335
|
return `'${value.replace(/'/g, "''")}'`;
|
|
332
336
|
}
|
|
333
337
|
/**
|
package/dist/index.js
CHANGED
|
@@ -60,7 +60,8 @@ program
|
|
|
60
60
|
.option("-c, --config <path>", "path to a JSON config file", "backupdrill.config.json")
|
|
61
61
|
.option("--database-url <url>", "Supabase Session Pooler connection string")
|
|
62
62
|
.option("--project-name <name>", "readable name for this project (used in the object key)")
|
|
63
|
-
.option("--schema <name...>", "schema
|
|
63
|
+
.option("--schema <name...>", "schema patterns to back up (default: public only). Unquoted ASCII letters fold to lowercase; " +
|
|
64
|
+
"use * and ? as wildcards, or '\"Sales\"' for an exact match. Leave out the database name")
|
|
64
65
|
.option("--bucket <name>", "target S3/R2/B2 bucket")
|
|
65
66
|
.option("--endpoint <url>", "S3-compatible endpoint (required for R2/B2; omit for AWS S3)")
|
|
66
67
|
.option("--region <region>", "bucket region (default: auto)")
|
|
@@ -107,7 +108,7 @@ program
|
|
|
107
108
|
// 只有显式要求 Auth(--auth / BACKUPDRILL_AUTH=on)而它没备上,才让这次运行报失败:
|
|
108
109
|
// 数据库备份照样完成;退出码 3 与"整个备份失败"的 1 区分开。默认情况下做不了只打警告,
|
|
109
110
|
// 升级到这个版本的定时任务不会因此变红
|
|
110
|
-
// (显式要求时 planAuth 把所有"做不了"都记成 failed
|
|
111
|
+
// (显式要求时 planAuth 把所有"做不了"都记成 failed;只有主 dump 已经带上两张 Auth 表时记 skipped——数据就在主 dump 里)
|
|
111
112
|
const authRequiredButMissing = config.auth === "on" && manifest.auth?.status === "failed";
|
|
112
113
|
// 2.12.0 起 Storage 失败或只复制了一部分时数据库照样备完;同样用退出码 3 区分,定时任务能看见
|
|
113
114
|
const storageIncomplete = Boolean(manifest.storageFailure || manifest.storage?.partial);
|
|
@@ -403,7 +404,7 @@ program
|
|
|
403
404
|
.description("Measure your DB + Storage size and project monthly Supabase egress cost")
|
|
404
405
|
.option("-c, --config <path>", "path to a JSON config file", "backupdrill.config.json")
|
|
405
406
|
.option("--database-url <url>", "Supabase Session Pooler connection string")
|
|
406
|
-
.option("--schema <name...>", "schema
|
|
407
|
+
.option("--schema <name...>", "schema patterns to measure, same rules as backup --schema (default: public only)")
|
|
407
408
|
.option("--plan <plan>", "your Supabase plan for the cost estimate: free | pro | team", "pro")
|
|
408
409
|
.action(async (opts) => {
|
|
409
410
|
try {
|
package/dist/manifest.d.ts
CHANGED
|
@@ -111,11 +111,13 @@ export interface Manifest {
|
|
|
111
111
|
/**
|
|
112
112
|
* Auth 用户备份的结果。只有 included 的快照带 dump 和统计;其余状态说明为什么没备上。
|
|
113
113
|
* - included:auth.dump 在快照里,行数可以合法为 0
|
|
114
|
-
* - skipped:默认开启但做不了(无权读取、没有 auth
|
|
114
|
+
* - skipped:默认开启但做不了(无权读取、没有 auth 表、存储不支持、主 dump 已含 auth、schema 名字不是普通名字、太大),不算失败。
|
|
115
|
+
* schemas_not_plain 是 2.12.1 之前的"用了模式写法";2.12.1 起按解析出的名字判断,记 schema_names_not_plain。
|
|
116
|
+
* server_too_old(2.12.1 起):源库是 PostgreSQL 11,数据库照常备,auth.dump 要 12
|
|
115
117
|
* - failed:权限够、却在导出或上传时出错;只有显式要求时备份才因此失败
|
|
116
118
|
*/
|
|
117
119
|
export declare const AUTH_STATUSES: readonly ["included", "skipped", "failed"];
|
|
118
|
-
export declare const AUTH_SKIP_REASONS: readonly ["no_permission", "no_auth_schema", "unsupported_destination", "schemas_include_auth", "schemas_not_plain", "too_large", "snapshot_unavailable"];
|
|
120
|
+
export declare const AUTH_SKIP_REASONS: readonly ["no_permission", "no_auth_schema", "unsupported_destination", "schemas_include_auth", "schemas_not_plain", "schema_names_not_plain", "too_large", "snapshot_unavailable", "server_too_old"];
|
|
119
121
|
export interface AuthTriggerInfo {
|
|
120
122
|
table: string;
|
|
121
123
|
name: string;
|
package/dist/manifest.js
CHANGED
|
@@ -23,7 +23,9 @@ export const MANIFEST_SCHEMA_VERSION = 2;
|
|
|
23
23
|
/**
|
|
24
24
|
* Auth 用户备份的结果。只有 included 的快照带 dump 和统计;其余状态说明为什么没备上。
|
|
25
25
|
* - included:auth.dump 在快照里,行数可以合法为 0
|
|
26
|
-
* - skipped:默认开启但做不了(无权读取、没有 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
|
|
27
29
|
* - failed:权限够、却在导出或上传时出错;只有显式要求时备份才因此失败
|
|
28
30
|
*/
|
|
29
31
|
export const AUTH_STATUSES = ["included", "skipped", "failed"];
|
|
@@ -33,8 +35,10 @@ export const AUTH_SKIP_REASONS = [
|
|
|
33
35
|
"unsupported_destination",
|
|
34
36
|
"schemas_include_auth",
|
|
35
37
|
"schemas_not_plain",
|
|
38
|
+
"schema_names_not_plain",
|
|
36
39
|
"too_large",
|
|
37
40
|
"snapshot_unavailable",
|
|
41
|
+
"server_too_old",
|
|
38
42
|
];
|
|
39
43
|
/** 结构断言失败时的统一出错口径:说清哪个字段坏了,让"桶里的 manifest 被篡改/截断"可定位。 */
|
|
40
44
|
function malformed(what) {
|
|
@@ -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
|
-
/**
|
|
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/recovery-doc.d.ts
CHANGED
|
@@ -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 字段的快照:
|
|
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;
|
package/dist/recovery-doc.js
CHANGED
|
@@ -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
|
-
|
|
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 字段的快照:
|
|
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
|
|
52
|
-
? `- **Supabase Auth users**:
|
|
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 全是普通名字(
|
|
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
|
-
:
|
|
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,7 +324,7 @@ 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(", ")}`
|
|
@@ -332,9 +364,9 @@ ${restoreSteps}
|
|
|
332
364
|
give the three roles Supabase's old default access to everything in \`public\`;
|
|
333
365
|
afterwards, revoke it on any table you had kept private:`}
|
|
334
366
|
|
|
335
|
-
|
|
336
|
-
${
|
|
337
|
-
|
|
367
|
+
${sqlFence}sql
|
|
368
|
+
${grantsSql}
|
|
369
|
+
${sqlFence}
|
|
338
370
|
|
|
339
371
|
## Restore Storage files
|
|
340
372
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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.
|
|
3
|
+
"version": "2.12.1",
|
|
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": {
|