backupdrill 2.12.0 → 2.14.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 +110 -15
- package/dist/auth-backup.d.ts +5 -14
- package/dist/auth-backup.js +6 -69
- package/dist/auth-restore.js +1 -1
- package/dist/backup.d.ts +12 -2
- package/dist/backup.js +93 -30
- package/dist/estimate.js +7 -4
- package/dist/grants.js +4 -0
- package/dist/index.js +4 -3
- package/dist/lib.d.ts +2 -2
- package/dist/lib.js +3 -2
- package/dist/manifest.d.ts +4 -2
- package/dist/manifest.js +5 -1
- package/dist/orphaned-foreign-keys.js +8 -1
- package/dist/recovery-doc.d.ts +64 -14
- package/dist/recovery-doc.js +506 -134
- package/dist/restore.js +7 -6
- package/dist/schema-patterns.d.ts +38 -0
- package/dist/schema-patterns.js +115 -0
- package/package.json +1 -1
package/dist/recovery-doc.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { recoveryGrantsSql } from "./grants.js";
|
|
2
2
|
import { plainSchemaName, restorableAuthObjects } from "./auth-backup.js";
|
|
3
3
|
import { authRestoreNotes, CLEAR_PENDING_AUTH_SQL } from "./auth-restore.js";
|
|
4
|
+
import { SUPABASE_ROOT_CA } from "./supabase-ca.js";
|
|
4
5
|
/**
|
|
5
6
|
* 原样写进 RECOVERY.md 的一段文字(例如 Auth 失败的原因,里面有从系统目录读来的约束名、索引名):放进代码段里,
|
|
6
7
|
* Markdown 不再解释里面的任何东西(链接、强调、HTML,GFM 也不会把裸网址自动变成链接)。按 CommonMark 的规则,
|
|
@@ -13,47 +14,198 @@ export function markdownCode(text) {
|
|
|
13
14
|
const fence = "`".repeat(longestRun + 1);
|
|
14
15
|
return `${fence} ${visible} ${fence}`;
|
|
15
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* 手册里列出的 schema 名字。2.12.1 起它们取自源库本身,可能带反引号、换行、Markdown 符号:
|
|
19
|
+
* 小写普通名字原样写(和以前的手册一样),其余放进行内代码,控制字符转义、反引号用更长的围栏挡住
|
|
20
|
+
*/
|
|
21
|
+
function markdownSchemaName(name) {
|
|
22
|
+
return /^[a-z_][a-z0-9_]*$/.test(name) ? name : markdownCode(name);
|
|
23
|
+
}
|
|
16
24
|
function quoteSqlIdent(name) {
|
|
17
25
|
return `"${name.replace(/"/g, '""')}"`;
|
|
18
26
|
}
|
|
19
27
|
const ereEscape = (s) => s.replace(/[.[\]{}()*+?^$|\\]/g, "\\$&");
|
|
28
|
+
/**
|
|
29
|
+
* 手动恢复连到目标的连接串:和引擎校验 Supabase 连接一样做 verify-full,根证书见 SAVE_CA_STEP。
|
|
30
|
+
* 连目标的命令都在子 shell 里先 export PGGSSENCMODE=disable(和 CLI 一样不走 GSSAPI 加密绕开 TLS);
|
|
31
|
+
* 用环境变量而不写进连接串:12 之前的 libpq 不认 gssencmode 参数,会直接拒绝连接串
|
|
32
|
+
*/
|
|
33
|
+
const TARGET_URL_TEMPLATE = "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt";
|
|
34
|
+
/**
|
|
35
|
+
* 第 4 步开头:先存 Supabase 根证书(引擎校验源库用的同一张,所有 Supabase 项目共用),后面每个连目标的块都用它。
|
|
36
|
+
* 放在第 4 步而不是第 1 步:authRecoveryText 的恢复步骤会被托管 worker 单独拿去拼 Drive 手册,证书得跟着命令走
|
|
37
|
+
*/
|
|
38
|
+
const SAVE_CA_STEP = ` Save Supabase's root certificate as \`supabase-ca.crt\` in the folder you run
|
|
39
|
+
the restore from. The connections below use it to check the Session Pooler's
|
|
40
|
+
certificate, as the BackupDrill CLI does:
|
|
41
|
+
|
|
42
|
+
\`\`\`bash
|
|
43
|
+
cat > supabase-ca.crt <<'PEM'
|
|
44
|
+
${SUPABASE_ROOT_CA.trim()}
|
|
45
|
+
PEM
|
|
46
|
+
\`\`\`
|
|
47
|
+
`;
|
|
48
|
+
/** 子 shell 里读目标库密码:隐藏输入,不进连接串、命令行和 shell 历史;子 shell 结束密码就没了 */
|
|
49
|
+
const READ_TARGET_PASSWORD = [
|
|
50
|
+
"IFS= read -rs PGPASSWORD || exit; export PGPASSWORD # hidden prompt",
|
|
51
|
+
// 和 CLI 一样:这些环境变量能把连接改到别的地址或项目(PGOPTIONS 里的 reference 会被 Supavisor 拿去路由)
|
|
52
|
+
"unset PGHOSTADDR PGOPTIONS PGSERVICE PGSERVICEFILE",
|
|
53
|
+
"export PGGSSENCMODE=disable",
|
|
54
|
+
];
|
|
55
|
+
/** 备份范围选了 auth、又没有单独 auth.dump 的快照:三种来源的开头都用这一句,只在这里改 */
|
|
56
|
+
const AUTH_IN_DUMP_OPENER = `This snapshot was set to include the
|
|
57
|
+
\`auth\` schema, which a new Supabase project already has: read the note at the
|
|
58
|
+
start of step 4 before restoring its database.`;
|
|
59
|
+
/** 新 Supabase 项目自带、而且里面已经有表的 schema:转储里带着它们的表,单事务恢复一定在建表时失败 */
|
|
60
|
+
const SUPABASE_SCHEMAS_WITH_TABLES = ["auth", "storage", "realtime"];
|
|
61
|
+
/**
|
|
62
|
+
* 生成 database.list 的几行 shell(放在 set -euo pipefail 的子 shell 里):主 dump 的目录里拿掉目标上已经有的
|
|
63
|
+
* schema 的 CREATE SCHEMA 条目——public、第 2 步为装扩展建好的,以及新项目自带的(比如 graphql)。和 CLI 的
|
|
64
|
+
* 单事务恢复(restore-engine prepareMainRestore)同一个做法:问目标库有哪些 schema,这些条目一执行就报"已存在",
|
|
65
|
+
* 单事务里一条错误就整体回滚。
|
|
66
|
+
* 目录行 "<id>; <oid> <oid> SCHEMA - <名字> <属主>" 里名字和属主都原样、都可能带空格,换行还被换成了空格,拆不准。
|
|
67
|
+
* 所以让 pg_restore 把每条 schema 条目写成 SQL,从 "CREATE SCHEMA " 那行取到结尾,交给目标库比:目标上某个 schema
|
|
68
|
+
* 按 pg_dump 的写法(fmtId:全是小写字母、数字、下划线且不以数字开头的照写,其余加双引号)写出的语句加换行,
|
|
69
|
+
* 是这段文字的开头,就说明它已经在。名字里有换行时语句跨行,照样比得上。
|
|
70
|
+
* 中间文件都在 mktemp -d 建的目录里,退出时整个删掉;写完才改名成 database.list:中途失败就没有清单,
|
|
71
|
+
* 后面的恢复打不开清单、什么也不做;同一目录里同时跑两次也拿不到对方的文件
|
|
72
|
+
*/
|
|
73
|
+
function databaseListLines(writeDatabaseList = true) {
|
|
74
|
+
return [
|
|
75
|
+
" work=$(mktemp -d backupdrill-restore.XXXXXX)",
|
|
76
|
+
" trap 'rm -rf \"$work\"' EXIT",
|
|
77
|
+
...(writeDatabaseList ? [" rm -f database.list"] : []),
|
|
78
|
+
...READ_TARGET_PASSWORD.map((line) => ` ${line}`),
|
|
79
|
+
' pg_restore -l dump.pgcustom > "$work/full.list"',
|
|
80
|
+
" schema_entry='^[0-9]+; [0-9]+ [0-9]+ SCHEMA - '",
|
|
81
|
+
" while IFS= read -r entry; do",
|
|
82
|
+
" if [[ $entry =~ $schema_entry ]]; then",
|
|
83
|
+
" printf '%s\\n' \"$entry\" > \"$work/entry.list\"",
|
|
84
|
+
" create=$(pg_restore -O -L \"$work/entry.list\" -f - dump.pgcustom | sed -n '/^CREATE SCHEMA /,$p')",
|
|
85
|
+
` exists=$(psql -X -At -v ON_ERROR_STOP=1 -v create="$create" --dbname "${TARGET_URL_TEMPLATE}" <<'SQL'`,
|
|
86
|
+
"select exists (select 1 from pg_namespace n,",
|
|
87
|
+
" lateral (values ('CREATE SCHEMA \"' || replace(n.nspname, '\"', '\"\"') || '\";'),",
|
|
88
|
+
" (case when n.nspname ~ '^[a-z_][a-z0-9_]*$' then 'CREATE SCHEMA ' || n.nspname || ';' end)) c(s)",
|
|
89
|
+
" where starts_with(:'create', c.s || E'\\n'));",
|
|
90
|
+
"SQL",
|
|
91
|
+
" )",
|
|
92
|
+
' if [ "$exists" = t ]; then continue; fi',
|
|
93
|
+
" fi",
|
|
94
|
+
" printf '%s\\n' \"$entry\"",
|
|
95
|
+
' done < "$work/full.list" > "$work/database.list"',
|
|
96
|
+
...(writeDatabaseList ? [' mv "$work/database.list" database.list'] : []),
|
|
97
|
+
];
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* 转储里带着新项目自带、已经有表的 schema(auth、storage、realtime)时,单事务恢复一定在建这些表时回滚。
|
|
101
|
+
* 如实写出来,不让读者照做到失败才知道
|
|
102
|
+
*/
|
|
103
|
+
function supabaseSchemaConflict(manifest) {
|
|
104
|
+
// auth 和开头用同一个判断(包括老 manifest 里 au* 这类模式加 schemas_include_auth 的情况)
|
|
105
|
+
const conflicting = SUPABASE_SCHEMAS_WITH_TABLES.filter((name) => name === "auth" ? authMaybeInMainDump(manifest) : schemaSelected(manifest, name));
|
|
106
|
+
if (!conflicting.length)
|
|
107
|
+
return "";
|
|
108
|
+
const quoted = conflicting.map((name) => `\`${name}\``);
|
|
109
|
+
const names = quoted.length === 1 ? quoted[0] : `${quoted.slice(0, -1).join(", ")} and ${quoted[quoted.length - 1]}`;
|
|
110
|
+
return ` This snapshot's schema list includes ${names}. A new Supabase project already
|
|
111
|
+
has ${conflicting.length === 1 ? "that schema" : "those schemas"}, with tables of its own: if the dump creates any of those
|
|
112
|
+
tables again, the restore rolls back there. If that happens, email
|
|
113
|
+
support@backupdrill.com with the project name and the snapshot time.
|
|
114
|
+
|
|
115
|
+
`;
|
|
116
|
+
}
|
|
20
117
|
const AUTH_NOT_INCLUDED_TEXT = {
|
|
21
118
|
no_permission: "the backup role couldn't read every row of the Auth tables",
|
|
22
119
|
no_auth_schema: "the source database has no Supabase auth schema",
|
|
23
120
|
unsupported_destination: "this destination couldn't hold the Auth archive",
|
|
24
|
-
|
|
121
|
+
// 2.12.1 之前的快照:用了模式写法,算不清选中了哪些 schema
|
|
25
122
|
schemas_not_plain: "the schema list used a pattern or a quoted name; the Auth users are in the database dump only if one of those patterns matched auth",
|
|
123
|
+
schema_names_not_plain: "one of the selected schema names blocks `auth.dump`. Each name must start with `a`–`z` or `_` and use only `a`–`z`, `0`–`9` and `_`. The database dump excludes `auth`",
|
|
26
124
|
too_large: "the Auth archive was larger than 2 GiB",
|
|
27
125
|
snapshot_unavailable: "a consistent snapshot for the Auth export couldn't be set up",
|
|
126
|
+
server_too_old: "the source database runs PostgreSQL 11, and a separate `auth.dump` requires PostgreSQL 12 or newer",
|
|
28
127
|
};
|
|
29
128
|
/** POSIX 安全的 shell 值引用:项目名/前缀里合法的空格与元字符不得拆散或改写命令。 */
|
|
30
129
|
function shellQuote(value) {
|
|
31
130
|
return /^[A-Za-z0-9._/:@=-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
|
|
32
131
|
}
|
|
132
|
+
/** 托管下载里的"取出归档"那一句(第 3 步开头):按索引里的键找到编号文件,复制成原文件名 */
|
|
133
|
+
function downloadGetArchives(snapshot, withAuth) {
|
|
134
|
+
return withAuth
|
|
135
|
+
? `3. Get both archives out of the download: in \`backupdrill-download.json\`, the
|
|
136
|
+
entries whose \`key\` is \`${snapshot}/dump.pgcustom\` and \`${snapshot}/auth.dump\`
|
|
137
|
+
each have a \`path\` (such as \`files/000002\`). Copy those two files to
|
|
138
|
+
\`dump.pgcustom\` and \`auth.dump\`, then verify them:`
|
|
139
|
+
: `3. Get the dump out of the download: in \`backupdrill-download.json\`, the entry
|
|
140
|
+
whose \`key\` is \`${snapshot}/dump.pgcustom\` has a \`path\` (such as
|
|
141
|
+
\`files/000002\`). Copy that file to \`dump.pgcustom\`, then verify it:`;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版、托管 worker 的 Google Drive 版和托管存储版
|
|
145
|
+
* 都由 renderRunbook 生成,共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,不能各写各的。
|
|
146
|
+
* 没有 auth 字段的快照:included 为 null;contentsLine 只在备份范围选了 auth 时有一行(见 authMaybeInMainDump),否则为空
|
|
147
|
+
*/
|
|
148
|
+
/**
|
|
149
|
+
* 没有 auth.dump、备份范围却选了 auth 的快照:Auth 用户可能在主 dump 里。manifest 的表清单是转储前查的,
|
|
150
|
+
* 证明不了归档里有(表归扩展所有、分区落在范围外、转储期间被删都会让归档里没有),手册只告诉读者怎么查,不担保
|
|
151
|
+
*/
|
|
152
|
+
export function authMaybeInMainDump(manifest) {
|
|
153
|
+
if (manifest.auth?.status === "included")
|
|
154
|
+
return false;
|
|
155
|
+
return schemaSelected(manifest, "auth") || manifest.auth?.reason === "schemas_include_auth";
|
|
156
|
+
}
|
|
157
|
+
/** 2.12.1 之前的 manifest 记的是用户写的 --schema 模式,之后记的是在源库上解析出的真实名字(见 manifest.ts) */
|
|
158
|
+
function schemasArePatterns(manifest) {
|
|
159
|
+
const m = /^(\d+)\.(\d+)\.(\d+)/.exec(manifest.toolVersion);
|
|
160
|
+
if (!m)
|
|
161
|
+
return false;
|
|
162
|
+
const [major, minor, patch] = m.slice(1).map(Number);
|
|
163
|
+
return major < 2 || (major === 2 && (minor < 12 || (minor === 12 && patch < 1)));
|
|
164
|
+
}
|
|
33
165
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
* 没有 auth 字段的快照:contentsLine 为空、included 为 null,手册和 2.10.0 之前一样
|
|
166
|
+
* 备份范围里有没有选这个 schema。2.12.1 起记的是真实名字,只认完全相同(源库里可以真有一个叫 AUTH 的 schema);
|
|
167
|
+
* 更早的 manifest 记的是模式:"auth"、AUTH(不加引号会折成小写)、带双引号的 "auth" 都算
|
|
37
168
|
*/
|
|
169
|
+
function schemaSelected(manifest, name) {
|
|
170
|
+
const schemas = manifest.database.schemas;
|
|
171
|
+
if (!schemasArePatterns(manifest))
|
|
172
|
+
return schemas.includes(name);
|
|
173
|
+
return schemas.some((pattern) => pattern === name || pattern === `"${name}"` || plainSchemaName(pattern) === name);
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Storage 访问策略(storage.objects 上的策略)在不在转储里:选了 storage 就在;老 manifest 里有认不出的模式
|
|
177
|
+
* (通配、带引号的其他写法)时说不准,手册教读者自己查,不下结论
|
|
178
|
+
*/
|
|
179
|
+
function storagePolicyCoverage(manifest) {
|
|
180
|
+
if (schemaSelected(manifest, "storage"))
|
|
181
|
+
return "included";
|
|
182
|
+
const unclear = schemasArePatterns(manifest) &&
|
|
183
|
+
manifest.database.schemas.some((pattern) => plainSchemaName(pattern) === null && !/^"[^"]+"$/.test(pattern));
|
|
184
|
+
return unclear ? "unknown" : "missing";
|
|
185
|
+
}
|
|
38
186
|
export function authRecoveryText(manifest, place) {
|
|
39
187
|
const db = manifest.database;
|
|
40
188
|
const mb = (bytes) => (bytes / 1024 / 1024).toFixed(1);
|
|
41
189
|
// 只有 included 的快照带 auth.dump
|
|
42
190
|
const auth = manifest.auth?.status === "included" ? manifest.auth : null;
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
191
|
+
const authListing = place.kind === "bucket"
|
|
192
|
+
? `\`${auth?.dump?.key ?? "auth.dump"}\``
|
|
193
|
+
: place.kind === "download"
|
|
194
|
+
? `\`${place.snapshot}/auth.dump\``
|
|
195
|
+
: "`auth.dump` in this folder";
|
|
47
196
|
const authLine = auth
|
|
48
197
|
? `- **Supabase Auth users**: ${authListing}
|
|
49
198
|
(pg_dump custom format, ${mb(auth.dump.bytes)} MB, sha256 \`${auth.dump.sha256}\`) — ${auth.rows.users.toLocaleString("en-US")} users, ${auth.rows.identities.toLocaleString("en-US")} sign-in identities
|
|
50
199
|
`
|
|
51
|
-
: manifest
|
|
52
|
-
? `- **Supabase Auth users**:
|
|
200
|
+
: authMaybeInMainDump(manifest)
|
|
201
|
+
? `- **Supabase Auth users**: this snapshot has no separate \`auth.dump\`. The schema list selected \`auth\`, so the database dump may hold them. To check, run \`pg_restore --list dump.pgcustom\` and look for \`TABLE DATA\` entries for \`auth.users\` and \`auth.identities\`.
|
|
53
202
|
`
|
|
54
|
-
:
|
|
203
|
+
: manifest.auth
|
|
204
|
+
? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? markdownCode(manifest.auth.reason ?? "not captured")})
|
|
205
|
+
`
|
|
206
|
+
: "";
|
|
55
207
|
// 空目标检查用的 schema 列表(SQL 字符串字面量,单引号按 SQL 规则加倍)
|
|
56
|
-
// 含 Auth 的快照里 schemas 全是普通名字(
|
|
208
|
+
// 含 Auth 的快照里 schemas 全是普通名字(备份端 planAuth 保证),按 pg_dump 的规则规范化后逐个比较
|
|
57
209
|
// plainSchemaName 只放行 [a-z0-9_],拼进 SQL 字面量是安全的;万一出现别的(不该发生),整项不放进去
|
|
58
210
|
const schemaListSql = db.schemas
|
|
59
211
|
.map((name) => plainSchemaName(name))
|
|
@@ -76,34 +228,51 @@ export function authRecoveryText(manifest, place) {
|
|
|
76
228
|
: [];
|
|
77
229
|
if (!auth)
|
|
78
230
|
return { contentsLine: authLine, included: null };
|
|
231
|
+
const storagePolicies = storagePolicyCoverage(manifest) === "missing" ? "Storage access policies, " : "";
|
|
79
232
|
const notCovered = `Supabase **Auth sessions and MFA factors, Auth settings (sign-in providers,
|
|
80
|
-
SMTP, redirect URLs, email templates), secret values, Edge Function
|
|
81
|
-
platform settings
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
233
|
+
SMTP, redirect URLs, email templates), ${storagePolicies}secret values, Edge Function
|
|
234
|
+
code and most platform settings aren't in this snapshot**. In the new project,
|
|
235
|
+
re-enter your secrets and redeploy your Edge Functions from your copies. Reapply
|
|
236
|
+
any other project settings your app depends on, and set up your sign-in providers,
|
|
237
|
+
SMTP, redirect URLs and email templates again.${storagePolicies ? " Recreate your policies on `storage.objects`." : ""} Sessions don't carry over, so users
|
|
238
|
+
sign in again, and users who had MFA enroll again. The Auth users themselves
|
|
239
|
+
(IDs, emails, password hashes, sign-in identities) are in this snapshot and are
|
|
240
|
+
restored in step 4 below, together with the database.
|
|
85
241
|
${authNotes.length ? `\n${authNotes.join("\n")}\n` : ""}`;
|
|
86
|
-
const
|
|
87
|
-
|
|
242
|
+
const getArchives = place.kind === "download"
|
|
243
|
+
? downloadGetArchives(place.snapshot, true)
|
|
244
|
+
: `3. Download \`${place.kind === "bucket" ? manifest.dump.key : "dump.pgcustom"}\` and \`${place.kind === "bucket" ? (auth.dump?.key ?? "auth.dump") : "auth.dump"}\` from this
|
|
245
|
+
${place.kind === "bucket" ? "bucket" : place.name}, then verify them:`;
|
|
246
|
+
const restoreSteps = `${getArchives}
|
|
88
247
|
|
|
89
248
|
\`\`\`bash
|
|
90
249
|
shasum -a 256 dump.pgcustom # must print ${manifest.dump.sha256}
|
|
91
250
|
shasum -a 256 auth.dump # must print ${auth.dump.sha256}
|
|
92
251
|
\`\`\`
|
|
93
252
|
|
|
94
|
-
4. Restore the Auth users and the database **in one transaction
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
253
|
+
4. Restore the Auth users and the database **in one transaction**.
|
|
254
|
+
${SAVE_CA_STEP}
|
|
255
|
+
Use \`pg_restore\` and \`psql\` from the same PostgreSQL client package, at least
|
|
256
|
+
as new as the version listed above and at least 17.6, 16.10, 15.14, 14.19 or
|
|
257
|
+
13.22 in their series (18 and newer are fine): older releases let an archive run
|
|
258
|
+
commands on your machine through psql. pg_restore 17 and newer write
|
|
259
|
+
\`SET transaction_timeout\`, which PostgreSQL 16 and older reject, so with those,
|
|
260
|
+
check that the target runs PostgreSQL 17 or newer.
|
|
261
|
+
|
|
262
|
+
Then turn both archives into one SQL file, \`restore.sql\`. The block asks the
|
|
263
|
+
target which schemas it already has: when the terminal pauses, type the target's
|
|
264
|
+
database password and press Enter (nothing shows while you type, and the password
|
|
265
|
+
stays out of the URL, the command line and your shell history). Go on only if the
|
|
266
|
+
last line prints \`restore.sql is complete\`:
|
|
98
267
|
|
|
99
268
|
\`\`\`bash
|
|
100
269
|
(
|
|
101
270
|
set -euo pipefail
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
${authObjects.length ? ` pg_restore -l auth.dump > auth.full.list
|
|
105
|
-
grep -E '^[0-9]+; [0-9]+ [0-9]+ (${authObjectsGrep}) ' auth.full.list > auth-objects.list
|
|
106
|
-
test "$(wc -l < auth-objects.list)" -eq ${authObjects.length}
|
|
271
|
+
rm -f restore.sql
|
|
272
|
+
${databaseListLines(false).join("\n")}
|
|
273
|
+
${authObjects.length ? ` pg_restore -l auth.dump > "$work/auth.full.list"
|
|
274
|
+
grep -E '^[0-9]+; [0-9]+ [0-9]+ (${authObjectsGrep}) ' "$work/auth.full.list" > "$work/auth-objects.list"
|
|
275
|
+
test "$(wc -l < "$work/auth-objects.list")" -eq ${authObjects.length}
|
|
107
276
|
` : ""} {
|
|
108
277
|
cat <<'SQL'
|
|
109
278
|
lock table auth.users, auth.identities in share row exclusive mode;
|
|
@@ -133,43 +302,78 @@ do $bd$ begin
|
|
|
133
302
|
end if;
|
|
134
303
|
end $bd$;
|
|
135
304
|
SQL
|
|
136
|
-
pg_restore --no-owner --no-privileges -L database.list -f - dump.pgcustom
|
|
137
|
-
${authObjects.length ? ` pg_restore --no-owner --no-privileges -L auth-objects.list -f - auth.dump
|
|
138
|
-
` : ""} } > restore.sql
|
|
305
|
+
pg_restore --no-owner --no-privileges -L "$work/database.list" -f - dump.pgcustom
|
|
306
|
+
${authObjects.length ? ` pg_restore --no-owner --no-privileges -L "$work/auth-objects.list" -f - auth.dump
|
|
307
|
+
` : ""} } > "$work/restore.sql"
|
|
308
|
+
mv "$work/restore.sql" restore.sql
|
|
139
309
|
echo "restore.sql is complete"
|
|
140
310
|
)
|
|
141
311
|
\`\`\`
|
|
142
312
|
|
|
143
|
-
Then run it against the empty target.
|
|
144
|
-
|
|
145
|
-
a PostgreSQL 17+ project (new Supabase projects are) or generate the file with a
|
|
146
|
-
pg_restore matching the target. Enter the password at a hidden prompt so it never
|
|
147
|
-
touches the URL, argv, or shell history:
|
|
313
|
+
Then run it against the empty target. Type the password again when the terminal
|
|
314
|
+
pauses, and wait for \`restore committed\` before setting the grants:
|
|
148
315
|
|
|
149
316
|
\`\`\`bash
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
317
|
+
(
|
|
318
|
+
set -euo pipefail
|
|
319
|
+
${READ_TARGET_PASSWORD.map((line) => ` ${line}`).join("\n")}
|
|
320
|
+
psql -X --single-transaction -v ON_ERROR_STOP=1 \\
|
|
321
|
+
--dbname "${TARGET_URL_TEMPLATE}" -f restore.sql
|
|
322
|
+
echo "restore committed"
|
|
323
|
+
)
|
|
154
324
|
\`\`\`
|
|
155
325
|
|
|
156
326
|
The script stops if the target already has Auth users, triggers or policies on the
|
|
157
327
|
Auth tables, or tables in the restored schemas, so it never merges into an
|
|
158
|
-
existing project.
|
|
159
|
-
\`auth.users\`
|
|
160
|
-
and codes for password resets, email confirmations and email or
|
|
161
|
-
that were pending at backup time are cleared. ${authObjects.length
|
|
162
|
-
? "
|
|
163
|
-
: "
|
|
328
|
+
existing project. It loads the Auth users first and keeps their original IDs, then
|
|
329
|
+
checks the \`auth.users\` and \`auth.identities\` row counts against this snapshot;
|
|
330
|
+
PostgreSQL can still reject a foreign key whose user isn't in the snapshot. Links and codes for password resets, email confirmations and email or
|
|
331
|
+
phone changes that were pending at backup time are cleared. ${authObjects.length
|
|
332
|
+
? "The script recreates the triggers on the Auth tables that it can; the notes under \"Not covered\" list any trigger or policy left for you to recreate."
|
|
333
|
+
: "The script recreates no triggers on the Auth tables; the notes under \"Not covered\" list any trigger or policy left for you to recreate."} An error before the commit rolls the restore back: the Auth users and the
|
|
334
|
+
snapshot's tables aren't left on the target, but the extensions from step 2 stay
|
|
335
|
+
installed, and a sequence that already existed there (such as one belonging to an
|
|
336
|
+
extension) can keep a new value. Fix the cause and run it again. If the connection
|
|
337
|
+
drops during the commit, reconnect and check for one of the snapshot's tables that
|
|
338
|
+
wasn't on the target before${auth.rows.users > 0
|
|
339
|
+
? `, or whether \`auth.users\`, empty before, now has ${auth.rows.users} rows`
|
|
340
|
+
: ""}. Run it again only once you've confirmed the restore rolled back. If a foreign
|
|
341
|
+
key reports a missing parent row, use the table and key values in the error to see
|
|
342
|
+
what the restore is missing; ${place.kind === "folder"
|
|
343
|
+
? "email support@backupdrill.com with the snapshot time and the constraint name from the error."
|
|
344
|
+
: "`backupdrill restore` can add such a key as `NOT VALID` after the commit when the snapshot has both tables and their data. That excludes keys involving partitioned tables, extension tables or generated columns, and if the CLI can't match the foreign key definitions to the archive's list, it keeps all of them in the main transaction."} Do **not** use \`--clean\` against a Supabase project: it drops and
|
|
164
345
|
recreates \`public\`, and the grants Supabase put on it go with it.
|
|
165
346
|
`;
|
|
166
347
|
return { contentsLine: authLine, included: { notCovered, restoreSteps } };
|
|
167
348
|
}
|
|
349
|
+
/** S3 兼容桶里的手册(CLI 每次备份写进快照前缀) */
|
|
168
350
|
export function renderRecoveryDoc(manifest, ctx) {
|
|
351
|
+
return renderRunbook(manifest, {
|
|
352
|
+
snapshot: ctx.snapshot,
|
|
353
|
+
projectName: ctx.projectName,
|
|
354
|
+
source: { kind: "bucket", bucket: ctx.bucket, endpoint: ctx.endpoint, region: ctx.region, prefix: ctx.prefix },
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* RECOVERY.md 全文。三种目标(自有桶、Google Drive、托管下载)共用这一份:恢复步骤、注意事项、授权 SQL
|
|
359
|
+
* 完全相同,只有"文件在哪、怎么拿到"和 CLI 命令的来源参数不同。
|
|
360
|
+
*/
|
|
361
|
+
export function renderRunbook(manifest, ctx) {
|
|
362
|
+
const source = ctx.source;
|
|
363
|
+
// 快照目录,和 CLI 读 Storage 时一样从 dump 的键反推(snapshot-store storageBaseOf),写手册不能和读取各算各的
|
|
169
364
|
const base = manifest.dump.key.replace(/\/dump\.pgcustom$/, "");
|
|
365
|
+
// 清单这类和 dump 放在一起的文件:按 dump 所在目录拼;dump 在桶根时就在桶根(Storage 路径另按上面 CLI 的算法)
|
|
366
|
+
const dumpDir = manifest.dump.key.includes("/") ? manifest.dump.key.slice(0, manifest.dump.key.lastIndexOf("/") + 1) : "";
|
|
170
367
|
const db = manifest.database;
|
|
171
368
|
const extensions = db.extensions ?? [];
|
|
172
|
-
|
|
369
|
+
// Google Drive 备份只有数据库:manifest 里即使带了 Storage 段,Drive 版也一律按没有 Storage 写,不自相矛盾
|
|
370
|
+
const storage = source.kind === "drive" ? null : manifest.storage;
|
|
371
|
+
// 授权 SQL 里有取自源库的 schema 和对象名,可能带反引号:围栏比 SQL 里最长的一串反引号还长,名字关不掉它
|
|
372
|
+
const grantsSql = recoveryGrantsSql(db);
|
|
373
|
+
let longestBacktickRun = 0;
|
|
374
|
+
for (const run of grantsSql.matchAll(/`+/g))
|
|
375
|
+
longestBacktickRun = Math.max(longestBacktickRun, run[0].length);
|
|
376
|
+
const sqlFence = "`".repeat(Math.max(3, longestBacktickRun + 1));
|
|
173
377
|
const mb = (bytes) => (bytes / 1024 / 1024).toFixed(1);
|
|
174
378
|
// 归档格式跟随 dump 工具版本(允许比服务端新):pg_restore 必须 ≥ 两者较大值,
|
|
175
379
|
// 只按服务端版本指引会让 PG17 的 pg_restore 读不了 PG18 pg_dump 写的归档。
|
|
@@ -183,70 +387,182 @@ export function renderRecoveryDoc(manifest, ctx) {
|
|
|
183
387
|
`create extension if not exists ${quoteSqlIdent(e.name)} schema ${quoteSqlIdent(e.schema)} cascade;`)
|
|
184
388
|
.join("\n")
|
|
185
389
|
: "-- (this snapshot records no extensions)";
|
|
390
|
+
// 文件在哪:清单里怎么称呼一个文件,第 3 步怎么拿到 dump
|
|
391
|
+
const fileRef = (name) => source.kind === "bucket"
|
|
392
|
+
? `\`${name === "dump.pgcustom" ? manifest.dump.key : `${dumpDir}${name}`}\``
|
|
393
|
+
: source.kind === "download"
|
|
394
|
+
? `\`${ctx.snapshot}/${name}\``
|
|
395
|
+
: `\`${name}\` in this folder`;
|
|
396
|
+
const storageLocation = source.kind === "bucket"
|
|
397
|
+
? `\`${base}/storage/<bucket>/<key>\``
|
|
398
|
+
: source.kind === "download"
|
|
399
|
+
? `\`${ctx.snapshot}/storage/<bucket>/<key>\``
|
|
400
|
+
: "`storage/<bucket>/<key>` in this folder";
|
|
401
|
+
const place = source.kind === "bucket"
|
|
402
|
+
? { kind: "bucket" }
|
|
403
|
+
: source.kind === "download"
|
|
404
|
+
? { kind: "download", snapshot: ctx.snapshot }
|
|
405
|
+
: { kind: "folder", name: "Google Drive folder" };
|
|
186
406
|
// Auth 用户(2.10.0 起):没有 auth 字段的快照,下面用到的三段都和以前一样
|
|
187
|
-
const authText = authRecoveryText(manifest,
|
|
407
|
+
const authText = authRecoveryText(manifest, place);
|
|
188
408
|
const auth = authText.included;
|
|
409
|
+
// 备份范围选了 auth:主 dump 里有整个 auth schema,新项目自带 auth schema,手动和 CLI 都恢复不了它,
|
|
410
|
+
// 备份范围选了 auth、又没有单独 auth.dump:开头换成提醒先读第 4 步,不给 CLI 那一节(CLI 的空目标检查必然拦下);手动步骤照给
|
|
411
|
+
const authInDump = authMaybeInMainDump(manifest);
|
|
412
|
+
// 不给 CLI 那一节的地方(Drive;备份范围选了 auth 的快照,CLI 的空目标检查必然拦下),正文也不拿 CLI 当退路
|
|
413
|
+
const hasCli = source.kind !== "drive" && !authMaybeInMainDump(manifest);
|
|
414
|
+
const storagePolicies = storagePolicyCoverage(manifest) === "missing" ? "Storage access policies, " : "";
|
|
189
415
|
// 2.0 形态:凭据只经环境变量(argv 对全机器可见);写入需要键入目标 ref 确认。
|
|
190
416
|
// DB-only 快照不出现 Storage 凭据与旗标——不为用不上的能力索要宽权限 key
|
|
417
|
+
const sourceArgs = source.kind === "bucket"
|
|
418
|
+
? [
|
|
419
|
+
` --snapshot ${shellQuote(ctx.snapshot)} \\`,
|
|
420
|
+
` --bucket ${shellQuote(source.bucket)} \\`,
|
|
421
|
+
...(source.endpoint ? [` --endpoint ${shellQuote(source.endpoint)} \\`] : []),
|
|
422
|
+
...(source.region ? [` --region ${shellQuote(source.region)} \\`] : []),
|
|
423
|
+
` --prefix ${shellQuote(source.prefix)} \\`,
|
|
424
|
+
` --project-name ${shellQuote(ctx.projectName)} \\`,
|
|
425
|
+
]
|
|
426
|
+
: [` --from-dir "<download folder>" \\`];
|
|
191
427
|
const cliRestoreCommand = [
|
|
192
428
|
`read -rs BACKUPDRILL_TARGET_DATABASE_URL && export BACKUPDRILL_TARGET_DATABASE_URL # hidden prompt`,
|
|
193
429
|
...(storage
|
|
194
430
|
? [`read -rs BACKUPDRILL_TARGET_SERVICE_ROLE_KEY && export BACKUPDRILL_TARGET_SERVICE_ROLE_KEY`]
|
|
195
431
|
: []),
|
|
196
432
|
`backupdrill restore \\`,
|
|
197
|
-
|
|
198
|
-
` --bucket ${shellQuote(ctx.bucket)} \\`,
|
|
199
|
-
...(ctx.endpoint ? [` --endpoint ${shellQuote(ctx.endpoint)} \\`] : []),
|
|
200
|
-
...(ctx.region ? [` --region ${shellQuote(ctx.region)} \\`] : []),
|
|
201
|
-
` --prefix ${shellQuote(ctx.prefix)} \\`,
|
|
202
|
-
` --project-name ${shellQuote(ctx.projectName)} \\`,
|
|
433
|
+
...sourceArgs,
|
|
203
434
|
` --database \\`,
|
|
204
435
|
...(storage ? [` --target-supabase-url https://<target-ref>.supabase.co \\`] : []),
|
|
205
436
|
` --confirm-target <target-ref>`,
|
|
206
437
|
].join("\n");
|
|
207
|
-
|
|
438
|
+
const cliHeading = auth ? "The BackupDrill CLI" : "Easiest path — the BackupDrill CLI";
|
|
439
|
+
const snapshotKind = storage
|
|
440
|
+
? storage.partial
|
|
441
|
+
? "This is a database snapshot with part of the Storage files (see above), not a full project image."
|
|
442
|
+
: "This is a database + Storage snapshot, not a full project image."
|
|
443
|
+
: "This is a database snapshot, not a full project image.";
|
|
444
|
+
// 没有 Auth 的快照。备份范围选了 auth 的快照另说:Auth 用户在主 dump 里,这里只列确实缺的东西
|
|
208
445
|
const notCovered = auth
|
|
209
446
|
? auth.notCovered
|
|
210
|
-
:
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
447
|
+
: authInDump
|
|
448
|
+
? `Supabase **Auth settings (sign-in providers, SMTP, redirect URLs, email templates),
|
|
449
|
+
${storagePolicies}secret values, Edge Function code and most platform settings aren't
|
|
450
|
+
in this snapshot**. In the new project, re-enter your secrets and redeploy your Edge
|
|
451
|
+
Functions from your copies. Reapply any other project settings your app depends on,
|
|
452
|
+
and set up your sign-in providers, SMTP, redirect URLs and email templates again.${storagePolicies ? " Recreate your policies on `storage.objects`." : ""}
|
|
453
|
+
`
|
|
454
|
+
: `Supabase **Auth users/sessions, ${storagePolicies}secret values, Edge Function code and
|
|
455
|
+
most platform settings aren't in this snapshot**. In the new project, re-enter your
|
|
456
|
+
secrets and redeploy your Edge Functions from your copies. Reapply your project
|
|
457
|
+
settings.${storagePolicies ? " Recreate your policies on `storage.objects`." : ""} ${snapshotKind}
|
|
458
|
+
|
|
216
459
|
If a table in this snapshot has a foreign key into \`auth.users\` (a \`profiles.id\`
|
|
217
|
-
that references it, for example), copy the Auth users into the new project
|
|
218
|
-
**before** restoring
|
|
219
|
-
|
|
220
|
-
|
|
460
|
+
that references it, for example), copy the Auth users into the new project,
|
|
461
|
+
keeping their original IDs, **before** restoring. When the restore adds such a key,
|
|
462
|
+
PostgreSQL checks the existing rows (it skips keys marked \`NOT VALID\` and, from
|
|
463
|
+
PostgreSQL 18, \`NOT ENFORCED\`): a row that points at a user the new project
|
|
464
|
+
doesn't have makes the restore stop before it commits. To see whether the dump has such keys, run
|
|
465
|
+
\`pg_restore --section=post-data -f - dump.pgcustom | grep -B1 -E 'REFERENCES "?auth"?\\."?users"?\\('\`.
|
|
466
|
+
If the old project and its users are gone for good, you can still restore the data
|
|
467
|
+
without those keys: the search shows each key's table (\`ALTER TABLE ONLY <table>\`)
|
|
468
|
+
and name (\`ADD CONSTRAINT <name>\`).
|
|
469
|
+
After the block in step 4 that writes \`database.list\`, delete the matching
|
|
470
|
+
\`FK CONSTRAINT <schema> <table> <name>\` lines from it, and the
|
|
471
|
+
\`COMMENT <schema> CONSTRAINT <name> ON <table>\` line of any key that has a comment,
|
|
472
|
+
before running the restore. Then add the keys back once the users exist, or as \`NOT VALID\` if some rows will
|
|
473
|
+
never have one. If PostgreSQL rejects \`NOT VALID\` on a partitioned table, leave
|
|
474
|
+
that key out until every row points to an existing user.${hasCli
|
|
475
|
+
? `
|
|
476
|
+
The CLI command under "${cliHeading}" below, run with \`--dry-run\` added (it needs
|
|
477
|
+
\`--database\` and the target connection string), checks those keys against the
|
|
478
|
+
new project: look for \`references outside the backup\` in its output. It reports
|
|
479
|
+
missing \`auth.users\` references for the keys PostgreSQL checks during the
|
|
480
|
+
restore, with row counts where it has them, and warns about checks it couldn't
|
|
481
|
+
complete.`
|
|
482
|
+
: ""}
|
|
221
483
|
Triggers on \`auth.users\` aren't in this snapshot either; recreate them afterwards.
|
|
222
|
-
|
|
484
|
+
`;
|
|
485
|
+
const getDump = source.kind === "download"
|
|
486
|
+
? downloadGetArchives(ctx.snapshot, false)
|
|
487
|
+
: `3. Download \`${source.kind === "bucket" ? manifest.dump.key : "dump.pgcustom"}\` from this ${source.kind === "bucket" ? "bucket" : "Google Drive folder"}, then verify it:`;
|
|
223
488
|
const restoreSteps = auth
|
|
224
489
|
? auth.restoreSteps
|
|
225
|
-
:
|
|
490
|
+
: `${getDump}
|
|
226
491
|
|
|
227
492
|
\`\`\`bash
|
|
228
493
|
shasum -a 256 dump.pgcustom # must print ${manifest.dump.sha256}
|
|
229
494
|
\`\`\`
|
|
230
495
|
|
|
231
|
-
4. Restore
|
|
232
|
-
|
|
496
|
+
4. Restore the database **in one transaction**.
|
|
497
|
+
${supabaseSchemaConflict(manifest)}${SAVE_CA_STEP}
|
|
498
|
+
Then write \`database.list\`, the archive's list without the \`CREATE SCHEMA\`
|
|
499
|
+
entries for schemas the target already has (\`public\`, the ones created for
|
|
500
|
+
extensions in step 2, and any other the new project comes with). The block uses
|
|
501
|
+
\`psql\` to ask the target which schemas it has: when the terminal pauses, type
|
|
502
|
+
the target's database password and press Enter (nothing shows while you type, and
|
|
503
|
+
the password stays out of the URL, the command line and your shell history). Go
|
|
504
|
+
on only if the last line prints \`database.list is ready\`:
|
|
233
505
|
|
|
234
506
|
\`\`\`bash
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
507
|
+
(
|
|
508
|
+
set -euo pipefail
|
|
509
|
+
${databaseListLines().join("\n")}
|
|
510
|
+
echo "database.list is ready"
|
|
511
|
+
)
|
|
239
512
|
\`\`\`
|
|
240
513
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
514
|
+
Then restore into the empty target, **without \`--clean\`**, with a \`pg_restore\`
|
|
515
|
+
at least as new as the version listed above. pg_restore 17 and newer write
|
|
516
|
+
\`SET transaction_timeout\`, which PostgreSQL 16 and older reject, so with those,
|
|
517
|
+
check that the target runs PostgreSQL 17 or newer. Type the password again when
|
|
518
|
+
the terminal pauses, and wait for \`restore committed\` before setting the grants:
|
|
519
|
+
|
|
520
|
+
\`\`\`bash
|
|
521
|
+
(
|
|
522
|
+
set -euo pipefail
|
|
523
|
+
${READ_TARGET_PASSWORD.map((line) => ` ${line}`).join("\n")}
|
|
524
|
+
pg_restore --single-transaction --exit-on-error --no-owner --no-privileges -L database.list \\
|
|
525
|
+
--dbname "${TARGET_URL_TEMPLATE}" dump.pgcustom
|
|
526
|
+
echo "restore committed"
|
|
527
|
+
)
|
|
528
|
+
\`\`\`
|
|
529
|
+
|
|
530
|
+
An error before the commit rolls the restore back: the snapshot's tables aren't
|
|
531
|
+
left on the target, but the extensions from step 2 stay installed, and a sequence
|
|
532
|
+
that already existed there (such as one belonging to an extension) can keep a new
|
|
533
|
+
value. Fix the cause and run it again. If the connection drops during the commit,
|
|
534
|
+
reconnect and check for one of the snapshot's tables that wasn't on the target
|
|
535
|
+
before. Run it again only once you've confirmed the restore rolled back.
|
|
536
|
+
If a foreign key into \`auth.users\`
|
|
537
|
+
fails with \`is not present in table "users"\`, some restored rows point at users
|
|
538
|
+
the new project doesn't have: copy those users in first, keeping their IDs (see
|
|
539
|
+
"Not covered" above). If another foreign key reports a missing parent row, use the
|
|
540
|
+
table and key values in the error to see what the restore is missing. If you need
|
|
541
|
+
the data before you can fix that, delete that key's \`FK CONSTRAINT\` line from
|
|
542
|
+
\`database.list\` (and its \`COMMENT ... CONSTRAINT\` line, if the key has a
|
|
543
|
+
comment), run the restore again, and add the key back after fixing the reference.${hasCli
|
|
544
|
+
? " `backupdrill restore` can add such a key as `NOT VALID` after the commit when the snapshot has both tables and their data. That excludes keys involving partitioned tables, extension tables or generated columns, and if the CLI can't match the foreign key definitions to the archive's list, it keeps all of them in the main transaction."
|
|
545
|
+
: ""} Do **not** use \`--clean\` against a Supabase project:
|
|
244
546
|
it drops and recreates \`public\`, and the grants Supabase put on it go with it.
|
|
245
547
|
`;
|
|
246
|
-
|
|
247
|
-
|
|
548
|
+
// 前面空一行:接在 --status 的列表后面时,不空行会被 Markdown 并进最后一条
|
|
549
|
+
const storageResume = storage
|
|
550
|
+
? `
|
|
551
|
+
|
|
552
|
+
If the Storage part is interrupted after the database restore committed, run the
|
|
553
|
+
same command again without \`--database\`, skipping the line that reads
|
|
554
|
+
\`BACKUPDRILL_TARGET_DATABASE_URL\`, to retry Storage alone. Files already in the
|
|
555
|
+
target whose size and SHA-256 match the snapshot are skipped; if one differs, the
|
|
556
|
+
CLI stops without writing anything.`
|
|
557
|
+
: "";
|
|
558
|
+
const dryRunLine = `Run the command with \`--dry-run\` first: it checks the archive and the target
|
|
559
|
+
without changing the target.`;
|
|
560
|
+
const cliSection = !hasCli
|
|
561
|
+
? ""
|
|
562
|
+
: auth
|
|
563
|
+
? `## ${cliHeading}
|
|
248
564
|
|
|
249
|
-
\`backupdrill restore\` 2.10.0 and newer does step 4 for you: the Auth users and the
|
|
565
|
+
\`backupdrill restore\` ${source.kind === "download" ? "2.12.0" : "2.10.0"} and newer does step 4 for you: the Auth users and the
|
|
250
566
|
database go in one transaction, and it checks the target before writing anything.
|
|
251
567
|
It needs \`psql\` from the same PostgreSQL client package as \`pg_restore\`.
|
|
252
568
|
|
|
@@ -255,62 +571,88 @@ npm install -g backupdrill
|
|
|
255
571
|
${cliRestoreCommand}
|
|
256
572
|
\`\`\`
|
|
257
573
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
574
|
+
${dryRunLine} (Skip the \`read\` lines to have the CLI prompt you itself; \`unset\` the
|
|
575
|
+
variables afterwards.) \`--skip-auth\` restores the database without the Auth users.
|
|
576
|
+
|
|
577
|
+
If it's interrupted while committing, run \`backupdrill restore --status\` on the same
|
|
578
|
+
machine with the same \`BACKUPDRILL_TARGET_DATABASE_URL\`:
|
|
579
|
+
|
|
580
|
+
- \`in progress\`: wait and check again;
|
|
581
|
+
- \`aborted\`: the restore rolled back; fix the cause and run it again;
|
|
582
|
+
- \`committed\`: the database transaction committed; if it says the grants or foreign keys after the commit may be missing, run
|
|
583
|
+
\`backupdrill restore${source.kind === "download" ? ' --from-dir "<download folder>"' : ""} --finish --confirm-target <target-ref>\` with the same settings${storage ? ". If Storage files are still missing, follow the Storage retry below" : ""};
|
|
584
|
+
- "This target isn't the database the record was written for": if
|
|
585
|
+
\`BACKUPDRILL_TARGET_DATABASE_URL\` points somewhere else, set it to the target you
|
|
586
|
+
restored into and run \`backupdrill restore --status\` again; if the database was
|
|
587
|
+
recreated since, its contents can't tell you what happened to the old one: check
|
|
588
|
+
that the replacement has nothing in the schemas you restore before starting a
|
|
589
|
+
new restore there;
|
|
590
|
+
- \`unknown\`, or no record on this machine: connect to the target and check for one
|
|
591
|
+
of the snapshot's tables that wasn't there before, and whether \`auth.users\` has
|
|
592
|
+
this snapshot's users; run the restore again only once you've confirmed it rolled
|
|
593
|
+
back.${storageResume}
|
|
265
594
|
|
|
266
595
|
`
|
|
267
|
-
|
|
596
|
+
: `## ${cliHeading}
|
|
268
597
|
|
|
269
598
|
\`\`\`bash
|
|
270
599
|
npm install -g backupdrill
|
|
271
600
|
${cliRestoreCommand}
|
|
272
601
|
\`\`\`
|
|
273
602
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
the extensions, restores the database in
|
|
279
|
-
engine
|
|
280
|
-
installed
|
|
281
|
-
retrying)
|
|
282
|
-
|
|
603
|
+
${dryRunLine} (Skip the \`read\` lines to have the CLI prompt you itself; \`unset\` ${storage ? "both variables" : "the variable"} afterwards.)
|
|
604
|
+
The CLI verifies the dump checksum and checks for existing objects in the schemas
|
|
605
|
+
being restored. It checks foreign keys that point outside the snapshot, such as
|
|
606
|
+
references to \`auth.users\`, and warns when it can't check one. It
|
|
607
|
+
installs the extensions, then restores the database in one transaction with the
|
|
608
|
+
engine BackupDrill's restore drills use: an SQL error before the commit rolls it back and the
|
|
609
|
+
extensions stay installed (if the connection drops while it commits, check the
|
|
610
|
+
target before retrying). After the commit it sets the grants above, adds foreign
|
|
611
|
+
keys whose rows point at a missing parent row as \`NOT VALID\` (under the conditions
|
|
612
|
+
in step 4), and checks table counts and row presence${storage ? ", then restores the Storage files" : ""}.${storageResume}
|
|
283
613
|
|
|
284
614
|
`;
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
This file was written next to the snapshot it describes
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
`
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
: "none (database-only snapshot)"}
|
|
308
|
-
${authText.contentsLine}- **Machine-readable inventory**: \`${base}/manifest.json\`
|
|
615
|
+
const intro = source.kind === "bucket"
|
|
616
|
+
? authInDump
|
|
617
|
+
? `This file was written next to the snapshot it describes. ${AUTH_IN_DUMP_OPENER}`
|
|
618
|
+
: `This file was written next to the snapshot it describes. The manual steps below use
|
|
619
|
+
standard PostgreSQL tools and the files in this bucket, and don't need the BackupDrill
|
|
620
|
+
service or website.`
|
|
621
|
+
: source.kind === "drive"
|
|
622
|
+
? `This file sits in the same Google Drive folder as the backup it describes:
|
|
623
|
+
${markdownCode(source.folderPath)}.${authInDump
|
|
624
|
+
? ` ${AUTH_IN_DUMP_OPENER}`
|
|
625
|
+
: " The manual steps below use standard PostgreSQL tools and the files in\nthis folder, and don't need the BackupDrill service or website."}`
|
|
626
|
+
: `To get this backup, open the project in BackupDrill, find this backup and select
|
|
627
|
+
**Download**, then run the download script it gives you in a terminal. The folder
|
|
628
|
+
the script creates holds \`backupdrill-download.json\` and a \`files/\` folder: every
|
|
629
|
+
file of the backup is in \`files/\` under a number (its \`path\`), and
|
|
630
|
+
\`backupdrill-download.json\` gives each one's original name (its \`key\`, such as
|
|
631
|
+
\`${ctx.snapshot}/dump.pgcustom\`).${authInDump
|
|
632
|
+
? ` ${AUTH_IN_DUMP_OPENER}`
|
|
633
|
+
: ` Once you have the download, the manual steps
|
|
634
|
+
below don't need the BackupDrill service or website.`}`;
|
|
635
|
+
const storageSection = storage
|
|
636
|
+
? `## Restore Storage files
|
|
309
637
|
|
|
310
|
-
|
|
638
|
+
${source.kind === "download"
|
|
639
|
+
? `In \`backupdrill-download.json\`, each file's original name,
|
|
640
|
+
\`${ctx.snapshot}/storage/<original-bucket>/<original-key>\`, is its \`key\`; its \`path\`
|
|
641
|
+
is where the file is in this download.`
|
|
642
|
+
: `Files live at \`${base}/storage/<original-bucket>/<original-key>\` in this
|
|
643
|
+
bucket.`} Recreate each bucket in the target project, then re-upload the files
|
|
644
|
+
${storage.buckets ? "(bucket attributes — public flag, size and MIME limits — are recorded in manifest.json under `storage.buckets`)" : "(bucket attributes were not captured for this snapshot; recreate buckets with the settings you know)"}.${storage.partial
|
|
645
|
+
? ` Only ${storage.partial.copied} of the ${storage.partial.total} files were copied into this snapshot; \`storage.partial\` in manifest.json counts the rest by reason.`
|
|
646
|
+
: ""}${storagePolicyCoverage(manifest) === "missing"
|
|
647
|
+
? " Storage access policies (the policies on `storage.objects`) aren't in this snapshot; recreate them in the new project."
|
|
648
|
+
: storagePolicyCoverage(manifest) === "unknown"
|
|
649
|
+
? " This snapshot's schema list is written as patterns, so check whether it has the Storage access policies: run `pg_restore --list dump.pgcustom` and look for `POLICY` entries on `storage.objects`, then recreate the ones that are missing."
|
|
650
|
+
: ""} Re-uploaded files don't keep their original owner (\`owner_id\`), so check that
|
|
651
|
+
policies based on the owner still give your users access.
|
|
311
652
|
|
|
312
|
-
|
|
313
|
-
|
|
653
|
+
`
|
|
654
|
+
: "";
|
|
655
|
+
const restoreDatabase = `## Restore the database (into an EMPTY project)
|
|
314
656
|
|
|
315
657
|
1. Create a **fresh** Supabase project (never restore onto the source project),
|
|
316
658
|
and use its **Session Pooler** connection string.
|
|
@@ -328,20 +670,50 @@ ${restoreSteps}
|
|
|
328
670
|
these roles (and \`PUBLIC\`) on everything the restore created, then grants back
|
|
329
671
|
what the source had at backup time (the same list is in manifest.json under
|
|
330
672
|
\`database.grants\`). A grant whose object isn't in this restore is skipped with a warning:`
|
|
331
|
-
: `This snapshot was taken before BackupDrill recorded grants.
|
|
332
|
-
|
|
333
|
-
|
|
673
|
+
: `This snapshot was taken before BackupDrill recorded grants. If you kept any
|
|
674
|
+
objects private, replace the statements below with grants that name the objects
|
|
675
|
+
and privileges each role needs. As written, they give the three roles every
|
|
676
|
+
privilege on all tables and sequences in \`public\` and \`EXECUTE\` on its
|
|
677
|
+
functions, which is what new Supabase projects used to grant by default. If the
|
|
678
|
+
Data API exposes \`public\`, these grants can let anyone with your project's anon
|
|
679
|
+
key read or change rows wherever RLS is disabled or permits the operation. Views use their
|
|
680
|
+
owner's rights by default and can show rows a caller couldn't read directly if the
|
|
681
|
+
owner bypasses RLS; a \`security_invoker\` view uses the caller's rights. Schemas
|
|
682
|
+
other than \`public\` get no grants here:`}
|
|
334
683
|
|
|
335
|
-
|
|
336
|
-
${
|
|
337
|
-
|
|
684
|
+
${sqlFence}sql
|
|
685
|
+
${grantsSql}
|
|
686
|
+
${sqlFence}
|
|
338
687
|
|
|
339
|
-
|
|
688
|
+
`;
|
|
689
|
+
return `# BackupDrill recovery runbook — ${ctx.projectName} @ ${ctx.snapshot}
|
|
340
690
|
|
|
341
|
-
|
|
342
|
-
bucket. Recreate each bucket in the target project, then re-upload the files
|
|
343
|
-
${storage?.buckets ? "(bucket attributes — public flag, size and MIME limits — are recorded in manifest.json under `storage.buckets`)" : "(bucket attributes were not captured for this snapshot; recreate buckets with the settings you know)"}.
|
|
691
|
+
${intro}
|
|
344
692
|
|
|
345
|
-
|
|
693
|
+
## What this snapshot contains
|
|
694
|
+
|
|
695
|
+
- **Database dump**: ${fileRef("dump.pgcustom")}
|
|
696
|
+
(pg_dump custom format, ${mb(manifest.dump.bytes)} MB, sha256 \`${manifest.dump.sha256}\`)
|
|
697
|
+
- schemas: ${db.schemas.map(markdownSchemaName).join(", ")} — ${db.tableCount} tables, ~${db.estimatedRowTotal.toLocaleString("en-US")} rows at backup time
|
|
698
|
+
- source PostgreSQL ${db.serverVersion}, archive written by ${db.pgDumpVersion} — restore with pg_restore ${requiredRestoreMajor} or newer (the archive format follows the dump tool, not the server)
|
|
699
|
+
${extensions.length
|
|
700
|
+
? ` - extensions required: ${extensions.map((e) => `${e.name} (schema "${e.schema}")`).join(", ")}`
|
|
701
|
+
: " - no extensions recorded"}
|
|
702
|
+
- **Storage files**: ${source.kind === "drive"
|
|
703
|
+
? "none. Google Drive backups contain the database only."
|
|
704
|
+
: storage
|
|
705
|
+
? storage.partial
|
|
706
|
+
? `copied ${storage.partial.copied} of ${storage.partial.total} files (${mb(storage.totalBytes)} MB) to ${storageLocation}. ` +
|
|
707
|
+
`See manifest.json for file checksums and \`storage.partial\` for skip counts by reason`
|
|
708
|
+
: `${storage.fileCount} files, ${mb(storage.totalBytes)} MB under ${storageLocation} — per-file sha256 in manifest.json`
|
|
709
|
+
: manifest.storageFailure
|
|
710
|
+
? `not in this snapshot — copying them failed (${markdownCode(manifest.storageFailure.reason)}); the database part is complete`
|
|
711
|
+
: "none (database-only snapshot)"}
|
|
712
|
+
${authText.contentsLine}- **Machine-readable inventory**: ${fileRef("manifest.json")}
|
|
713
|
+
|
|
714
|
+
## Not covered — plan for these separately
|
|
715
|
+
|
|
716
|
+
${notCovered}
|
|
717
|
+
${restoreDatabase}${storageSection}${authInDump ? "" : cliSection}More: https://backupdrill.com/docs/restore
|
|
346
718
|
`;
|
|
347
719
|
}
|