backupdrill 2.7.2 → 2.8.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 +39 -8
- package/dist/drill.d.ts +10 -0
- package/dist/drill.js +10 -0
- package/dist/dump-sql.d.ts +8 -0
- package/dist/dump-sql.js +10 -0
- package/dist/lib.d.ts +1 -0
- package/dist/orphaned-foreign-keys.d.ts +71 -0
- package/dist/orphaned-foreign-keys.js +206 -0
- package/dist/restore-engine.d.ts +17 -12
- package/dist/restore-engine.js +202 -49
- package/dist/restore.d.ts +3 -0
- package/dist/restore.js +18 -1
- 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
|
@@ -207,7 +207,7 @@ backupdrill restore --database --target-supabase-url https://<ref>.supabase.co -
|
|
|
207
207
|
|
|
208
208
|
Prefer files on disk instead? Skip the Storage target and pass `--storage-dir ./recovered`.
|
|
209
209
|
|
|
210
|
-
`--dry-run` writes nothing to the target. Besides checking the target (not the source project, schemas empty, Postgres and `pg_restore` versions, extensions available), it downloads the dump to a temporary directory, checks its sha256 and looks for foreign keys that point outside the backup (see [Tables that reference auth.users](#tables-that-reference-authusers)). The real run repeats those checks before it writes anything; a foreign key into a table that one of the recorded extensions creates is checked again once the extensions are installed. The database restore then runs in a single transaction: if any statement fails, nothing from the snapshot stays on the target, and you can run it again on the same project once you've fixed the cause. (If the connection drops while it commits, the error says so and asks you to check the target first.) Extensions the run installed stay installed, since the next run needs them too, and the empty-target check doesn't count objects that belong to an extension (except an extension's configuration tables, whose rows a dump can carry). One transaction holds a lock on every table, index and sequence until it commits, so a very large schema can run out of lock slots: on Supabase's smallest compute size, about a thousand tables (partitions count as tables). The restore then stops with nothing written and tells you how to raise `max_locks_per_transaction`.
|
|
210
|
+
`--dry-run` writes nothing to the target. Besides checking the target (not the source project, schemas empty, Postgres and `pg_restore` versions, extensions available), it downloads the dump to a temporary directory, checks its sha256 and looks for foreign keys that point outside the backup (see [Tables that reference auth.users](#tables-that-reference-authusers)). The real run repeats those checks before it writes anything; a foreign key into a table that one of the recorded extensions creates is checked again once the extensions are installed. The database restore then runs in a single transaction: if any statement fails, nothing from the snapshot stays on the target, and you can run it again on the same project once you've fixed the cause. (If the connection drops while it commits, the error says so and asks you to check the target first.) Foreign keys between two tables in the backup are the exception: they're added right after that transaction commits, in a second one. If rows in your data already break one of them (deleting with triggers switched off, for example under `session_replication_role = replica`, can leave rows like that), the key is added as `NOT VALID` instead of failing the restore. Those rows come back as they are, new writes are still checked, and the report names the key and, when it can count them, how many rows break it. Two kinds of key stay in the main transaction, so a broken one still fails the restore there: keys on partitioned tables, and every key in an archive whose foreign key statements BackupDrill can't fully read. A drill reports these keys as failures, because the rows are worth cleaning up. If the second step fails for any other reason, the tables and data are already on the target and the error says so. Extensions the run installed stay installed, since the next run needs them too, and the empty-target check doesn't count objects that belong to an extension (except an extension's configuration tables, whose rows a dump can carry). One transaction holds a lock on every table, index and sequence until it commits, so a very large schema can run out of lock slots: on Supabase's smallest compute size, about a thousand tables (partitions count as tables). The restore then stops with nothing written and tells you how to raise `max_locks_per_transaction`.
|
|
211
211
|
|
|
212
212
|
Or restore the dump by hand — into an **empty** database, without `--clean`:
|
|
213
213
|
|
|
@@ -265,14 +265,45 @@ every process on the machine):
|
|
|
265
265
|
|
|
266
266
|
## GitHub Action / scheduled backups
|
|
267
267
|
|
|
268
|
-
Want this running on a schedule without paying for a server?
|
|
268
|
+
Want this running on a schedule without paying for a server? Use the [Supabase Backup with BackupDrill](https://github.com/backupdrill/supabase-backup-action) action. It installs `pg_dump` 17 from the PostgreSQL apt repo (PGDG), runs `backupdrill backup` with the newest 2.x release of this CLI, and with `drill: "true"` restores the new snapshot into a throwaway Postgres on the runner and checks it.
|
|
269
269
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
270
|
+
```yaml
|
|
271
|
+
# .github/workflows/supabase-backup.yml in your own (private) repo
|
|
272
|
+
name: supabase-backup
|
|
273
|
+
on:
|
|
274
|
+
schedule:
|
|
275
|
+
- cron: "0 3 * * 0" # weekly; read the egress section above before going daily
|
|
276
|
+
workflow_dispatch: {}
|
|
277
|
+
permissions:
|
|
278
|
+
contents: read
|
|
279
|
+
concurrency:
|
|
280
|
+
group: supabase-backup
|
|
281
|
+
cancel-in-progress: false
|
|
282
|
+
jobs:
|
|
283
|
+
backup:
|
|
284
|
+
runs-on: ubuntu-latest
|
|
285
|
+
steps:
|
|
286
|
+
- uses: backupdrill/supabase-backup-action@v1
|
|
287
|
+
with:
|
|
288
|
+
database-url: ${{ secrets.BACKUPDRILL_DATABASE_URL }}
|
|
289
|
+
s3-bucket: ${{ secrets.BACKUPDRILL_S3_BUCKET }}
|
|
290
|
+
s3-access-key-id: ${{ secrets.BACKUPDRILL_S3_ACCESS_KEY_ID }}
|
|
291
|
+
s3-secret-access-key: ${{ secrets.BACKUPDRILL_S3_SECRET_ACCESS_KEY }}
|
|
292
|
+
s3-endpoint: ${{ secrets.BACKUPDRILL_S3_ENDPOINT }}
|
|
293
|
+
s3-region: ${{ secrets.BACKUPDRILL_S3_REGION }}
|
|
294
|
+
drill: "true"
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
Add the secrets under Settings → Secrets and variables → Actions:
|
|
298
|
+
|
|
299
|
+
- **Required:** `BACKUPDRILL_DATABASE_URL`, `BACKUPDRILL_S3_BUCKET`, `BACKUPDRILL_S3_ACCESS_KEY_ID`, `BACKUPDRILL_S3_SECRET_ACCESS_KEY`
|
|
300
|
+
- **Optional (destination):** `BACKUPDRILL_S3_ENDPOINT` (for R2/B2) and `BACKUPDRILL_S3_REGION` (AWS S3 needs the bucket's region; R2 works with the default `auto`). A readable project name goes in the `project-name` input.
|
|
301
|
+
- **Optional (alerts):** `BACKUPDRILL_PING_URL`, passed as `ping-url`. See [Alerts with Healthchecks.io](#alerts-with-healthchecksio).
|
|
302
|
+
- **Optional (Storage files):** the four `BACKUPDRILL_SUPABASE_STORAGE_*` values, passed as the `supabase-storage-endpoint`, `-region`, `-access-key-id` and `-secret-access-key` inputs. Leave them out to back up the database only.
|
|
303
|
+
|
|
304
|
+
The action's README lists every input and output.
|
|
305
|
+
|
|
306
|
+
Prefer a plain workflow file? [`examples/scheduled-backup.yml`](examples/scheduled-backup.yml) runs the backup without the action and without a drill. Copy it into your own repo at `.github/workflows/scheduled-backup.yml` and add the same secrets. (It lives under `examples/` here so GitHub doesn't try to run it in this repo.) It runs daily and can also be started by hand from the Actions tab.
|
|
276
307
|
|
|
277
308
|
Before switching to a **daily** schedule, read the egress-cost section above — every run is egress on your Supabase bill.
|
|
278
309
|
|
package/dist/drill.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { BackupConfig } from "./config.js";
|
|
2
2
|
import type { Manifest } from "./manifest.js";
|
|
3
3
|
import { type SnapshotStore } from "./snapshot-store.js";
|
|
4
|
+
import type { OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
4
5
|
/**
|
|
5
6
|
* 无放回随机抽样:部分 Fisher-Yates,只洗出前 n 位(O(n) 次交换,不必全 shuffle)。
|
|
6
7
|
* 此前恒取 manifest 顺序的前 CAP 个 → 超过 CAP 的项目里排序靠后的文件永远不被校验;
|
|
@@ -40,6 +41,13 @@ export interface DrillReport {
|
|
|
40
41
|
containerId: string;
|
|
41
42
|
connString: string;
|
|
42
43
|
};
|
|
44
|
+
/** 源库自带孤儿行的外键:演练把它们记为失败,真实恢复会把它们建成 NOT VALID。没有时不出现 */
|
|
45
|
+
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
46
|
+
/**
|
|
47
|
+
* 失败的唯一原因是这些孤儿行:备份完整、恢复能成功,是用户库里的数据违反了自己的外键。
|
|
48
|
+
* worker 据此把失败报告直接发给用户,不当成我们要排查的故障。
|
|
49
|
+
*/
|
|
50
|
+
failureCause?: "source-data";
|
|
43
51
|
}
|
|
44
52
|
export interface SandboxTuning {
|
|
45
53
|
settings: string[];
|
|
@@ -54,6 +62,8 @@ export declare function sandboxDataVolumeTarget(major: number): string;
|
|
|
54
62
|
interface PostDataResult {
|
|
55
63
|
supabaseSkipped: number;
|
|
56
64
|
failures: string[];
|
|
65
|
+
/** 已同时计入 failures */
|
|
66
|
+
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
57
67
|
}
|
|
58
68
|
/** 兼容层:历史签名保留,分类逻辑的单一权威在统一引擎(restore-engine.ts)。 */
|
|
59
69
|
export declare function classifyPostDataErrors(stderr: string): PostDataResult;
|
package/dist/drill.js
CHANGED
|
@@ -316,6 +316,7 @@ async function pgRestore(dumpPath, connString, dumpedSchemas, jobs) {
|
|
|
316
316
|
return {
|
|
317
317
|
supabaseSkipped: result.postData.expectedSkips,
|
|
318
318
|
failures: result.postData.failures,
|
|
319
|
+
orphanedForeignKeys: result.orphanedForeignKeys,
|
|
319
320
|
};
|
|
320
321
|
}
|
|
321
322
|
// ── 校验 ────────────────────────────────────────────────────────────
|
|
@@ -631,6 +632,15 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
631
632
|
restoredTableCount: verify.tableCount,
|
|
632
633
|
restoredRowTotal: verify.rowTotal,
|
|
633
634
|
};
|
|
635
|
+
const orphaned = postData.orphanedForeignKeys ?? [];
|
|
636
|
+
if (orphaned.length) {
|
|
637
|
+
report.orphanedForeignKeys = orphaned;
|
|
638
|
+
// 孤儿外键是 post-data 里仅有的失败、其余检查全过 → 失败只因用户数据
|
|
639
|
+
const onlyOrphans = postData.failures.length === orphaned.length;
|
|
640
|
+
if (!pass && onlyOrphans && checks.every((c) => c.pass || c.name === "post-data objects")) {
|
|
641
|
+
report.failureCause = "source-data";
|
|
642
|
+
}
|
|
643
|
+
}
|
|
634
644
|
if (opts.keepSandboxOnFailure && !pass) {
|
|
635
645
|
// 写进报告让 --keep 可被脚本消费(拿连接串排查),不只靠人眼看日志
|
|
636
646
|
report.keptSandbox = { containerId: pg.containerId, connString: pg.connString };
|
package/dist/dump-sql.d.ts
CHANGED
|
@@ -17,6 +17,12 @@ export interface ForeignKeyDef {
|
|
|
17
17
|
* 都不校验,恢复不会因为缺行而失败,所以不用查。
|
|
18
18
|
*/
|
|
19
19
|
validatesRows: boolean;
|
|
20
|
+
/** MATCH FULL:有一列为空、另一列不空的行同样违反约束(默认 MATCH SIMPLE 只查全非空的行) */
|
|
21
|
+
matchFull: boolean;
|
|
22
|
+
/** 不带 ONLY 的 ALTER TABLE = 分区父表上的外键 */
|
|
23
|
+
onPartitionedTable: boolean;
|
|
24
|
+
/** pg_dump 写出的整条语句,原样可执行 */
|
|
25
|
+
statement: string;
|
|
20
26
|
}
|
|
21
27
|
/**
|
|
22
28
|
* pg_dump 的外键语句(dumpConstraint):
|
|
@@ -25,6 +31,8 @@ export interface ForeignKeyDef {
|
|
|
25
31
|
* 调用方拿条目数对账,差多少就如实报多少条没检查。
|
|
26
32
|
*/
|
|
27
33
|
export declare function parseForeignKeys(sql: string): ForeignKeyDef[];
|
|
34
|
+
/** pg_dump 的建表语句(dumpTableSchema)建的表:CREATE [UNLOGGED ]TABLE <表> (…) / OF <类型>… */
|
|
35
|
+
export declare function parseCreatedTables(sql: string): QualifiedName[];
|
|
28
36
|
/** pg_dump 的挂分区语句(dumpTableAttach):ALTER TABLE ONLY <父> ATTACH PARTITION <子> <边界>; */
|
|
29
37
|
export declare function parsePartitionAttachments(sql: string): Array<{
|
|
30
38
|
parent: QualifiedName;
|
package/dist/dump-sql.js
CHANGED
|
@@ -39,9 +39,19 @@ export function parseForeignKeys(sql) {
|
|
|
39
39
|
references: { schema: unquoteIdent(match[5]), name: unquoteIdent(match[6]) },
|
|
40
40
|
referencedColumns: splitColumns(match[7]),
|
|
41
41
|
validatesRows: !/\bNOT (?:VALID|ENFORCED)\b/.test(options),
|
|
42
|
+
matchFull: /\bMATCH FULL\b/.test(options),
|
|
43
|
+
onPartitionedTable: !/^ALTER (?:FOREIGN )?TABLE ONLY /.test(match[0]),
|
|
44
|
+
statement: match[0],
|
|
42
45
|
};
|
|
43
46
|
});
|
|
44
47
|
}
|
|
48
|
+
/** pg_dump 的建表语句(dumpTableSchema)建的表:CREATE [UNLOGGED ]TABLE <表> (…) / OF <类型>… */
|
|
49
|
+
export function parseCreatedTables(sql) {
|
|
50
|
+
return [...sql.matchAll(new RegExp(String.raw `^CREATE (?:UNLOGGED )?TABLE ${QUALIFIED} `, "gm"))].map((match) => ({
|
|
51
|
+
schema: unquoteIdent(match[1]),
|
|
52
|
+
name: unquoteIdent(match[2]),
|
|
53
|
+
}));
|
|
54
|
+
}
|
|
45
55
|
/** pg_dump 的挂分区语句(dumpTableAttach):ALTER TABLE ONLY <父> ATTACH PARTITION <子> <边界>; */
|
|
46
56
|
export function parsePartitionAttachments(sql) {
|
|
47
57
|
const pattern = new RegExp(String.raw `^ALTER TABLE ONLY ${QUALIFIED} ATTACH PARTITION ${QUALIFIED} `, "gm");
|
package/dist/lib.d.ts
CHANGED
|
@@ -12,5 +12,6 @@ export type { SnapshotStore, SnapshotWriter, SnapshotReader, DumpUpload, Storage
|
|
|
12
12
|
export type { BackupConfig, LoadedBackupConfig, StorageConfig, SupabaseStorageConfig, } from "./config.js";
|
|
13
13
|
export type { BucketAttrs, ExtensionInfo, Manifest, StorageFile, TableStat } from "./manifest.js";
|
|
14
14
|
export type { DrillReport, DrillCheck, DrillSupervision, DrillPhase } from "./drill.js";
|
|
15
|
+
export type { OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
15
16
|
export type { RestoreResult } from "./restore.js";
|
|
16
17
|
export type { EgressPricing, EgressProjection } from "./estimate.js";
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Client } from "pg";
|
|
2
|
+
import { type ForeignKeyDef, type QualifiedName } from "./dump-sql.js";
|
|
3
|
+
export interface OrphanedForeignKey {
|
|
4
|
+
constraint: string;
|
|
5
|
+
/** schema.name */
|
|
6
|
+
table: string;
|
|
7
|
+
referencedTable: string;
|
|
8
|
+
/** 外键列和被引用列,逐列对应:报告/邮件据此给出定位这些行的查询 */
|
|
9
|
+
columns: string[];
|
|
10
|
+
referencedColumns: string[];
|
|
11
|
+
/** MATCH FULL:引用列部分为空的行也算违反(定位查询要按这个口径写) */
|
|
12
|
+
matchFull: boolean;
|
|
13
|
+
/** 违反约束的行数;数不出来(比如列类型没有可用的 = 运算符)时为 null */
|
|
14
|
+
orphanRows: number | null;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* 归档目录里由 dump 自己建、又带着数据的表的建表条目:`<id>; 1259 <oid> TABLE …` 和
|
|
18
|
+
* `<id>; 0 <oid> TABLE DATA …` 的 oid 相同。只看 TABLE DATA 不够:扩展的配置表(pg_extension_config_dump)
|
|
19
|
+
* 由 CREATE EXTENSION 建、没有 TABLE 条目,数据条目里只有过了扩展过滤条件的行(交叉审查复现)。
|
|
20
|
+
* 按 oid 配对,不按名字:目录里的名字和属主都不加引号、可以带空格,拆不准(交叉审查复现)。
|
|
21
|
+
* 确切的表名由调用方让 pg_restore 把这些条目写成 SQL 再读(parseCreatedTables)。
|
|
22
|
+
*/
|
|
23
|
+
export declare function fullyDumpedTableEntries(listing: string): string[];
|
|
24
|
+
export declare function tableKey(table: QualifiedName): string;
|
|
25
|
+
/**
|
|
26
|
+
* 能交给 addForeignKeys 处理的外键:两端的行都完整地在快照里(fullyDumped,tableKey)、会校验已有行、
|
|
27
|
+
* 不在分区父表上。指向分区表的外键也照旧严格:分区表自己没有 TABLE DATA,数据在各个分区上。
|
|
28
|
+
*/
|
|
29
|
+
export declare function isDeferrableForeignKey(fk: ForeignKeyDef, fullyDumped: Set<string>): boolean;
|
|
30
|
+
/** 同一条语句改成 NOT VALID:选项(ON DELETE、DEFERRABLE…)之后、分号之前。 */
|
|
31
|
+
export declare function notValidStatement(statement: string): string;
|
|
32
|
+
/**
|
|
33
|
+
* 外键自己比较时用的运算符(pg_constraint.conpfeqop,逐列 PK = FK)和被引用表是不是分区表。
|
|
34
|
+
* 从刚建好的约束上读:裸 = 的语义可能不同(citext 列上外键按不区分大小写比),继承子表也不该算进来。
|
|
35
|
+
*/
|
|
36
|
+
export interface ComparisonPlan {
|
|
37
|
+
operators: Array<{
|
|
38
|
+
schema: string;
|
|
39
|
+
name: string;
|
|
40
|
+
left: string;
|
|
41
|
+
right: string;
|
|
42
|
+
}>;
|
|
43
|
+
referencedPartitioned: boolean;
|
|
44
|
+
}
|
|
45
|
+
export declare const COMPARISON_PLAN_SQL = "\n select n.nspname as schema, o.oprname as name,\n format_type(o.oprleft, null) as left, format_type(o.oprright, null) as right,\n (select relkind = 'p' from pg_class where oid = c.confrelid) as referenced_partitioned\n from pg_constraint c\n cross join lateral unnest(c.conpfeqop) with ordinality as u(op, i)\n join pg_operator o on o.oid = u.op\n join pg_namespace n on n.oid = o.oprnamespace\n where c.conname = $1 and c.conrelid = $2::regclass\n order by u.i";
|
|
46
|
+
/**
|
|
47
|
+
* 数违反外键的行,与 PostgreSQL 校验外键(RI_Initial_Check)同一个口径:引用方 ONLY(外键不管继承子表),
|
|
48
|
+
* 被引用方普通表 ONLY、分区表带上分区;比较用约束记录的运算符和类型。
|
|
49
|
+
* MATCH SIMPLE 只查引用列全非空的行;MATCH FULL 另算"部分为空"的行。
|
|
50
|
+
*/
|
|
51
|
+
export declare function orphanCountSql(fk: ForeignKeyDef, plan: ComparisonPlan): string;
|
|
52
|
+
/** 一条孤儿外键给人看的说法(演练报告的失败项、真实恢复报告的说明共用)。 */
|
|
53
|
+
export declare function describeOrphanedForeignKey(orphaned: OrphanedForeignKey): string;
|
|
54
|
+
export interface AddForeignKeysResult {
|
|
55
|
+
orphaned: OrphanedForeignKey[];
|
|
56
|
+
/** 沙箱托管豁免命中数(与 classifyBlocks 同口径) */
|
|
57
|
+
expectedSkips: number;
|
|
58
|
+
/** 其余失败,只在 stopOnError=false 时出现 */
|
|
59
|
+
failures: string[];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 在一个事务里逐条加外键,每条一个 savepoint。23503 → 改加 NOT VALID 并数孤儿行。
|
|
63
|
+
* 其余错误:stopOnError(真实目标)= 回滚整个事务并抛出;否则(沙箱)按 allow 分类后继续。
|
|
64
|
+
* 调用方负责连接和最终的 commit/rollback 之外的一切——这里自己 begin/commit。
|
|
65
|
+
*/
|
|
66
|
+
export declare function addForeignKeys(client: Client, fks: ForeignKeyDef[], opts: {
|
|
67
|
+
allow: RegExp;
|
|
68
|
+
stopOnError: boolean;
|
|
69
|
+
/** 这些外键上的 COMMENT(pg_restore 写出的 SQL):外键加完再执行,不然注释对象还不存在 */
|
|
70
|
+
commentSql?: string;
|
|
71
|
+
}): Promise<AddForeignKeysResult>;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { formatQualified } from "./dump-sql.js";
|
|
2
|
+
import { quoteIdent } from "./restore-engine.js";
|
|
3
|
+
/**
|
|
4
|
+
* 归档目录里由 dump 自己建、又带着数据的表的建表条目:`<id>; 1259 <oid> TABLE …` 和
|
|
5
|
+
* `<id>; 0 <oid> TABLE DATA …` 的 oid 相同。只看 TABLE DATA 不够:扩展的配置表(pg_extension_config_dump)
|
|
6
|
+
* 由 CREATE EXTENSION 建、没有 TABLE 条目,数据条目里只有过了扩展过滤条件的行(交叉审查复现)。
|
|
7
|
+
* 按 oid 配对,不按名字:目录里的名字和属主都不加引号、可以带空格,拆不准(交叉审查复现)。
|
|
8
|
+
* 确切的表名由调用方让 pg_restore 把这些条目写成 SQL 再读(parseCreatedTables)。
|
|
9
|
+
*/
|
|
10
|
+
export function fullyDumpedTableEntries(listing) {
|
|
11
|
+
const lines = listing.split("\n");
|
|
12
|
+
const withData = new Set();
|
|
13
|
+
for (const line of lines) {
|
|
14
|
+
const match = /^\d+; 0 (\d+) TABLE DATA /.exec(line);
|
|
15
|
+
if (match)
|
|
16
|
+
withData.add(match[1]);
|
|
17
|
+
}
|
|
18
|
+
return lines.filter((line) => {
|
|
19
|
+
const match = /^\d+; \d+ (\d+) TABLE (?!DATA )/.exec(line);
|
|
20
|
+
return match !== null && withData.has(match[1]);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
export function tableKey(table) {
|
|
24
|
+
return `${table.schema}\u0000${table.name}`;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* 能交给 addForeignKeys 处理的外键:两端的行都完整地在快照里(fullyDumped,tableKey)、会校验已有行、
|
|
28
|
+
* 不在分区父表上。指向分区表的外键也照旧严格:分区表自己没有 TABLE DATA,数据在各个分区上。
|
|
29
|
+
*/
|
|
30
|
+
export function isDeferrableForeignKey(fk, fullyDumped) {
|
|
31
|
+
return (fk.validatesRows &&
|
|
32
|
+
!fk.onPartitionedTable &&
|
|
33
|
+
fullyDumped.has(tableKey(fk.table)) &&
|
|
34
|
+
fullyDumped.has(tableKey(fk.references)));
|
|
35
|
+
}
|
|
36
|
+
/** 同一条语句改成 NOT VALID:选项(ON DELETE、DEFERRABLE…)之后、分号之前。 */
|
|
37
|
+
export function notValidStatement(statement) {
|
|
38
|
+
return statement.replace(/;\s*$/, " NOT VALID;");
|
|
39
|
+
}
|
|
40
|
+
export const COMPARISON_PLAN_SQL = `
|
|
41
|
+
select n.nspname as schema, o.oprname as name,
|
|
42
|
+
format_type(o.oprleft, null) as left, format_type(o.oprright, null) as right,
|
|
43
|
+
(select relkind = 'p' from pg_class where oid = c.confrelid) as referenced_partitioned
|
|
44
|
+
from pg_constraint c
|
|
45
|
+
cross join lateral unnest(c.conpfeqop) with ordinality as u(op, i)
|
|
46
|
+
join pg_operator o on o.oid = u.op
|
|
47
|
+
join pg_namespace n on n.oid = o.oprnamespace
|
|
48
|
+
where c.conname = $1 and c.conrelid = $2::regclass
|
|
49
|
+
order by u.i`;
|
|
50
|
+
/**
|
|
51
|
+
* 数违反外键的行,与 PostgreSQL 校验外键(RI_Initial_Check)同一个口径:引用方 ONLY(外键不管继承子表),
|
|
52
|
+
* 被引用方普通表 ONLY、分区表带上分区;比较用约束记录的运算符和类型。
|
|
53
|
+
* MATCH SIMPLE 只查引用列全非空的行;MATCH FULL 另算"部分为空"的行。
|
|
54
|
+
*/
|
|
55
|
+
export function orphanCountSql(fk, plan) {
|
|
56
|
+
const child = (column) => `c.${quoteIdent(column)}`;
|
|
57
|
+
const allSet = fk.columns.map((column) => `${child(column)} is not null`).join(" and ");
|
|
58
|
+
const anySet = fk.columns.map((column) => `${child(column)} is not null`).join(" or ");
|
|
59
|
+
const matches = fk.columns
|
|
60
|
+
.map((column, i) => {
|
|
61
|
+
const op = plan.operators[i];
|
|
62
|
+
return (`p.${quoteIdent(fk.referencedColumns[i])}::${op.left} ` +
|
|
63
|
+
`OPERATOR(${quoteIdent(op.schema)}.${op.name}) ${child(column)}::${op.right}`);
|
|
64
|
+
})
|
|
65
|
+
.join(" and ");
|
|
66
|
+
const parent = `${plan.referencedPartitioned ? "" : "only "}${quoteIdent(fk.references.schema)}.${quoteIdent(fk.references.name)}`;
|
|
67
|
+
const missing = `not exists (select 1 from ${parent} p where ${matches})`;
|
|
68
|
+
const where = fk.matchFull ? `(${anySet}) and (not (${allSet}) or ${missing})` : `${allSet} and ${missing}`;
|
|
69
|
+
return `select count(*)::bigint as n from only ${quoteIdent(fk.table.schema)}.${quoteIdent(fk.table.name)} c where ${where}`;
|
|
70
|
+
}
|
|
71
|
+
/** 一条孤儿外键给人看的说法(演练报告的失败项、真实恢复报告的说明共用)。 */
|
|
72
|
+
export function describeOrphanedForeignKey(orphaned) {
|
|
73
|
+
const rows = orphaned.orphanRows === null ? "Some rows" : `${orphaned.orphanRows} row(s)`;
|
|
74
|
+
// 不说"指向不存在的行":MATCH FULL 下部分为空的行也算违反,它们未必缺对应的行(文案审查)
|
|
75
|
+
return `${rows} in ${orphaned.table} break foreign key ${orphaned.constraint}, which references ${orphaned.referencedTable}`;
|
|
76
|
+
}
|
|
77
|
+
/** 外键两端的键列里有没有生成列(attgenerated:存储型 's',PostgreSQL 18 起还有虚拟型 'v') */
|
|
78
|
+
async function hasGeneratedKeyColumn(client, fk) {
|
|
79
|
+
const qualified = (table) => `${quoteIdent(table.schema)}.${quoteIdent(table.name)}`;
|
|
80
|
+
const { rows } = await client.query(`select exists (
|
|
81
|
+
select 1 from pg_attribute
|
|
82
|
+
where ((attrelid = to_regclass($1) and attname = any($2::text[]))
|
|
83
|
+
or (attrelid = to_regclass($3) and attname = any($4::text[])))
|
|
84
|
+
and attgenerated <> ''
|
|
85
|
+
) as generated`, [qualified(fk.table), fk.columns, qualified(fk.references), fk.referencedColumns]);
|
|
86
|
+
return rows[0].generated;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* 在一个事务里逐条加外键,每条一个 savepoint。23503 → 改加 NOT VALID 并数孤儿行。
|
|
90
|
+
* 其余错误:stopOnError(真实目标)= 回滚整个事务并抛出;否则(沙箱)按 allow 分类后继续。
|
|
91
|
+
* 调用方负责连接和最终的 commit/rollback 之外的一切——这里自己 begin/commit。
|
|
92
|
+
*/
|
|
93
|
+
export async function addForeignKeys(client, fks, opts) {
|
|
94
|
+
const result = { orphaned: [], expectedSkips: 0, failures: [] };
|
|
95
|
+
// 和 pg_restore 的脚本头一样关掉超时:角色上配的 statement_timeout 会让大表的外键校验中途被掐断。
|
|
96
|
+
// search_path 钉在 pg_catalog:pg_dump 的语句都是全限定名,计数用的类型名和运算符也就不会被用户
|
|
97
|
+
// schema 里的同名对象截走(沙箱里这条连接是超级用户)。
|
|
98
|
+
// row_security 也和 pg_restore 一样关掉:这时策略已经建好,表属主在 FORCE ROW LEVEL SECURITY 下
|
|
99
|
+
// 加外键,PostgreSQL 的校验查询会被策略滤掉行,孤儿行照样被标成已校验;关掉后改为直接报错(交叉审查复现)
|
|
100
|
+
await client.query("set statement_timeout = 0; set lock_timeout = 0; set idle_in_transaction_session_timeout = 0; " +
|
|
101
|
+
"set search_path = pg_catalog; set row_security = off");
|
|
102
|
+
// transaction_timeout 是 PostgreSQL 17 才有的参数,旧版本上 set 会报"无此参数",忽略即可
|
|
103
|
+
await client.query("set transaction_timeout = 0").catch((error) => {
|
|
104
|
+
if (error.code !== "42704")
|
|
105
|
+
throw error;
|
|
106
|
+
});
|
|
107
|
+
await client.query("begin");
|
|
108
|
+
try {
|
|
109
|
+
// 这些外键在 pg_restore 那边本来排在启用行级安全之前;挪到这里时策略已经生效。表属主在
|
|
110
|
+
// FORCE ROW LEVEL SECURITY 下加外键会撞上 row_security = off(数据没问题也报错,交叉审查复现)。
|
|
111
|
+
// 在同一个事务里先 NO FORCE、加完再 FORCE 回去:属主不受策略约束,PostgreSQL 照常看全部行校验,
|
|
112
|
+
// 事务外看不到中间状态。超级用户和 BYPASSRLS 角色本来就不受影响,执行这两句也无害
|
|
113
|
+
const forced = await client.query(
|
|
114
|
+
// to_regclass:沙箱里某张表可能没建出来,那条外键自会记成失败,这里不该整体报错
|
|
115
|
+
"select oid::regclass::text as name from pg_class " +
|
|
116
|
+
"where oid in (select to_regclass(name) from unnest($1::text[]) as name) and relforcerowsecurity", [[...new Set(fks.flatMap((fk) => [fk.table, fk.references]).map((t) => `${quoteIdent(t.schema)}.${quoteIdent(t.name)}`))]]);
|
|
117
|
+
for (const { name } of forced.rows)
|
|
118
|
+
await client.query(`alter table only ${name} no force row level security`);
|
|
119
|
+
for (const fk of fks) {
|
|
120
|
+
await client.query("savepoint add_fk");
|
|
121
|
+
try {
|
|
122
|
+
await client.query(fk.statement);
|
|
123
|
+
await client.query("release savepoint add_fk");
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
await client.query("rollback to savepoint add_fk");
|
|
128
|
+
const pgError = error;
|
|
129
|
+
// 生成列的值是恢复时重算的,不是快照里的原值:生成函数改过定义,重算出的键就可能对不上,
|
|
130
|
+
// 这种违反不是源库带来的,不能放宽(交叉审查复现)
|
|
131
|
+
if (pgError.code !== "23503" || (await hasGeneratedKeyColumn(client, fk))) {
|
|
132
|
+
if (opts.stopOnError)
|
|
133
|
+
throw error;
|
|
134
|
+
if (opts.allow.test(pgError.message))
|
|
135
|
+
result.expectedSkips += 1;
|
|
136
|
+
else
|
|
137
|
+
result.failures.push(`foreign key ${fk.constraint} on ${formatQualified(fk.table)}: ${pgError.message}`);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// NOT VALID 失败就是真失败:不在这里吞
|
|
142
|
+
try {
|
|
143
|
+
await client.query(notValidStatement(fk.statement));
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
await client.query("rollback to savepoint add_fk");
|
|
147
|
+
if (opts.stopOnError)
|
|
148
|
+
throw error;
|
|
149
|
+
result.failures.push(`foreign key ${fk.constraint} on ${formatQualified(fk.table)}: ${error.message}`);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
// 计数只为报告:失败(类型没有 = 运算符等)不影响已经加上的外键
|
|
153
|
+
await client.query("savepoint count_orphans");
|
|
154
|
+
let orphanRows = null;
|
|
155
|
+
try {
|
|
156
|
+
const plan = await client.query(COMPARISON_PLAN_SQL, [fk.constraint, `${quoteIdent(fk.table.schema)}.${quoteIdent(fk.table.name)}`]);
|
|
157
|
+
if (plan.rows.length !== fk.columns.length)
|
|
158
|
+
throw new Error("comparison operators not found");
|
|
159
|
+
const counted = await client.query(orphanCountSql(fk, {
|
|
160
|
+
operators: plan.rows,
|
|
161
|
+
referencedPartitioned: plan.rows[0].referenced_partitioned,
|
|
162
|
+
}));
|
|
163
|
+
orphanRows = Number(counted.rows[0].n);
|
|
164
|
+
await client.query("release savepoint count_orphans");
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
await client.query("rollback to savepoint count_orphans");
|
|
168
|
+
}
|
|
169
|
+
await client.query("release savepoint add_fk");
|
|
170
|
+
result.orphaned.push({
|
|
171
|
+
constraint: fk.constraint,
|
|
172
|
+
table: formatQualified(fk.table),
|
|
173
|
+
referencedTable: formatQualified(fk.references),
|
|
174
|
+
columns: fk.columns,
|
|
175
|
+
referencedColumns: fk.referencedColumns,
|
|
176
|
+
matchFull: fk.matchFull,
|
|
177
|
+
orphanRows,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
if (opts.commentSql) {
|
|
181
|
+
await client.query("savepoint add_comments");
|
|
182
|
+
try {
|
|
183
|
+
await client.query(opts.commentSql);
|
|
184
|
+
await client.query("release savepoint add_comments");
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
await client.query("rollback to savepoint add_comments");
|
|
188
|
+
if (opts.stopOnError)
|
|
189
|
+
throw error;
|
|
190
|
+
const message = error.message;
|
|
191
|
+
if (opts.allow.test(message))
|
|
192
|
+
result.expectedSkips += 1;
|
|
193
|
+
else
|
|
194
|
+
result.failures.push(`comments on foreign keys: ${message}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
for (const { name } of forced.rows)
|
|
198
|
+
await client.query(`alter table only ${name} force row level security`);
|
|
199
|
+
await client.query("commit");
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
await client.query("rollback").catch(() => { });
|
|
203
|
+
throw error;
|
|
204
|
+
}
|
|
205
|
+
return result;
|
|
206
|
+
}
|
package/dist/restore-engine.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Client } from "pg";
|
|
2
2
|
import type { ExtensionInfo } from "./manifest.js";
|
|
3
|
+
import { type OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
3
4
|
export type RestoreTargetKind = "sandbox" | "supabase";
|
|
4
5
|
/** 主机名规范化:先按驱动语义百分号解码(pg-connection-string / libpq 都会解码主机名,
|
|
5
6
|
* `supabase%2Ecom` 在驱动眼里就是 supabase.com),再剥掉合法的 DNS 根点(db.x.supabase.co. ≡
|
|
@@ -27,14 +28,29 @@ export declare function refFromStorageEndpoint(endpoint: string): string | null;
|
|
|
27
28
|
export interface ClassifiedPass {
|
|
28
29
|
/** allowlist 命中数(环境预期/托管冲突)——如实入报告,不算失败 */
|
|
29
30
|
expectedSkips: number;
|
|
30
|
-
/** 真失败(
|
|
31
|
+
/** 真失败(压缩空白、按 FAILURE_DETAIL_MAX_CHARS 截断的错误块) */
|
|
31
32
|
failures: string[];
|
|
32
33
|
}
|
|
33
34
|
export interface EngineResult {
|
|
34
35
|
preData: ClassifiedPass;
|
|
35
36
|
postData: ClassifiedPass;
|
|
36
37
|
ok: boolean;
|
|
38
|
+
/** 因源库自带孤儿行而以 NOT VALID 建成的外键(见 orphaned-foreign-keys.ts);沙箱里它们同时记为失败 */
|
|
39
|
+
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
40
|
+
/**
|
|
41
|
+
* 真实目标:失败发生在主事务提交之后(外键那一步),表和数据已经在目标上。
|
|
42
|
+
* 调用方据此如实说明,不能再说"已整体回滚"。
|
|
43
|
+
*/
|
|
44
|
+
committed?: boolean;
|
|
37
45
|
}
|
|
46
|
+
/** 演练里孤儿外键记成失败项时的说法:数据问题出在源库,真实恢复会怎样。 */
|
|
47
|
+
export declare function sandboxOrphanFailure(orphaned: OrphanedForeignKey): string;
|
|
48
|
+
/**
|
|
49
|
+
* 新版 pg_restore 的脚本首尾各有一条 psql 元命令(\restrict <key> / \unrestrict <key>),node-pg 执行不了。
|
|
50
|
+
* 只认位置:开头那条是第一行非空、非 -- 注释的行,结尾那条是最后一行非空行。注释正文是字符串,
|
|
51
|
+
* 里面换行后恰好以 \restrict 开头的行要原样保留(交叉审查)。
|
|
52
|
+
*/
|
|
53
|
+
export declare function withoutRestrictWrapper(script: string): string;
|
|
38
54
|
/**
|
|
39
55
|
* libpq 子进程(pg_dump / pg_restore)的环境。`supabaseHost` 为真时再剔除 PGOPTIONS:Supavisor 会从
|
|
40
56
|
* options 里读租户覆盖(reference=…),而 Node 客户端对 Supabase 主机已显式钉死 options;非 Supabase
|
|
@@ -73,17 +89,6 @@ export declare function sandboxManagedError(dumpedSchemas?: string[]): RegExp;
|
|
|
73
89
|
/** 默认形态(什么托管 schema 都没转):兼容层与"只转 public"的托管 worker 路径。 */
|
|
74
90
|
export declare const SANDBOX_MANAGED_ERROR: RegExp;
|
|
75
91
|
export declare const SCHEMA_EXISTS_ERROR: RegExp;
|
|
76
|
-
/**
|
|
77
|
-
* 把 pg_restore 的 stderr 拆成单个错误块并按 allowlist 分类。
|
|
78
|
-
* **只对 ERROR 那一行分类**:不看 "Command was:" 之后的语句文本,也不看 DETAIL /
|
|
79
|
-
* CONTEXT / LINE 行。前者的理由:一个恰好引用 auth.uid 的用户对象因"损坏/语法错误"
|
|
80
|
-
* 失败时,会被误判成预期跳过。后者(交叉审查 2026-09-11 复现):DETAIL 里带的是**行值**
|
|
81
|
-
* —— `Key (message)=(relation "auth.users" does not exist) already exists` 是用户的数据,
|
|
82
|
-
* 不是错误原因,拿它匹配等于让用户数据决定演练结论;一条失败的唯一索引就能这样混过去。
|
|
83
|
-
* Postgres 的主消息恒为单行,且在块的第一行(`pg_restore: error: ... ERROR: …`)。
|
|
84
|
-
* 抽出 `ERROR:` 之后的那段作为主消息,allowlist 对它**整条**匹配(两端锚定,见上);
|
|
85
|
-
* 没有 `ERROR:` 前缀的块(归档器致命错等)整行当主消息,锚定的 allowlist 不会认它 → 失败。
|
|
86
|
-
*/
|
|
87
92
|
export declare function classifyBlocks(stderr: string, allow: RegExp): ClassifiedPass;
|
|
88
93
|
/**
|
|
89
94
|
* 一遍恢复的最终裁决,两条独立规则:
|
package/dist/restore-engine.js
CHANGED
|
@@ -12,11 +12,14 @@
|
|
|
12
12
|
// 真实目标(2.7.0 起)整份恢复放在一个事务里:失败就整体回滚,目标还是空的,修好原因可以在同一个
|
|
13
13
|
// 项目上直接重跑。此前两遍恢复各自自动提交,post-data 里一条外键失败,表和数据已经落库,重跑被
|
|
14
14
|
// 空目标门挡住(2026-10-22 实验:profiles → auth.users)。沙箱用完即毁,不需要事务,保留两遍 + 并行。
|
|
15
|
+
// 两端都在备份里的外键(2.8.0 起)在主事务提交后另起一个事务加,源库自带孤儿行的建成 NOT VALID,
|
|
16
|
+
// 沙箱走同一个函数(orphaned-foreign-keys.ts)。
|
|
15
17
|
import { spawn } from "node:child_process";
|
|
16
18
|
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
17
19
|
import { tmpdir } from "node:os";
|
|
18
20
|
import { join } from "node:path";
|
|
19
|
-
import { MAX_COPY_HEADER, parseCopyHeader, parseCreateSchemas } from "./dump-sql.js";
|
|
21
|
+
import { MAX_COPY_HEADER, parseCopyHeader, parseCreatedTables, parseCreateSchemas, parseForeignKeys, } from "./dump-sql.js";
|
|
22
|
+
import { addForeignKeys, describeOrphanedForeignKey, fullyDumpedTableEntries, isDeferrableForeignKey, tableKey, } from "./orphaned-foreign-keys.js";
|
|
20
23
|
import { resolvePgRestoreBin } from "./pgbin.js";
|
|
21
24
|
import { dumpUrlFor, connectPg, isSupabaseHost } from "./supabase-ca.js";
|
|
22
25
|
import { interrupted, onInterrupt, stopOnInterrupt } from "./interrupt.js";
|
|
@@ -97,6 +100,86 @@ export function refFromStorageEndpoint(endpoint) {
|
|
|
97
100
|
return null;
|
|
98
101
|
}
|
|
99
102
|
}
|
|
103
|
+
/** 演练里孤儿外键记成失败项时的说法:数据问题出在源库,真实恢复会怎样。 */
|
|
104
|
+
export function sandboxOrphanFailure(orphaned) {
|
|
105
|
+
return (`${describeOrphanedForeignKey(orphaned)}. Your database already had these rows when it was backed up. ` +
|
|
106
|
+
`A restore brings them back and adds this foreign key as NOT VALID; clean up the rows to make the drill pass.`);
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* 从目录条目里挑出交给 addForeignKeys 的外键(isDeferrableForeignKey)。让 pg_restore 把全部外键条目
|
|
110
|
+
* 写成 SQL,第 i 条语句对第 i 行(-L 按清单顺序输出)。对不上数或对不上名字(认不出的外键形态)
|
|
111
|
+
* 就一条也不挪:全部留给 pg_restore,行为和以前一样。
|
|
112
|
+
* 这些外键上的 COMMENT 一起挪:它们依赖外键本身,留在原处会因为对象还不存在而失败(交叉审查复现)。
|
|
113
|
+
*/
|
|
114
|
+
async function deferredForeignKeys(bin, dumpPath, entries, listDir) {
|
|
115
|
+
const none = { lines: new Set(), fks: [] };
|
|
116
|
+
const fkEntries = entries.filter((line) => /^\d+; \d+ \d+ FK CONSTRAINT /.test(line));
|
|
117
|
+
if (!fkEntries.length)
|
|
118
|
+
return none;
|
|
119
|
+
// 沙箱那边传进来的只有 post-data 条目,数据条目要看完整目录
|
|
120
|
+
const fullListing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
121
|
+
if (fullListing.code !== 0)
|
|
122
|
+
return none;
|
|
123
|
+
const tableEntries = fullyDumpedTableEntries(fullListing.stdout);
|
|
124
|
+
if (!tableEntries.length)
|
|
125
|
+
return none;
|
|
126
|
+
const tableList = join(listDir, "tables.list");
|
|
127
|
+
await writeFile(tableList, tableEntries.join("\n") + "\n");
|
|
128
|
+
const tableDdl = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${tableList}`, dumpPath]);
|
|
129
|
+
if (tableDdl.code !== 0)
|
|
130
|
+
return none;
|
|
131
|
+
const fullyDumped = new Set(parseCreatedTables(tableDdl.stdout).map(tableKey));
|
|
132
|
+
const listFile = join(listDir, "foreign-keys.list");
|
|
133
|
+
await writeFile(listFile, fkEntries.join("\n") + "\n");
|
|
134
|
+
const ddl = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${listFile}`, dumpPath]);
|
|
135
|
+
const parsed = parseForeignKeys(ddl.stdout);
|
|
136
|
+
if (ddl.code !== 0 || parsed.length !== fkEntries.length)
|
|
137
|
+
return none;
|
|
138
|
+
if (parsed.some((fk, i) => !fkEntries[i].includes(fk.constraint)))
|
|
139
|
+
return none;
|
|
140
|
+
const lines = new Set();
|
|
141
|
+
const fks = [];
|
|
142
|
+
parsed.forEach((fk, i) => {
|
|
143
|
+
if (!isDeferrableForeignKey(fk, fullyDumped))
|
|
144
|
+
return;
|
|
145
|
+
lines.add(fkEntries[i]);
|
|
146
|
+
fks.push(fk);
|
|
147
|
+
});
|
|
148
|
+
// 目录里的注释条目:`<id>; 0 0 COMMENT <schema> CONSTRAINT <名> ON <表> <属主>`。这里的名字经过 fmtId,
|
|
149
|
+
// 需要时带双引号(大写、空格、关键字),所以原样和加引号两种写法都认(交叉审查复现)。
|
|
150
|
+
// 多挪了一条别的外键的注释无害:那条外键已在主事务里建好,注释晚一点加照样成功
|
|
151
|
+
const spellings = (name) => [name, `"${name.replace(/"/g, '""')}"`];
|
|
152
|
+
const commentLines = entries.filter((line) => /^\d+; \d+ \d+ COMMENT /.test(line) &&
|
|
153
|
+
fks.some((fk) => spellings(fk.constraint).some((constraint) => spellings(fk.table.name).some((table) => line.includes(` CONSTRAINT ${constraint} ON ${table}`)))));
|
|
154
|
+
if (!commentLines.length)
|
|
155
|
+
return { lines, fks };
|
|
156
|
+
const commentList = join(listDir, "foreign-key-comments.list");
|
|
157
|
+
await writeFile(commentList, commentLines.join("\n") + "\n");
|
|
158
|
+
const comments = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${commentList}`, dumpPath]);
|
|
159
|
+
if (comments.code !== 0)
|
|
160
|
+
return none;
|
|
161
|
+
for (const line of commentLines)
|
|
162
|
+
lines.add(line);
|
|
163
|
+
return { lines, fks, commentSql: withoutRestrictWrapper(comments.stdout) };
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* 新版 pg_restore 的脚本首尾各有一条 psql 元命令(\restrict <key> / \unrestrict <key>),node-pg 执行不了。
|
|
167
|
+
* 只认位置:开头那条是第一行非空、非 -- 注释的行,结尾那条是最后一行非空行。注释正文是字符串,
|
|
168
|
+
* 里面换行后恰好以 \restrict 开头的行要原样保留(交叉审查)。
|
|
169
|
+
*/
|
|
170
|
+
export function withoutRestrictWrapper(script) {
|
|
171
|
+
const lines = script.split("\n");
|
|
172
|
+
const opening = lines.findIndex((line) => line.trim() !== "" && !line.startsWith("--"));
|
|
173
|
+
let closing = lines.length - 1;
|
|
174
|
+
while (closing >= 0 && lines[closing].trim() === "")
|
|
175
|
+
closing -= 1;
|
|
176
|
+
const drop = new Set();
|
|
177
|
+
if (opening >= 0 && /^\\restrict \S+$/.test(lines[opening]))
|
|
178
|
+
drop.add(opening);
|
|
179
|
+
if (closing > opening && /^\\unrestrict \S+$/.test(lines[closing]))
|
|
180
|
+
drop.add(closing);
|
|
181
|
+
return lines.filter((_, i) => !drop.has(i)).join("\n");
|
|
182
|
+
}
|
|
100
183
|
/**
|
|
101
184
|
* libpq 环境变量里会改写**连接到哪里、以谁的身份**的那些:剔除它们,子进程才只认 --dbname 里的
|
|
102
185
|
* URL。TLS 策略(PGSSLMODE / PGSSLROOTCERT…)、超时、编码、应用名这类**不改目标**的变量保留——
|
|
@@ -258,6 +341,12 @@ const NEVER_MATCH = /(?!)/;
|
|
|
258
341
|
* 抽出 `ERROR:` 之后的那段作为主消息,allowlist 对它**整条**匹配(两端锚定,见上);
|
|
259
342
|
* 没有 `ERROR:` 前缀的块(归档器致命错等)整行当主消息,锚定的 allowlist 不会认它 → 失败。
|
|
260
343
|
*/
|
|
344
|
+
/**
|
|
345
|
+
* 单条失败写进报告时的长度上限。要装得下 ERROR 行 + DETAIL 行:外键校验失败时,被引用的父表名和
|
|
346
|
+
* 完整的键只在 DETAIL 里,原先 200 字符会把它们截掉(2026-10-30 一次外键失败的报告只剩半个 UUID)。
|
|
347
|
+
* 末尾的 "Command was:" 语句最先被截,无妨。
|
|
348
|
+
*/
|
|
349
|
+
const FAILURE_DETAIL_MAX_CHARS = 500;
|
|
261
350
|
export function classifyBlocks(stderr, allow) {
|
|
262
351
|
const blocks = stderr
|
|
263
352
|
.split(/(?=pg_restore: error:)/)
|
|
@@ -271,7 +360,7 @@ export function classifyBlocks(stderr, allow) {
|
|
|
271
360
|
expectedSkips += 1;
|
|
272
361
|
}
|
|
273
362
|
else {
|
|
274
|
-
failures.push(block.replace(/\s+/g, " ").trim().slice(0,
|
|
363
|
+
failures.push(block.replace(/\s+/g, " ").trim().slice(0, FAILURE_DETAIL_MAX_CHARS));
|
|
275
364
|
}
|
|
276
365
|
}
|
|
277
366
|
return { expectedSkips, failures };
|
|
@@ -657,9 +746,14 @@ function mergePasses(passes) {
|
|
|
657
746
|
* 代价是锁:每张表连同索引、序列、TOAST 各占一个锁槽,直到提交。max_connections 60 的目标上实测
|
|
658
747
|
* 900 张表能过、1200 张表报 out of shared memory(restore.ts restoreFailureAdvice 给出调参办法);
|
|
659
748
|
* 撞上了也是整体回滚,不会留半截。
|
|
749
|
+
*
|
|
750
|
+
* 例外是两端都在备份里的外键(deferredForeignKeys):它们不进这个事务,提交之后在另一个事务里
|
|
751
|
+
* 逐条加(addForeignKeys),源库自带孤儿行的那几条建成 NOT VALID,恢复照样成功。代价是那一步
|
|
752
|
+
* 出别的错时表和数据已经提交(committed);可能的原因只剩连接断开、锁槽这类和数据无关的情况——
|
|
753
|
+
* 被引用的表和唯一索引都已在主事务里建好。
|
|
660
754
|
*/
|
|
661
755
|
async function restoreInOneTransaction(bin, dumpPath, connString, common, env, childOpts) {
|
|
662
|
-
const fail = (failure) => ({ expectedSkips: 0, failures: [failure] });
|
|
756
|
+
const fail = (failure) => ({ pass: { expectedSkips: 0, failures: [failure] } });
|
|
663
757
|
const listing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
664
758
|
if (listing.code !== 0) {
|
|
665
759
|
return fail(`pg_restore --list exited with code ${listing.code}: ${listing.stderr.trim().replace(/\s+/g, " ").slice(0, 200)}`);
|
|
@@ -692,14 +786,36 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
692
786
|
await client.end();
|
|
693
787
|
}
|
|
694
788
|
}
|
|
789
|
+
const deferred = await deferredForeignKeys(bin, dumpPath, entries, listDir);
|
|
695
790
|
const listFile = join(listDir, "restore.list");
|
|
696
|
-
await writeFile(listFile, entries.filter((line) => !skip.has(line)).join("\n") + "\n");
|
|
791
|
+
await writeFile(listFile, entries.filter((line) => !skip.has(line) && !deferred.lines.has(line)).join("\n") + "\n");
|
|
697
792
|
const run = await spawnPgRestore(bin, ["--single-transaction", `--use-list=${listFile}`, ...common], env, childOpts);
|
|
698
|
-
if (run.code === 0)
|
|
699
|
-
return { expectedSkips: 0, failures: [] };
|
|
700
793
|
if (run.code === null)
|
|
701
794
|
return fail(`pg_restore was killed by a signal: ${firstRestoreError(run.stderr)}`);
|
|
702
|
-
|
|
795
|
+
if (run.code !== 0)
|
|
796
|
+
return fail(firstRestoreError(run.stderr));
|
|
797
|
+
if (!deferred.fks.length)
|
|
798
|
+
return { pass: { expectedSkips: 0, failures: [] } };
|
|
799
|
+
try {
|
|
800
|
+
const client = await connectPg(connString);
|
|
801
|
+
try {
|
|
802
|
+
const added = await addForeignKeys(client, deferred.fks, {
|
|
803
|
+
allow: NEVER_MATCH,
|
|
804
|
+
stopOnError: true,
|
|
805
|
+
commentSql: deferred.commentSql,
|
|
806
|
+
});
|
|
807
|
+
return { pass: { expectedSkips: 0, failures: [] }, orphaned: added.orphaned };
|
|
808
|
+
}
|
|
809
|
+
finally {
|
|
810
|
+
await client.end();
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
catch (error) {
|
|
814
|
+
return {
|
|
815
|
+
pass: { expectedSkips: 0, failures: [`adding foreign keys failed: ${error.message}`] },
|
|
816
|
+
committed: true,
|
|
817
|
+
};
|
|
818
|
+
}
|
|
703
819
|
}
|
|
704
820
|
finally {
|
|
705
821
|
await rm(listDir, { recursive: true, force: true });
|
|
@@ -749,8 +865,14 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
749
865
|
const common = ["--no-owner", "--no-privileges", "--dbname", url, opts.dumpPath];
|
|
750
866
|
const childOpts = { supabaseHost: isSupabaseHost(opts.connString), urlSslMode: urlSslModeOf(url) };
|
|
751
867
|
if (opts.target === "supabase") {
|
|
752
|
-
const pass = await restoreInOneTransaction(bin, opts.dumpPath, opts.connString, common, env, childOpts);
|
|
753
|
-
return {
|
|
868
|
+
const { pass, orphaned, committed } = await restoreInOneTransaction(bin, opts.dumpPath, opts.connString, common, env, childOpts);
|
|
869
|
+
return {
|
|
870
|
+
preData: pass,
|
|
871
|
+
postData: { expectedSkips: 0, failures: [] },
|
|
872
|
+
ok: pass.failures.length === 0,
|
|
873
|
+
orphanedForeignKeys: orphaned,
|
|
874
|
+
committed,
|
|
875
|
+
};
|
|
754
876
|
}
|
|
755
877
|
const jobs = Math.max(1, Math.floor(opts.jobs ?? 1));
|
|
756
878
|
const parallel = jobs > 1;
|
|
@@ -761,61 +883,92 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
761
883
|
return { preData, postData: { expectedSkips: 0, failures: [] }, ok: false };
|
|
762
884
|
}
|
|
763
885
|
const postDataAllow = opts.target === "sandbox" ? sandboxManagedError(opts.dumpedSchemas ?? []) : NEVER_MATCH;
|
|
764
|
-
if (!parallel) {
|
|
765
|
-
const second = await spawnPgRestore(bin, ["--section=post-data", ...common], env, childOpts);
|
|
766
|
-
const postData = finalizePass(second.code, second.stderr, classifyBlocks(second.stderr, postDataAllow));
|
|
767
|
-
return { preData, postData, ok: postData.failures.length === 0 };
|
|
768
|
-
}
|
|
769
886
|
const listing = await pgRestoreOutput(bin, ["--list", "--section=post-data", opts.dumpPath]);
|
|
770
887
|
if (listing.code !== 0) {
|
|
771
888
|
const detail = listing.stderr.trim().replace(/\s+/g, " ").slice(0, 200) || "(no stderr)";
|
|
772
889
|
const postData = { expectedSkips: 0, failures: [`pg_restore --list exited with code ${listing.code}: ${detail}`] };
|
|
773
890
|
return { preData, postData, ok: false };
|
|
774
891
|
}
|
|
775
|
-
const { indexBuilds, rest } = splitPostDataList(listing.stdout);
|
|
776
892
|
const listDir = await mkdtemp(join(tmpdir(), "backupdrill-restore-"));
|
|
777
893
|
const forgetListDir = onInterrupt(() => rm(listDir, { recursive: true, force: true }).catch(() => { }));
|
|
894
|
+
let orphanedForeignKeys;
|
|
778
895
|
try {
|
|
896
|
+
const postEntries = listing.stdout.split("\n").filter((line) => /^\d+;/.test(line));
|
|
897
|
+
// 两端都在备份里的外键不交给 pg_restore,最后由 addForeignKeys 加:与真实恢复同一套判定
|
|
898
|
+
const deferred = await deferredForeignKeys(bin, opts.dumpPath, postEntries, listDir);
|
|
779
899
|
const passes = [];
|
|
780
|
-
if (
|
|
781
|
-
const
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
const
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
900
|
+
if (!parallel) {
|
|
901
|
+
const args = ["--section=post-data", ...common];
|
|
902
|
+
if (deferred.lines.size) {
|
|
903
|
+
const listFile = join(listDir, "post-data.list");
|
|
904
|
+
await writeFile(listFile, postEntries.filter((line) => !deferred.lines.has(line)).join("\n") + "\n");
|
|
905
|
+
args.splice(1, 0, `--use-list=${listFile}`);
|
|
906
|
+
}
|
|
907
|
+
const second = await spawnPgRestore(bin, args, env, childOpts);
|
|
908
|
+
passes.push(finalizePass(second.code, second.stderr, classifyBlocks(second.stderr, postDataAllow)));
|
|
909
|
+
}
|
|
910
|
+
else {
|
|
911
|
+
const { indexBuilds, rest: allRest } = splitPostDataList(listing.stdout);
|
|
912
|
+
const rest = allRest.filter((line) => !deferred.lines.has(line));
|
|
913
|
+
if (indexBuilds.length) {
|
|
914
|
+
const listFile = join(listDir, "index-builds.list");
|
|
915
|
+
await writeFile(listFile, indexBuilds.join("\n") + "\n");
|
|
916
|
+
const run = await spawnPgRestore(bin, ["--section=post-data", `--use-list=${listFile}`, "--verbose", ...jobsArg, ...common], env, childOpts);
|
|
917
|
+
// 退出码 0 = 一个错都没有。出过错时不读交错的报错正文,只取出错条目的 dumpId,把这些条目
|
|
918
|
+
// 单连接重跑、照单连接的规则分类:一条 CREATE INDEX / ADD CONSTRAINT 失败不留半成品,
|
|
919
|
+
// 重跑得到的就是 jobs=1 时的结论(交叉审查:引用托管 schema 函数的索引在单连接时是预期
|
|
920
|
+
// 跳过,并行时不能因此判失败;也不能靠忽略"已存在"去猜哪些建好了,沙箱里预装的扩展
|
|
921
|
+
// 对象会和用户索引撞名)。资源原因偶发失败的条目,重跑成功即通过,和单连接本来一样。
|
|
922
|
+
if (run.code !== 0) {
|
|
923
|
+
const failedIds = failedTocEntries(run.stderr);
|
|
924
|
+
const failed = indexBuilds.filter((line) => failedIds.has(line.slice(0, line.indexOf(";"))));
|
|
925
|
+
// 被信号杀死、没有汇总行(中途致命退出,后面的条目根本没跑)、或认不出任何出错条目:
|
|
926
|
+
// 都说明这一遍没走完或没法归因,直接失败,不重跑
|
|
927
|
+
// 出错条目的编号即使被用户 SQL 冒充,也只会多重跑一条、让它报"已存在"而判失败,不会漏掉真错误
|
|
928
|
+
const finished = run.code !== null && ignoredErrorTotal(run.stderr) !== null && failed.length > 0;
|
|
929
|
+
if (!finished) {
|
|
930
|
+
const detail = run.stderr.trim().replace(/\s+/g, " ").slice(-200) || "(no stderr)";
|
|
931
|
+
passes.push({
|
|
932
|
+
expectedSkips: 0,
|
|
933
|
+
failures: [`parallel index builds did not finish cleanly (exit ${run.code ?? "signal"}): ${detail}`],
|
|
934
|
+
});
|
|
935
|
+
}
|
|
936
|
+
else {
|
|
937
|
+
const rerunFile = join(listDir, "index-builds-rerun.list");
|
|
938
|
+
await writeFile(rerunFile, failed.join("\n") + "\n");
|
|
939
|
+
const rerun = await spawnPgRestore(bin, ["--section=post-data", `--use-list=${rerunFile}`, ...common], env, childOpts);
|
|
940
|
+
passes.push(finalizePass(rerun.code, rerun.stderr, classifyBlocks(rerun.stderr, postDataAllow)));
|
|
941
|
+
}
|
|
808
942
|
}
|
|
809
943
|
}
|
|
944
|
+
if (rest.length) {
|
|
945
|
+
const listFile = join(listDir, "rest.list");
|
|
946
|
+
await writeFile(listFile, rest.join("\n") + "\n");
|
|
947
|
+
const run = await spawnPgRestore(bin, ["--section=post-data", `--use-list=${listFile}`, ...common], env, childOpts);
|
|
948
|
+
passes.push(finalizePass(run.code, run.stderr, classifyBlocks(run.stderr, postDataAllow)));
|
|
949
|
+
}
|
|
810
950
|
}
|
|
811
|
-
if (
|
|
812
|
-
const
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
951
|
+
if (deferred.fks.length) {
|
|
952
|
+
const client = await connectPg(opts.connString);
|
|
953
|
+
try {
|
|
954
|
+
const added = await addForeignKeys(client, deferred.fks, {
|
|
955
|
+
allow: postDataAllow,
|
|
956
|
+
stopOnError: false,
|
|
957
|
+
commentSql: deferred.commentSql,
|
|
958
|
+
});
|
|
959
|
+
// 演练仍判失败(用户该清理的数据问题),但说清真实恢复会怎样
|
|
960
|
+
passes.push({
|
|
961
|
+
expectedSkips: added.expectedSkips,
|
|
962
|
+
failures: [...added.failures, ...added.orphaned.map(sandboxOrphanFailure)],
|
|
963
|
+
});
|
|
964
|
+
orphanedForeignKeys = added.orphaned;
|
|
965
|
+
}
|
|
966
|
+
finally {
|
|
967
|
+
await client.end();
|
|
968
|
+
}
|
|
816
969
|
}
|
|
817
970
|
const postData = mergePasses(passes);
|
|
818
|
-
return { preData, postData, ok: postData.failures.length === 0 };
|
|
971
|
+
return { preData, postData, ok: postData.failures.length === 0, orphanedForeignKeys };
|
|
819
972
|
}
|
|
820
973
|
finally {
|
|
821
974
|
await rm(listDir, { recursive: true, force: true });
|
package/dist/restore.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { Manifest } from "./manifest.js";
|
|
|
3
3
|
import { type SnapshotStore } from "./snapshot-store.js";
|
|
4
4
|
import { type DrillCheck } from "./drill.js";
|
|
5
5
|
import { type StorageRestoreSummary } from "./storage-restore.js";
|
|
6
|
+
import { type OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
6
7
|
/** 归档可读性要求:pg_restore 必须 ≥ max(写入工具版本, 源服务端版本)——格式跟随写入工具。 */
|
|
7
8
|
export declare function requiredRestoreToolMajor(manifest: Manifest): number;
|
|
8
9
|
export interface RestoreResult {
|
|
@@ -17,6 +18,8 @@ export interface RestoreResult {
|
|
|
17
18
|
* 不能只看 restoredToDatabase——"恢复完成"与"恢复通过验证"是两个事实。
|
|
18
19
|
*/
|
|
19
20
|
databaseVerified?: boolean;
|
|
21
|
+
/** 因快照自带孤儿行而以 NOT VALID 建成的外键(数据照样全部恢复);没有时不出现 */
|
|
22
|
+
orphanedForeignKeys?: OrphanedForeignKey[];
|
|
20
23
|
/** Storage 回传摘要(提供了目标 Storage 凭据时);本地下载模式不存在 */
|
|
21
24
|
storageSummary?: StorageRestoreSummary;
|
|
22
25
|
storageFilesWritten: number;
|
package/dist/restore.js
CHANGED
|
@@ -11,6 +11,7 @@ import { checkExternalReferences, describe } from "./external-refs.js";
|
|
|
11
11
|
import { verifyRestored } from "./drill.js";
|
|
12
12
|
import { restoreStorage, planStorageRestore, } from "./storage-restore.js";
|
|
13
13
|
import { connectPg } from "./supabase-ca.js";
|
|
14
|
+
import { describeOrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
14
15
|
import { localPgRestoreMajor, restoreToolTargetBlocker } from "./pgbin.js";
|
|
15
16
|
import { parsePgDumpMajor } from "./backup.js";
|
|
16
17
|
import { log } from "./log.js";
|
|
@@ -691,15 +692,31 @@ export async function runRestore(config, opts) {
|
|
|
691
692
|
if (!engine.ok) {
|
|
692
693
|
const failures = [...engine.preData.failures, ...engine.postData.failures];
|
|
693
694
|
throw new Error(`database restore failed: ${failures.join(" | ")}.` +
|
|
694
|
-
(
|
|
695
|
+
(engine.committed
|
|
696
|
+
? " The tables and data were already committed to the target; some or all of the foreign keys " +
|
|
697
|
+
"between them may be missing. Check the target before doing anything else; restore won't write " +
|
|
698
|
+
"into it again while those objects are there."
|
|
699
|
+
: await targetStateAfterFailure(targetUrl, manifest.database.schemas)) +
|
|
695
700
|
restoreFailureAdvice(failures.join(" ")));
|
|
696
701
|
}
|
|
697
702
|
result.restoredToDatabase = true;
|
|
703
|
+
const orphaned = engine.orphanedForeignKeys ?? [];
|
|
698
704
|
// 与演练同一套表级验证:两条路径对同一快照必须同一结论(PRD §5.2 验收)
|
|
699
705
|
log.step("Verifying restored tables…");
|
|
700
706
|
const verified = await verifyRestored(targetUrl, manifest, dumpPath);
|
|
701
707
|
result.databaseChecks = verified.checks;
|
|
702
708
|
result.databaseVerified = verified.checks.every((c) => c.pass);
|
|
709
|
+
if (orphaned.length) {
|
|
710
|
+
result.orphanedForeignKeys = orphaned;
|
|
711
|
+
// 数据一行不少,外键也在(只是不回头查已有的行):算通过,但写进报告让人看见
|
|
712
|
+
result.databaseChecks.push({
|
|
713
|
+
name: "foreign keys",
|
|
714
|
+
pass: true,
|
|
715
|
+
detail: `${orphaned.length} added as NOT VALID because the snapshot holds rows that break them: ` +
|
|
716
|
+
`${orphaned.map(describeOrphanedForeignKey).join("; ")}. New writes are still checked. ` +
|
|
717
|
+
`Clean up those rows, then run ALTER TABLE … VALIDATE CONSTRAINT to check the old ones too.`,
|
|
718
|
+
});
|
|
719
|
+
}
|
|
703
720
|
for (const check of verified.checks) {
|
|
704
721
|
(check.pass ? log.ok : log.warn)(`${check.name}: ${check.detail}`);
|
|
705
722
|
}
|
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.7.
|
|
10
|
+
The agent runs every command as `npx -y backupdrill@2.7.2`, 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.7.
|
|
10
|
+
Always run it as `npx -y backupdrill@2.7.2 <command>`, so every run uses the same version.
|
|
11
11
|
|
|
12
12
|
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
13
|
|
|
@@ -69,7 +69,7 @@ Every backup reads the whole database, and every configured Storage file, out of
|
|
|
69
69
|
```sh
|
|
70
70
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
71
71
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
72
|
-
npx -y backupdrill@2.7.
|
|
72
|
+
npx -y backupdrill@2.7.2 estimate --plan pro )
|
|
73
73
|
```
|
|
74
74
|
|
|
75
75
|
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 +80,7 @@ Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the pr
|
|
|
80
80
|
report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "stdout → $report"
|
|
81
81
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
82
82
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
83
|
-
npx -y backupdrill@2.7.
|
|
83
|
+
npx -y backupdrill@2.7.2 backup ) > "$report"
|
|
84
84
|
```
|
|
85
85
|
|
|
86
86
|
- 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 +93,7 @@ report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "
|
|
|
93
93
|
```sh
|
|
94
94
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
95
95
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
96
|
-
npx -y backupdrill@2.7.
|
|
96
|
+
npx -y backupdrill@2.7.2 drill )
|
|
97
97
|
```
|
|
98
98
|
|
|
99
99
|
- 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 +112,7 @@ A restore writes data, so go step by step and let the user drive.
|
|
|
112
112
|
```sh
|
|
113
113
|
( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
|
|
114
114
|
set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
|
|
115
|
-
npx -y backupdrill@2.7.
|
|
115
|
+
npx -y backupdrill@2.7.2 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
|
|
116
116
|
```
|
|
117
117
|
|
|
118
118
|
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`.
|
|
@@ -95,7 +95,7 @@ jobs:
|
|
|
95
95
|
|
|
96
96
|
- name: Run backupdrill
|
|
97
97
|
# Pinned so every run uses the same CLI. Raise it on purpose when you upgrade.
|
|
98
|
-
run: npx -y backupdrill@2.7.
|
|
98
|
+
run: npx -y backupdrill@2.7.2 backup
|
|
99
99
|
env:
|
|
100
100
|
# --- required ---
|
|
101
101
|
BACKUPDRILL_DATABASE_URL: ${{ secrets.BACKUPDRILL_DATABASE_URL }}
|