backupdrill 2.9.2 → 2.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -5
- package/dist/auth-backup.d.ts +110 -0
- package/dist/auth-backup.js +383 -0
- package/dist/auth-drill.d.ts +69 -0
- package/dist/auth-drill.js +469 -0
- package/dist/auth-restore.d.ts +120 -0
- package/dist/auth-restore.js +633 -0
- package/dist/backup.d.ts +17 -0
- package/dist/backup.js +372 -19
- package/dist/config.d.ts +9 -0
- package/dist/config.js +17 -0
- package/dist/drill.d.ts +24 -3
- package/dist/drill.js +43 -3
- package/dist/dump-sql.d.ts +6 -0
- package/dist/dump-sql.js +31 -0
- package/dist/external-refs.d.ts +6 -1
- package/dist/external-refs.js +5 -0
- package/dist/index.js +67 -3
- package/dist/lib.d.ts +9 -3
- package/dist/lib.js +4 -2
- package/dist/manifest.d.ts +63 -0
- package/dist/manifest.js +78 -0
- package/dist/orphaned-foreign-keys.d.ts +13 -0
- package/dist/orphaned-foreign-keys.js +75 -25
- package/dist/pgbin.d.ts +7 -0
- package/dist/pgbin.js +24 -0
- package/dist/ping.js +1 -0
- package/dist/recovery-doc.d.ts +25 -0
- package/dist/recovery-doc.js +232 -53
- package/dist/restore-engine.d.ts +73 -1
- package/dist/restore-engine.js +155 -77
- package/dist/restore-record.d.ts +47 -0
- package/dist/restore-record.js +57 -0
- package/dist/restore.d.ts +64 -0
- package/dist/restore.js +348 -34
- package/dist/snapshot-store.d.ts +13 -0
- package/dist/snapshot-store.js +25 -0
- package/dist/snapshots.d.ts +2 -0
- package/dist/snapshots.js +10 -3
- package/package.json +1 -1
- package/plugin/README.md +1 -1
- package/plugin/skills/supabase-backup/SKILL.md +9 -7
- package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +6 -1
- package/plugin/skills/supabase-backup/references/postgres-backup-basics.md +94 -0
package/dist/restore-engine.js
CHANGED
|
@@ -101,6 +101,27 @@ export function refFromStorageEndpoint(endpoint) {
|
|
|
101
101
|
return null;
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* 空目标门数的对象(见 restore.ts assertEmptyTarget):这些 schema 里不属于扩展的关系、函数、类型。
|
|
106
|
+
* schemas 是一个 text[] 表达式(参数 $1::text[] 或字面量数组)。带 Auth 的恢复在事务里锁住之后用同一判据重查
|
|
107
|
+
*/
|
|
108
|
+
export function userObjectCountSql(schemas) {
|
|
109
|
+
return `(select count(*) from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
110
|
+
where n.nspname = any(${schemas}) and c.relkind in ('r','p','m','v','S','f','c')
|
|
111
|
+
and not (exists (select 1 from pg_depend d where d.deptype = 'e'
|
|
112
|
+
and ((d.classid = 'pg_class'::regclass and d.objid = c.oid)
|
|
113
|
+
-- 扩展建的复合类型(dblink 的 dblink_pkey_results)登记在类型上,不在关系上
|
|
114
|
+
or (d.classid = 'pg_type'::regclass and d.objid = c.reltype)))
|
|
115
|
+
and not exists (select 1 from pg_extension e where c.oid = any(e.extconfig))))
|
|
116
|
+
+ (select count(*) from pg_proc p join pg_namespace n on n.oid = p.pronamespace
|
|
117
|
+
where n.nspname = any(${schemas})
|
|
118
|
+
and not exists (select 1 from pg_depend d where d.classid = 'pg_proc'::regclass
|
|
119
|
+
and d.objid = p.oid and d.deptype = 'e'))
|
|
120
|
+
+ (select count(*) from pg_type t join pg_namespace n on n.oid = t.typnamespace
|
|
121
|
+
where n.nspname = any(${schemas}) and t.typtype in ('e','d','r')
|
|
122
|
+
and not exists (select 1 from pg_depend d where d.classid = 'pg_type'::regclass
|
|
123
|
+
and d.objid = t.oid and d.deptype = 'e'))`;
|
|
124
|
+
}
|
|
104
125
|
async function applyGrants(connString, grants) {
|
|
105
126
|
const client = await connectPg(connString);
|
|
106
127
|
try {
|
|
@@ -135,15 +156,25 @@ async function lockDownAfterGrantFailure(connString, schemas) {
|
|
|
135
156
|
* 就一条也不挪:全部留给 pg_restore,行为和以前一样。
|
|
136
157
|
* 这些外键上的 COMMENT 一起挪:它们依赖外键本身,留在原处会因为对象还不存在而失败(交叉审查复现)。
|
|
137
158
|
*/
|
|
138
|
-
async function deferredForeignKeys(bin, dumpPath, entries, listDir
|
|
159
|
+
async function deferredForeignKeys(bin, dumpPath, entries, listDir, alsoFullyDumped = [],
|
|
160
|
+
/**
|
|
161
|
+
* restore --finish 用:读不出来就报错,不退回"一条也不挪"。正常恢复里退回是安全的(外键全留给 pg_restore,
|
|
162
|
+
* 在主事务里建),接着做的时候退回就是漏加外键
|
|
163
|
+
*/
|
|
164
|
+
strict = false) {
|
|
139
165
|
const none = { lines: new Set(), fks: [] };
|
|
166
|
+
const giveUp = (why) => {
|
|
167
|
+
if (strict)
|
|
168
|
+
throw new Error(`the foreign keys to add couldn't be read from the dump (${why})`);
|
|
169
|
+
return none;
|
|
170
|
+
};
|
|
140
171
|
const fkEntries = entries.filter((line) => /^\d+; \d+ \d+ FK CONSTRAINT /.test(line));
|
|
141
172
|
if (!fkEntries.length)
|
|
142
173
|
return none;
|
|
143
174
|
// 沙箱那边传进来的只有 post-data 条目,数据条目要看完整目录
|
|
144
175
|
const fullListing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
145
176
|
if (fullListing.code !== 0)
|
|
146
|
-
return
|
|
177
|
+
return giveUp(`pg_restore --list exited with code ${fullListing.code}`);
|
|
147
178
|
const tableEntries = fullyDumpedTableEntries(fullListing.stdout);
|
|
148
179
|
if (!tableEntries.length)
|
|
149
180
|
return none;
|
|
@@ -151,16 +182,16 @@ async function deferredForeignKeys(bin, dumpPath, entries, listDir) {
|
|
|
151
182
|
await writeFile(tableList, tableEntries.join("\n") + "\n");
|
|
152
183
|
const tableDdl = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${tableList}`, dumpPath]);
|
|
153
184
|
if (tableDdl.code !== 0)
|
|
154
|
-
return
|
|
155
|
-
const fullyDumped = new Set(parseCreatedTables(tableDdl.stdout).map(tableKey));
|
|
185
|
+
return giveUp(`pg_restore exited with code ${tableDdl.code} writing the table definitions`);
|
|
186
|
+
const fullyDumped = new Set([...parseCreatedTables(tableDdl.stdout).map(tableKey), ...alsoFullyDumped]);
|
|
156
187
|
const listFile = join(listDir, "foreign-keys.list");
|
|
157
188
|
await writeFile(listFile, fkEntries.join("\n") + "\n");
|
|
158
189
|
const ddl = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${listFile}`, dumpPath]);
|
|
159
190
|
const parsed = parseForeignKeys(ddl.stdout);
|
|
160
191
|
if (ddl.code !== 0 || parsed.length !== fkEntries.length)
|
|
161
|
-
return
|
|
192
|
+
return giveUp("the foreign key definitions didn't match the listing");
|
|
162
193
|
if (parsed.some((fk, i) => !fkEntries[i].includes(fk.constraint)))
|
|
163
|
-
return
|
|
194
|
+
return giveUp("the foreign key definitions didn't match the listing");
|
|
164
195
|
const lines = new Set();
|
|
165
196
|
const fks = [];
|
|
166
197
|
parsed.forEach((fk, i) => {
|
|
@@ -181,7 +212,7 @@ async function deferredForeignKeys(bin, dumpPath, entries, listDir) {
|
|
|
181
212
|
await writeFile(commentList, commentLines.join("\n") + "\n");
|
|
182
213
|
const comments = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${commentList}`, dumpPath]);
|
|
183
214
|
if (comments.code !== 0)
|
|
184
|
-
return
|
|
215
|
+
return giveUp(`pg_restore exited with code ${comments.code} writing the foreign key comments`);
|
|
185
216
|
for (const line of commentLines)
|
|
186
217
|
lines.add(line);
|
|
187
218
|
return { lines, fks, commentSql: withoutRestrictWrapper(comments.stdout) };
|
|
@@ -284,6 +315,9 @@ export function spawnPgRestore(bin, args, extraEnv = {}, opts = { supabaseHost:
|
|
|
284
315
|
// 收到信号之后不再起新的一遍(两遍恢复、并行建索引后的重跑都是一个接一个起的)
|
|
285
316
|
if (interrupted())
|
|
286
317
|
return Promise.reject(new Error("interrupted; not starting pg_restore"));
|
|
318
|
+
// 调用方叫停(演练的 Auth 检查超时):已叫停就不起,起了就停掉。不传 signal 的调用方行为不变
|
|
319
|
+
if (opts.signal?.aborted)
|
|
320
|
+
return Promise.reject(new Error("stopped by the caller; not starting pg_restore"));
|
|
287
321
|
return new Promise((resolve, reject) => {
|
|
288
322
|
const proc = spawn(bin, args, {
|
|
289
323
|
stdio: ["ignore", "ignore", "pipe"],
|
|
@@ -291,6 +325,9 @@ export function spawnPgRestore(bin, args, extraEnv = {}, opts = { supabaseHost:
|
|
|
291
325
|
});
|
|
292
326
|
// `kill <pid>` 只发给 node 时 pg_restore 收不到;中断时由我们停掉它
|
|
293
327
|
stopOnInterrupt(proc);
|
|
328
|
+
const stopOnAbort = () => proc.kill("SIGTERM");
|
|
329
|
+
opts.signal?.addEventListener("abort", stopOnAbort, { once: true });
|
|
330
|
+
proc.once("close", () => opts.signal?.removeEventListener("abort", stopOnAbort));
|
|
294
331
|
let stderr = "";
|
|
295
332
|
proc.stderr.setEncoding("utf8");
|
|
296
333
|
proc.stderr.on("data", (d) => (stderr += d));
|
|
@@ -721,10 +758,13 @@ export function splitPostDataList(listing) {
|
|
|
721
758
|
return { indexBuilds, rest };
|
|
722
759
|
}
|
|
723
760
|
/** 不连库的 pg_restore(--list、-f - 出 SQL),整段收集 stdout。只用于目录和 DDL 这类小输出。 */
|
|
724
|
-
export function pgRestoreOutput(bin, args) {
|
|
761
|
+
export function pgRestoreOutput(bin, args, opts = {}) {
|
|
725
762
|
// 和 spawnPgRestore 一样:收到信号之后不再起,起了的中断时停掉(并行演练里读目录的那一步也是它)
|
|
726
763
|
if (interrupted())
|
|
727
764
|
return Promise.reject(new Error("interrupted; not starting pg_restore"));
|
|
765
|
+
// 调用方叫停同理;不传 signal 的调用方行为不变
|
|
766
|
+
if (opts.signal?.aborted)
|
|
767
|
+
return Promise.reject(new Error("stopped by the caller; not starting pg_restore"));
|
|
728
768
|
return new Promise((resolve, reject) => {
|
|
729
769
|
// 只读归档、不连库,但同样钉 C locale,和恢复子进程一致
|
|
730
770
|
const proc = spawn(bin, args, {
|
|
@@ -732,6 +772,9 @@ export function pgRestoreOutput(bin, args) {
|
|
|
732
772
|
env: libpqChildEnv(),
|
|
733
773
|
});
|
|
734
774
|
stopOnInterrupt(proc);
|
|
775
|
+
const stopOnAbort = () => proc.kill("SIGTERM");
|
|
776
|
+
opts.signal?.addEventListener("abort", stopOnAbort, { once: true });
|
|
777
|
+
proc.once("close", () => opts.signal?.removeEventListener("abort", stopOnAbort));
|
|
735
778
|
let stdout = "";
|
|
736
779
|
let stderr = "";
|
|
737
780
|
// 按流解码:一个多字节字符可能被拆在两块里,逐块 toString 会把它解坏(schema 名里的中文就会对不上)
|
|
@@ -778,90 +821,125 @@ function mergePasses(passes) {
|
|
|
778
821
|
*/
|
|
779
822
|
async function restoreInOneTransaction(bin, dumpPath, connString, common, env, childOpts, grantsToRestore) {
|
|
780
823
|
const fail = (failure) => ({ pass: { expectedSkips: 0, failures: [failure] } });
|
|
781
|
-
const listing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
782
|
-
if (listing.code !== 0) {
|
|
783
|
-
return fail(`pg_restore --list exited with code ${listing.code}: ${listing.stderr.trim().replace(/\s+/g, " ").slice(0, 200)}`);
|
|
784
|
-
}
|
|
785
|
-
const entries = listing.stdout.split("\n").filter((line) => /^\d+;/.test(line));
|
|
786
824
|
const listDir = await mkdtemp(join(tmpdir(), "backupdrill-restore-"));
|
|
787
825
|
try {
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
const
|
|
792
|
-
if (schemaEntries.length) {
|
|
793
|
-
const schemaList = join(listDir, "schemas.list");
|
|
794
|
-
await writeFile(schemaList, schemaEntries.join("\n") + "\n");
|
|
795
|
-
const ddl = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${schemaList}`, dumpPath]);
|
|
796
|
-
const names = parseCreateSchemas(ddl.stdout);
|
|
797
|
-
if (ddl.code !== 0 || names.length !== schemaEntries.length) {
|
|
798
|
-
return fail(`could not read the schema entries in the archive (pg_restore exited with code ${ddl.code})`);
|
|
799
|
-
}
|
|
800
|
-
const client = await connectPg(connString);
|
|
801
|
-
try {
|
|
802
|
-
const existing = await client.query("select nspname from pg_namespace where nspname = any($1::text[])", [names]);
|
|
803
|
-
const present = new Set(existing.rows.map((row) => row.nspname));
|
|
804
|
-
schemaEntries.forEach((line, i) => {
|
|
805
|
-
if (present.has(names[i]))
|
|
806
|
-
skip.add(line);
|
|
807
|
-
});
|
|
808
|
-
}
|
|
809
|
-
finally {
|
|
810
|
-
await client.end();
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
const deferred = await deferredForeignKeys(bin, dumpPath, entries, listDir);
|
|
814
|
-
const listFile = join(listDir, "restore.list");
|
|
815
|
-
await writeFile(listFile, entries.filter((line) => !skip.has(line) && !deferred.lines.has(line)).join("\n") + "\n");
|
|
816
|
-
const run = await spawnPgRestore(bin, ["--single-transaction", `--use-list=${listFile}`, ...common], env, childOpts);
|
|
826
|
+
const prepared = await prepareMainRestore(bin, dumpPath, connString, listDir);
|
|
827
|
+
if (!prepared.ok)
|
|
828
|
+
return fail(prepared.failure);
|
|
829
|
+
const run = await spawnPgRestore(bin, ["--single-transaction", `--use-list=${prepared.listFile}`, ...common], env, childOpts);
|
|
817
830
|
if (run.code === null)
|
|
818
831
|
return fail(`pg_restore was killed by a signal: ${firstRestoreError(run.stderr)}`);
|
|
819
832
|
if (run.code !== 0)
|
|
820
833
|
return fail(firstRestoreError(run.stderr));
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
834
|
+
return await afterCommit(connString, grantsToRestore, prepared.deferred);
|
|
835
|
+
}
|
|
836
|
+
finally {
|
|
837
|
+
await rm(listDir, { recursive: true, force: true });
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* 单事务恢复要交给 pg_restore 的清单:目标上已经有的 schema 条目拿掉(见 restoreInOneTransaction),
|
|
842
|
+
* 两端都在备份里的外键拿掉、留到提交之后加。alsoFullyDumped(tableKey)是同一次恢复里另外整表写进去的表
|
|
843
|
+
* ——带 Auth 的恢复里的 auth.users、auth.identities:指向它们的外键也留到提交之后,源库的孤儿行建成 NOT VALID
|
|
844
|
+
*/
|
|
845
|
+
export async function prepareMainRestore(bin, dumpPath, connString, listDir, opts = {}) {
|
|
846
|
+
const listing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
847
|
+
if (listing.code !== 0) {
|
|
848
|
+
return {
|
|
849
|
+
ok: false,
|
|
850
|
+
failure: `pg_restore --list exited with code ${listing.code}: ${listing.stderr.trim().replace(/\s+/g, " ").slice(0, 200)}`,
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
const entries = listing.stdout.split("\n").filter((line) => /^\d+;/.test(line));
|
|
854
|
+
// 目录行里的名字和属主之间只隔一个空格,名字本身又可以带空格,拆不准。让 pg_restore 把这几条
|
|
855
|
+
// 写成 SQL,按顺序读 CREATE SCHEMA 后面的标识符,第 i 条语句就是第 i 行
|
|
856
|
+
const schemaEntries = entries.filter((line) => /^\d+; \d+ \d+ SCHEMA - /.test(line));
|
|
857
|
+
const skip = new Set();
|
|
858
|
+
if (schemaEntries.length) {
|
|
859
|
+
const schemaList = join(listDir, "schemas.list");
|
|
860
|
+
await writeFile(schemaList, schemaEntries.join("\n") + "\n");
|
|
861
|
+
const ddl = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${schemaList}`, dumpPath]);
|
|
862
|
+
const names = parseCreateSchemas(ddl.stdout);
|
|
863
|
+
if (ddl.code !== 0 || names.length !== schemaEntries.length) {
|
|
864
|
+
return { ok: false, failure: `could not read the schema entries in the archive (pg_restore exited with code ${ddl.code})` };
|
|
865
|
+
}
|
|
866
|
+
const client = await connectPg(connString);
|
|
824
867
|
try {
|
|
825
|
-
|
|
868
|
+
const existing = await client.query("select nspname from pg_namespace where nspname = any($1::text[])", [names]);
|
|
869
|
+
// 同一个事务里先建好的 schema(带 Auth 的恢复在事务开头装扩展,会建扩展所在的 schema)也算已存在
|
|
870
|
+
const present = new Set([...existing.rows.map((row) => row.nspname), ...(opts.schemasCreatedFirst ?? [])]);
|
|
871
|
+
schemaEntries.forEach((line, i) => {
|
|
872
|
+
if (present.has(names[i]))
|
|
873
|
+
skip.add(line);
|
|
874
|
+
});
|
|
826
875
|
}
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
return {
|
|
830
|
-
pass: {
|
|
831
|
-
expectedSkips: 0,
|
|
832
|
-
failures: [`setting grants for the Data API roles failed: ${error.message}; ${fallback}`],
|
|
833
|
-
},
|
|
834
|
-
committed: true,
|
|
835
|
-
};
|
|
876
|
+
finally {
|
|
877
|
+
await client.end();
|
|
836
878
|
}
|
|
837
|
-
|
|
838
|
-
|
|
879
|
+
}
|
|
880
|
+
const deferred = await deferredForeignKeys(bin, dumpPath, entries, listDir, opts.alsoFullyDumped);
|
|
881
|
+
const listFile = join(listDir, "restore.list");
|
|
882
|
+
await writeFile(listFile, entries.filter((line) => !skip.has(line) && !deferred.lines.has(line)).join("\n") + "\n");
|
|
883
|
+
return { ok: true, listFile, deferred };
|
|
884
|
+
}
|
|
885
|
+
/**
|
|
886
|
+
* 主事务提交之后:先补授权,再加留下来的外键。授权紧跟着主事务、放在外键前面:提交到这里之间,恢复出来的
|
|
887
|
+
* 对象用的是目标的默认授权(主事务插不进别的语句)。外键那一步更可能失败,不能让它拖住授权
|
|
888
|
+
*/
|
|
889
|
+
export async function afterCommit(connString, grantsToRestore, deferred, opts = {}) {
|
|
890
|
+
// committed 只在提交之后的步骤出错时带上(和拆分之前一样):调用方据此说明"数据已经在目标上了"
|
|
891
|
+
let grants;
|
|
892
|
+
try {
|
|
893
|
+
grants = await applyGrants(connString, grantsToRestore);
|
|
894
|
+
}
|
|
895
|
+
catch (error) {
|
|
896
|
+
const fallback = await lockDownAfterGrantFailure(connString, grantsToRestore.schemas);
|
|
897
|
+
return {
|
|
898
|
+
pass: {
|
|
899
|
+
expectedSkips: 0,
|
|
900
|
+
failures: [`setting grants for the Data API roles failed: ${error.message}; ${fallback}`],
|
|
901
|
+
},
|
|
902
|
+
committed: true,
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
await opts.onGrantsApplied?.();
|
|
906
|
+
if (!deferred.fks.length)
|
|
907
|
+
return { pass: { expectedSkips: 0, failures: [] }, grants };
|
|
908
|
+
try {
|
|
909
|
+
const client = await connectPg(connString);
|
|
839
910
|
try {
|
|
840
|
-
const
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
return { pass: { expectedSkips: 0, failures: [] }, orphaned: added.orphaned, grants };
|
|
848
|
-
}
|
|
849
|
-
finally {
|
|
850
|
-
await client.end();
|
|
851
|
-
}
|
|
911
|
+
const added = await addForeignKeys(client, deferred.fks, {
|
|
912
|
+
allow: NEVER_MATCH,
|
|
913
|
+
stopOnError: true,
|
|
914
|
+
commentSql: deferred.commentSql,
|
|
915
|
+
resume: opts.resume,
|
|
916
|
+
});
|
|
917
|
+
return { pass: { expectedSkips: 0, failures: [] }, orphaned: added.orphaned, grants };
|
|
852
918
|
}
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
pass: { expectedSkips: 0, failures: [`adding foreign keys failed: ${error.message}`] },
|
|
856
|
-
committed: true,
|
|
857
|
-
grants,
|
|
858
|
-
};
|
|
919
|
+
finally {
|
|
920
|
+
await client.end();
|
|
859
921
|
}
|
|
860
922
|
}
|
|
861
|
-
|
|
862
|
-
|
|
923
|
+
catch (error) {
|
|
924
|
+
return {
|
|
925
|
+
pass: { expectedSkips: 0, failures: [`adding foreign keys failed: ${error.message}`] },
|
|
926
|
+
committed: true,
|
|
927
|
+
grants,
|
|
928
|
+
};
|
|
863
929
|
}
|
|
864
930
|
}
|
|
931
|
+
/**
|
|
932
|
+
* restore --finish 用:提交之后要加的外键,和那次恢复算出来的一模一样(同一份 dump、同一套 deferredForeignKeys 规则)
|
|
933
|
+
*/
|
|
934
|
+
export async function deferredForeignKeysOf(dumpPath, listDir, alsoFullyDumped) {
|
|
935
|
+
const bin = resolvePgRestoreBin();
|
|
936
|
+
const listing = await pgRestoreOutput(bin, ["--list", dumpPath]);
|
|
937
|
+
if (listing.code !== 0)
|
|
938
|
+
throw new Error(`pg_restore --list exited with code ${listing.code}`);
|
|
939
|
+
const entries = listing.stdout.split("\n").filter((line) => /^\d+;/.test(line));
|
|
940
|
+
const deferred = await deferredForeignKeys(bin, dumpPath, entries, listDir, alsoFullyDumped, true);
|
|
941
|
+
return { fks: deferred.fks, commentSql: deferred.commentSql };
|
|
942
|
+
}
|
|
865
943
|
/**
|
|
866
944
|
* 单事务恢复只会有一条错误(--exit-on-error)。给人看的形态:主消息 + DETAIL/HINT 全文,再带上出错
|
|
867
945
|
* 语句的开头,方便认出是哪个对象。不再截成 200 字符——那样会把 "is not present in table" 这半句
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { TargetIdentity } from "./auth-restore.js";
|
|
2
|
+
export type RestorePhase =
|
|
3
|
+
/** 事务开着,COMMIT 的结果还没确认 */
|
|
4
|
+
"transaction"
|
|
5
|
+
/** 已提交,提交之后的步骤(补授权、补外键)还没做完 */
|
|
6
|
+
| "committed"
|
|
7
|
+
/** 授权已补,外键还没加完 */
|
|
8
|
+
| "grants"
|
|
9
|
+
/** 全部做完 */
|
|
10
|
+
| "done"
|
|
11
|
+
/** 事务回滚了,目标上什么都没留下 */
|
|
12
|
+
| "rolled_back";
|
|
13
|
+
export interface RestoreRecord {
|
|
14
|
+
version: 1;
|
|
15
|
+
snapshot: string;
|
|
16
|
+
projectName: string;
|
|
17
|
+
/**
|
|
18
|
+
* 那份快照的 dump 的 sha256:--finish 只接着做同一份快照。快照名只是时间戳,
|
|
19
|
+
* 别的项目、别的桶里可能有同名的快照,拿它补授权会改错目标上的权限
|
|
20
|
+
*/
|
|
21
|
+
dumpSha256: string;
|
|
22
|
+
/**
|
|
23
|
+
* 整份 manifest.json 的 sha256:--finish 补的授权、要的 schema 都来自 manifest,dump 没变而 manifest 被改过
|
|
24
|
+
* 也不能接着做
|
|
25
|
+
*/
|
|
26
|
+
manifestSha256?: string;
|
|
27
|
+
/** 给人看的目标说明(ref 或 主机/库名),不含密码 */
|
|
28
|
+
target: string;
|
|
29
|
+
identity: TargetIdentity;
|
|
30
|
+
xid: string;
|
|
31
|
+
phase: RestorePhase;
|
|
32
|
+
startedAt: string;
|
|
33
|
+
updatedAt: string;
|
|
34
|
+
}
|
|
35
|
+
export interface RestoreRecordStore {
|
|
36
|
+
load(key: string): Promise<RestoreRecord | null>;
|
|
37
|
+
save(key: string, record: RestoreRecord): Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* 一个目标对应一条记录。Supabase 项目按 ref 认(直连和连接池两种连接串是同一个目标),其余按主机、端口、库名、用户;
|
|
41
|
+
* 只存哈希,文件名里不出现主机名
|
|
42
|
+
*/
|
|
43
|
+
export declare function restoreRecordKey(connString: string): string;
|
|
44
|
+
/** 给人看的目标说明:ref 或 主机:端口/库名。不带用户名和密码 */
|
|
45
|
+
export declare function describeTarget(connString: string): string;
|
|
46
|
+
/** 本机文件:<目录>/<key>.json,只有当前用户可读写。先写临时文件再改名,写到一半崩溃不会留下坏文件 */
|
|
47
|
+
export declare function fileRestoreRecords(dir?: string): RestoreRecordStore;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 带 Auth 的恢复的记录(PRD 增补 §5.2 第 2、3、4 步):事务号在写 COMMIT 之前存下来,连同目标是谁、哪份快照、
|
|
3
|
+
* 做到了哪一步。协调程序崩溃、连接在提交时断掉,事后 `restore --status` 能拿它问出提交了没有;
|
|
4
|
+
* 提交之后的步骤(补授权、补外键)没做完,`restore --finish` 照它接着做。
|
|
5
|
+
*
|
|
6
|
+
* CLI 存在本机文件里(fileRestoreRecords);托管恢复由 worker 提供自己的实现,存进恢复任务记录。
|
|
7
|
+
* 记录里没有任何秘密:不存密码、不存连接串原文。
|
|
8
|
+
*/
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { projectRefOf } from "./restore-engine.js";
|
|
14
|
+
/**
|
|
15
|
+
* 一个目标对应一条记录。Supabase 项目按 ref 认(直连和连接池两种连接串是同一个目标),其余按主机、端口、库名、用户;
|
|
16
|
+
* 只存哈希,文件名里不出现主机名
|
|
17
|
+
*/
|
|
18
|
+
export function restoreRecordKey(connString) {
|
|
19
|
+
const url = new URL(connString);
|
|
20
|
+
const database = decodeURIComponent(url.pathname.replace(/^\//, "")) || "postgres";
|
|
21
|
+
const ref = projectRefOf(connString);
|
|
22
|
+
const identity = ref
|
|
23
|
+
? `supabase:${ref}/${database}`
|
|
24
|
+
: `${url.hostname.toLowerCase()}:${url.port || "5432"}/${database}?user=${decodeURIComponent(url.username)}`;
|
|
25
|
+
return createHash("sha256").update(identity).digest("hex").slice(0, 32);
|
|
26
|
+
}
|
|
27
|
+
/** 给人看的目标说明:ref 或 主机:端口/库名。不带用户名和密码 */
|
|
28
|
+
export function describeTarget(connString) {
|
|
29
|
+
const url = new URL(connString);
|
|
30
|
+
const database = decodeURIComponent(url.pathname.replace(/^\//, "")) || "postgres";
|
|
31
|
+
const ref = projectRefOf(connString);
|
|
32
|
+
return ref ? `Supabase project ${ref} (database ${database})` : `${url.hostname}:${url.port || "5432"}/${database}`;
|
|
33
|
+
}
|
|
34
|
+
/** 本机文件:<目录>/<key>.json,只有当前用户可读写。先写临时文件再改名,写到一半崩溃不会留下坏文件 */
|
|
35
|
+
export function fileRestoreRecords(dir = process.env.BACKUPDRILL_STATE_DIR || join(homedir(), ".backupdrill", "restores")) {
|
|
36
|
+
return {
|
|
37
|
+
async load(key) {
|
|
38
|
+
try {
|
|
39
|
+
const parsed = JSON.parse(await readFile(join(dir, `${key}.json`), "utf8"));
|
|
40
|
+
// manifestSha256 是后加的:没有它的记录照样能给 --status 看,--finish 会拒绝并说明
|
|
41
|
+
return parsed?.version === 1 && typeof parsed.xid === "string" && typeof parsed.dumpSha256 === "string" ? parsed : null;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error.code === "ENOENT")
|
|
45
|
+
return null;
|
|
46
|
+
throw new Error(`the restore record couldn't be read (${error.message})`);
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
async save(key, record) {
|
|
50
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
51
|
+
const file = join(dir, `${key}.json`);
|
|
52
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
53
|
+
await writeFile(temporary, JSON.stringify(record, null, 2) + "\n", { mode: 0o600 });
|
|
54
|
+
await rename(temporary, file);
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
package/dist/restore.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ 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
6
|
import { type OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
7
|
+
import { type RestorePhase, type RestoreRecordStore } from "./restore-record.js";
|
|
7
8
|
/** 归档可读性要求:pg_restore 必须 ≥ max(写入工具版本, 源服务端版本)——格式跟随写入工具。 */
|
|
8
9
|
export declare function requiredRestoreToolMajor(manifest: Manifest): number;
|
|
9
10
|
export interface RestoreResult {
|
|
@@ -24,6 +25,25 @@ export interface RestoreResult {
|
|
|
24
25
|
storageSummary?: StorageRestoreSummary;
|
|
25
26
|
storageFilesWritten: number;
|
|
26
27
|
storageDir?: string;
|
|
28
|
+
/**
|
|
29
|
+
* 快照里有 Auth 用户时才有(2.10.0 起):这次恢复有没有把它们写进目标,写了多少,恢复后要注意什么。
|
|
30
|
+
* 不含 Auth 的快照没有这一项,输出和以前一样
|
|
31
|
+
*/
|
|
32
|
+
auth?: RestoreAuthResult;
|
|
33
|
+
}
|
|
34
|
+
export interface RestoreAuthResult {
|
|
35
|
+
/** true:Auth 用户、identities 和数据库在同一个事务里写进了目标 */
|
|
36
|
+
restored: boolean;
|
|
37
|
+
/** 没写的原因(--skip-auth、读不到 auth.dump) */
|
|
38
|
+
reason?: string;
|
|
39
|
+
users?: number;
|
|
40
|
+
identities?: number;
|
|
41
|
+
/** 补建了的触发器 */
|
|
42
|
+
triggers?: string[];
|
|
43
|
+
/** 恢复后登录会受影响的用户、要手工加回的授权 */
|
|
44
|
+
notes?: string[];
|
|
45
|
+
/** 没有自动补建、要手工处理的触发器和策略 */
|
|
46
|
+
manual?: string[];
|
|
27
47
|
}
|
|
28
48
|
/**
|
|
29
49
|
* restore 无源库配置时的占位连接串(纯 flag 驱动、没有 backupdrill.config.json 的场景)。
|
|
@@ -101,4 +121,48 @@ export declare function runRestore(config: BackupConfig, opts: {
|
|
|
101
121
|
storageDir?: string;
|
|
102
122
|
/** 快照从哪读;省略 = config.storage 指的 S3 兼容桶 */
|
|
103
123
|
store?: SnapshotStore;
|
|
124
|
+
/**
|
|
125
|
+
* 不写快照里的 Auth 用户,数据库按 2.9 的方式恢复(逃生口:新路径在某个目标上出问题时照样能恢复;
|
|
126
|
+
* 也用于用户已经自己把 Auth 用户复制到目标上的情况)
|
|
127
|
+
*/
|
|
128
|
+
skipAuth?: boolean;
|
|
129
|
+
/**
|
|
130
|
+
* 带 Auth 的恢复把事务号、目标、进度记在这里(写 COMMIT 之前先记),供 restore --status / --finish 用。
|
|
131
|
+
* CLI 传本机文件(fileRestoreRecords);托管恢复传自己的实现。不传就不记
|
|
132
|
+
*/
|
|
133
|
+
restoreRecords?: RestoreRecordStore;
|
|
134
|
+
}): Promise<RestoreResult>;
|
|
135
|
+
export interface RestoreStatus {
|
|
136
|
+
/** 给人看的目标说明 */
|
|
137
|
+
target: string;
|
|
138
|
+
/** 没有记录时为 false,其余字段都没有 */
|
|
139
|
+
recorded: boolean;
|
|
140
|
+
snapshot?: string;
|
|
141
|
+
xid?: string;
|
|
142
|
+
phase?: RestorePhase;
|
|
143
|
+
/** 目标对这个事务的回答;目标不是记录里那个库、或者查不了时是 unknown */
|
|
144
|
+
transaction?: "committed" | "aborted" | "in progress" | "unknown";
|
|
145
|
+
/** 下一步该做什么,一句话 */
|
|
146
|
+
next: string;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* restore --status:只读。读这台机器上对这个目标的恢复记录,核对目标还是那个库,再用事务号问它提交了没有
|
|
150
|
+
*/
|
|
151
|
+
export declare function restoreStatus(opts: {
|
|
152
|
+
targetDatabaseUrl: string;
|
|
153
|
+
restoreRecords: RestoreRecordStore;
|
|
154
|
+
/** 连接加查询的总时限:目标不回应时到点断开,答"查不清",不一直挂着 */
|
|
155
|
+
timeoutMs?: number;
|
|
156
|
+
}): Promise<RestoreStatus>;
|
|
157
|
+
/**
|
|
158
|
+
* restore --finish:只做提交之后的步骤(补授权、补外键),和一次正常恢复用同一段代码、同一套规则(孤儿行建成
|
|
159
|
+
* NOT VALID 等)。只对记录里"已提交、后面的步骤没做完"的那次恢复做;目标不是那个库就拒绝。可以重复执行:
|
|
160
|
+
* 授权本来就是幂等的,已经加上的外键定义一样就跳过,不一样就停下报告
|
|
161
|
+
*/
|
|
162
|
+
export declare function finishRestore(config: BackupConfig, opts: {
|
|
163
|
+
targetDatabaseUrl: string;
|
|
164
|
+
confirmTarget?: string;
|
|
165
|
+
restoreRecords: RestoreRecordStore;
|
|
166
|
+
snapshot?: string;
|
|
167
|
+
store?: SnapshotStore;
|
|
104
168
|
}): Promise<RestoreResult>;
|