backupdrill 2.7.3 → 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 +1 -1
- 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 +16 -0
- package/dist/restore-engine.js +195 -48
- package/dist/restore.d.ts +3 -0
- package/dist/restore.js +18 -1
- package/package.json +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
|
|
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. ≡
|
|
@@ -34,7 +35,22 @@ 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
|
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…)、超时、编码、应用名这类**不改目标**的变量保留——
|
|
@@ -663,9 +746,14 @@ function mergePasses(passes) {
|
|
|
663
746
|
* 代价是锁:每张表连同索引、序列、TOAST 各占一个锁槽,直到提交。max_connections 60 的目标上实测
|
|
664
747
|
* 900 张表能过、1200 张表报 out of shared memory(restore.ts restoreFailureAdvice 给出调参办法);
|
|
665
748
|
* 撞上了也是整体回滚,不会留半截。
|
|
749
|
+
*
|
|
750
|
+
* 例外是两端都在备份里的外键(deferredForeignKeys):它们不进这个事务,提交之后在另一个事务里
|
|
751
|
+
* 逐条加(addForeignKeys),源库自带孤儿行的那几条建成 NOT VALID,恢复照样成功。代价是那一步
|
|
752
|
+
* 出别的错时表和数据已经提交(committed);可能的原因只剩连接断开、锁槽这类和数据无关的情况——
|
|
753
|
+
* 被引用的表和唯一索引都已在主事务里建好。
|
|
666
754
|
*/
|
|
667
755
|
async function restoreInOneTransaction(bin, dumpPath, connString, common, env, childOpts) {
|
|
668
|
-
const fail = (failure) => ({ expectedSkips: 0, failures: [failure] });
|
|
756
|
+
const fail = (failure) => ({ pass: { expectedSkips: 0, failures: [failure] } });
|
|
669
757
|
const listing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
670
758
|
if (listing.code !== 0) {
|
|
671
759
|
return fail(`pg_restore --list exited with code ${listing.code}: ${listing.stderr.trim().replace(/\s+/g, " ").slice(0, 200)}`);
|
|
@@ -698,14 +786,36 @@ async function restoreInOneTransaction(bin, dumpPath, connString, common, env, c
|
|
|
698
786
|
await client.end();
|
|
699
787
|
}
|
|
700
788
|
}
|
|
789
|
+
const deferred = await deferredForeignKeys(bin, dumpPath, entries, listDir);
|
|
701
790
|
const listFile = join(listDir, "restore.list");
|
|
702
|
-
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");
|
|
703
792
|
const run = await spawnPgRestore(bin, ["--single-transaction", `--use-list=${listFile}`, ...common], env, childOpts);
|
|
704
|
-
if (run.code === 0)
|
|
705
|
-
return { expectedSkips: 0, failures: [] };
|
|
706
793
|
if (run.code === null)
|
|
707
794
|
return fail(`pg_restore was killed by a signal: ${firstRestoreError(run.stderr)}`);
|
|
708
|
-
|
|
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
|
+
}
|
|
709
819
|
}
|
|
710
820
|
finally {
|
|
711
821
|
await rm(listDir, { recursive: true, force: true });
|
|
@@ -755,8 +865,14 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
755
865
|
const common = ["--no-owner", "--no-privileges", "--dbname", url, opts.dumpPath];
|
|
756
866
|
const childOpts = { supabaseHost: isSupabaseHost(opts.connString), urlSslMode: urlSslModeOf(url) };
|
|
757
867
|
if (opts.target === "supabase") {
|
|
758
|
-
const pass = await restoreInOneTransaction(bin, opts.dumpPath, opts.connString, common, env, childOpts);
|
|
759
|
-
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
|
+
};
|
|
760
876
|
}
|
|
761
877
|
const jobs = Math.max(1, Math.floor(opts.jobs ?? 1));
|
|
762
878
|
const parallel = jobs > 1;
|
|
@@ -767,61 +883,92 @@ export async function restoreDatabaseArtifact(opts) {
|
|
|
767
883
|
return { preData, postData: { expectedSkips: 0, failures: [] }, ok: false };
|
|
768
884
|
}
|
|
769
885
|
const postDataAllow = opts.target === "sandbox" ? sandboxManagedError(opts.dumpedSchemas ?? []) : NEVER_MATCH;
|
|
770
|
-
if (!parallel) {
|
|
771
|
-
const second = await spawnPgRestore(bin, ["--section=post-data", ...common], env, childOpts);
|
|
772
|
-
const postData = finalizePass(second.code, second.stderr, classifyBlocks(second.stderr, postDataAllow));
|
|
773
|
-
return { preData, postData, ok: postData.failures.length === 0 };
|
|
774
|
-
}
|
|
775
886
|
const listing = await pgRestoreOutput(bin, ["--list", "--section=post-data", opts.dumpPath]);
|
|
776
887
|
if (listing.code !== 0) {
|
|
777
888
|
const detail = listing.stderr.trim().replace(/\s+/g, " ").slice(0, 200) || "(no stderr)";
|
|
778
889
|
const postData = { expectedSkips: 0, failures: [`pg_restore --list exited with code ${listing.code}: ${detail}`] };
|
|
779
890
|
return { preData, postData, ok: false };
|
|
780
891
|
}
|
|
781
|
-
const { indexBuilds, rest } = splitPostDataList(listing.stdout);
|
|
782
892
|
const listDir = await mkdtemp(join(tmpdir(), "backupdrill-restore-"));
|
|
783
893
|
const forgetListDir = onInterrupt(() => rm(listDir, { recursive: true, force: true }).catch(() => { }));
|
|
894
|
+
let orphanedForeignKeys;
|
|
784
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);
|
|
785
899
|
const passes = [];
|
|
786
|
-
if (
|
|
787
|
-
const
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
const
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
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
|
+
}
|
|
814
942
|
}
|
|
815
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
|
+
}
|
|
816
950
|
}
|
|
817
|
-
if (
|
|
818
|
-
const
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
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
|
+
}
|
|
822
969
|
}
|
|
823
970
|
const postData = mergePasses(passes);
|
|
824
|
-
return { preData, postData, ok: postData.failures.length === 0 };
|
|
971
|
+
return { preData, postData, ok: postData.failures.length === 0, orphanedForeignKeys };
|
|
825
972
|
}
|
|
826
973
|
finally {
|
|
827
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