@rebasepro/server-postgres 0.23.0 → 0.24.1-canary.g19596ef

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.
Files changed (208) hide show
  1. package/README.md +16 -0
  2. package/dist/{BranchService-DGPL6G_C.js → BranchService-UgKa416x.js} +47 -19
  3. package/dist/BranchService-UgKa416x.js.map +1 -0
  4. package/dist/PostgresBackendDriver.d.ts +187 -13
  5. package/dist/PostgresBootstrapper.d.ts +101 -2
  6. package/dist/auth/ensure-tables.d.ts +12 -0
  7. package/dist/auth/services.d.ts +78 -14
  8. package/dist/{auth-users-columns-D2LBFrMH.js → auth-users-columns-C72EMoDJ.js} +17 -1
  9. package/dist/{auth-users-columns-D2LBFrMH.js.map → auth-users-columns-C72EMoDJ.js.map} +1 -1
  10. package/dist/backup/backup-cli.d.ts +75 -2
  11. package/dist/backup/backup-service.d.ts +2 -2
  12. package/dist/backup/pg-binary.d.ts +5 -0
  13. package/dist/{backup-cli-24v4OlSp.js → backup-cli-yiKd1GsC.js} +168 -75
  14. package/dist/backup-cli-yiKd1GsC.js.map +1 -0
  15. package/dist/{backup-service-HQ9GC4tN.js → backup-service-AZWc2wvI.js} +104 -35
  16. package/dist/backup-service-AZWc2wvI.js.map +1 -0
  17. package/dist/boot-ddl-B9ZmBJ75.js +105 -0
  18. package/dist/boot-ddl-B9ZmBJ75.js.map +1 -0
  19. package/dist/cli-console-DGee3Zl7.js +225 -0
  20. package/dist/cli-console-DGee3Zl7.js.map +1 -0
  21. package/dist/cli-console.d.ts +39 -0
  22. package/dist/cli-errors-oVUuD8k0.js +2180 -0
  23. package/dist/cli-errors-oVUuD8k0.js.map +1 -0
  24. package/dist/cli-errors.d.ts +133 -9
  25. package/dist/{cli-flags-BglvpjHv.js → cli-flags-DnPHXjRH.js} +56 -6
  26. package/dist/cli-flags-DnPHXjRH.js.map +1 -0
  27. package/dist/cli-flags.d.ts +15 -0
  28. package/dist/cli-helpers.d.ts +88 -34
  29. package/dist/cli-output.d.ts +16 -28
  30. package/dist/{arg-Dni7MzLB.js → cli-prompt-egtNKkZl.js} +49 -3
  31. package/dist/cli-prompt-egtNKkZl.js.map +1 -0
  32. package/dist/cli-prompt.d.ts +19 -0
  33. package/dist/cli-push.d.ts +87 -0
  34. package/dist/cli-scratch-database.d.ts +33 -8
  35. package/dist/cli.js +826 -230
  36. package/dist/cli.js.map +1 -1
  37. package/dist/{column-plan-helpers-DF-8dTVa.js → column-plan-helpers-D_V4oaZh.js} +43 -27
  38. package/dist/column-plan-helpers-D_V4oaZh.js.map +1 -0
  39. package/dist/{databasePoolManager-Bj5FbeAs.js → connection-C938nR3E.js} +25 -113
  40. package/dist/connection-C938nR3E.js.map +1 -0
  41. package/dist/connection.d.ts +13 -2
  42. package/dist/data-transformer.d.ts +0 -8
  43. package/dist/databasePoolManager-DZgnBOgj.js +119 -0
  44. package/dist/databasePoolManager-DZgnBOgj.js.map +1 -0
  45. package/dist/deferred-index-build-BqmEHGaD.js +1051 -0
  46. package/dist/deferred-index-build-BqmEHGaD.js.map +1 -0
  47. package/dist/{doctor-Cb2thZ8s.js → doctor-CUAAOFZm.js} +281 -89
  48. package/dist/doctor-CUAAOFZm.js.map +1 -0
  49. package/dist/ensure-collection-policies-Bb51V2OV.js +541 -0
  50. package/dist/ensure-collection-policies-Bb51V2OV.js.map +1 -0
  51. package/dist/ensure-collection-tables-egjGBjhv.js +532 -0
  52. package/dist/ensure-collection-tables-egjGBjhv.js.map +1 -0
  53. package/dist/{ensure-tables-Dhn9KM3B.js → ensure-tables-DMPWhJ6R.js} +180 -77
  54. package/dist/ensure-tables-DMPWhJ6R.js.map +1 -0
  55. package/dist/enum-labels-kept-Msq5gMcb.js +56 -0
  56. package/dist/enum-labels-kept-Msq5gMcb.js.map +1 -0
  57. package/dist/generate-drizzle-schema-DrA-YgXv.js +57 -0
  58. package/dist/generate-drizzle-schema-DrA-YgXv.js.map +1 -0
  59. package/dist/{generate-drizzle-schema-logic-BfzK7UQd.js → generate-drizzle-schema-logic-BaT0H7Gq.js} +29 -11
  60. package/dist/generate-drizzle-schema-logic-BaT0H7Gq.js.map +1 -0
  61. package/dist/generate-files-OoRJLEdk.js +199 -0
  62. package/dist/generate-files-OoRJLEdk.js.map +1 -0
  63. package/dist/generate-postgres-ddl-logic-B4k9djAV.js +152 -0
  64. package/dist/generate-postgres-ddl-logic-B4k9djAV.js.map +1 -0
  65. package/dist/{generated-schema-staleness-Di9c4ZxN.js → generated-schema-staleness-BWN_PsMi.js} +2 -2
  66. package/dist/{generated-schema-staleness-Di9c4ZxN.js.map → generated-schema-staleness-BWN_PsMi.js.map} +1 -1
  67. package/dist/generated-sql.d.ts +34 -0
  68. package/dist/history/HistoryService.d.ts +64 -5
  69. package/dist/history/ensure-history-table.d.ts +63 -4
  70. package/dist/index.d.ts +1 -0
  71. package/dist/index.es.js +139 -16738
  72. package/dist/index.es.js.map +1 -1
  73. package/dist/{introspect-db-logic-WMuAfxvw.js → introspect-db-logic-BCc1Jym2.js} +654 -353
  74. package/dist/introspect-db-logic-BCc1Jym2.js.map +1 -0
  75. package/dist/introspect-db-queries-BhhJg0b8.js +364 -0
  76. package/dist/introspect-db-queries-BhhJg0b8.js.map +1 -0
  77. package/dist/open-rebase-CAjWpPjs.js +20895 -0
  78. package/dist/open-rebase-CAjWpPjs.js.map +1 -0
  79. package/dist/open-rebase.d.ts +94 -0
  80. package/dist/pg-error-utils-Bs_Ue4wn.js +395 -0
  81. package/dist/pg-error-utils-Bs_Ue4wn.js.map +1 -0
  82. package/dist/{plan-schema-C0fxM8dY.js → plan-schema-CsNgK0qi.js} +279 -534
  83. package/dist/plan-schema-CsNgK0qi.js.map +1 -0
  84. package/dist/{policy-drift-DljYdrpW.js → policy-drift-BKC50y2p.js} +33 -9
  85. package/dist/policy-drift-BKC50y2p.js.map +1 -0
  86. package/dist/push-index-prebuild-C_qhyoJa.js +45 -0
  87. package/dist/push-index-prebuild-C_qhyoJa.js.map +1 -0
  88. package/dist/push-legacy-renames-5g9h3HOa.js +34 -0
  89. package/dist/push-legacy-renames-5g9h3HOa.js.map +1 -0
  90. package/dist/{generate-postgres-ddl-logic-Bt2d2mRH.js → render-ddl-CrfEe__B.js} +24 -157
  91. package/dist/render-ddl-CrfEe__B.js.map +1 -0
  92. package/dist/{rls-bootstrap-sql-B8EclDyM.js → rls-bootstrap-sql-Bd-hJk08.js} +125 -1101
  93. package/dist/rls-bootstrap-sql-Bd-hJk08.js.map +1 -0
  94. package/dist/{rls-enforcement-C6Xk0lA6.js → rls-enforcement-D7P4-ZYX.js} +138 -18
  95. package/dist/rls-enforcement-D7P4-ZYX.js.map +1 -0
  96. package/dist/{__vite-browser-external-BnuHet1e.js → rolldown-runtime-V7rFbMRe.js} +1 -8
  97. package/dist/schema/atlas-exclude.d.ts +42 -0
  98. package/dist/schema/auth-schema.d.ts +172 -2
  99. package/dist/schema/boot-ddl.d.ts +47 -0
  100. package/dist/schema/carved-out-migration.d.ts +5 -4
  101. package/dist/schema/classify-change.d.ts +29 -1
  102. package/dist/schema/collection-index.d.ts +45 -0
  103. package/dist/schema/column-plan-helpers.d.ts +38 -21
  104. package/dist/schema/deferred-index-build.d.ts +131 -0
  105. package/dist/schema/destructive-sql.d.ts +50 -2
  106. package/dist/schema/doctor-cli.js +110 -6
  107. package/dist/schema/doctor-cli.js.map +1 -1
  108. package/dist/schema/doctor-search-scale.d.ts +45 -0
  109. package/dist/schema/doctor.d.ts +53 -1
  110. package/dist/schema/ensure-collection-policies.d.ts +95 -35
  111. package/dist/schema/ensure-collection-tables.d.ts +56 -3
  112. package/dist/schema/enum-labels-kept.d.ts +26 -0
  113. package/dist/schema/generate-drizzle-schema.js +1 -1
  114. package/dist/schema/generate-files.d.ts +44 -0
  115. package/dist/schema/generate-next-step.d.ts +0 -13
  116. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
  117. package/dist/schema/generate-postgres-ddl.js +10 -81
  118. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  119. package/dist/schema/generate-schema-commit.d.ts +12 -0
  120. package/dist/schema/generated-schema-diff.d.ts +7 -0
  121. package/dist/schema/introspect-db-logic.d.ts +63 -0
  122. package/dist/schema/introspect-db-queries.d.ts +21 -2
  123. package/dist/schema/introspect-db-search.d.ts +22 -0
  124. package/dist/schema/introspect-db-storage.d.ts +83 -0
  125. package/dist/schema/introspect-db-structure.d.ts +10 -0
  126. package/dist/schema/introspect-db.js +29 -21
  127. package/dist/schema/introspect-db.js.map +1 -1
  128. package/dist/schema/migrate-baseline.d.ts +33 -0
  129. package/dist/schema/migration-post-process.d.ts +34 -0
  130. package/dist/schema/plan/diff-plan.d.ts +127 -1
  131. package/dist/schema/plan/plan-schema.d.ts +16 -8
  132. package/dist/schema/plan/render-ddl.d.ts +8 -1
  133. package/dist/schema/plan/types.d.ts +45 -11
  134. package/dist/schema/push-index-prebuild.d.ts +25 -0
  135. package/dist/schema/push-legacy-renames.d.ts +20 -0
  136. package/dist/schema/rls-bootstrap-sql.d.ts +15 -0
  137. package/dist/schema/undeclarable-constraints.d.ts +59 -0
  138. package/dist/search-column-BM-GV6vH.js +442 -0
  139. package/dist/search-column-BM-GV6vH.js.map +1 -0
  140. package/dist/security/policy-drift.d.ts +1 -1
  141. package/dist/security/rls-enforcement.d.ts +39 -4
  142. package/dist/services/BranchService.d.ts +29 -1
  143. package/dist/services/FetchService.d.ts +63 -12
  144. package/dist/services/PersistService.d.ts +15 -0
  145. package/dist/services/RelationService.d.ts +106 -3
  146. package/dist/services/cdc/CdcListener.d.ts +26 -10
  147. package/dist/services/cdc/identity-columns.d.ts +19 -0
  148. package/dist/services/cdc/trigger-cdc.d.ts +180 -18
  149. package/dist/services/channel-bus/PostgresChannelBus.d.ts +12 -7
  150. package/dist/services/channel-bus/index.d.ts +1 -1
  151. package/dist/services/channel-history.d.ts +32 -5
  152. package/dist/services/collection-helpers.d.ts +26 -1
  153. package/dist/services/field-viewer.d.ts +15 -1
  154. package/dist/services/pg-notify-listener.d.ts +95 -6
  155. package/dist/services/realtimeService.d.ts +467 -53
  156. package/dist/services/row-pipeline.d.ts +16 -9
  157. package/dist/services/socket-liveness.d.ts +85 -0
  158. package/dist/services/soft-delete.d.ts +12 -0
  159. package/dist/services/sql-script.d.ts +275 -0
  160. package/dist/services/vector-iterative-scan.d.ts +40 -0
  161. package/dist/services/write-depth.d.ts +22 -0
  162. package/dist/services/write-transaction-scope.d.ts +15 -3
  163. package/dist/socket-opt-ins.d.ts +64 -0
  164. package/dist/source-DB6xJv3p.js +873 -0
  165. package/dist/source-DB6xJv3p.js.map +1 -0
  166. package/dist/tsx-loader.d.ts +14 -0
  167. package/dist/utils/connection-string.d.ts +31 -0
  168. package/dist/utils/drizzle-conditions.d.ts +63 -3
  169. package/dist/utils/error-cause.d.ts +7 -0
  170. package/dist/utils/pg-error-utils.d.ts +2 -4
  171. package/dist/utils/result-rows.d.ts +10 -0
  172. package/dist/{vector-index-CMJKb3C9.js → vector-index-BFhyEaiz.js} +2 -2
  173. package/dist/{vector-index-CMJKb3C9.js.map → vector-index-BFhyEaiz.js.map} +1 -1
  174. package/dist/websocket-DUiiwQd2.js +1632 -0
  175. package/dist/websocket-DUiiwQd2.js.map +1 -0
  176. package/dist/websocket.d.ts +63 -18
  177. package/package.json +7 -7
  178. package/dist/BranchService-DGPL6G_C.js.map +0 -1
  179. package/dist/__vite-browser-external-BnuHet1e.js.map +0 -1
  180. package/dist/arg-Dni7MzLB.js.map +0 -1
  181. package/dist/backup-cli-24v4OlSp.js.map +0 -1
  182. package/dist/backup-service-HQ9GC4tN.js.map +0 -1
  183. package/dist/cli-errors-B8qHg02P.js +0 -798
  184. package/dist/cli-errors-B8qHg02P.js.map +0 -1
  185. package/dist/cli-flags-BglvpjHv.js.map +0 -1
  186. package/dist/cli-output-CNdMql-L.js +0 -47
  187. package/dist/cli-output-CNdMql-L.js.map +0 -1
  188. package/dist/collection-index-DdnsxiJ_.js +0 -286
  189. package/dist/collection-index-DdnsxiJ_.js.map +0 -1
  190. package/dist/column-plan-helpers-DF-8dTVa.js.map +0 -1
  191. package/dist/databasePoolManager-Bj5FbeAs.js.map +0 -1
  192. package/dist/doctor-Cb2thZ8s.js.map +0 -1
  193. package/dist/ensure-collection-policies-RHUcEp4v.js +0 -105
  194. package/dist/ensure-collection-policies-RHUcEp4v.js.map +0 -1
  195. package/dist/ensure-collection-tables-BEEjn5cn.js +0 -857
  196. package/dist/ensure-collection-tables-BEEjn5cn.js.map +0 -1
  197. package/dist/ensure-tables-Dhn9KM3B.js.map +0 -1
  198. package/dist/generate-drizzle-schema-logic-BfzK7UQd.js.map +0 -1
  199. package/dist/generate-drizzle-schema-yzY_BLhr.js +0 -123
  200. package/dist/generate-drizzle-schema-yzY_BLhr.js.map +0 -1
  201. package/dist/generate-postgres-ddl-logic-Bt2d2mRH.js.map +0 -1
  202. package/dist/introspect-db-logic-WMuAfxvw.js.map +0 -1
  203. package/dist/plan-schema-C0fxM8dY.js.map +0 -1
  204. package/dist/policy-drift-DljYdrpW.js.map +0 -1
  205. package/dist/rls-bootstrap-sql-B8EclDyM.js.map +0 -1
  206. package/dist/rls-enforcement-C6Xk0lA6.js.map +0 -1
  207. package/dist/source-Br7L7GOI.js +0 -410
  208. package/dist/source-Br7L7GOI.js.map +0 -1
@@ -1,47 +1,100 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { a as __toESM, t as require___vite_browser_external } from "./__vite-browser-external-BnuHet1e.js";
4
- import { n as outError, r as outWarn, t as out } from "./cli-output-CNdMql-L.js";
5
- import { D as parseBackupDestination, P as withDatabaseName, T as globalsFileForDump, h as validateDump, i as createDump, j as resolveConnectionString, k as parseDbNameFromUrl, l as listBackups, m as uploadBackup, n as applyGlobals, o as discardPartialDump, p as restoreDump, s as ensureDatabaseExists, t as BackupToolError, u as preflight } from "./backup-service-HQ9GC4tN.js";
6
- import { t as chalk } from "./source-Br7L7GOI.js";
7
- import { t as require_arg } from "./arg-Dni7MzLB.js";
8
- import { r as parseDriverLine } from "./cli-flags-BglvpjHv.js";
9
- import { parseEnvBoolean } from "@rebasepro/types";
10
- import fs from "fs";
3
+ import { Y as redactConnectionPasswords, t as checkDatabaseConnectivity } from "./cli-errors-oVUuD8k0.js";
4
+ import { a as outWarn, i as outError, r as out, t as chalk } from "./source-DB6xJv3p.js";
5
+ import { A as parseDbNameFromUrl, E as globalsFileForDump, F as withDatabaseName, M as resolveConnectionString, O as parseBackupDestination, f as restoreDump, i as createDump, l as listBackups, m as validateDump, n as applyGlobals, o as discardPartialDump, p as uploadBackup, s as ensureDatabaseExists, t as BackupToolError, u as preflight } from "./backup-service-AZWc2wvI.js";
6
+ import { t as promptConfirm } from "./cli-prompt-egtNKkZl.js";
7
+ import { i as parseCommandFlags } from "./cli-flags-DnPHXjRH.js";
11
8
  import path from "path";
9
+ import fs from "fs";
12
10
  import os from "os";
11
+ import { Readable } from "stream";
12
+ import { pipeline } from "stream/promises";
13
13
  //#region src/backup/backup-cli.ts
14
- var import_arg = /* @__PURE__ */ __toESM(require_arg(), 1);
15
- var import___vite_browser_external = /* @__PURE__ */ __toESM(require___vite_browser_external(), 1);
16
14
  function formatBytes(bytes) {
17
15
  if (bytes < 1024) return `${bytes} B`;
18
16
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
19
17
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
20
18
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
21
19
  }
20
+ /** A web stream's chunks, for piping into a file. */
21
+ async function* webChunks(stream) {
22
+ const reader = stream.getReader();
23
+ try {
24
+ for (;;) {
25
+ const { done, value } = await reader.read();
26
+ if (done) return;
27
+ yield value;
28
+ }
29
+ } finally {
30
+ reader.releaseLock();
31
+ }
32
+ }
22
33
  /**
23
- * Build a StorageController for an object-storage destination from the same
24
- * `S3_*` env vars the backend uses. Returns `null` for local destinations.
34
+ * The controller for an object-storage destination, or `null` for a local one.
35
+ *
36
+ * Built by `backupStorageFromEnv` from `@rebasepro/server` — the function the
37
+ * Backups panel's routes use — so the CLI and the panel read a bucket the same
38
+ * way. This file had its own copy, and the two had already drifted once
39
+ * (`S3_FORCE_PATH_STYLE` read as `=== "true"`, so a MinIO backup addressed the
40
+ * bucket as a host).
41
+ *
42
+ * Exported for its test.
25
43
  */
26
44
  async function resolveStorageForDestination(dest, env) {
27
45
  if (dest.kind === "local") return null;
28
- if (dest.kind === "gcs") {
29
- const { GCSStorageController } = await import("@rebasepro/server");
30
- return new GCSStorageController({
31
- type: "gcs",
32
- bucket: dest.bucket
33
- });
46
+ const { backupStorageFromEnv } = await import("@rebasepro/server");
47
+ try {
48
+ return backupStorageFromEnv(dest, env);
49
+ } catch (error) {
50
+ throw new BackupToolError(error instanceof Error ? error.message : String(error), "Set the same S3_* variables your backend uses for storage.");
34
51
  }
35
- if (!env.S3_ACCESS_KEY_ID || !env.S3_SECRET_ACCESS_KEY) throw new BackupToolError("S3 destination requires S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY in the environment.", "Set the same S3_* variables your backend uses for storage.");
36
- const { S3StorageController } = await import("@rebasepro/server");
37
- return new S3StorageController({
38
- type: "s3",
39
- bucket: dest.bucket,
40
- region: env.S3_REGION || "auto",
41
- accessKeyId: env.S3_ACCESS_KEY_ID,
42
- secretAccessKey: env.S3_SECRET_ACCESS_KEY,
43
- endpoint: env.S3_ENDPOINT,
44
- forcePathStyle: parseEnvBoolean(env.S3_FORCE_PATH_STYLE)
52
+ }
53
+ /**
54
+ * The directory `rebase` was run from, which `rebase` puts here for the driver.
55
+ *
56
+ * The driver runs in the project's `backend/`, so a relative path resolved
57
+ * against its own working directory named a different place from the one the
58
+ * user typed it in: `rebase db backup --out ./backups` wrote to `<root>/backups`
59
+ * (the CLI resolves explicit paths itself) while `rebase db backups list`
60
+ * looked in `<root>/backend/backups`. Spelled the same in
61
+ * `packages/cli/src/commands/db.ts`.
62
+ */
63
+ var INVOCATION_CWD_ENV = "REBASE_INVOCATION_CWD";
64
+ /** Where a relative path the user typed is relative to: where they ran `rebase`. */
65
+ function invocationDir(env = process.env) {
66
+ const dir = env[INVOCATION_CWD_ENV]?.trim();
67
+ return dir && path.isAbsolute(dir) ? dir : process.cwd();
68
+ }
69
+ /**
70
+ * Where `db backup` writes and `db backups list` reads, by one rule.
71
+ *
72
+ * - `--out` is relative to where `rebase` was run, like any path typed on a
73
+ * command line.
74
+ * - `BACKUP_DESTINATION` is relative to the backend directory, because the
75
+ * server reads the same variable there: the Backups panel and the scheduled
76
+ * backup have to find what the CLI wrote.
77
+ * - With neither, `./backups` where `rebase` was run, as the help says.
78
+ *
79
+ * An `s3://` or `gs://` destination is returned as given.
80
+ */
81
+ function resolveBackupLocation(opts) {
82
+ const flag = opts.flag?.trim();
83
+ if (flag) return isRemoteDestination(flag) ? flag : path.resolve(opts.invocationDir, flag);
84
+ const configured = opts.configured?.trim();
85
+ if (configured) return isRemoteDestination(configured) ? configured : path.resolve(opts.backendDir, configured);
86
+ return path.join(opts.invocationDir, "backups");
87
+ }
88
+ function isRemoteDestination(value) {
89
+ return parseBackupDestination(value).kind !== "local";
90
+ }
91
+ /** {@link resolveBackupLocation} for this process. */
92
+ function backupLocation(flag) {
93
+ return resolveBackupLocation({
94
+ flag,
95
+ configured: process.env.BACKUP_DESTINATION,
96
+ invocationDir: invocationDir(),
97
+ backendDir: process.cwd()
45
98
  });
46
99
  }
47
100
  function requireConnection() {
@@ -52,45 +105,43 @@ function requireConnection() {
52
105
  }
53
106
  return conn;
54
107
  }
55
- async function promptConfirm(question) {
56
- if (!process.stdin.isTTY) return false;
57
- const rl = import___vite_browser_external.default.createInterface({
58
- input: process.stdin,
59
- output: process.stdout
60
- });
61
- try {
62
- const answer = await new Promise((resolve) => rl.question(question, resolve));
63
- return /^y(es)?$/i.test(answer.trim());
64
- } finally {
65
- rl.close();
66
- }
108
+ var BACKUP_FLAGS = {
109
+ "--out": String,
110
+ "--output": "--out",
111
+ "--exclude-schema": [String],
112
+ "--no-owner": Boolean,
113
+ "--enable-row-security": Boolean,
114
+ "--row-security-role": String,
115
+ "-o": "--out"
116
+ };
117
+ /**
118
+ * Parse a `rebase db backup …` line. An undeclared flag is refused (see
119
+ * `parseCommandFlags`), and so is a positional: `rebase db backup ./backups`
120
+ * means `--out ./backups`, and taken as nothing it wrote to the default
121
+ * directory.
122
+ */
123
+ function parseBackupLine(rawArgs) {
124
+ const args = parseCommandFlags(BACKUP_FLAGS, rawArgs.slice(2), "db backup");
125
+ const [stray] = args._;
126
+ if (stray !== void 0) throw new Error(`\`rebase db backup\` takes no argument "${stray}". Nothing was run. To choose where the backup goes, pass --out ${stray}.`);
127
+ return args;
67
128
  }
68
129
  async function backupCommand(rawArgs) {
69
- const args = (0, import_arg.default)({
70
- "--out": String,
71
- "--output": "--out",
72
- "--exclude-schema": [String],
73
- "--no-owner": Boolean,
74
- "--enable-row-security": Boolean,
75
- "--row-security-role": String,
76
- "-o": "--out"
77
- }, {
78
- argv: rawArgs.slice(2),
79
- permissive: true
80
- });
81
- if (args._.includes("--help") || rawArgs.includes("--help")) {
130
+ if (rawArgs.includes("--help")) {
82
131
  printBackupHelp();
83
132
  return;
84
133
  }
134
+ const args = parseBackupLine(rawArgs);
85
135
  const connectionString = requireConnection();
86
136
  const dbName = parseDbNameFromUrl(connectionString) ?? "database";
87
- const out$1 = args["--out"] || process.env.BACKUP_DESTINATION || path.join(process.cwd(), "backups");
137
+ const out$1 = backupLocation(args["--out"]);
88
138
  const dest = parseBackupDestination(out$1);
89
139
  out("");
90
140
  out(chalk.bold(" 💾 Rebase DB Backup"));
91
141
  out(chalk.gray(` Database: ${dbName}`));
92
142
  out(chalk.gray(` Destination: ${out$1}`));
93
143
  out("");
144
+ await checkDatabaseConnectivity(connectionString);
94
145
  const pf = await preflight("pg_dump", connectionString);
95
146
  if (!pf.compatible) {
96
147
  outError(chalk.red(` ✗ ${pf.reason}`));
@@ -167,17 +218,29 @@ var RESTORE_FLAGS = {
167
218
  "--yes": Boolean,
168
219
  "-y": "--yes"
169
220
  };
170
- /** Parse a `rebase db restore …` line; the first positional is the backup. */
221
+ /**
222
+ * Parse a `rebase db restore …` line; the one positional is the backup.
223
+ *
224
+ * Strict, because this is the command where a typo costs most: parsed
225
+ * permissively, `--targt-db x` became a second positional, the target fell
226
+ * back to DATABASE_URL's own database, and the restore ran against the live
227
+ * one.
228
+ */
171
229
  function parseRestoreLine(rawArgs) {
172
- return parseDriverLine(RESTORE_FLAGS, rawArgs);
230
+ const args = parseCommandFlags(RESTORE_FLAGS, rawArgs.slice(2), "db restore");
231
+ if (args._.length > 1) throw new Error(`\`rebase db restore\` restores one backup, and was given ${args._.length}: ${args._.map((word) => `"${word}"`).join(", ")}. Nothing was run.`);
232
+ return args;
173
233
  }
174
234
  async function restoreCommand(rawArgs) {
235
+ if (rawArgs.includes("--help")) {
236
+ printRestoreHelp();
237
+ return;
238
+ }
175
239
  const args = parseRestoreLine(rawArgs);
176
240
  const backupArg = args._[0];
177
- if (!backupArg || rawArgs.includes("--help")) {
241
+ if (!backupArg) {
178
242
  printRestoreHelp();
179
- if (!backupArg && !rawArgs.includes("--help")) process.exit(1);
180
- return;
243
+ process.exit(1);
181
244
  }
182
245
  const baseConnection = requireConnection();
183
246
  const targetDb = args["--target-db"] ?? parseDbNameFromUrl(baseConnection) ?? void 0;
@@ -187,6 +250,7 @@ async function restoreCommand(rawArgs) {
187
250
  out(chalk.gray(` Source: ${backupArg}`));
188
251
  out(chalk.gray(` Target: ${targetDb ?? "(from DATABASE_URL)"}`));
189
252
  out("");
253
+ await checkDatabaseConnectivity(baseConnection);
190
254
  let localFile;
191
255
  let globalsSql = null;
192
256
  let cleanupTemp = false;
@@ -196,16 +260,16 @@ async function restoreCommand(rawArgs) {
196
260
  if (!storage) throw new BackupToolError("Could not resolve storage for the given URL.");
197
261
  const key = backupArg.replace(/^(s3|gs):\/\/[^/]+\//, "");
198
262
  const bucket = backupArg.replace(/^(s3|gs):\/\/([^/]+)\/.*$/, "$2");
199
- const file = await storage.getObject(key, bucket);
200
- if (!file) throw new BackupToolError(`Backup not found in storage: ${backupArg}`);
201
263
  const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "rebase-restore-"));
202
264
  localFile = path.join(tmpDir, path.basename(key));
203
- fs.writeFileSync(localFile, Buffer.from(await file.arrayBuffer()));
204
265
  cleanupTemp = true;
266
+ const object = storage.getObjectStream ? await storage.getObjectStream(key, { bucket }) : await storage.getObject(key, bucket).then((file) => file && { stream: file.stream() });
267
+ if (!object) throw new BackupToolError(`Backup not found in storage: ${backupArg}`);
268
+ await pipeline(Readable.from(webChunks(object.stream)), fs.createWriteStream(localFile));
205
269
  const globalsObj = await storage.getObject(globalsFileForDump(key), bucket);
206
270
  if (globalsObj) globalsSql = Buffer.from(await globalsObj.arrayBuffer()).toString("utf-8");
207
271
  } else {
208
- localFile = path.resolve(backupArg);
272
+ localFile = path.resolve(invocationDir(), backupArg);
209
273
  if (!fs.existsSync(localFile)) {
210
274
  outError(chalk.red(` ✗ Backup file not found: ${localFile}`));
211
275
  process.exit(1);
@@ -255,7 +319,7 @@ async function restoreCommand(rawArgs) {
255
319
  out("");
256
320
  } catch (err) {
257
321
  reportError(err);
258
- process.exit(1);
322
+ process.exitCode = 1;
259
323
  } finally {
260
324
  if (cleanupTemp && typeof localFile === "string" && fs.existsSync(localFile)) fs.rmSync(path.dirname(localFile), {
261
325
  recursive: true,
@@ -273,20 +337,20 @@ async function backupsCommand(rawArgs) {
273
337
  outError(chalk.red(`Unknown backups action: "${action}". Valid: list`));
274
338
  process.exit(1);
275
339
  }
276
- const out$2 = (0, import_arg.default)({
340
+ const args = parseCommandFlags({
277
341
  "--out": String,
278
342
  "--output": "--out",
279
343
  "-o": "--out"
280
- }, {
281
- argv: rawArgs.slice(3),
282
- permissive: true
283
- })["--out"] || process.env.BACKUP_DESTINATION || path.join(process.cwd(), "backups");
344
+ }, rawArgs.slice(3), "db backups list");
345
+ const out$2 = backupLocation(args["--out"]);
284
346
  const dest = parseBackupDestination(out$2);
285
347
  try {
286
348
  const backups = await listBackups(dest, await resolveStorageForDestination(dest, process.env) ?? void 0);
287
349
  out("");
288
- if (backups.length === 0) out(chalk.gray(` No backups found at ${out$2}.`));
289
- else {
350
+ if (backups.length === 0) {
351
+ out(chalk.gray(` No backups found at ${out$2}.`));
352
+ await mentionBackendBackups(out$2, args["--out"]);
353
+ } else {
290
354
  out(chalk.bold(` 💾 ${backups.length} backup(s) at ${out$2}:`));
291
355
  out("");
292
356
  for (const b of backups) {
@@ -310,6 +374,26 @@ async function backupsCommand(rawArgs) {
310
374
  }
311
375
  }
312
376
  /**
377
+ * Point at `<backend>/backups` when the default listing is empty and that
378
+ * directory holds dumps.
379
+ *
380
+ * Earlier releases resolved the default there, so after an upgrade the
381
+ * backups a project already has are one directory away from the listing.
382
+ */
383
+ async function mentionBackendBackups(listed, flag) {
384
+ if (flag || process.env.BACKUP_DESTINATION?.trim()) return;
385
+ const backendBackups = path.join(process.cwd(), "backups");
386
+ if (path.resolve(listed) === backendBackups) return;
387
+ const found = await listBackups({
388
+ kind: "local",
389
+ path: backendBackups
390
+ }).catch(() => []);
391
+ if (found.length === 0) return;
392
+ out(chalk.gray(` ${found.length} backup(s) are in ${backendBackups}, where earlier releases of`));
393
+ out(chalk.gray(` \`rebase db backup\` wrote by default. List them with:`));
394
+ out(chalk.gray(` rebase db backups list --out ${path.relative(invocationDir(), backendBackups) || "."}`));
395
+ }
396
+ /**
313
397
  * Verify a freshly written dump; abort the command if it looks corrupt.
314
398
  *
315
399
  * Discards the artifact on the way out. Refusing to *report* success was never
@@ -327,11 +411,20 @@ async function assertDumpValid(localFile) {
327
411
  throw new BackupToolError(`The backup failed validation and was discarded: ${check.reason}`, "The dump was corrupt or truncated, so nothing was kept. Investigate before relying on this destination.");
328
412
  }
329
413
  }
414
+ /**
415
+ * Say why a backup command failed, with no password in it.
416
+ *
417
+ * What reaches here is often a client tool's failure, and execa's message
418
+ * repeats the tool's command line. The tools get the password through
419
+ * `PGPASSWORD` now, so it is not on that line, but a connection string can
420
+ * still arrive inside a message from elsewhere; this is the last place to
421
+ * stop it reaching a terminal or a CI log.
422
+ */
330
423
  function reportError(err) {
331
424
  if (err instanceof BackupToolError) {
332
- outError(chalk.red(` ✗ ${err.message}`));
333
- if (err.hint) outError(chalk.gray(` ${err.hint}`));
334
- } else outError(chalk.red(` ✗ ${err instanceof Error ? err.message : String(err)}`));
425
+ outError(chalk.red(` ✗ ${redactConnectionPasswords(err.message)}`));
426
+ if (err.hint) outError(chalk.gray(` ${redactConnectionPasswords(err.hint)}`));
427
+ } else outError(chalk.red(` ✗ ${redactConnectionPasswords(err instanceof Error ? err.message : String(err))}`));
335
428
  }
336
429
  function printBackupHelp() {
337
430
  out(`
@@ -409,4 +502,4 @@ ${chalk.green.bold("Usage")}
409
502
  //#endregion
410
503
  export { backupCommand, backupsCommand, restoreCommand };
411
504
 
412
- //# sourceMappingURL=backup-cli-24v4OlSp.js.map
505
+ //# sourceMappingURL=backup-cli-yiKd1GsC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup-cli-yiKd1GsC.js","names":[],"sources":["../src/backup/backup-cli.ts"],"sourcesContent":["/**\n * CLI handlers for `rebase db backup`, `rebase db restore`, and\n * `rebase db backups list`. Kept out of the main `cli.ts` dispatcher so the\n * backup surface stays self-contained.\n */\nimport type arg from \"arg\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport os from \"os\";\nimport { Readable } from \"stream\";\nimport { pipeline } from \"stream/promises\";\nimport chalk from \"chalk\";\n// Aliased: `out` is already a local in two of the commands below (the `--out`\n// backup destination).\nimport { out as print, outWarn, outError } from \"../cli-output\";\nimport { parseCommandFlags } from \"../cli-flags\";\nimport { redactConnectionPasswords } from \"../utils/connection-string\";\nimport { promptConfirm } from \"../cli-prompt\";\nimport { checkDatabaseConnectivity } from \"../cli-errors\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport {\n BackupDestination,\n globalsFileForDump,\n parseBackupDestination,\n parseDbNameFromUrl,\n resolveConnectionString,\n withDatabaseName\n} from \"./pg-tools\";\nimport {\n applyGlobals,\n BackupToolError,\n createDump,\n discardPartialDump,\n ensureDatabaseExists,\n listBackups,\n preflight,\n restoreDump,\n uploadBackup,\n validateDump\n} from \"./backup-service\";\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;\n}\n\n/** A web stream's chunks, for piping into a file. */\nasync function* webChunks(stream: ReadableStream<Uint8Array>): AsyncGenerator<Uint8Array> {\n const reader = stream.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) return;\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/**\n * The controller for an object-storage destination, or `null` for a local one.\n *\n * Built by `backupStorageFromEnv` from `@rebasepro/server` — the function the\n * Backups panel's routes use — so the CLI and the panel read a bucket the same\n * way. This file had its own copy, and the two had already drifted once\n * (`S3_FORCE_PATH_STYLE` read as `=== \"true\"`, so a MinIO backup addressed the\n * bucket as a host).\n *\n * Exported for its test.\n */\nexport async function resolveStorageForDestination(\n dest: BackupDestination,\n env: Record<string, string | undefined>\n): Promise<StorageController | null> {\n if (dest.kind === \"local\") return null;\n const { backupStorageFromEnv } = await import(\"@rebasepro/server\");\n try {\n return backupStorageFromEnv(dest, env);\n } catch (error) {\n throw new BackupToolError(\n error instanceof Error ? error.message : String(error),\n \"Set the same S3_* variables your backend uses for storage.\"\n );\n }\n}\n\n/**\n * The directory `rebase` was run from, which `rebase` puts here for the driver.\n *\n * The driver runs in the project's `backend/`, so a relative path resolved\n * against its own working directory named a different place from the one the\n * user typed it in: `rebase db backup --out ./backups` wrote to `<root>/backups`\n * (the CLI resolves explicit paths itself) while `rebase db backups list`\n * looked in `<root>/backend/backups`. Spelled the same in\n * `packages/cli/src/commands/db.ts`.\n */\nexport const INVOCATION_CWD_ENV = \"REBASE_INVOCATION_CWD\";\n\n/** Where a relative path the user typed is relative to: where they ran `rebase`. */\nexport function invocationDir(env: Readonly<Record<string, string | undefined>> = process.env): string {\n const dir = env[INVOCATION_CWD_ENV]?.trim();\n return dir && path.isAbsolute(dir) ? dir : process.cwd();\n}\n\n/**\n * Where `db backup` writes and `db backups list` reads, by one rule.\n *\n * - `--out` is relative to where `rebase` was run, like any path typed on a\n * command line.\n * - `BACKUP_DESTINATION` is relative to the backend directory, because the\n * server reads the same variable there: the Backups panel and the scheduled\n * backup have to find what the CLI wrote.\n * - With neither, `./backups` where `rebase` was run, as the help says.\n *\n * An `s3://` or `gs://` destination is returned as given.\n */\nexport function resolveBackupLocation(opts: {\n flag?: string;\n configured?: string;\n invocationDir: string;\n backendDir: string;\n}): string {\n const flag = opts.flag?.trim();\n if (flag) return isRemoteDestination(flag) ? flag : path.resolve(opts.invocationDir, flag);\n const configured = opts.configured?.trim();\n if (configured) return isRemoteDestination(configured) ? configured : path.resolve(opts.backendDir, configured);\n return path.join(opts.invocationDir, \"backups\");\n}\n\nfunction isRemoteDestination(value: string): boolean {\n return parseBackupDestination(value).kind !== \"local\";\n}\n\n/** {@link resolveBackupLocation} for this process. */\nfunction backupLocation(flag: string | undefined): string {\n return resolveBackupLocation({\n flag,\n configured: process.env.BACKUP_DESTINATION,\n invocationDir: invocationDir(),\n backendDir: process.cwd()\n });\n}\n\nfunction requireConnection(): string {\n const conn = resolveConnectionString(process.env);\n if (!conn) {\n outError(chalk.red(\"✗ DATABASE_URL is not set. Make sure your .env file is configured.\"));\n process.exit(1);\n }\n return conn;\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backup\n// ─────────────────────────────────────────────────────────────────────────\nconst BACKUP_FLAGS = {\n \"--out\": String,\n // The same alias `build` and `cloud env pull` carry. `--output` is the\n // canonical spelling in this CLI, and `rebase db backup --output ./backups`\n // has to write there.\n \"--output\": \"--out\",\n \"--exclude-schema\": [String],\n \"--no-owner\": Boolean,\n \"--enable-row-security\": Boolean,\n \"--row-security-role\": String,\n \"-o\": \"--out\"\n} satisfies arg.Spec;\n\n/**\n * Parse a `rebase db backup …` line. An undeclared flag is refused (see\n * `parseCommandFlags`), and so is a positional: `rebase db backup ./backups`\n * means `--out ./backups`, and taken as nothing it wrote to the default\n * directory.\n */\nexport function parseBackupLine(rawArgs: string[]) {\n const args = parseCommandFlags(BACKUP_FLAGS, rawArgs.slice(2), \"db backup\");\n const [stray] = args._;\n if (stray !== undefined) {\n throw new Error(\n `\\`rebase db backup\\` takes no argument \"${stray}\". Nothing was run. ` +\n `To choose where the backup goes, pass --out ${stray}.`\n );\n }\n return args;\n}\n\nexport async function backupCommand(rawArgs: string[]): Promise<void> {\n if (rawArgs.includes(\"--help\")) {\n printBackupHelp();\n return;\n }\n const args = parseBackupLine(rawArgs);\n\n const connectionString = requireConnection();\n const dbName = parseDbNameFromUrl(connectionString) ?? \"database\";\n const out = backupLocation(args[\"--out\"]);\n const dest = parseBackupDestination(out);\n\n print(\"\");\n print(chalk.bold(\" 💾 Rebase DB Backup\"));\n print(chalk.gray(` Database: ${dbName}`));\n print(chalk.gray(` Destination: ${out}`));\n print(\"\");\n\n // A database that is not running is said the way `db push` says it — the\n // host, the port and what to start — before pg_dump's version probe meets\n // it as a bare `connect ECONNREFUSED`.\n await checkDatabaseConnectivity(connectionString);\n\n // Version pre-flight (doctor-style).\n const pf = await preflight(\"pg_dump\", connectionString);\n if (!pf.compatible) {\n outError(chalk.red(` ✗ ${pf.reason}`));\n process.exit(1);\n }\n print(chalk.gray(` Using pg_dump ${pf.toolMajor} against server ${pf.serverMajor}.`));\n\n // Opt-in, and loud. With row security on, pg_dump stops refusing to read\n // rows it cannot see and starts leaving them out — an exit-0 backup that\n // is quietly short. Anyone choosing that should know they chose it.\n const rowSecurity = args[\"--enable-row-security\"]\n ? { uid: \"rebase-db-backup\", roles: [args[\"--row-security-role\"] || \"admin\"] }\n : undefined;\n\n if (rowSecurity) {\n outWarn(\"\");\n outWarn(chalk.yellow(\" ⚠ Dumping with row-level security ON.\"));\n outWarn(chalk.gray(` Reading as roles [${rowSecurity.roles.join(\", \")}], which satisfies the generated`));\n outWarn(chalk.gray(\" `admin_full_access` policy. This backup contains exactly the rows those\"));\n outWarn(chalk.gray(\" policies admit — a table whose policies have no admin rule comes out short,\"));\n outWarn(chalk.gray(\" and pg_dump will not say so. Prefer granting the dumping role BYPASSRLS.\"));\n outWarn(\"\");\n }\n\n try {\n if (dest.kind === \"local\") {\n // Honour an explicit `…/name.dump` path; otherwise treat it as a\n // directory and auto-name the file.\n const explicitFile = dest.path.endsWith(\".dump\");\n const dump = await createDump({\n connectionString,\n dbName,\n outDir: explicitFile ? path.dirname(dest.path) : dest.path,\n fileName: explicitFile ? path.basename(dest.path) : undefined,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n await assertDumpValid(dump.localFile);\n print(\"\");\n print(chalk.green(` ✓ Backup written to ${dump.localFile} (${formatBytes(dump.sizeBytes)})`));\n if (dump.globalsFile) {\n print(chalk.gray(` ✓ Roles captured to ${dump.globalsFile} (needed so RLS survives a restore).`));\n }\n } else {\n const storage = await resolveStorageForDestination(dest, process.env);\n const dump = await createDump({\n connectionString,\n dbName,\n excludeSchemas: args[\"--exclude-schema\"],\n noOwner: args[\"--no-owner\"],\n inheritStdio: true,\n rowSecurity\n });\n try {\n await assertDumpValid(dump.localFile);\n const uploaded = await uploadBackup(storage!, dump.localFile, dest);\n print(\"\");\n print(chalk.green(` ✓ Backup uploaded to ${uploaded.storageUrl} (${formatBytes(dump.sizeBytes)})`));\n // Upload the roles sidecar next to the dump so a restore can\n // recreate roles the dump's GRANT/RLS statements depend on.\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) {\n const globalsUpload = await uploadBackup(storage!, dump.globalsFile, dest);\n print(chalk.gray(` ✓ Roles uploaded to ${globalsUpload.storageUrl} (needed so RLS survives a restore).`));\n }\n print(chalk.gray(\" Ensure this bucket is private — backups may contain secrets and PII.\"));\n } finally {\n if (fs.existsSync(dump.localFile)) fs.unlinkSync(dump.localFile);\n if (dump.globalsFile && fs.existsSync(dump.globalsFile)) fs.unlinkSync(dump.globalsFile);\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db restore <backup>\n// ─────────────────────────────────────────────────────────────────────────\nconst RESTORE_FLAGS = {\n \"--target-db\": String,\n \"--create-db\": Boolean,\n \"--clean\": Boolean,\n \"--no-owner\": Boolean,\n \"--continue-on-error\": Boolean,\n \"--yes\": Boolean,\n \"-y\": \"--yes\"\n} satisfies arg.Spec;\n\n/**\n * Parse a `rebase db restore …` line; the one positional is the backup.\n *\n * Strict, because this is the command where a typo costs most: parsed\n * permissively, `--targt-db x` became a second positional, the target fell\n * back to DATABASE_URL's own database, and the restore ran against the live\n * one.\n */\nexport function parseRestoreLine(rawArgs: string[]) {\n const args = parseCommandFlags(RESTORE_FLAGS, rawArgs.slice(2), \"db restore\");\n if (args._.length > 1) {\n throw new Error(\n `\\`rebase db restore\\` restores one backup, and was given ${args._.length}: ` +\n `${args._.map(word => `\"${word}\"`).join(\", \")}. Nothing was run.`\n );\n }\n return args;\n}\n\nexport async function restoreCommand(rawArgs: string[]): Promise<void> {\n if (rawArgs.includes(\"--help\")) {\n printRestoreHelp();\n return;\n }\n const args = parseRestoreLine(rawArgs);\n\n const backupArg = args._[0];\n if (!backupArg) {\n printRestoreHelp();\n process.exit(1);\n }\n\n const baseConnection = requireConnection();\n\n // Choose the target connection: an explicit --target-db swaps the database\n // name so the live one isn't clobbered. Without it the target is\n // DATABASE_URL's own database, and `--create-db` only creates it when it is\n // missing.\n const targetDb = args[\"--target-db\"] ?? parseDbNameFromUrl(baseConnection) ?? undefined;\n const targetConnection = args[\"--target-db\"]\n ? withDatabaseName(baseConnection, args[\"--target-db\"])\n : baseConnection;\n\n print(\"\");\n print(chalk.bold(\" ♻️ Rebase DB Restore\"));\n print(chalk.gray(` Source: ${backupArg}`));\n print(chalk.gray(` Target: ${targetDb ?? \"(from DATABASE_URL)\"}`));\n print(\"\");\n\n // Before anything is downloaded, and in `db push`'s words: see backupCommand.\n await checkDatabaseConnectivity(baseConnection);\n\n // Resolve the local file to restore from (download object-storage keys).\n // Also resolve the `.globals.sql` roles sidecar so cluster roles can be\n // recreated before the restore — without them the dump's GRANT/RLS\n // statements fail and RLS is silently lost.\n let localFile: string;\n let globalsSql: string | null = null;\n let cleanupTemp = false;\n try {\n if (/^(s3|gs):\\/\\//.test(backupArg)) {\n const dest = parseBackupDestination(backupArg.replace(/\\/[^/]+$/, \"\"));\n const storage = await resolveStorageForDestination(dest, process.env);\n if (!storage) throw new BackupToolError(\"Could not resolve storage for the given URL.\");\n const key = backupArg.replace(/^(s3|gs):\\/\\/[^/]+\\//, \"\");\n const bucket = backupArg.replace(/^(s3|gs):\\/\\/([^/]+)\\/.*$/, \"$2\");\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), \"rebase-restore-\"));\n localFile = path.join(tmpDir, path.basename(key));\n cleanupTemp = true;\n // Streamed to disk: buffered, a dump was held twice in memory and\n // one over 2 GiB could not be written in one call at all.\n const object = storage.getObjectStream\n ? await storage.getObjectStream(key, { bucket })\n : await storage.getObject(key, bucket).then((file) => file && { stream: file.stream() });\n if (!object) throw new BackupToolError(`Backup not found in storage: ${backupArg}`);\n await pipeline(Readable.from(webChunks(object.stream)), fs.createWriteStream(localFile));\n const globalsObj = await storage.getObject(globalsFileForDump(key), bucket);\n if (globalsObj) globalsSql = Buffer.from(await globalsObj.arrayBuffer()).toString(\"utf-8\");\n } else {\n localFile = path.resolve(invocationDir(), backupArg);\n if (!fs.existsSync(localFile)) {\n outError(chalk.red(` ✗ Backup file not found: ${localFile}`));\n process.exit(1);\n }\n const globalsPath = globalsFileForDump(localFile);\n if (fs.existsSync(globalsPath)) globalsSql = fs.readFileSync(globalsPath, \"utf-8\");\n }\n\n // Version pre-flight. Check against the base connection — the server\n // version is identical for every database, and the target may not\n // exist yet when --create-db is used.\n const pf = await preflight(\"pg_restore\", baseConnection);\n if (!pf.compatible) {\n outError(chalk.red(` ✗ ${pf.reason}`));\n process.exit(1);\n }\n\n // `--create-db` needs a name before anything else can be decided.\n if (args[\"--create-db\"] && !targetDb) {\n outError(chalk.red(\" ✗ --create-db requires a resolvable target database name (use --target-db).\"));\n process.exit(1);\n }\n\n // Destructive-action gate. Restores overwrite data; never run without\n // an explicit yes (interactive confirmation or --yes).\n //\n // Ahead of `--create-db`, not after it. Creating the database first\n // meant an aborted run had already changed the cluster, while printing\n // \"No changes were made\" — and it left an empty database behind that a\n // second, confirmed run then reported as \"already exists\". The gate is\n // now the first thing that can stop the command, so its own message is\n // true whichever way the answer goes.\n if (!args[\"--yes\"]) {\n outWarn(chalk.yellow(\n ` ⚠️ This will restore into \"${targetDb ?? \"the target database\"}\" and may overwrite existing data.`\n ));\n const confirmed = await promptConfirm(chalk.yellow(\" Type 'yes' to continue: \"));\n if (!confirmed) {\n print(chalk.gray(\" Aborted. No changes were made.\"));\n process.exit(1);\n }\n }\n\n // Create the target database when requested.\n if (args[\"--create-db\"]) {\n const created = await ensureDatabaseExists(baseConnection, targetDb!);\n print(chalk.gray(created ? ` ✓ Created database \"${targetDb}\".` : ` • Database \"${targetDb}\" already exists.`));\n }\n\n // Recreate cluster roles before restoring so GRANT/RLS statements in\n // the dump apply. Best-effort and idempotent (see applyGlobals).\n if (globalsSql) {\n print(chalk.gray(\" Recreating cluster roles from the backup's roles sidecar…\"));\n const { applied, skipped } = await applyGlobals(\n targetConnection,\n globalsSql,\n (m) => print(chalk.gray(m))\n );\n print(chalk.gray(` ✓ Roles: ${applied} applied, ${skipped} skipped (already present or not permitted).`));\n } else {\n outWarn(chalk.yellow(\" ⚠️ No roles sidecar (.globals.sql) accompanies this backup.\"));\n outWarn(chalk.yellow(\" If the dump grants to roles that don't exist (e.g. rebase_user), the restore\"));\n outWarn(chalk.yellow(\" will fail — recreate those roles first, or use a backup that includes its globals.\"));\n }\n\n await restoreDump({\n connectionString: targetConnection,\n inputFile: localFile,\n clean: args[\"--clean\"],\n noOwner: args[\"--no-owner\"],\n // Fail loudly by default so a skipped GRANT never leaves RLS off.\n exitOnError: !args[\"--continue-on-error\"],\n inheritStdio: true\n });\n\n print(\"\");\n print(chalk.green(` ✓ Restore completed into \"${targetDb ?? \"the target database\"}\".`));\n print(\"\");\n } catch (err) {\n reportError(err);\n // An exit code, not `process.exit`: exiting here skipped the `finally`\n // below, and a failed restore from object storage left its downloaded\n // dump, every row of the database, in the temp directory.\n process.exitCode = 1;\n } finally {\n if (cleanupTemp && typeof localFile! === \"string\" && fs.existsSync(localFile!)) {\n fs.rmSync(path.dirname(localFile!), { recursive: true, force: true });\n }\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// rebase db backups list\n// ─────────────────────────────────────────────────────────────────────────\nexport async function backupsCommand(rawArgs: string[]): Promise<void> {\n const action = rawArgs[2];\n if (!action || action === \"--help\") {\n printBackupsHelp();\n return;\n }\n if (action !== \"list\") {\n outError(chalk.red(`Unknown backups action: \"${action}\". Valid: list`));\n process.exit(1);\n }\n\n const args = parseCommandFlags(\n { \"--out\": String, \"--output\": \"--out\", \"-o\": \"--out\" },\n rawArgs.slice(3),\n \"db backups list\"\n );\n const out = backupLocation(args[\"--out\"]);\n const dest = parseBackupDestination(out);\n\n try {\n const storage = await resolveStorageForDestination(dest, process.env);\n const backups = await listBackups(dest, storage ?? undefined);\n print(\"\");\n if (backups.length === 0) {\n print(chalk.gray(` No backups found at ${out}.`));\n await mentionBackendBackups(out, args[\"--out\"]);\n } else {\n print(chalk.bold(` 💾 ${backups.length} backup(s) at ${out}:`));\n print(\"\");\n for (const b of backups) {\n const when = b.createdAt ? b.createdAt.toISOString() : \"unknown date\";\n const name = dest.kind === \"local\" ? path.basename(b.key) : b.key;\n // An empty file is called out rather than listed as a peer of\n // the real ones. Older failures could leave a 0-byte dump here\n // (fixed at the source now), and retention protects the newest\n // by date whatever they contain — so a corpse left in place can\n // hold a `keepMinimum` slot against a backup that matters.\n const empty = b.sizeBytes === 0;\n const size = b.sizeBytes === undefined ? \"\" : ` — ${formatBytes(b.sizeBytes)}`;\n if (empty) {\n print(` ${chalk.red(\"○\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}`)}${chalk.red(\" — EMPTY, not restorable\")}`);\n } else {\n print(` ${chalk.green(\"●\")} ${chalk.bold(name)} ${chalk.gray(`— ${when}${size}`)}`);\n }\n }\n if (backups.some(b => b.sizeBytes === 0)) {\n print(\"\");\n print(chalk.yellow(\" ⚠ Empty files above are leftovers from a failed backup. Delete them:\"));\n print(chalk.gray(\" they count as recent backups for retention but restore nothing.\"));\n }\n }\n print(\"\");\n } catch (err) {\n reportError(err);\n process.exit(1);\n }\n}\n\n/**\n * Point at `<backend>/backups` when the default listing is empty and that\n * directory holds dumps.\n *\n * Earlier releases resolved the default there, so after an upgrade the\n * backups a project already has are one directory away from the listing.\n */\nasync function mentionBackendBackups(listed: string, flag: string | undefined): Promise<void> {\n if (flag || process.env.BACKUP_DESTINATION?.trim()) return;\n const backendBackups = path.join(process.cwd(), \"backups\");\n if (path.resolve(listed) === backendBackups) return;\n const found = await listBackups({ kind: \"local\", path: backendBackups }).catch(() => []);\n if (found.length === 0) return;\n print(chalk.gray(` ${found.length} backup(s) are in ${backendBackups}, where earlier releases of`));\n print(chalk.gray(` \\`rebase db backup\\` wrote by default. List them with:`));\n print(chalk.gray(` rebase db backups list --out ${path.relative(invocationDir(), backendBackups) || \".\"}`));\n}\n\n/**\n * Verify a freshly written dump; abort the command if it looks corrupt.\n *\n * Discards the artifact on the way out. Refusing to *report* success was never\n * enough on its own: the file stayed on disk, `rebase db backups list` showed\n * it as an ordinary entry, and retention — which ranks by timestamp and never\n * looks at size — would protect it as one of the `keepMinimum` newest while\n * pruning a real backup underneath it. The roles sidecar goes too; the two are\n * uploaded and pruned as a pair, so half a pair is not a backup either.\n */\nasync function assertDumpValid(localFile: string): Promise<void> {\n const check = await validateDump(localFile);\n if (!check.ok) {\n discardPartialDump(globalsFileForDump(localFile));\n discardPartialDump(localFile);\n throw new BackupToolError(\n `The backup failed validation and was discarded: ${check.reason}`,\n \"The dump was corrupt or truncated, so nothing was kept. Investigate before relying on this destination.\"\n );\n }\n}\n\n/**\n * Say why a backup command failed, with no password in it.\n *\n * What reaches here is often a client tool's failure, and execa's message\n * repeats the tool's command line. The tools get the password through\n * `PGPASSWORD` now, so it is not on that line, but a connection string can\n * still arrive inside a message from elsewhere; this is the last place to\n * stop it reaching a terminal or a CI log.\n */\nfunction reportError(err: unknown): void {\n if (err instanceof BackupToolError) {\n outError(chalk.red(` ✗ ${redactConnectionPasswords(err.message)}`));\n if (err.hint) outError(chalk.gray(` ${redactConnectionPasswords(err.hint)}`));\n } else {\n outError(chalk.red(` ✗ ${redactConnectionPasswords(err instanceof Error ? err.message : String(err))}`));\n }\n}\n\nfunction printBackupHelp(): void {\n print(`\n${chalk.bold(\"rebase db backup\")} — Create a database backup (pg_dump, custom format)\n\n${chalk.green.bold(\"Usage\")}\n rebase db backup [--out <path|s3://bucket/prefix>] [options]\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--out, -o\")} <dest> Local path or s3://…/gs://… URL (default: ./backups)\n ${chalk.blue(\"--exclude-schema\")} <s> Exclude a schema (repeatable)\n ${chalk.blue(\"--no-owner\")} Omit ownership commands from the dump\n ${chalk.blue(\"--enable-row-security\")} Dump as an admin subject instead of failing on RLS\n ${chalk.red(\"(may produce a partial dump — see below)\")}\n ${chalk.blue(\"--row-security-role\")} <r> Role to read as with the flag above (default: admin)\n\n${chalk.green.bold(\"Row-level security\")}\n On a managed Postgres the dumping role usually owns nothing and has no\n BYPASSRLS, so pg_dump refuses:\n\n ERROR: query would be affected by row-level security policy for table \"...\"\n\n That refusal is the safe behaviour. --enable-row-security replaces it by\n reading as an admin subject: Rebase sets app.uid/app.user_roles so the\n generated admin_full_access policy admits the dump. The dump then contains\n exactly what those policies admit ${chalk.red(\"and no error is raised for what they do not\")} —\n a table whose policies lack an admin rule comes out short, silently.\n\n Granting the dumping role BYPASSRLS is the option that keeps a backup\n meaning \"every row\".\n\n${chalk.green.bold(\"Notes\")}\n Backups may contain secrets and PII. Use private storage destinations and\n enable encryption-at-rest. See docs/backups.md.\n`);\n}\n\nfunction printRestoreHelp(): void {\n print(`\n${chalk.bold(\"rebase db restore\")} — Restore a database from a backup (pg_restore)\n\n${chalk.green.bold(\"Usage\")}\n rebase db restore <backup> [options]\n\n${chalk.green.bold(\"Arguments\")}\n <backup> Local .dump file, or s3://…/gs://… object key\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--target-db\")} <name> Restore into this database instead of DATABASE_URL's\n ${chalk.blue(\"--create-db\")} Create the target database first if it doesn't exist\n ${chalk.blue(\"--clean\")} Drop existing objects before recreating them\n ${chalk.blue(\"--no-owner\")} Ignore ownership from the dump\n ${chalk.blue(\"--continue-on-error\")} Log and continue past errors ${chalk.red(\"(may leave RLS un-enforced!)\")}\n ${chalk.blue(\"--yes, -y\")} Skip the interactive confirmation ${chalk.red(\"(destructive!)\")}\n\n${chalk.red.bold(\"Warning\")}\n Restore is destructive and never runs automatically. Without --yes it\n requires an interactive 'yes'. Prefer --create-db/--target-db to restore\n into a fresh database rather than overwriting a live one.\n\n By default the restore aborts on the first error (--exit-on-error) so a\n skipped GRANT never silently leaves RLS un-enforced. Roles are recreated\n from the backup's .globals.sql sidecar first; keep that file next to the\n dump. Use --continue-on-error only when you understand the consequences.\n`);\n}\n\nfunction printBackupsHelp(): void {\n print(`\n${chalk.bold(\"rebase db backups\")} — Manage stored backups\n\n${chalk.green.bold(\"Usage\")}\n rebase db backups list [--out <path|s3://bucket/prefix>]\n rebase db backup list [--out <path|s3://bucket/prefix>] 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