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 CHANGED
@@ -21,6 +21,7 @@ This CLI gets your database into a bucket **you** control, with a manifest you c
21
21
  ## Requirements
22
22
 
23
23
  - Node.js ≥ 20
24
+ - A source database on PostgreSQL 11 or newer (12 or newer for a separate `auth.dump`, see `BACKUPDRILL_AUTH` below). `backup` checks the version before it creates a snapshot.
24
25
  - `pg_dump` whose **major version ≥ your Supabase Postgres version** (Supabase runs PG 15–17). On macOS: `brew install libpq` then add it to `PATH`, or point `BACKUPDRILL_PG_DUMP` at the binary. The CLI checks this and refuses to run a mismatched dump.
25
26
 
26
27
  ## Install
@@ -76,8 +77,8 @@ All recognized variables:
76
77
  |---|---|---|
77
78
  | `BACKUPDRILL_DATABASE_URL` | Source connection string (falls back to `DATABASE_URL`) | — (required) |
78
79
  | `BACKUPDRILL_PROJECT_NAME` | Readable name used in object keys and the manifest | `supabase` |
79
- | `BACKUPDRILL_SCHEMAS` | Comma-separated schemas to dump. If the list includes `auth`, `dump.pgcustom` copies the Auth tables as-is, including any pending password-reset and confirmation tokens, and BackupDrill skips the separate `auth.dump`. When BackupDrill writes a separate `auth.dump`, it clears those tokens before upload | `public` |
80
- | `BACKUPDRILL_AUTH` | Supabase Auth users (`auth.users` + `auth.identities`) go into `auth.dump` next to the database dump whenever the role can read them. `off` leaves them out. `on` makes a backup that can't include them exit with code 3; the database backup still completes either way. Also `--auth` / `--no-auth`, or `"auth": true/false` in the config file | on when possible |
80
+ | `BACKUPDRILL_SCHEMAS` | Comma-separated `pg_dump --schema` patterns, such as `public,app_*`. See [Choosing schemas](#choosing-schemas) | `public` |
81
+ | `BACKUPDRILL_AUTH` | On PostgreSQL 12+, BackupDrill tries to write Supabase Auth users to `auth.dump` beside `dump.pgcustom` if the backup role can read every row in `auth.users` and `auth.identities`. `off` skips only `auth.dump`. `on` saves the database backup and exits with code 3 if neither archive contains both tables. Also set with `--auth`, `--no-auth` or `"auth": true/false`. See [Choosing schemas](#choosing-schemas). | on when possible |
81
82
  | `BACKUPDRILL_S3_ENDPOINT` | S3-compatible endpoint (R2/B2/self-hosted; omit for AWS S3) | — |
82
83
  | `BACKUPDRILL_S3_REGION` | Destination bucket region | `auto` |
83
84
  | `BACKUPDRILL_S3_BUCKET` | Destination bucket | — (required) |
@@ -91,6 +92,19 @@ All recognized variables:
91
92
  | `BACKUPDRILL_STATE_DIR` | Where `restore` keeps its record of restores with Auth users, for `--status` and `--finish` | `~/.backupdrill/restores` |
92
93
  | `BACKUPDRILL_PING_URL` | Healthchecks.io ping URL for `backup` and `drill` — see [Alerts with Healthchecks.io](#alerts-with-healthchecksio) | — |
93
94
 
95
+ ### Choosing schemas
96
+
97
+ `BACKUPDRILL_SCHEMAS` and `--schema` take `pg_dump --schema` patterns. Outside double quotes, ASCII letters become lowercase and `*` and `?` act as wildcards, so `app_*` matches every schema whose name starts with `app_`. To match `Sales` exactly, quote it: `export BACKUPDRILL_SCHEMAS='"Sales"'`. Leave out the database name. A name containing a comma can't go in the variable; use `--schema` or the config file's `schemas` array.
98
+
99
+ `manifest.json` lists the schemas the patterns matched, with their tables and grants. Before it creates a snapshot, BackupDrill checks that at least one schema matches and that none of them are PostgreSQL system schemas such as `pg_catalog` or `information_schema`. After the dump it matches the patterns again and fails the backup if a different set of schemas matches.
100
+
101
+ If your patterns select `auth`, BackupDrill skips `auth.dump` and lets `pg_dump` export the `auth` schema. If `dump.pgcustom` includes `auth.users`, any pending password-reset and confirmation tokens stay intact. BackupDrill also skips `auth.dump` unless every matched schema name starts with a lowercase ASCII letter or `_` and contains only lowercase ASCII letters, digits and `_`. When BackupDrill writes a separate `auth.dump`, it clears those tokens before upload.
102
+
103
+ Two known limits, until a later release checks the dump's own table list:
104
+
105
+ - If a schema name has non-ASCII characters and the client encoding isn't UTF-8, `manifest.json` can list a schema that `pg_dump` didn't dump. Run the backup with `PGCLIENTENCODING=UTF8` and leave `client_encoding` out of the connection string.
106
+ - A schema renamed and renamed back, or an Auth table dropped, while the backup runs can go unnoticed. Don't change the database structure during a backup.
107
+
94
108
  ### Config file
95
109
 
96
110
  Copy `backupdrill.config.example.json` → `backupdrill.config.json` (it's gitignored) and fill it in. Keep secrets in env vars even when using a file. To also back up Storage files, start from `backupdrill.config.with-storage.example.json` instead — only copy the `supabaseStorage` block once you actually have S3 access keys for your project's Storage.
@@ -152,7 +166,7 @@ Rough cost (Pro, Spend Cap OFF, backups = your only egress):
152
166
  | 10 GB | $0/month (within 250 GB) | ~$4.50/month |
153
167
  | 50 GB | ~$0/month | **~$112/month** ⚠ |
154
168
 
155
- Cost scales with **size × frequency**. Run `backupdrill estimate` to project it for *your* project, and prefer weekly (or a smaller scope) once your data is large. The compressed dump is smaller than raw DB size, so real DB egress is below the `estimate` upper bound; Storage egress is exact.
169
+ Cost scales with **size × frequency**. Run `backupdrill estimate` to project it for *your* project, and prefer weekly (or a smaller scope) once your data is large. The compressed dump is smaller than raw DB size, so real DB egress is below the `estimate` upper bound; for Storage, `estimate` totals the file sizes from the current listing, and the next backup's egress depends on what it actually downloads.
156
170
 
157
171
  ```bash
158
172
  backupdrill estimate --plan pro # measures your DB + Storage, prints the projection + warnings
@@ -236,25 +250,106 @@ Snapshots taken with 2.10.0 or later usually hold the Auth users as well. For th
236
250
  - **`psql` is needed.** It comes from the same PostgreSQL client package as `pg_restore`, and it must be 17.6, 16.10, 15.14, 14.19, 13.22 or newer. Those releases protect psql from commands smuggled into an archive.
237
251
  - **The target has to be a new project.** No Auth users, and no triggers or policies of its own on the Auth tables.
238
252
  - **Links and codes from before don't work.** Password-reset, email-confirmation and email or phone change links that were pending at backup time are cleared.
239
- - **Everyone signs in again**, because sessions aren't in the snapshot.
253
+ - **Sessions don't carry over**, so users sign in again. Anonymous users can't get back into their old accounts, and users whose password hashes were encrypted with the old project's key need a password reset; the Auth notes from `backupdrill restore` and in the snapshot's `RECOVERY.md` give how many of each there are.
240
254
  - **Auth settings are yours to set up again.** Sign-in providers, SMTP, redirect URLs and the site URL live in the Supabase dashboard, not in the database. Users who signed in with Google or GitHub keep that sign-in method; reconfigure the same OAuth app in the new project.
241
255
  - **MFA factors aren't backed up.** Users who had MFA sign in with one factor until they enroll again.
242
256
 
243
- If the restore is cut off while it commits, `backupdrill restore --status` (same `BACKUPDRILL_TARGET_DATABASE_URL`, same machine) says whether it committed. If it did, `backupdrill restore --finish --confirm-target <ref>` does the grants and foreign keys that come after the commit, and it can be run again safely. `--skip-auth` leaves the Auth users out and restores the database the way 2.9 did; use it if you already copied the users into the target yourself.
257
+ If the restore is cut off while it commits, run `backupdrill restore --status` on the same machine with the same `BACKUPDRILL_TARGET_DATABASE_URL`:
258
+
259
+ - `in progress`: wait and run `--status` again.
260
+ - `aborted`: the restore rolled back. Fix the cause, then run the restore again.
261
+ - `committed`: the database transaction committed. If it says the grants or foreign keys after the commit may be missing, run `backupdrill restore --finish --confirm-target <ref>` with the original snapshot settings (including `--from-dir` if you used it); it can be run again safely.
262
+ - "This target isn't the database the record was written for": if `BACKUPDRILL_TARGET_DATABASE_URL` points somewhere else, set it to the target you restored into and run `--status` again. If the database was recreated since, its contents can't tell you what happened to the old one: check that the replacement has nothing in the schemas you restore before starting a new restore there.
263
+ - `unknown`, or no record on this machine: connect to the target and check for one of the snapshot's tables that wasn't there before, and whether `auth.users` has the snapshot's users. Run the restore again only once you've confirmed it rolled back.
264
+
265
+ `--skip-auth` leaves the Auth users out and restores the database the way 2.9 did; use it if you already copied the users into the target yourself.
266
+
267
+ Or restore by hand. For a snapshot with Auth users, follow step 4 of its `RECOVERY.md`, which restores `auth.dump` and `dump.pgcustom` in one transaction. For a snapshot without them, restore the dump into an **empty** database in one transaction too, without `--clean`; a `RECOVERY.md` written by 2.13.0 or later has the same commands. Install the extensions the snapshot lists first (step 2 of its `RECOVERY.md`, or `database.extensions` in `manifest.json`): the dump uses their types. If the snapshot's schema list includes `auth`, `storage` or `realtime`, keep in mind that a new Supabase project already has those schemas, with tables of their own: if the dump creates any of those tables again, the restore rolls back there. If that happens, email support@backupdrill.com with the project name and the snapshot time.
268
+
269
+ First save Supabase's root certificate as `supabase-ca.crt` in the folder you run the restore from. The connections below use it to check the Session Pooler's certificate, as the CLI does:
270
+
271
+ ```bash
272
+ cat > supabase-ca.crt <<'PEM'
273
+ -----BEGIN CERTIFICATE-----
274
+ MIIDxDCCAqygAwIBAgIUbLxMod62P2ktCiAkxnKJwtE9VPYwDQYJKoZIhvcNAQEL
275
+ BQAwazELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB0RlbHdhcmUxEzARBgNVBAcMCk5l
276
+ dyBDYXN0bGUxFTATBgNVBAoMDFN1cGFiYXNlIEluYzEeMBwGA1UEAwwVU3VwYWJh
277
+ c2UgUm9vdCAyMDIxIENBMB4XDTIxMDQyODEwNTY1M1oXDTMxMDQyNjEwNTY1M1ow
278
+ azELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB0RlbHdhcmUxEzARBgNVBAcMCk5ldyBD
279
+ YXN0bGUxFTATBgNVBAoMDFN1cGFiYXNlIEluYzEeMBwGA1UEAwwVU3VwYWJhc2Ug
280
+ Um9vdCAyMDIxIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqQXW
281
+ QyHOB+qR2GJobCq/CBmQ40G0oDmCC3mzVnn8sv4XNeWtE5XcEL0uVih7Jo4Dkx1Q
282
+ DmGHBH1zDfgs2qXiLb6xpw/CKQPypZW1JssOTMIfQppNQ87K75Ya0p25Y3ePS2t2
283
+ GtvHxNjUV6kjOZjEn2yWEcBdpOVCUYBVFBNMB4YBHkNRDa/+S4uywAoaTWnCJLUi
284
+ cvTlHmMw6xSQQn1UfRQHk50DMCEJ7Cy1RxrZJrkXXRP3LqQL2ijJ6F4yMfh+Gyb4
285
+ O4XajoVj/+R4GwywKYrrS8PrSNtwxr5StlQO8zIQUSMiq26wM8mgELFlS/32Uclt
286
+ NaQ1xBRizkzpZct9DwIDAQABo2AwXjALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFKjX
287
+ uXY32CztkhImng4yJNUtaUYsMB8GA1UdIwQYMBaAFKjXuXY32CztkhImng4yJNUt
288
+ aUYsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAB8spzNn+4VU
289
+ tVxbdMaX+39Z50sc7uATmus16jmmHjhIHz+l/9GlJ5KqAMOx26mPZgfzG7oneL2b
290
+ VW+WgYUkTT3XEPFWnTp2RJwQao8/tYPXWEJDc0WVQHrpmnWOFKU/d3MqBgBm5y+6
291
+ jB81TU/RG2rVerPDWP+1MMcNNy0491CTL5XQZ7JfDJJ9CCmXSdtTl4uUQnSuv/Qx
292
+ Cea13BX2ZgJc7Au30vihLhub52De4P/4gonKsNHYdbWjg7OWKwNv/zitGDVDB9Y2
293
+ CMTyZKG3XEu5Ghl1LEnI3QmEKsqaCLv12BnVjbkSeZsMnevJPs1Ye6TjjJwdik5P
294
+ o/bKiIz+Fq8=
295
+ -----END CERTIFICATE-----
296
+ PEM
297
+ ```
298
+
299
+ Then write `database.list`, the archive's list without the `CREATE SCHEMA` entries for schemas the target already has (`public`, the ones you created for extensions, and the ones a new project comes with). The block uses `psql` to ask the target which schemas it has: when the terminal pauses, type the target's database password and press Enter (nothing shows while you type, and the password stays out of the URL, the command line and your shell history). Go on only if it prints `database.list is ready`; if it fails, fix the error and run it again:
300
+
301
+ ```bash
302
+ (
303
+ set -euo pipefail
304
+ work=$(mktemp -d backupdrill-restore.XXXXXX)
305
+ trap 'rm -rf "$work"' EXIT
306
+ rm -f database.list
307
+ IFS= read -rs PGPASSWORD || exit; export PGPASSWORD # hidden prompt
308
+ unset PGHOSTADDR PGOPTIONS PGSERVICE PGSERVICEFILE
309
+ export PGGSSENCMODE=disable
310
+ pg_restore -l dump.pgcustom > "$work/full.list"
311
+ schema_entry='^[0-9]+; [0-9]+ [0-9]+ SCHEMA - '
312
+ while IFS= read -r entry; do
313
+ if [[ $entry =~ $schema_entry ]]; then
314
+ printf '%s\n' "$entry" > "$work/entry.list"
315
+ create=$(pg_restore -O -L "$work/entry.list" -f - dump.pgcustom | sed -n '/^CREATE SCHEMA /,$p')
316
+ exists=$(psql -X -At -v ON_ERROR_STOP=1 -v create="$create" --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt" <<'SQL'
317
+ select exists (select 1 from pg_namespace n,
318
+ lateral (values ('CREATE SCHEMA "' || replace(n.nspname, '"', '""') || '";'),
319
+ (case when n.nspname ~ '^[a-z_][a-z0-9_]*$' then 'CREATE SCHEMA ' || n.nspname || ';' end)) c(s)
320
+ where starts_with(:'create', c.s || E'\n'));
321
+ SQL
322
+ )
323
+ if [ "$exists" = t ]; then continue; fi
324
+ fi
325
+ printf '%s\n' "$entry"
326
+ done < "$work/full.list" > "$work/database.list"
327
+ mv "$work/database.list" database.list
328
+ echo "database.list is ready"
329
+ )
330
+ ```
244
331
 
245
- Or restore by hand. For a snapshot with Auth users, follow step 4 of its `RECOVERY.md`, which restores `auth.dump` and `dump.pgcustom` in one transaction. For a snapshot without them, restore the dump into an **empty** database, without `--clean`:
332
+ Then restore. Use a `pg_restore` at least as new as the `pg_dump` that wrote the archive (`database.pgDumpVersion` in `manifest.json`). pg_restore 17 and newer write `SET transaction_timeout`, which PostgreSQL 16 and older reject, so with those the target has to run PostgreSQL 17 or newer. Type the password again when the terminal pauses, and wait for `restore committed` before you set the grants:
246
333
 
247
334
  ```bash
248
- pg_restore --no-owner --no-privileges --dbname "<target-connection-string>" dump.pgcustom
335
+ (
336
+ set -euo pipefail
337
+ IFS= read -rs PGPASSWORD || exit; export PGPASSWORD # hidden prompt
338
+ unset PGHOSTADDR PGOPTIONS PGSERVICE PGSERVICEFILE
339
+ export PGGSSENCMODE=disable
340
+ pg_restore --single-transaction --exit-on-error --no-owner --no-privileges -L database.list \
341
+ --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt" dump.pgcustom
342
+ echo "restore committed"
343
+ )
249
344
  ```
250
345
 
251
- One error is expected and harmless: `schema "public" already exists` — the target always has it. An error on a foreign key into `auth.users` means the users have to be copied in first (see [Tables that reference auth.users](#tables-that-reference-authusers)). After that, set the grants yourself (next section). Don't use `--clean` against a Supabase project: it drops and recreates the `public` schema, and with it the grants Supabase put on it. The `backupdrill restore` command above handles all of this (plus verification) for you.
346
+ An error before the commit rolls the restore back: the snapshot's tables aren't left on the target, but extensions you installed first stay, and a sequence that already existed there can keep a new value. If the connection drops during the commit, reconnect and check for one of the snapshot's tables that wasn't on the target before. Run it again only once you've confirmed the restore rolled back. If a foreign key into `auth.users` fails with `is not present in table "users"`, some restored rows point at users the target doesn't have; copy them in first, keeping their IDs (see [Tables that reference auth.users](#tables-that-reference-authusers)). If another foreign key reports a missing parent row, use the table and key values in the error to see what the restore is missing. If you need the data before you can fix that, delete that key's `FK CONSTRAINT` line from `database.list` (and its `COMMENT ... CONSTRAINT` line, if the key has a comment), run the restore again, and add the key back after fixing the reference. `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. Don't use `--clean` against a Supabase project: it drops and recreates the `public` schema, and with it the grants Supabase put on it. `backupdrill restore` runs these steps for you and checks the target before and after; it doesn't copy in Auth users the snapshot doesn't have.
252
347
 
253
348
  ### Grants for anon, authenticated and service_role
254
349
 
255
350
  supabase-js and the other client libraries reach your tables through the Data API, as `anon`, `authenticated` or `service_role`. Postgres refuses any table those roles have no grant on, with `42501 permission denied`, before row-level security even runs.
256
351
 
257
- The dump doesn't carry grants, so a restored table only gets what the target project hands out by default. Supabase used to grant every new table in `public` to all three roles. It stopped doing that for new projects on May 30, 2026, and for existing projects on October 30, 2026 ([Supabase's announcement](https://github.com/orgs/supabase/discussions/45329)). On a project that has switched, a plain `pg_restore` brings back every table and row, and the app still gets `42501` on all of them. On a project that hasn't switched yet, it does the opposite: every restored table is open to `anon`, including the ones you had closed.
352
+ The dump doesn't carry grants, so a restored table only gets what the target project hands out by default. Supabase used to grant every new table in `public` to all three roles. It stopped doing that for new projects on May 30, 2026, and for existing projects on October 30, 2026 ([Supabase's announcement](https://github.com/orgs/supabase/discussions/45329)). On a project that has switched, a plain `pg_restore` brings back every table and row, and the app still gets `42501` on all of them. If the target grants `anon` access to new `public` tables by default, restored tables inherit those grants, including tables you kept private on the source. Views use their owner's rights by default and can expose rows if the owner bypasses RLS. A `security_invoker` view uses the caller's rights.
258
353
 
259
354
  So each backup also records, in `manifest.json` under `database.grants`, what `anon`, `authenticated`, `service_role` and `PUBLIC` were granted on every table, view, sequence and function in the backed-up schemas (column-level grants and schema `USAGE` included). It reads them right before and right after the dump and keeps only the grants both reads agree on, for objects that weren't dropped and recreated in between. A grant added or removed while the dump runs is left off until the next backup. One taken away and given back during the dump looks unchanged to both reads, so it is kept. After the data is in, `restore` and `drill` take those four roles off every restored object and grant back exactly what the source had, whatever the target's defaults are, then read the grants back to check they took. Objects that belong to an extension are left alone. The report has an `API grants` line. `pg_restore` runs in its own process, so the grants can't go into its transaction: for the moment between its commit and the grants, the restored objects have the target's defaults. If setting the grants fails, `restore` tries to revoke those roles' access to the restored objects instead. If that works, your app gets `42501` until you grant what it needs; if it fails too, the error tells you to check the target's default grants before the app goes live.
260
355
 
@@ -278,18 +373,18 @@ A drill of such a snapshot can't catch this. Its sandbox has no `auth.users` at
278
373
  ✗ references outside the backup: public.profiles → auth.users (profiles_id_fkey): 200 of 200 row(s) point at auth.users rows the target doesn't have
279
374
  ```
280
375
 
281
- While that check fails, no snapshot data is written. Copy the users into the new project first, then run the restore. While the old project is still reachable, the Postgres tools can do it. Use the Session pooler string of each project, and type the passwords at hidden prompts so they stay out of your shell history:
376
+ While that check fails, no snapshot data is written. Copy the users into the new project first, then run the restore. While the old project is still reachable, the Postgres tools can do it. Use the Session pooler string of each project and save `supabase-ca.crt` as shown under the manual restore above. When the terminal pauses, type the old project's database password and press Enter, then the new project's (nothing shows while you type, and the passwords stay out of your shell history):
282
377
 
283
378
  ```bash
284
379
  read -rs OLD_PW; read -rs NEW_PW
285
- PGPASSWORD="$OLD_PW" pg_dump --data-only --table=auth.users --table=auth.identities \
286
- "postgresql://postgres.<old-ref>@<old-pooler-host>:5432/postgres" |
287
- PGPASSWORD="$NEW_PW" psql -v ON_ERROR_STOP=1 \
288
- "postgresql://postgres.<new-ref>@<new-pooler-host>:5432/postgres"
380
+ PGGSSENCMODE=disable PGPASSWORD="$OLD_PW" pg_dump --data-only --table=auth.users --table=auth.identities \
381
+ "postgresql://postgres.<old-ref>@<old-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt" |
382
+ PGGSSENCMODE=disable PGPASSWORD="$NEW_PW" psql -v ON_ERROR_STOP=1 \
383
+ "postgresql://postgres.<new-ref>@<new-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt"
289
384
  unset OLD_PW NEW_PW
290
385
  ```
291
386
 
292
- `auth.identities` holds each user's sign-in methods; users copied with it can sign in to the new project with their old password. If the old project is gone, the users can only come from a backup that includes them: a backupdrill snapshot taken with 2.10.0 or later, or Supabase's own daily backups on a paid plan.
387
+ Copy `auth.identities` with `auth.users` to keep the sign-in records, and set up the providers again in the new project. A recreated SSO provider gets a new ID, so check whether its users can still reach their original accounts. Users can keep their old passwords if the new project can read their password hashes; users whose hashes were encrypted with the old project's key need a password reset. If the old project is gone, the users can only come from a backup that includes them: a backupdrill snapshot taken with 2.10.0 or later, or Supabase's own daily backups on a paid plan.
293
388
 
294
389
  Triggers you created on `auth.users`, such as the common one that inserts a `profiles` row on sign-up, belong to that table, so a snapshot without Auth users doesn't have them either. Create them again after the restore.
295
390
 
@@ -19,22 +19,13 @@ export declare const AUTH_TABLES: readonly ["users", "identities"];
19
19
  /** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
20
20
  export declare const AUTH_DUMP_MAX_BYTES: number;
21
21
  /**
22
- * schemas 配置和 Auth 备份的关系。单独的 Auth 备份只在每一项都是普通 schema 名字时才做:
23
- * 模式写法(通配、正则、"库.schema")由 PostgreSQL 自己解析,我们在这里算不准它最终选中哪些 schema,
24
- * 也就没法可靠地判断"会不会重复导出"和"恢复时目标里哪些 schema 该是空的"——干脆不做。
25
- * - "yes":明写了 auth(主 dump 里已经有),或某个模式确定匹配得到 auth(例如 "*");
26
- * - "maybe":有模式写法,而又不能确定它包含 auth;
27
- * - "no":全是普通名字,且没有 auth。
28
- */
29
- export declare function authInSchemas(schemas: string[]): "yes" | "maybe" | "no";
30
- /**
31
- * 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
32
- * 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
33
- * 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
22
+ * 小写的普通 schema 名字:按 pg_dump 的规则,不加引号的名字折成小写;只有字母数字和下划线的才返回,其余返回 null。
23
+ * 名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
24
+ * 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会。
25
+ * 2.12.1 起 manifest.database.schemas 记的是解析好的真实名字(见 schema-patterns.ts),单独的 auth.dump 只在
26
+ * 每个名字都满足 plainSchemaName(name) === name 时才做;更早的快照记的是用户写的模式,带 Auth 的那些也全是普通名字
34
27
  */
35
28
  export declare function plainSchemaName(pattern: string): string | null;
36
- /** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
37
- export declare function schemasMayIncludeAuth(schemas: string[]): boolean;
38
29
  /**
39
30
  * 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
40
31
  * Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
@@ -5,78 +5,15 @@ export const AUTH_TABLES = ["users", "identities"];
5
5
  /** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
6
6
  export const AUTH_DUMP_MAX_BYTES = 2 * 1024 * 1024 * 1024;
7
7
  /**
8
- * 把一个 pg_dump 的 --schema 模式转成正则。只解析最简单、两边规则一定一致的写法:
9
- * - 双引号外:普通字符(字母折成小写、数字、_、$)和 * 任意串、? 任意一个字符;
10
- * - 双引号内:按字面、保留大小写,"" 表示一个双引号。
11
- * 其余写法(方括号、括号、|、+、{}、^、反斜杠,以及"库.schema"的点)走的是 PostgreSQL 自己的正则,
12
- * 和 JavaScript 不完全一样(例如 [[:alpha:]] 这类字符类),一律返回 null,调用方按"可能包含"处理。
13
- */
14
- function schemaPatternRegex(pattern) {
15
- let re = "";
16
- let quoted = false;
17
- for (let i = 0; i < pattern.length; i++) {
18
- const ch = pattern[i];
19
- if (ch === '"') {
20
- if (quoted && pattern[i + 1] === '"') {
21
- re += '"';
22
- i++;
23
- }
24
- else {
25
- quoted = !quoted;
26
- }
27
- continue;
28
- }
29
- if (quoted) {
30
- re += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
31
- continue;
32
- }
33
- if (ch === "*")
34
- re += ".*";
35
- else if (ch === "?")
36
- re += ".";
37
- else if (ch === "$")
38
- re += "\\$";
39
- else if (/[A-Za-z0-9_]/.test(ch))
40
- re += ch.toLowerCase();
41
- else
42
- return null;
43
- }
44
- return new RegExp(`^(?:${re})$`);
45
- }
46
- /**
47
- * schemas 配置和 Auth 备份的关系。单独的 Auth 备份只在每一项都是普通 schema 名字时才做:
48
- * 模式写法(通配、正则、"库.schema")由 PostgreSQL 自己解析,我们在这里算不准它最终选中哪些 schema,
49
- * 也就没法可靠地判断"会不会重复导出"和"恢复时目标里哪些 schema 该是空的"——干脆不做。
50
- * - "yes":明写了 auth(主 dump 里已经有),或某个模式确定匹配得到 auth(例如 "*");
51
- * - "maybe":有模式写法,而又不能确定它包含 auth;
52
- * - "no":全是普通名字,且没有 auth。
53
- */
54
- export function authInSchemas(schemas) {
55
- let maybe = false;
56
- for (const pattern of schemas) {
57
- const plain = plainSchemaName(pattern);
58
- if (plain === "auth")
59
- return "yes";
60
- if (plain !== null)
61
- continue;
62
- if (schemaPatternRegex(pattern)?.test("auth"))
63
- return "yes";
64
- maybe = true;
65
- }
66
- return maybe ? "maybe" : "no";
67
- }
68
- /**
69
- * 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
70
- * 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
71
- * 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
8
+ * 小写的普通 schema 名字:按 pg_dump 的规则,不加引号的名字折成小写;只有字母数字和下划线的才返回,其余返回 null。
9
+ * 名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
10
+ * 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会。
11
+ * 2.12.1 起 manifest.database.schemas 记的是解析好的真实名字(见 schema-patterns.ts),单独的 auth.dump 只在
12
+ * 每个名字都满足 plainSchemaName(name) === name 时才做;更早的快照记的是用户写的模式,带 Auth 的那些也全是普通名字
72
13
  */
73
14
  export function plainSchemaName(pattern) {
74
15
  return /^[A-Za-z_][A-Za-z0-9_]*$/.test(pattern) ? pattern.toLowerCase() : null;
75
16
  }
76
- /** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
77
- export function schemasMayIncludeAuth(schemas) {
78
- return authInSchemas(schemas) !== "no";
79
- }
80
17
  /**
81
18
  * 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
82
19
  * Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
@@ -444,7 +381,7 @@ async function firstNonStockObject(client) {
444
381
  * 用户自己建在 extensions 之类里的函数不在任何一份归档里,新项目里也没有。
445
382
  */
446
383
  function schemaCovered(schema, backedUpSchemas) {
447
- // 走到这里的 schemas 都是普通名字(带模式写法的根本不做 Auth 备份,见 authInSchemas)
384
+ // 带 Auth 的快照里 schemas 都是普通名字(见 plainSchemaName)
448
385
  return backedUpSchemas.some((name) => plainSchemaName(name) === schema);
449
386
  }
450
387
  /** 触发器依赖的函数所在的全部 schema(触发函数 + WHEN 里调用的);旧记录没有 dependencySchemas 时只看触发函数 */
@@ -461,7 +461,7 @@ export async function restoreWithAuth(opts) {
461
461
  return null;
462
462
  return `pg_restore stopped while writing out ${what} (${code === null ? "killed by a signal" : `exit code ${code}`}): ${firstRestoreError(genStderr)}`;
463
463
  };
464
- // 带 Auth 的快照里 schemas 全是普通名字(备份端 authInSchemas 保证),按 pg_dump 的规则规范化后才是真正的 schema 名;
464
+ // 带 Auth 的快照里 schemas 全是普通名字(备份端 planAuth 保证),按 pg_dump 的规则规范化后才是真正的 schema 名;
465
465
  // plainSchemaName 只放行 [a-z0-9_],拼进 SQL 字面量是安全的
466
466
  const schemaNames = opts.schemas.map((name) => plainSchemaName(name)).filter((name) => name !== null);
467
467
  const schemaArray = `array[${schemaNames.map((name) => `'${name}'`).join(", ")}]::text[]`;
package/dist/backup.d.ts CHANGED
@@ -4,8 +4,18 @@ import type { Manifest } from "./manifest.js";
4
4
  import { type StorageSyncOptions } from "./storage.js";
5
5
  import { parsePgDumpMajor } from "./pgbin.js";
6
6
  export { parsePgDumpMajor };
7
- /** 主 dump 的 pg_dump 参数。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样) */
8
- export declare function mainDumpArgs(schemas: string[], snapshotId?: string): string[];
7
+ /**
8
+ * 能备份的最老服务端:PostgreSQL 11,读授权要 pg_proc.prokind(11 起才有)。再老的库以前会在备份半途报一句
9
+ * "column does not exist",现在动手之前就挡。Supabase 的项目都在 15 以上,这条只挡自建的老库
10
+ */
11
+ export declare const MIN_SERVER_VERSION_NUM = 110000;
12
+ /** 另备 Auth 用户(auth.dump)要 12:检查 auth.users 用到 pg_attribute.attgenerated(12 起才有) */
13
+ export declare const MIN_AUTH_SERVER_VERSION_NUM = 120000;
14
+ /**
15
+ * 主 dump 的 pg_dump 参数。patterns 是用户写的 --schema 模式,原样交给 pg_dump(为什么不换成解析出的名字见
16
+ * schema-patterns.ts)。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样)
17
+ */
18
+ export declare function mainDumpArgs(patterns: string[], snapshotId?: string): string[];
9
19
  /**
10
20
  * Auth 一侧的两个时限(导出供测试调短,产品里不改):
11
21
  * - waitAfterMainMs:主 dump 完成后还肯等 Auth 导出多久
package/dist/backup.js CHANGED
@@ -4,7 +4,7 @@ import { Transform } from "node:stream";
4
4
  import { promisify } from "node:util";
5
5
  import { s3SnapshotStore } from "./snapshot-store.js";
6
6
  import { MANIFEST_SCHEMA_VERSION } from "./manifest.js";
7
- import { AUTH_DUMP_MAX_BYTES, authDumpArgs, exportSharedSnapshot, inspectAuth, authInSchemas, manualAuthObjects, redactValues, } from "./auth-backup.js";
7
+ import { AUTH_DUMP_MAX_BYTES, AUTH_TABLES, authDumpArgs, exportSharedSnapshot, inspectAuth, manualAuthObjects, plainSchemaName, redactValues, } from "./auth-backup.js";
8
8
  import { scrubPendingAuthTokens } from "./auth-archive.js";
9
9
  import { syncStorage, StorageSyncError } from "./storage.js";
10
10
  import { inspectBucketAttrs } from "./storage-catalog.js";
@@ -14,6 +14,7 @@ import { TOOL_VERSION } from "./version.js";
14
14
  import { parsePgDumpMajor } from "./pgbin.js";
15
15
  import { relationBytes } from "./estimate.js";
16
16
  import { captureIdentifiedGrants, grantsHeldThroughout } from "./grants.js";
17
+ import { resolveSchemaPatterns, schemaNamesText } from "./schema-patterns.js";
17
18
  // 解析函数搬到了 pgbin(演练与恢复都要读 pg_restore 版本,放这里会成环);保留旧出口
18
19
  export { parsePgDumpMajor };
19
20
  import { dumpUrlFor, connectPg, isSupabaseHost } from "./supabase-ca.js";
@@ -23,6 +24,13 @@ function majorOf(serverVersionNum) {
23
24
  // server_version_num: 150004 → 15, 170002 → 17
24
25
  return Math.floor(serverVersionNum / 10000);
25
26
  }
27
+ /**
28
+ * 能备份的最老服务端:PostgreSQL 11,读授权要 pg_proc.prokind(11 起才有)。再老的库以前会在备份半途报一句
29
+ * "column does not exist",现在动手之前就挡。Supabase 的项目都在 15 以上,这条只挡自建的老库
30
+ */
31
+ export const MIN_SERVER_VERSION_NUM = 110000;
32
+ /** 另备 Auth 用户(auth.dump)要 12:检查 auth.users 用到 pg_attribute.attgenerated(12 起才有) */
33
+ export const MIN_AUTH_SERVER_VERSION_NUM = 120000;
26
34
  async function pgDumpVersion(bin) {
27
35
  try {
28
36
  const { stdout } = await execFileAsync(bin, ["--version"]);
@@ -41,13 +49,18 @@ async function pgDumpVersion(bin) {
41
49
  throw error;
42
50
  }
43
51
  }
44
- async function inspectDatabase(databaseUrl, schemas) {
52
+ async function inspectDatabase(databaseUrl, patterns) {
45
53
  // Supabase 主机 → 用打包的根 CA 做 verify-full(pooler 证书自签、不在系统信任库);
46
54
  // 非 Supabase(本 CLI 不限制目标)→ 保持默认,别把开源用户挡在门外
47
55
  const client = await connectPg(databaseUrl);
48
56
  try {
49
57
  const version = await client.query("show server_version");
50
58
  const versionNum = await client.query("show server_version_num");
59
+ if (Number(versionNum.rows[0].server_version_num) < MIN_SERVER_VERSION_NUM) {
60
+ throw new Error(`This database runs PostgreSQL ${version.rows[0].server_version}. BackupDrill backs up PostgreSQL 11 or newer ` +
61
+ `(12 or newer for a separate auth.dump).`);
62
+ }
63
+ const schemas = await resolveSchemaPatterns(client, patterns);
51
64
  // 只统计将被 dump 的 schema,manifest 才与转储内容一致。
52
65
  // 口径 = pg_class relkind in ('r','p','m'):普通表 + 分区父表 + 物化视图,
53
66
  // 与 pg_dump 实际转储的关系集合一致,且必须与 drill 校验端(verifyRestored)
@@ -61,6 +74,17 @@ async function inspectDatabase(databaseUrl, schemas) {
61
74
  where c.relkind in ('r', 'p', 'm')
62
75
  and n.nspname = any($1::text[])
63
76
  order by 1, 2`, [schemas]);
77
+ // 备份范围带上 auth 时,两张 Auth 表会不会进主 dump 决定这次算不算备了 Auth 用户(见 planAuth)。
78
+ // 只算普通表:分区表的行在各个分区里,分区可以建在备份范围之外的 schema,pg_dump 只按 schema 导出;
79
+ // 扩展自己的表 pg_dump 不导出,也不算。Supabase 的这两张表都是普通表
80
+ const authTablesDumped = schemas.includes("auth")
81
+ ? (await client.query(`select c.relname as name
82
+ from pg_class c
83
+ join pg_namespace n on n.oid = c.relnamespace
84
+ where n.nspname = 'auth' and c.relname = any($1::text[]) and c.relkind = 'r'
85
+ and not exists (select 1 from pg_depend d
86
+ where d.classid = 'pg_catalog.pg_class'::regclass and d.objid = c.oid and d.deptype = 'e')`, [[...AUTH_TABLES]])).rows.map((r) => r.name)
87
+ : [];
64
88
  // 非内置扩展清单(排除必装的 plpgsql):--schema 转储不含 CREATE EXTENSION,
65
89
  // 演练沙箱要靠它在恢复前把扩展类型(如 vector)装回来
66
90
  const extensions = await client.query(`select e.extname as name, e.extversion as version, n.nspname as schema
@@ -80,6 +104,8 @@ async function inspectDatabase(databaseUrl, schemas) {
80
104
  return {
81
105
  serverVersion: version.rows[0].server_version,
82
106
  serverVersionNum: Number(versionNum.rows[0].server_version_num),
107
+ schemas,
108
+ authTablesDumped,
83
109
  tables: tables.rows.map((r) => ({
84
110
  schema: r.schema,
85
111
  name: r.name,
@@ -93,6 +119,15 @@ async function inspectDatabase(databaseUrl, schemas) {
93
119
  await client.end();
94
120
  }
95
121
  }
122
+ async function readSchemaNames(databaseUrl, patterns) {
123
+ const client = await connectPg(databaseUrl);
124
+ try {
125
+ return await resolveSchemaPatterns(client, patterns);
126
+ }
127
+ finally {
128
+ await client.end();
129
+ }
130
+ }
96
131
  async function readGrants(databaseUrl, schemas) {
97
132
  const client = await connectPg(databaseUrl);
98
133
  try {
@@ -102,14 +137,17 @@ async function readGrants(databaseUrl, schemas) {
102
137
  await client.end();
103
138
  }
104
139
  }
105
- /** 主 dump 的 pg_dump 参数。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样) */
106
- export function mainDumpArgs(schemas, snapshotId) {
140
+ /**
141
+ * 主 dump 的 pg_dump 参数。patterns 是用户写的 --schema 模式,原样交给 pg_dump(为什么不换成解析出的名字见
142
+ * schema-patterns.ts)。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样)
143
+ */
144
+ export function mainDumpArgs(patterns, snapshotId) {
107
145
  return [
108
146
  "--format=custom",
109
147
  "--no-owner",
110
148
  "--no-privileges",
111
149
  ...(snapshotId ? [`--snapshot=${snapshotId}`] : []),
112
- ...schemas.map((s) => `--schema=${s}`),
150
+ ...patterns.map((s) => `--schema=${s}`),
113
151
  ];
114
152
  }
115
153
  class AuthDumpTooLarge extends Error {
@@ -277,11 +315,16 @@ const AUTH_SKIP_TEXT = {
277
315
  no_permission: "the backup role can't read every row of auth.users and auth.identities (it needs BYPASSRLS or superuser, plus read access)",
278
316
  no_auth_schema: "this database has no Supabase auth schema",
279
317
  unsupported_destination: "this backup destination can't hold the Auth archive yet",
280
- schemas_include_auth: "your schema list includes auth, so the Auth users are in the database dump",
318
+ schemas_include_auth: "the selected schemas include auth, so the Auth users are in the database dump",
319
+ // 2.12.1 之前:模式写法算不清选中哪些 schema。新快照不再记这个原因,旧快照的说法照旧
281
320
  schemas_not_plain: "your schema list uses a pattern or a quoted name, so the Auth users aren't backed up separately " +
282
321
  "(they are in the database dump only if one of those patterns matches auth)",
322
+ schema_names_not_plain: "one of the selected schema names blocks auth.dump, and the database dump excludes auth. " +
323
+ "Each name must start with a–z or _ and use only a–z, 0–9 and _",
283
324
  too_large: "the Auth archive is larger than 2 GiB",
284
325
  snapshot_unavailable: "a consistent snapshot for the Auth export couldn't be set up",
326
+ server_too_old: "the source database runs PostgreSQL 11, and a separate auth.dump requires PostgreSQL 12 or newer " +
327
+ "(BackupDrill checks auth.users with a column added in 12); the database itself is backed up",
285
328
  };
286
329
  /** 报错只留第一行、截短:pg_dump / 上传的错误不该把大段原文(更不能是行值)带进 manifest 和告警 */
287
330
  function shortReason(error) {
@@ -291,33 +334,44 @@ function shortReason(error) {
291
334
  * 决定这次要不要、能不能另外备 Auth。任何"不能"都在这里落成 skipped/failed,不抛错——
292
335
  * 主 dump 永远不因 Auth 受影响。返回 dump 时,共享快照已经导出,调用方负责释放。
293
336
  */
294
- async function planAuth(config, writer, mode) {
295
- // 2.11.1 起只有 auth.dump 抹掉待处理 token;schemas 里明写了 auth 时,主 dump 里的 Auth 表还是原样(含 token),
296
- // 每次备份提醒一句。不管 Auth 备份开没开都提醒:主 dump 的内容和它无关
297
- if (authInSchemas(config.schemas) === "yes") {
337
+ async function planAuth(writer, mode, db, databaseUrl) {
338
+ // db.schemas 是备份范围在源库上解析出来的 schema 名字,和主 dump 导出的一致(见 schema-patterns.ts)
339
+ const authDumped = db.schemas.includes("auth");
340
+ const authTablesDumped = AUTH_TABLES.every((name) => db.authTablesDumped.includes(name));
341
+ // 2.11.1 起只有 auth.dump 抹掉待处理 token;主 dump 带着 auth.users 时,里面的 token 还是原样,
342
+ // 每次备份提醒一句(只看 auth.users,token 都在这张表里)。不管 Auth 备份开没开都提醒:主 dump 的内容和它无关
343
+ if (db.authTablesDumped.includes("users")) {
298
344
  log.warn("Your schema list includes auth, so dump.pgcustom holds the Auth tables as they are, " +
299
345
  "including pending password-reset and confirmation tokens. Only auth.dump has them cleared.");
300
346
  }
301
347
  if (mode === "off")
302
348
  return { kind: "none" };
303
- // schemas 已经(可能)把 auth 带进主 dump:今天怎样以后还怎样,不另备一份。
304
- // 确定包含 → skipped(数据就在主 dump 里);说不准 → 默认模式也 skipped,显式要求时记 failed,
305
- // 不能在 Auth 用户可能哪份归档都不在的情况下报成功
306
- const inSchemas = authInSchemas(config.schemas);
307
- if (inSchemas === "yes") {
308
- return { kind: "settled", section: { status: "skipped", reason: "schemas_include_auth" } };
349
+ // 主 dump 已经带上 auth:今天怎样以后还怎样,不另备一份。两张 Auth 表都会进主 dump 才算备上了(skipped,数据在主 dump 里);
350
+ // auth 这个 schema 在、表缺了一张(不是 Supabase 的库,或表归扩展所有、pg_dump 不导出),
351
+ // 显式要求时记 failed——不能在 Auth 用户哪份归档都不在时报成功
352
+ if (authDumped) {
353
+ return {
354
+ kind: "settled",
355
+ section: authTablesDumped ? { status: "skipped", reason: "schemas_include_auth" } : authNotDone(mode, "no_auth_schema"),
356
+ };
309
357
  }
310
- if (inSchemas === "maybe") {
311
- return { kind: "settled", section: authNotDone(mode, "schemas_not_plain") };
358
+ // 单独的 auth.dump 只在每个 schema 名字都是小写普通名字时才做:名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,
359
+ // 恢复端也按这个规则读(plainSchemaName)。带大写、$ 这类字符的名字(加引号建的 schema)不给拼接出错的机会
360
+ if (!db.schemas.every((name) => plainSchemaName(name) === name)) {
361
+ return { kind: "settled", section: authNotDone(mode, "schema_names_not_plain") };
312
362
  }
313
363
  if (!writer.uploadAuthDump || !writer.authDumpKey) {
314
364
  return { kind: "settled", section: authNotDone(mode, "unsupported_destination") };
315
365
  }
366
+ // PostgreSQL 11 的库照常备数据库,只是做不了 auth.dump(见 MIN_AUTH_SERVER_VERSION_NUM)
367
+ if (db.serverVersionNum < MIN_AUTH_SERVER_VERSION_NUM) {
368
+ return { kind: "settled", section: authNotDone(mode, "server_too_old") };
369
+ }
316
370
  // 导出快照和统计都发生在主 dump 之前,必须有总时限:连接池满时新连接会一直排队,
317
371
  // 不能让数据库备份陪着等。到点就按"快照不可用"放弃,并立刻断开 Auth 的两条连接
318
372
  // (不管它们还在排队还是在跑查询),把连接让给主 dump
319
373
  const stop = new AbortController();
320
- const prepared = prepareAuthDump(config, writer, mode, stop.signal);
374
+ const prepared = prepareAuthDump(databaseUrl, writer, mode, stop.signal);
321
375
  prepared.catch(() => { });
322
376
  let deadline;
323
377
  const timedOut = new Promise((resolve) => {
@@ -331,13 +385,13 @@ async function planAuth(config, writer, mode) {
331
385
  clearTimeout(deadline);
332
386
  return plan;
333
387
  }
334
- async function prepareAuthDump(config, writer, mode, signal) {
335
- const shared = await exportSharedSnapshot(config.databaseUrl, signal);
388
+ async function prepareAuthDump(databaseUrl, writer, mode, signal) {
389
+ const shared = await exportSharedSnapshot(databaseUrl, signal);
336
390
  if (!shared)
337
391
  return { kind: "settled", section: authNotDone(mode, "snapshot_unavailable") };
338
392
  let inspection;
339
393
  try {
340
- inspection = await inspectAuth(config.databaseUrl, shared.id, signal);
394
+ inspection = await inspectAuth(databaseUrl, shared.id, signal);
341
395
  }
342
396
  catch (error) {
343
397
  await shared.release();
@@ -557,8 +611,9 @@ export async function runBackup(config, opts = {}) {
557
611
  const pgDumpBin = process.env.BACKUPDRILL_PG_DUMP || "pg_dump";
558
612
  log.step("Inspecting database…");
559
613
  const db = await inspectDatabase(config.databaseUrl, config.schemas);
614
+ // 授权、Auth 判断、manifest 用解析出来的 schema 名字;pg_dump 拿原样的模式(见 schema-patterns.ts)
560
615
  const serverMajor = majorOf(db.serverVersionNum);
561
- log.ok(`Postgres ${db.serverVersion} — schema(s) ${config.schemas.join(", ")}: ` +
616
+ log.ok(`Postgres ${db.serverVersion} — schema(s) ${schemaNamesText(db.schemas)}: ` +
562
617
  `${db.tables.length} tables, ` +
563
618
  `~${db.tables.reduce((n, t) => n + t.estimatedRows, 0).toLocaleString()} rows`);
564
619
  // pg_dump 主版本必须 ≥ 服务端,否则转储会失败或不完整(PRD §4.2)
@@ -580,11 +635,11 @@ export async function runBackup(config, opts = {}) {
580
635
  // 授权在转储前后各读一次,只记两次都有的(为什么见 grantsHeldThroughout)。
581
636
  // 哪次读不到都让备份失败,不留一份缺授权记录的快照:恢复端把"没有记录"当成 2.9.0 之前的旧快照,
582
637
  // 按 Supabase 以前的默认授权开放 public,会把源库关着的表打开
583
- const grantsBeforeDump = await readGrants(config.databaseUrl, config.schemas);
584
- // Auth 用户另备一份(2.10.0 起,见 auth-backup.ts)。库调用方没传 = 关闭,下面走的就是之前的那条路,
585
- // 参数、文件、manifest 都和之前一样。共享快照在转储前一刻才导出,尽量少占连接
638
+ const grantsBeforeDump = await readGrants(config.databaseUrl, db.schemas);
639
+ // Auth 用户另备一份(2.10.0 起,见 auth-backup.ts)。库调用方没传 = 关闭:不另导 auth.dump、pg_dump 不带 --snapshot,
640
+ // manifest 里没有 auth 段。共享快照在转储前一刻才导出,尽量少占连接
586
641
  const authMode = config.auth ?? "off";
587
- const authPlan = await planAuth(config, writer, authMode);
642
+ const authPlan = await planAuth(writer, authMode, db, config.databaseUrl);
588
643
  let auth = authPlan.kind === "settled" ? authPlan.section : undefined;
589
644
  log.step(`Dumping → ${writer.describe("dump.pgcustom")}`);
590
645
  let bytes;
@@ -604,8 +659,16 @@ export async function runBackup(config, opts = {}) {
604
659
  }
605
660
  log.ok(`Database dumped (${(bytes / 1024 / 1024).toFixed(1)} MB, sha256 ${sha256.slice(0, 12)}…)`);
606
661
  if (auth)
607
- logAuthOutcome(auth, config.schemas);
608
- const grants = grantsHeldThroughout(grantsBeforeDump, await readGrants(config.databaseUrl, config.schemas));
662
+ logAuthOutcome(auth, db.schemas);
663
+ // 转储前解析的 schema 名字要在转储后还是同一份:中间有人建、删、改名了 schema,pg_dump 按它那一刻的样子导出,
664
+ // manifest 却记着之前的名字,两边对不上。pg_dump 的快照落在这两次解析之间,两次一样就说明它看到的也一样
665
+ const schemasAfterDump = await readSchemaNames(config.databaseUrl, config.schemas);
666
+ if (schemasAfterDump.join("\u0000") !== db.schemas.join("\u0000")) {
667
+ throw new Error(`The schemas matching your patterns changed while the backup ran ` +
668
+ `(before: ${schemaNamesText(db.schemas)}; after: ${schemaNamesText(schemasAfterDump)}), ` +
669
+ `so this snapshot's manifest might not match its dump. Run the backup again.`);
670
+ }
671
+ const grants = grantsHeldThroughout(grantsBeforeDump, await readGrants(config.databaseUrl, db.schemas));
609
672
  // Storage 文件同步(源配置存在才做;否则只备数据库)。2.12.0 起 Storage 失败不拖累数据库:
610
673
  // 列不出来、读不了、写不进目标时这份快照照常完成,manifest 记 storageFailure,storage 为 null
611
674
  let storageResult = null;
@@ -669,7 +732,7 @@ export async function runBackup(config, opts = {}) {
669
732
  database: {
670
733
  serverVersion: db.serverVersion,
671
734
  pgDumpVersion: pgd.raw,
672
- schemas: config.schemas,
735
+ schemas: db.schemas,
673
736
  tableCount: db.tables.length,
674
737
  estimatedRowTotal: db.tables.reduce((n, t) => n + t.estimatedRows, 0),
675
738
  tables: db.tables,