backupdrill 2.10.0 → 2.11.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/README.md CHANGED
@@ -179,6 +179,8 @@ backupdrill drill # latest snapshot; add --snapshot <timestam
179
179
  backupdrill drill --verify-all-files # also checksum every Storage file, not just a sample
180
180
  ```
181
181
 
182
+ After the restore, the drill counts the rows of every table in the sandbox and compares each count with the number of rows that table has in the backup file. One row more or less in any table fails the drill. The backup's count comes from reading the dump itself, not from your database, so this adds no queries against production; it costs the drill one extra read of the dump. Materialized views and partitioned parent tables have no rows of their own in the dump, and tables created by an extension hold rows the extension adds itself, so these are checked for being non-empty instead. `restore` runs the same comparison on the target project.
183
+
182
184
  Backups record your installed Postgres extensions in the manifest, and the drill pre-installs them in the sandbox before restoring — including switching to a pgvector-enabled sandbox image when your database uses `vector` columns.
183
185
 
184
186
  The sandbox restore runs up to 4 parallel `pg_restore` jobs, sized from the CPUs and memory Docker reports, so a 2 vCPU / 8 GB machine gets 2. Table data and index builds run in parallel. Foreign keys, triggers and policies run on a single connection to keep their error messages separate, including errors about Supabase-managed objects such as `auth.users`. `backupdrill restore` into a real Supabase project stays on a single connection.
@@ -336,6 +338,32 @@ Prefer a plain workflow file? [`examples/scheduled-backup.yml`](examples/schedul
336
338
 
337
339
  Before switching to a **daily** schedule, read the egress-cost section above — every run is egress on your Supabase bill.
338
340
 
341
+ ## Docker / scheduled backups on your own server
342
+
343
+ If you'd rather run backups on a machine you already have (a home server, a NAS, Unraid, any Docker host), use the image at `ghcr.io/backupdrill/backupdrill`. The image includes the CLI and `pg_dump` 17. It contains no credentials; configure it with the `BACKUPDRILL_*` environment variables listed above.
344
+
345
+ Set `BACKUPDRILL_CRON` and the container stays up and runs `backupdrill backup` on that schedule. The time zone comes from `TZ` (UTC if unset). If a scheduled backup is still running when the next one is due, the scheduler skips that run. A backup you start yourself with `docker exec` isn't covered by this and can overlap with a scheduled one.
346
+
347
+ ```bash
348
+ docker run -d --name backupdrill --restart unless-stopped \
349
+ -e BACKUPDRILL_CRON="0 3 * * 0" \
350
+ -e TZ="Europe/Berlin" \
351
+ -e BACKUPDRILL_DATABASE_URL="postgresql://postgres.<ref>:<pw>@<pooler-host>:5432/postgres" \
352
+ -e BACKUPDRILL_PROJECT_NAME="my-app" \
353
+ -e BACKUPDRILL_S3_ENDPOINT="https://<account>.r2.cloudflarestorage.com" \
354
+ -e BACKUPDRILL_S3_BUCKET="my-backups" \
355
+ -e BACKUPDRILL_S3_ACCESS_KEY_ID="…" \
356
+ -e BACKUPDRILL_S3_SECRET_ACCESS_KEY="…" \
357
+ -e BACKUPDRILL_PING_URL="https://hc-ping.com/<uuid>" \
358
+ ghcr.io/backupdrill/backupdrill:latest
359
+ ```
360
+
361
+ - Without `BACKUPDRILL_CRON` the container runs one backup and exits with the CLI's exit code, which suits a host cron job or a scheduler you already use.
362
+ - Arguments go straight to the CLI: `docker run --rm -e … ghcr.io/backupdrill/backupdrill estimate` or `… --help`. To start a backup now in a running scheduled container: `docker exec backupdrill backupdrill backup`.
363
+ - `BACKUPDRILL_CRON` takes a standard 5-field expression or a shortcut such as `@daily`. Anything else stops the container at start (exit code 64) instead of leaving it idle.
364
+ - `drill` needs Docker to start its throwaway Postgres, and the image doesn't get access to your Docker daemon, so run drills where Docker is available (your machine, or the GitHub Action with `drill: "true"`).
365
+ - Tags: `latest`, the CLI version (e.g. `2.10.1`), and `sha-<commit>`. Images are built for amd64 and arm64.
366
+
339
367
  ## Alerts with Healthchecks.io
340
368
 
341
369
  A scheduled backup can fail quietly, or not run at all: a cron entry that never fires, a runner that dies, a workflow GitHub disabled. `backup` and `drill` can report every run to a [Healthchecks.io](https://healthchecks.io) check (a self-hosted Healthchecks works the same), and Healthchecks alerts you when a run fails or a success ping doesn't arrive on time.
package/dist/drill.d.ts CHANGED
@@ -78,9 +78,25 @@ interface PostDataResult {
78
78
  export declare function classifyPostDataErrors(stderr: string): PostDataResult;
79
79
  /** 兼容层:见 restore-engine.ts finalizePass(非零退出且零错误块 = 通用失败)。 */
80
80
  export declare function postDataResult(code: number | null, stderr: string): PostDataResult;
81
+ /** 恢复出的一张表(verifyRestored 里查到的口径) */
82
+ interface RestoredTable {
83
+ schema: string;
84
+ name: string;
85
+ kind: string;
86
+ extension_member: boolean;
87
+ }
88
+ /**
89
+ * 第 4 项检查:恢复后每张表的行数和备份文件里的确切行数逐表相等。
90
+ * 只比普通表(含分区的叶子):matview 的数据是 REFRESH、分区父表不存行,dump 里都没有行可数;
91
+ * 扩展建的表 dump 里只有一部分行(见 verifyRestored 的 extension_member)。
92
+ * 备份文件数不出来、某张表在备份文件里找不到数据段,都判失败:比不了就是没验证过,不拿估算顶上。
93
+ */
94
+ export declare function rowCountsCheck(inBackup: Map<string, number> | null, manifest: Manifest, restoredTables: RestoredTable[],
95
+ /** 键 = tableKey */
96
+ restoredRows: Map<string, number>): DrillCheck;
81
97
  /** 导出:真实恢复(restore.ts)复用同一套表级验证——两条路径对同一快照必须同一结论。 */
82
98
  export declare function verifyRestored(connString: string, manifest: Manifest,
83
- /** 恢复用的那份 dump:恢复出空表时回查它,见第 3 项检查 */
99
+ /** 恢复用的那份 dump:逐表行数从它里面数(第 4 项检查),恢复出空表时也回查它(第 3 项) */
84
100
  dumpPath?: string): Promise<{
85
101
  checks: DrillCheck[];
86
102
  tableCount: number;
package/dist/drill.js CHANGED
@@ -7,9 +7,9 @@ import { promisify } from "node:util";
7
7
  import { parseManifest } from "./manifest.js";
8
8
  import { hashObject } from "./snapshots.js";
9
9
  import { s3SnapshotStore } from "./snapshot-store.js";
10
- import { SANDBOX_MANAGED_ERROR, classifyBlocks, finalizePass, installExtensions, quoteIdent, restoreDatabaseArtifact, installSandboxShim, tableDataInDump, } from "./restore-engine.js";
10
+ import { SANDBOX_MANAGED_ERROR, classifyBlocks, finalizePass, installExtensions, quoteIdent, restoreDatabaseArtifact, installSandboxShim, tableDataInDump, countRowsInDump, } from "./restore-engine.js";
11
11
  import { connectPg } from "./supabase-ca.js";
12
- import { orphanedForeignKeysCheck } from "./orphaned-foreign-keys.js";
12
+ import { orphanedForeignKeysCheck, tableKey } from "./orphaned-foreign-keys.js";
13
13
  import { grantsCheck } from "./grants.js";
14
14
  import { localPgRestoreMajor, restoreToolBreaksOnTarget, sandboxMajorFor } from "./pgbin.js";
15
15
  import { log } from "./log.js";
@@ -172,6 +172,10 @@ async function startEphemeralPostgres(image, major, resourceName) {
172
172
  await ensureImage(image);
173
173
  // 名字先定好:Ctrl+C 可能落在 docker run 还没返回 ID 的时候,按名字才删得掉
174
174
  const name = resourceName ?? `backupdrill-drill-${randomBytes(6).toString("hex")}`;
175
+ // 沙箱里是恢复出来的生产数据。端口只绑 127.0.0.1,但同机的其他系统账号照样连得上,
176
+ // 固定密码等于没设:每个沙箱一个随机密码。只写 "-e POSTGRES_PASSWORD" 不带值,
177
+ // docker 从它自己的环境变量取值,密码就不进 argv(ps 看得到 argv)
178
+ const password = randomBytes(16).toString("hex");
175
179
  throwIfInterrupted();
176
180
  const started = execFileAsync("docker", [
177
181
  "run",
@@ -181,7 +185,7 @@ async function startEphemeralPostgres(image, major, resourceName) {
181
185
  name,
182
186
  ...(resourceName ? ["--mount", `type=volume,source=${resourceName},target=${dataVolumeTarget}`] : []),
183
187
  "-e",
184
- "POSTGRES_PASSWORD=drill",
188
+ "POSTGRES_PASSWORD",
185
189
  "-e",
186
190
  "POSTGRES_DB=postgres",
187
191
  "-p",
@@ -190,7 +194,7 @@ async function startEphemeralPostgres(image, major, resourceName) {
190
194
  image,
191
195
  "postgres",
192
196
  ...tuning.settings.flatMap((kv) => ["-c", kv]),
193
- ]);
197
+ ], { env: { ...process.env, POSTGRES_PASSWORD: password } });
194
198
  // 删容器只有一份:正常收尾(drillDump 的 finally)和中断收尾(interrupt.ts)等的是同一个 promise。
195
199
  // 两边各发一次 docker rm 会撞上 "removal already in progress",后到的那个报删除失败,
196
200
  // 进程又在真正删完之前就退出了(信号测试抓到的竞争)。
@@ -259,7 +263,7 @@ async function startEphemeralPostgres(image, major, resourceName) {
259
263
  ]);
260
264
  // 形如 "127.0.0.1:54321"
261
265
  const port = portOut.stdout.trim().split(":").pop().trim();
262
- const connString = `postgresql://postgres:drill@127.0.0.1:${port}/postgres`;
266
+ const connString = `postgresql://postgres:${password}@127.0.0.1:${port}/postgres`;
263
267
  // 等就绪(容器内 pg_isready),最多 ~30s。
264
268
  // 必须 -h 127.0.0.1 强制走 TCP:官方镜像 initdb 阶段先起一个只听 unix socket 的临时
265
269
  // 服务跑初始化,默认(socket)检查在该阶段就通过,pg_restore 随后连 TCP 正撞上
@@ -330,22 +334,78 @@ async function pgRestore(dumpPath, connString, dumpedSchemas, jobs, grants) {
330
334
  grants: result.grants,
331
335
  };
332
336
  }
333
- // ── 校验 ────────────────────────────────────────────────────────────
337
+ /**
338
+ * 第 4 项检查:恢复后每张表的行数和备份文件里的确切行数逐表相等。
339
+ * 只比普通表(含分区的叶子):matview 的数据是 REFRESH、分区父表不存行,dump 里都没有行可数;
340
+ * 扩展建的表 dump 里只有一部分行(见 verifyRestored 的 extension_member)。
341
+ * 备份文件数不出来、某张表在备份文件里找不到数据段,都判失败:比不了就是没验证过,不拿估算顶上。
342
+ */
343
+ export function rowCountsCheck(inBackup, manifest, restoredTables,
344
+ /** 键 = tableKey */
345
+ restoredRows) {
346
+ const name = "row counts match the backup";
347
+ if (!inBackup) {
348
+ return { name, pass: false, detail: "couldn't count the rows in the backup file, so row counts weren't compared" };
349
+ }
350
+ const inManifest = new Set(manifest.database.tables.map((t) => tableKey(t)));
351
+ const format = (n) => n.toLocaleString("en-US");
352
+ const differ = [];
353
+ const notInFile = [];
354
+ let compared = 0;
355
+ let rows = 0;
356
+ for (const t of restoredTables) {
357
+ if (t.kind !== "r" || t.extension_member || !inManifest.has(tableKey(t)))
358
+ continue;
359
+ const label = `${t.schema}.${t.name}`;
360
+ const expected = inBackup.get(tableKey(t));
361
+ if (expected === undefined) {
362
+ notInFile.push(label);
363
+ continue;
364
+ }
365
+ compared++;
366
+ rows += expected;
367
+ const restored = restoredRows.get(tableKey(t)) ?? 0;
368
+ if (restored !== expected)
369
+ differ.push(`${label} has ${format(restored)}, the backup has ${format(expected)}`);
370
+ }
371
+ const problems = [...differ, ...notInFile.map((label) => `${label} has no data section in the backup file`)];
372
+ if (problems.length > 0) {
373
+ const shown = problems.slice(0, 5).join("; ");
374
+ const more = problems.length > 5 ? `; and ${problems.length - 5} more` : "";
375
+ return { name, pass: false, detail: `${shown}${more}` };
376
+ }
377
+ return {
378
+ name,
379
+ pass: true,
380
+ detail: compared === 0
381
+ ? "no tables to compare"
382
+ : `all ${format(compared)} tables match the backup exactly (${format(rows)} rows)`,
383
+ };
384
+ }
334
385
  /** 导出:真实恢复(restore.ts)复用同一套表级验证——两条路径对同一快照必须同一结论。 */
335
386
  export async function verifyRestored(connString, manifest,
336
- /** 恢复用的那份 dump:恢复出空表时回查它,见第 3 项检查 */
387
+ /** 恢复用的那份 dump:逐表行数从它里面数(第 4 项检查),恢复出空表时也回查它(第 3 项) */
337
388
  dumpPath) {
338
389
  // pgConnectOptions:真实 Supabase 目标(restore 复用本函数)需要打包根 CA;
339
390
  // 沙箱的 docker 连接串非 Supabase 主机,原样透传,行为不变
340
391
  const client = await connectPg(connString);
392
+ // 备份文件里的确切行数只读本地文件、不连库,和下面逐表 count(*) 同时跑,省掉一段等待。
393
+ // 连上库之后才开始;这一步中途失败时由 finally 停掉它,不让它在演练收尾之后还在后台读整份 dump
394
+ const stopCounting = new AbortController();
395
+ const backupRowsP = dumpPath ? countRowsInDump(dumpPath, stopCounting.signal) : null;
341
396
  try {
342
397
  const schemas = manifest.database.schemas;
343
398
  // 口径必须与 manifest 统计端(backup.ts inspectDatabase)完全一致:
344
399
  // pg_class relkind in ('r','p','m')。此前这里用 pg_tables(不含 matview),
345
400
  // manifest 用 pg_stat_user_tables(含 matview)——任何有 matview 的库
346
401
  // 演练必然误报"表数不符 + 缺表"。
347
- const tablesRes = await client.query(`select n.nspname as schema, c.relname as name,
348
- c.relkind as kind, c.relispopulated as populated
402
+ const tablesRes = await client.query(
403
+ // extension_member:扩展建的表(比如装在 public 里的 PostGIS spatial_ref_sys)。CREATE EXTENSION 会自带
404
+ // 初始行,dump 里只有过了扩展过滤条件的那部分,恢复后的行数天然比 dump 多,不做逐行比对
405
+ `select n.nspname as schema, c.relname as name,
406
+ c.relkind as kind, c.relispopulated as populated,
407
+ exists (select 1 from pg_depend d
408
+ where d.classid = 'pg_class'::regclass and d.objid = c.oid and d.deptype = 'e') as extension_member
349
409
  from pg_class c
350
410
  join pg_namespace n on n.oid = c.relnamespace
351
411
  where c.relkind in ('r', 'p', 'm')
@@ -357,7 +417,8 @@ dumpPath) {
357
417
  const unpopulatedMatviews = new Set();
358
418
  let rowTotal = 0;
359
419
  for (const t of restoredTables) {
360
- const key = `${t.schema}.${t.name}`;
420
+ // tableKey(NUL 分隔),不用点号拼:public."a.b" 和 "public.a".b 拼出来都是 public.a.b,会串表
421
+ const key = tableKey(t);
361
422
  // 未填充的 matview 无法 count(*)(Postgres 直接报错)。它要么备份时就没数据
362
423
  // (dump 里本来就没有 REFRESH),要么 REFRESH 在 post-data 阶段失败——后者已由
363
424
  // post-data 检查如实记录,这里按 0 行处理即可。
@@ -368,7 +429,10 @@ dumpPath) {
368
429
  }
369
430
  // 名字来自恢复出的库(= 来自 dump = 桶里的数据):必须走标识符转义,
370
431
  // 内嵌引号的合法名不炸,构造名不注入
371
- const c = await client.query(`select count(*)::bigint as n from ${quoteIdent(t.schema)}.${quoteIdent(t.name)}`);
432
+ // 普通表用 only:老式继承的父表 count(*) 会连子表的行一起算,dump 里父表只有它自己的行。
433
+ // 分区父表本身不存行,照旧数全部分区(只用于"有没有数据",不参与逐表比对)
434
+ const only = t.kind === "r" ? "only " : "";
435
+ const c = await client.query(`select count(*)::bigint as n from ${only}${quoteIdent(t.schema)}.${quoteIdent(t.name)}`);
372
436
  const n = Number(c.rows[0].n);
373
437
  counts.set(key, n);
374
438
  // 分区父表的 count(*) 是子分区行的总和,子分区又各自计一次;
@@ -385,7 +449,7 @@ dumpPath) {
385
449
  });
386
450
  // 2. manifest 里的每张表都还原出来了
387
451
  const restoredSet = new Set(counts.keys());
388
- const missing = manifest.database.tables.filter((t) => !restoredSet.has(`${t.schema}.${t.name}`));
452
+ const missing = manifest.database.tables.filter((t) => !restoredSet.has(tableKey(t)));
389
453
  checks.push({
390
454
  name: "no missing tables",
391
455
  pass: missing.length === 0,
@@ -398,8 +462,8 @@ dumpPath) {
398
462
  // = 演练失败,Supabase 托管依赖 = 预期跳过),这里再报一次会把环境预期
399
463
  // 误标成备份损坏。
400
464
  const restoredEmpty = manifest.database.tables.filter((t) => t.estimatedRows > 0 &&
401
- !unpopulatedMatviews.has(`${t.schema}.${t.name}`) &&
402
- (counts.get(`${t.schema}.${t.name}`) ?? 0) === 0);
465
+ !unpopulatedMatviews.has(tableKey(t)) &&
466
+ (counts.get(tableKey(t)) ?? 0) === 0);
403
467
  // manifest 的行数是 pg_dump 之前另开连接取的 n_live_tup(统计估算),和 dump 不是同一个快照。
404
468
  // 队列、会话、一次性密钥这类表,取统计时有行、dump 时已经删光,恢复出 0 行是对的
405
469
  // (2026-10-24 生产演练:recovery_job_secrets)。所以拿 dump 本身作证:dump 里也是 0 行才放过,
@@ -420,9 +484,17 @@ dumpPath) {
420
484
  ? `no populated table restored empty (already empty in the backup: ${names(emptyInBackup)})`
421
485
  : "no populated table restored empty",
422
486
  });
487
+ // 4. 逐表行数和备份文件里一模一样。manifest 的行数是统计估算,只能管"别变空";确切的备份行数
488
+ // 从 dump 本身数(dump 是 pg_dump 在一个一致快照里导出的,它的行数就是这次备份下来的行数),
489
+ // 不去源库 count(*):那要在用户的库上全表扫一遍。数不出来就判失败,不退回估算
490
+ if (backupRowsP)
491
+ checks.push(rowCountsCheck(await backupRowsP, manifest, restoredTables, counts));
423
492
  return { checks, tableCount: restoredTables.length, rowTotal };
424
493
  }
425
494
  finally {
495
+ // 正常走完时它早已结束,这两步什么都不做
496
+ stopCounting.abort();
497
+ await backupRowsP;
426
498
  await client.end();
427
499
  }
428
500
  }
@@ -51,8 +51,12 @@ export declare function parseTableColumns(sql: string): Map<string, Map<string,
51
51
  * 和 parseTableColumns 同样按位置读列,只是每列再看一眼这一行剩下的部分
52
52
  */
53
53
  export declare function parseGeneratedColumns(sql: string): Map<string, Set<string>>;
54
- /** 一个 COPY 头最长读这么多字符;超过就当作读不了,免得坏归档把内存吃满。 */
55
- export declare const MAX_COPY_HEADER = 100000;
54
+ /**
55
+ * 一个 COPY 头最长读这么多字符;超过就当作读不了,免得坏归档把内存吃满。
56
+ * 合法的头可以很长:1600 列(上限)、每个列名 63 字节且带引号要转义时,光列清单就有二十多万字符。
57
+ * 1 MB 留足余量,仍然挡得住坏归档。
58
+ */
59
+ export declare const MAX_COPY_HEADER = 1000000;
56
60
  /**
57
61
  * 数据段的 COPY 头(dumpTableData_copy):"COPY <表> <列清单> FROM stdin;"。没有列的表列清单是空串,
58
62
  * 所以那一行中间是两个空格,返回空列表。
package/dist/dump-sql.js CHANGED
@@ -120,8 +120,12 @@ export function parseGeneratedColumns(sql) {
120
120
  }
121
121
  return tables;
122
122
  }
123
- /** 一个 COPY 头最长读这么多字符;超过就当作读不了,免得坏归档把内存吃满。 */
124
- export const MAX_COPY_HEADER = 100_000;
123
+ /**
124
+ * 一个 COPY 头最长读这么多字符;超过就当作读不了,免得坏归档把内存吃满。
125
+ * 合法的头可以很长:1600 列(上限)、每个列名 63 字节且带引号要转义时,光列清单就有二十多万字符。
126
+ * 1 MB 留足余量,仍然挡得住坏归档。
127
+ */
128
+ export const MAX_COPY_HEADER = 1_000_000;
125
129
  /**
126
130
  * 数据段的 COPY 头(dumpTableData_copy):"COPY <表> <列清单> FROM stdin;"。没有列的表列清单是空串,
127
131
  * 所以那一行中间是两个空格,返回空列表。
@@ -335,4 +335,25 @@ export declare function copyDataProbe(schema: string, table: string): (chunk: st
335
335
  * 都返回 "unknown",由调用方按"查不清"处理。
336
336
  */
337
337
  export declare function tableDataInDump(dumpPath: string, schema: string, table: string): Promise<"rows" | "empty" | "unknown">;
338
+ /**
339
+ * 逐块读 `pg_restore --data-only -f -` 的整份输出,数出每个 COPY 段的数据行数(键 = tableKey)。
340
+ * 返回喂数据的 feed 和收尾的 finish;读不懂的 COPY 头、超长的头、没收尾的 COPY 段都让 finish 返回 null:
341
+ * 数不准就不给数,绝不拿半截结果去比。纯函数,方便单测。
342
+ *
343
+ * COPY 文本格式里一行就是一条记录(值里的换行被转义成 \n),所以数 \n 就是数行;结束符是只有 \. 的一行,
344
+ * 数据里以 \. 开头的值会被转义成 \\.。数据行只记前三个字符,不缓存整行:大 bytea 行能有几百 MB。
345
+ * COPY 头的多行拼接和解析与 copyDataProbe 相同(带引号的名字里可以有换行)。
346
+ */
347
+ export declare function copyRowCounter(): {
348
+ feed(chunk: string): void;
349
+ finish(): Map<string, number> | null;
350
+ };
351
+ /**
352
+ * 备份文件里每张表的确切行数:让 pg_restore 把 dump 的数据段写成 SQL,边读边数(copyRowCounter)。
353
+ * 只写 TABLE DATA 条目(--use-list):序列的 setval、大对象这些 SQL 里有字符串字面量,
354
+ * 带换行的名字能在里面造出一行以 "COPY " 开头的假头,混进来就会多数行。
355
+ * 不连库,也不碰源库。matview 的数据是 REFRESH、分区父表没有自己的数据,都不会出现在结果里。
356
+ * pg_restore 起不来、出错退出、被中断,或者输出读不懂,都返回 null,由调用方按"数不出来"处理。
357
+ */
358
+ export declare function countRowsInDump(dumpPath: string, signal?: AbortSignal): Promise<Map<string, number> | null>;
338
359
  export {};
@@ -1184,3 +1184,173 @@ export function tableDataInDump(dumpPath, schema, table) {
1184
1184
  });
1185
1185
  });
1186
1186
  }
1187
+ /**
1188
+ * 逐块读 `pg_restore --data-only -f -` 的整份输出,数出每个 COPY 段的数据行数(键 = tableKey)。
1189
+ * 返回喂数据的 feed 和收尾的 finish;读不懂的 COPY 头、超长的头、没收尾的 COPY 段都让 finish 返回 null:
1190
+ * 数不准就不给数,绝不拿半截结果去比。纯函数,方便单测。
1191
+ *
1192
+ * COPY 文本格式里一行就是一条记录(值里的换行被转义成 \n),所以数 \n 就是数行;结束符是只有 \. 的一行,
1193
+ * 数据里以 \. 开头的值会被转义成 \\.。数据行只记前三个字符,不缓存整行:大 bytea 行能有几百 MB。
1194
+ * COPY 头的多行拼接和解析与 copyDataProbe 相同(带引号的名字里可以有换行)。
1195
+ */
1196
+ export function copyRowCounter() {
1197
+ const counts = new Map();
1198
+ let broken = false;
1199
+ // 不在数据段时:当前行已读到的内容(只在它可能是 COPY 头时才攒),以及攒到一半的多行 COPY 头
1200
+ let line = "";
1201
+ let skippingLine = false;
1202
+ let header = null;
1203
+ // 在数据段时:正在数的表、已数的行数、当前行的前三个字符
1204
+ let current = null;
1205
+ let rows = 0;
1206
+ let linePrefix = "";
1207
+ const endOfHeaderLine = (complete) => {
1208
+ header = header === null ? complete : `${header}\n${complete}`;
1209
+ const balanced = (header.split('"').length - 1) % 2 === 0;
1210
+ if (!(balanced && header.endsWith(" FROM stdin;"))) {
1211
+ if (header.length > MAX_COPY_HEADER)
1212
+ broken = true;
1213
+ return;
1214
+ }
1215
+ const parsed = parseCopyHeader(header);
1216
+ header = null;
1217
+ if (!parsed) {
1218
+ broken = true;
1219
+ return;
1220
+ }
1221
+ current = tableKey(parsed.table);
1222
+ rows = 0;
1223
+ linePrefix = "";
1224
+ };
1225
+ return {
1226
+ feed(chunk) {
1227
+ let at = 0;
1228
+ while (!broken && at < chunk.length) {
1229
+ const newline = chunk.indexOf("\n", at);
1230
+ const end = newline < 0 ? chunk.length : newline;
1231
+ if (current !== null) {
1232
+ if (linePrefix.length < 3)
1233
+ linePrefix += chunk.slice(at, Math.min(end, at + 3 - linePrefix.length));
1234
+ if (newline < 0)
1235
+ break;
1236
+ if (linePrefix === "\\.") {
1237
+ counts.set(current, (counts.get(current) ?? 0) + rows);
1238
+ current = null;
1239
+ }
1240
+ else {
1241
+ rows++;
1242
+ }
1243
+ linePrefix = "";
1244
+ }
1245
+ else if (skippingLine) {
1246
+ if (newline < 0)
1247
+ break;
1248
+ skippingLine = false;
1249
+ }
1250
+ else {
1251
+ line += chunk.slice(at, end);
1252
+ // 不在拼 COPY 头、这一行也不以 COPY 开头:SET、注释、setval、大对象数据,整行跳过不攒
1253
+ if (header === null && line.length >= 5 && !line.startsWith("COPY ")) {
1254
+ line = "";
1255
+ skippingLine = newline < 0;
1256
+ if (newline < 0)
1257
+ break;
1258
+ }
1259
+ else if ((header?.length ?? 0) + line.length > MAX_COPY_HEADER) {
1260
+ broken = true;
1261
+ break;
1262
+ }
1263
+ else if (newline >= 0) {
1264
+ const complete = line;
1265
+ line = "";
1266
+ if (header !== null || complete.startsWith("COPY "))
1267
+ endOfHeaderLine(complete);
1268
+ }
1269
+ }
1270
+ at = end + 1;
1271
+ }
1272
+ },
1273
+ finish() {
1274
+ // 输出停在 COPY 段或 COPY 头中间 = pg_restore 没写完,不给数
1275
+ if (broken || current !== null || header !== null)
1276
+ return null;
1277
+ return counts;
1278
+ },
1279
+ };
1280
+ }
1281
+ /**
1282
+ * 备份文件里每张表的确切行数:让 pg_restore 把 dump 的数据段写成 SQL,边读边数(copyRowCounter)。
1283
+ * 只写 TABLE DATA 条目(--use-list):序列的 setval、大对象这些 SQL 里有字符串字面量,
1284
+ * 带换行的名字能在里面造出一行以 "COPY " 开头的假头,混进来就会多数行。
1285
+ * 不连库,也不碰源库。matview 的数据是 REFRESH、分区父表没有自己的数据,都不会出现在结果里。
1286
+ * pg_restore 起不来、出错退出、被中断,或者输出读不懂,都返回 null,由调用方按"数不出来"处理。
1287
+ */
1288
+ export async function countRowsInDump(dumpPath, signal) {
1289
+ // 绝不抛错:调用方是在逐表 count(*) 之前就把它挂在后台的,临时目录建不了、写不进、删不掉,
1290
+ // 都只能落成"数不出来",不能变成没人接的 rejection 把演练进程带崩
1291
+ try {
1292
+ return await countRowsInDumpOrThrow(dumpPath, signal);
1293
+ }
1294
+ catch {
1295
+ return null;
1296
+ }
1297
+ }
1298
+ async function countRowsInDumpOrThrow(dumpPath, signal) {
1299
+ if (interrupted() || signal?.aborted)
1300
+ return null;
1301
+ const bin = resolvePgRestoreBin();
1302
+ let listing;
1303
+ try {
1304
+ listing = await pgRestoreOutput(bin, ["--list", dumpPath], { signal });
1305
+ }
1306
+ catch {
1307
+ return null;
1308
+ }
1309
+ if (listing.code !== 0)
1310
+ return null;
1311
+ const dataEntries = listing.stdout.split("\n").filter((line) => /^\d+; 0 \d+ TABLE DATA /.test(line));
1312
+ if (dataEntries.length === 0)
1313
+ return new Map();
1314
+ if (signal?.aborted)
1315
+ return null;
1316
+ const listDir = await mkdtemp(join(tmpdir(), "backupdrill-rowcount-"));
1317
+ try {
1318
+ const listFile = join(listDir, "table-data.list");
1319
+ await writeFile(listFile, dataEntries.join("\n") + "\n");
1320
+ // 建临时目录、写清单的这两步里也可能被叫停。abort 事件已经发过,后面挂的监听收不到,
1321
+ // 不在这里再看一眼,起来的 pg_restore 就会把整份 dump 读完。这一眼和下面挂监听在同一拍里,中间没有空档
1322
+ if (signal?.aborted)
1323
+ return null;
1324
+ return await new Promise((resolve) => {
1325
+ // 和 pgRestoreOutput 一样钉 C locale
1326
+ const proc = spawn(bin, ["--data-only", `--use-list=${listFile}`, "--file=-", dumpPath], {
1327
+ stdio: ["ignore", "pipe", "ignore"],
1328
+ env: libpqChildEnv(),
1329
+ });
1330
+ const forget = stopOnInterrupt(proc);
1331
+ const counter = copyRowCounter();
1332
+ // 按流解码:多字节字符可能被拆在两块里
1333
+ proc.stdout.setEncoding("utf8");
1334
+ proc.stdout.on("data", (chunk) => counter.feed(chunk));
1335
+ let settled = false;
1336
+ const settle = (result) => {
1337
+ if (settled)
1338
+ return;
1339
+ settled = true;
1340
+ forget();
1341
+ resolve(result);
1342
+ };
1343
+ // 调用方叫停(演练别处已经失败):停掉 pg_restore,不在后台把整份 dump 读完
1344
+ const stop = () => proc.kill("SIGTERM");
1345
+ signal?.addEventListener("abort", stop, { once: true });
1346
+ proc.on("error", () => settle(null));
1347
+ proc.on("close", (code) => {
1348
+ signal?.removeEventListener("abort", stop);
1349
+ settle(code === 0 && !signal?.aborted ? counter.finish() : null);
1350
+ });
1351
+ });
1352
+ }
1353
+ finally {
1354
+ await rm(listDir, { recursive: true, force: true });
1355
+ }
1356
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backupdrill",
3
- "version": "2.10.0",
3
+ "version": "2.11.0",
4
4
  "description": "Open-source CLI to back up a Supabase project — Postgres database and Storage files — to your own S3/R2/B2 bucket, with a checksummed manifest.",
5
5
  "type": "module",
6
6
  "bin": {
package/plugin/README.md CHANGED
@@ -7,7 +7,7 @@ Back up a Supabase project to a bucket you own and prove the backup restores, by
7
7
  - `drill` restores a snapshot into a throwaway Postgres in Docker, checks that the tables and their data came back, and checksums a sample of the Storage files.
8
8
  - `restore` puts a snapshot into a new, empty Supabase project, after a dry run and only once you confirm the target.
9
9
 
10
- The agent runs every command as `npx -y backupdrill@2.10.0`, so the CLI version stays fixed.
10
+ The agent runs every command as `npx -y backupdrill@2.10.1`, so the CLI version stays fixed.
11
11
 
12
12
  ## What you need
13
13
 
@@ -7,7 +7,9 @@ description: Use when the user wants to back up a Supabase project to their own
7
7
 
8
8
  backupdrill is an open-source (MIT) command-line tool. `backup` dumps the project's Postgres database with `pg_dump`, copies Storage files too once their S3 keys are set, and writes everything to a bucket the user owns, with a checksummed `manifest.json` and a `RECOVERY.md` in every snapshot. `drill` restores a snapshot into a throwaway Postgres in Docker and checks that it came back. The CLI runs on the user's machine. It talks to their Supabase project, their bucket and the local Docker daemon, and sends nothing to BackupDrill.
9
9
 
10
- Always run it as `npx -y backupdrill@2.10.0 <command>`, so every run uses the same version.
10
+ Always run it as `npx -y backupdrill@2.10.1 <command>`, so every run uses the same version. Every command and option is documented at [backupdrill.com/docs/cli](https://backupdrill.com/docs/cli); check there before using an option this skill doesn't mention.
11
+
12
+ If the user asks what Supabase already backs up on their plan, wants a plain `pg_dump` backup without the CLI, or wants to test a restore by hand, read [references/postgres-backup-basics.md](references/postgres-backup-basics.md).
11
13
 
12
14
  You need a shell on the user's machine for this. If you don't have one, walk the user through the same commands instead of running them.
13
15
 
@@ -69,7 +71,7 @@ Every backup reads the whole database, and every configured Storage file, out of
69
71
  ```sh
70
72
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
71
73
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
72
- npx -y backupdrill@2.10.0 estimate --plan pro )
74
+ npx -y backupdrill@2.10.1 estimate --plan pro )
73
75
  ```
74
76
 
75
77
  Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the projection back before suggesting a daily schedule. On a large database, suggest weekly.
@@ -80,7 +82,7 @@ Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the pr
80
82
  report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "stdout → $report"
81
83
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
82
84
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
83
- npx -y backupdrill@2.10.0 backup ) > "$report"
85
+ npx -y backupdrill@2.10.1 backup ) > "$report"
84
86
  ```
85
87
 
86
88
  - The progress lines on stderr show where everything went (`Dumping → s3://…`, `Manifest written → s3://…`) and end with `Backup complete — N tables + M Storage files`. stdout goes to the file named on the first line, a new one each run that only the user can read: one line of JSON with the whole manifest, which lists every table and Storage file, so read only the fields you need from it.
@@ -93,7 +95,7 @@ report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "
93
95
  ```sh
94
96
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
95
97
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
96
- npx -y backupdrill@2.10.0 drill )
98
+ npx -y backupdrill@2.10.1 drill )
97
99
  ```
98
100
 
99
101
  - It reads the latest snapshot from the bucket, restores it into a throwaway Postgres container, runs its checks and removes the container. It doesn't connect to the Supabase project. The first run pulls a Postgres image from Docker Hub.
@@ -112,7 +114,7 @@ A restore writes data, so go step by step and let the user drive.
112
114
  ```sh
113
115
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
114
116
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
115
- npx -y backupdrill@2.10.0 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
117
+ npx -y backupdrill@2.10.1 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
116
118
  ```
117
119
 
118
120
  Leave out `--target-supabase-url` when the snapshot is database only. To write Storage files to a local folder instead of the new project, use `--storage-dir ./recovered`.
@@ -99,7 +99,7 @@ jobs:
99
99
 
100
100
  - name: Run backupdrill
101
101
  # Pinned so every run uses the same CLI. Raise it on purpose when you upgrade.
102
- run: npx -y backupdrill@2.10.0 backup
102
+ run: npx -y backupdrill@2.10.1 backup
103
103
  env:
104
104
  # --- required ---
105
105
  BACKUPDRILL_DATABASE_URL: ${{ secrets.BACKUPDRILL_DATABASE_URL }}
@@ -0,0 +1,94 @@
1
+ # Supabase backups without the CLI: pg_dump, pg_restore and the Free plan
2
+
3
+ Read this when the user asks what Supabase already backs up for them, wants a plain `pg_dump` backup instead of the CLI, or wants to test a restore by hand. The commands here are what `backupdrill backup` and `backupdrill drill` automate.
4
+
5
+ ## What Supabase keeps for you
6
+
7
+ - **Free plan:** no access to automatic backups. Supabase's docs tell Free projects to export their data themselves (`supabase db dump`) and keep off-site copies. Free projects are paused after a week of inactivity; the pause snapshot lets the user restore the paused project from the dashboard for up to a year.
8
+ - **Pro and Team:** daily backups, kept 7 days on Pro and 14 on Team, restorable from the dashboard. On the physical backup process that current projects use they can't be downloaded. Point-in-time recovery is a paid add-on: about $100/month per project for 7 days of history.
9
+ - **Storage files are not in any database backup.** A database restore brings back the `storage.objects` rows, which only point at files. The files themselves need a separate copy (the CLI copies them once the Storage S3 keys are set).
10
+
11
+ Every backup taken from outside the project counts as egress on the user's Supabase bill. Free includes 5 GB a month, shared with whatever the app already serves. Run `backupdrill estimate --plan free` for an upper-bound estimate of the project's backup egress. As a rough guide, if each run transfers 500 MB (the Free database limit), weekly backups use about 2 GB a month and daily ones about 15 GB, three times the allowance.
12
+
13
+ ## Use the Session pooler connection string
14
+
15
+ In the dashboard, **Connect** → **Session pooler**: port 5432, user `postgres.<project-ref>`. Copy the host from there as it is; it can't be worked out from the region. Without the IPv4 add-on, the direct connection needs IPv6, so on an IPv4-only home or CI network it won't connect. Don't use port 6543, the transaction pooler: `pg_dump` needs a session.
16
+
17
+ ## Match client and server versions
18
+
19
+ - `pg_dump`'s major version must be at least the server's. Supabase runs Postgres 15 to 17, so a version 17 client covers all of them. Check with `pg_dump --version`.
20
+ - `pg_restore` must be at least as new as the `pg_dump` that wrote the archive. Archives from `pg_dump` 18 can contain SQL that Postgres 17 rejects, so stay on 17 unless the project runs something newer.
21
+
22
+ ## A plain backup
23
+
24
+ Keep the password off the command line, where other users on the machine can see it in the process list. Ask the user to add one line to `~/.pgpass` themselves and make the file private (`chmod 600 ~/.pgpass`); `pg_dump`, `pg_restore` and `psql` read it, so the connection string carries no password:
25
+
26
+ ```
27
+ <pooler-host>:5432:postgres:postgres.<project-ref>:<password>
28
+ ```
29
+
30
+ In that file a `:` or `\` inside the password has to be written as `\:` or `\\`.
31
+
32
+ ```sh
33
+ export DB_URL="postgresql://postgres.<project-ref>@<pooler-host>:5432/postgres?sslmode=require"
34
+ export BACKUP_FILE="backup-$(date +%Y%m%dT%H%M%S).dump"
35
+
36
+ # umask 077 in a subshell: the dump is production data, so only the user can read it
37
+ ( umask 077 && pg_dump "$DB_URL" --format=custom --schema=public --file="$BACKUP_FILE" ) \
38
+ && pg_restore --list "$BACKUP_FILE" > /dev/null && echo "archive is readable"
39
+ ```
40
+
41
+ - `sslmode=require` encrypts the connection. To also check the server's certificate, download the CA certificate from the project's database settings (SSL Configuration) and use `sslmode=verify-full&sslrootcert=<path to the certificate>`.
42
+ - `--format=custom` writes an archive that only `pg_restore` reads; it allows selective and parallel restores. A plain-text dump goes through `psql` instead.
43
+ - `--schema=public` leaves out Supabase-managed schemas, including `auth`, so Auth users aren't in this file. Add `--schema=<name>` for each of the app's own schemas.
44
+ - With `--schema`, `pg_dump` also leaves out large objects (the `lo_*` / `oid` kind, not Storage files). If the app uses them, add `--large-objects`.
45
+ - Never ask for the password in the chat. With the CLI, it lives in `.env.backupdrill` as `SKILL.md` describes.
46
+
47
+ ## Test the restore by hand
48
+
49
+ A dump that has never been restored is a guess. Restore it into a throwaway Postgres and look at the data. The container will hold a copy of production data, and every account on the machine can reach a port on `127.0.0.1`, so give it a new random password. Start the container and wait until it accepts connections:
50
+
51
+ ```sh
52
+ TEST_PW="$(openssl rand -hex 16)"
53
+ # docker run can print an ID and still fail (port taken), so only a zero exit counts.
54
+ # -e with no value makes docker read the password from its own environment, not from its arguments.
55
+ cid="$(POSTGRES_PASSWORD="$TEST_PW" docker run -d --rm -e POSTGRES_PASSWORD -p 127.0.0.1:55432:5432 postgres:17-alpine)" || cid=""
56
+ [ -n "$cid" ] \
57
+ && for i in $(seq 60); do docker exec "$cid" pg_isready -q -h 127.0.0.1 -U postgres && break; sleep 1; done \
58
+ && docker exec "$cid" pg_isready -h 127.0.0.1 -U postgres
59
+ echo "container: ${cid:-not started}"
60
+ ```
61
+
62
+ If it prints `container: not started` (port 55432 already taken, for example) or the last `pg_isready` says `no response`, stop and fix that first. Then restore and check:
63
+
64
+ ```sh
65
+ export TEST_DB="postgresql://postgres@127.0.0.1:55432/postgres"
66
+ # PGPASSWORD goes on each command, not exported: exported, it would also replace
67
+ # ~/.pgpass for the production connection in this shell.
68
+
69
+ # The dump creates schema public itself, so drop the empty one first. Then add stand-ins
70
+ # for what a Supabase project provides, so policies that mention them restore.
71
+ # --no-privileges skips GRANT and REVOKE: this test checks the data, not who can read it.
72
+ PGPASSWORD="$TEST_PW" psql "$TEST_DB" --set ON_ERROR_STOP=1 -c "
73
+ drop schema public;
74
+ create role anon; create role authenticated; create role service_role;
75
+ create schema auth;
76
+ create function auth.uid() returns uuid language sql stable as 'select null::uuid';
77
+ create function auth.role() returns text language sql stable as 'select null::text';
78
+ create function auth.email() returns text language sql stable as 'select null::text';
79
+ create function auth.jwt() returns jsonb language sql stable as 'select null::jsonb';" \
80
+ && PGPASSWORD="$TEST_PW" pg_restore --no-owner --no-privileges --dbname "$TEST_DB" "$BACKUP_FILE"
81
+
82
+ PGPASSWORD="$TEST_PW" psql "$TEST_DB" -c "select count(*) from pg_tables where schemaname = 'public';"
83
+ PGPASSWORD="$TEST_PW" psql "$TEST_DB" -c "select count(*) from public.<a table that must never be empty>;"
84
+ ```
85
+
86
+ When you're done, remove only the container you started: `docker rm -f "$cid"`.
87
+
88
+ - `pg_restore` keeps going after an error and prints how many it ignored at the end. Read every error. The one expected failure is a foreign key to `auth.users` (a `profiles` table usually has one): this dump has no Auth users, so the constraint can't be created here. Anything else is a failed test.
89
+ - Compare the table count and a few row counts with the same queries on production. For a table that only grows, `max(created_at)` shows how recent the backup is.
90
+ - If the schema uses extensions, the restore fails on the first object that needs one the container doesn't have. Install the missing extension in the container first. The CLI's drill tries to install the extensions listed in the snapshot's manifest and reports any its container can't install; a restore can still fail on those.
91
+
92
+ ## What the CLI adds
93
+
94
+ `backupdrill backup` runs the same `pg_dump`, copies Storage files, and writes a checksummed `manifest.json` and a `RECOVERY.md` next to the dump in the user's bucket. `backupdrill drill` does the restore test above against the latest snapshot in that bucket and reports each check. The full command reference is at [backupdrill.com/docs/cli](https://backupdrill.com/docs/cli).