backupdrill 2.10.1 → 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 +2 -0
- package/dist/drill.d.ts +17 -1
- package/dist/drill.js +79 -11
- package/dist/dump-sql.d.ts +6 -2
- package/dist/dump-sql.js +6 -2
- package/dist/restore-engine.d.ts +21 -0
- package/dist/restore-engine.js +170 -0
- package/package.json +1 -1
- package/plugin/README.md +1 -1
- package/plugin/skills/supabase-backup/SKILL.md +5 -5
- package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +1 -1
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.
|
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
|
|
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";
|
|
@@ -334,22 +334,78 @@ async function pgRestore(dumpPath, connString, dumpedSchemas, jobs, grants) {
|
|
|
334
334
|
grants: result.grants,
|
|
335
335
|
};
|
|
336
336
|
}
|
|
337
|
-
|
|
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
|
+
}
|
|
338
385
|
/** 导出:真实恢复(restore.ts)复用同一套表级验证——两条路径对同一快照必须同一结论。 */
|
|
339
386
|
export async function verifyRestored(connString, manifest,
|
|
340
|
-
/** 恢复用的那份 dump
|
|
387
|
+
/** 恢复用的那份 dump:逐表行数从它里面数(第 4 项检查),恢复出空表时也回查它(第 3 项) */
|
|
341
388
|
dumpPath) {
|
|
342
389
|
// pgConnectOptions:真实 Supabase 目标(restore 复用本函数)需要打包根 CA;
|
|
343
390
|
// 沙箱的 docker 连接串非 Supabase 主机,原样透传,行为不变
|
|
344
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;
|
|
345
396
|
try {
|
|
346
397
|
const schemas = manifest.database.schemas;
|
|
347
398
|
// 口径必须与 manifest 统计端(backup.ts inspectDatabase)完全一致:
|
|
348
399
|
// pg_class relkind in ('r','p','m')。此前这里用 pg_tables(不含 matview),
|
|
349
400
|
// manifest 用 pg_stat_user_tables(含 matview)——任何有 matview 的库
|
|
350
401
|
// 演练必然误报"表数不符 + 缺表"。
|
|
351
|
-
const tablesRes = await client.query(
|
|
352
|
-
|
|
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
|
|
353
409
|
from pg_class c
|
|
354
410
|
join pg_namespace n on n.oid = c.relnamespace
|
|
355
411
|
where c.relkind in ('r', 'p', 'm')
|
|
@@ -361,7 +417,8 @@ dumpPath) {
|
|
|
361
417
|
const unpopulatedMatviews = new Set();
|
|
362
418
|
let rowTotal = 0;
|
|
363
419
|
for (const t of restoredTables) {
|
|
364
|
-
|
|
420
|
+
// tableKey(NUL 分隔),不用点号拼:public."a.b" 和 "public.a".b 拼出来都是 public.a.b,会串表
|
|
421
|
+
const key = tableKey(t);
|
|
365
422
|
// 未填充的 matview 无法 count(*)(Postgres 直接报错)。它要么备份时就没数据
|
|
366
423
|
// (dump 里本来就没有 REFRESH),要么 REFRESH 在 post-data 阶段失败——后者已由
|
|
367
424
|
// post-data 检查如实记录,这里按 0 行处理即可。
|
|
@@ -372,7 +429,10 @@ dumpPath) {
|
|
|
372
429
|
}
|
|
373
430
|
// 名字来自恢复出的库(= 来自 dump = 桶里的数据):必须走标识符转义,
|
|
374
431
|
// 内嵌引号的合法名不炸,构造名不注入
|
|
375
|
-
|
|
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)}`);
|
|
376
436
|
const n = Number(c.rows[0].n);
|
|
377
437
|
counts.set(key, n);
|
|
378
438
|
// 分区父表的 count(*) 是子分区行的总和,子分区又各自计一次;
|
|
@@ -389,7 +449,7 @@ dumpPath) {
|
|
|
389
449
|
});
|
|
390
450
|
// 2. manifest 里的每张表都还原出来了
|
|
391
451
|
const restoredSet = new Set(counts.keys());
|
|
392
|
-
const missing = manifest.database.tables.filter((t) => !restoredSet.has(
|
|
452
|
+
const missing = manifest.database.tables.filter((t) => !restoredSet.has(tableKey(t)));
|
|
393
453
|
checks.push({
|
|
394
454
|
name: "no missing tables",
|
|
395
455
|
pass: missing.length === 0,
|
|
@@ -402,8 +462,8 @@ dumpPath) {
|
|
|
402
462
|
// = 演练失败,Supabase 托管依赖 = 预期跳过),这里再报一次会把环境预期
|
|
403
463
|
// 误标成备份损坏。
|
|
404
464
|
const restoredEmpty = manifest.database.tables.filter((t) => t.estimatedRows > 0 &&
|
|
405
|
-
!unpopulatedMatviews.has(
|
|
406
|
-
(counts.get(
|
|
465
|
+
!unpopulatedMatviews.has(tableKey(t)) &&
|
|
466
|
+
(counts.get(tableKey(t)) ?? 0) === 0);
|
|
407
467
|
// manifest 的行数是 pg_dump 之前另开连接取的 n_live_tup(统计估算),和 dump 不是同一个快照。
|
|
408
468
|
// 队列、会话、一次性密钥这类表,取统计时有行、dump 时已经删光,恢复出 0 行是对的
|
|
409
469
|
// (2026-10-24 生产演练:recovery_job_secrets)。所以拿 dump 本身作证:dump 里也是 0 行才放过,
|
|
@@ -424,9 +484,17 @@ dumpPath) {
|
|
|
424
484
|
? `no populated table restored empty (already empty in the backup: ${names(emptyInBackup)})`
|
|
425
485
|
: "no populated table restored empty",
|
|
426
486
|
});
|
|
487
|
+
// 4. 逐表行数和备份文件里一模一样。manifest 的行数是统计估算,只能管"别变空";确切的备份行数
|
|
488
|
+
// 从 dump 本身数(dump 是 pg_dump 在一个一致快照里导出的,它的行数就是这次备份下来的行数),
|
|
489
|
+
// 不去源库 count(*):那要在用户的库上全表扫一遍。数不出来就判失败,不退回估算
|
|
490
|
+
if (backupRowsP)
|
|
491
|
+
checks.push(rowCountsCheck(await backupRowsP, manifest, restoredTables, counts));
|
|
427
492
|
return { checks, tableCount: restoredTables.length, rowTotal };
|
|
428
493
|
}
|
|
429
494
|
finally {
|
|
495
|
+
// 正常走完时它早已结束,这两步什么都不做
|
|
496
|
+
stopCounting.abort();
|
|
497
|
+
await backupRowsP;
|
|
430
498
|
await client.end();
|
|
431
499
|
}
|
|
432
500
|
}
|
package/dist/dump-sql.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
55
|
-
|
|
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
|
-
/**
|
|
124
|
-
|
|
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
|
* 所以那一行中间是两个空格,返回空列表。
|
package/dist/restore-engine.d.ts
CHANGED
|
@@ -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 {};
|
package/dist/restore-engine.js
CHANGED
|
@@ -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
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.
|
|
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,7 @@ 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.
|
|
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
11
|
|
|
12
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).
|
|
13
13
|
|
|
@@ -71,7 +71,7 @@ Every backup reads the whole database, and every configured Storage file, out of
|
|
|
71
71
|
```sh
|
|
72
72
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
73
73
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
74
|
-
npx -y backupdrill@2.10.
|
|
74
|
+
npx -y backupdrill@2.10.1 estimate --plan pro )
|
|
75
75
|
```
|
|
76
76
|
|
|
77
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.
|
|
@@ -82,7 +82,7 @@ Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the pr
|
|
|
82
82
|
report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "stdout → $report"
|
|
83
83
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
84
84
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
85
|
-
npx -y backupdrill@2.10.
|
|
85
|
+
npx -y backupdrill@2.10.1 backup ) > "$report"
|
|
86
86
|
```
|
|
87
87
|
|
|
88
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.
|
|
@@ -95,7 +95,7 @@ report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "
|
|
|
95
95
|
```sh
|
|
96
96
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
97
97
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
98
|
-
npx -y backupdrill@2.10.
|
|
98
|
+
npx -y backupdrill@2.10.1 drill )
|
|
99
99
|
```
|
|
100
100
|
|
|
101
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.
|
|
@@ -114,7 +114,7 @@ A restore writes data, so go step by step and let the user drive.
|
|
|
114
114
|
```sh
|
|
115
115
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
116
116
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
117
|
-
npx -y backupdrill@2.10.
|
|
117
|
+
npx -y backupdrill@2.10.1 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
|
|
118
118
|
```
|
|
119
119
|
|
|
120
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.
|
|
102
|
+
run: npx -y backupdrill@2.10.1 backup
|
|
103
103
|
env:
|
|
104
104
|
# --- required ---
|
|
105
105
|
BACKUPDRILL_DATABASE_URL: ${{ secrets.BACKUPDRILL_DATABASE_URL }}
|