@rebasepro/server-postgres 0.25.0 → 0.26.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.
Files changed (144) hide show
  1. package/dist/{BranchService-iXXZeVYD.js → BranchService-CWBnDhcv.js} +88 -12
  2. package/dist/BranchService-CWBnDhcv.js.map +1 -0
  3. package/dist/PostgresBackendDriver.d.ts +13 -0
  4. package/dist/PostgresBootstrapper.d.ts +7 -0
  5. package/dist/auth/services.d.ts +8 -1
  6. package/dist/auth/verify-auth-tables.d.ts +21 -0
  7. package/dist/backup/backup-cli.d.ts +40 -3
  8. package/dist/backup/backup-service.d.ts +11 -0
  9. package/dist/{backup-service-Bb39plam.js → backup-cli-PoRG-zEq.js} +777 -10
  10. package/dist/backup-cli-PoRG-zEq.js.map +1 -0
  11. package/dist/{boot-ddl-s_3Hkz94.js → boot-ddl-EsgqDkx0.js} +3 -3
  12. package/dist/{boot-ddl-s_3Hkz94.js.map → boot-ddl-EsgqDkx0.js.map} +1 -1
  13. package/dist/branch-argv.d.ts +15 -0
  14. package/dist/branch-diff-CxE4VlxT.js +1396 -0
  15. package/dist/branch-diff-CxE4VlxT.js.map +1 -0
  16. package/dist/branch-diff-report-DpvVf7hR.js +48 -0
  17. package/dist/branch-diff-report-DpvVf7hR.js.map +1 -0
  18. package/dist/branching/branch-diff-report.d.ts +7 -0
  19. package/dist/branching/branch-diff.d.ts +115 -0
  20. package/dist/{cli-console-DQ_K-sdM.js → cli-console-f0k6_TsJ.js} +41 -9
  21. package/dist/cli-console-f0k6_TsJ.js.map +1 -0
  22. package/dist/cli-console.d.ts +17 -1
  23. package/dist/{cli-errors-DwQnNATs.js → cli-errors-DsYyNYzd.js} +90 -11
  24. package/dist/cli-errors-DsYyNYzd.js.map +1 -0
  25. package/dist/cli-errors.d.ts +14 -0
  26. package/dist/cli-flags.d.ts +51 -0
  27. package/dist/{cli-prompt-egtNKkZl.js → cli-prompt-DXG0yk-h.js} +39 -4
  28. package/dist/{cli-prompt-egtNKkZl.js.map → cli-prompt-DXG0yk-h.js.map} +1 -1
  29. package/dist/cli.js +121 -271
  30. package/dist/cli.js.map +1 -1
  31. package/dist/{collections-schema-version-T6cGvrDi.js → collections-schema-version-D7bDI0PJ.js} +13 -9
  32. package/dist/collections-schema-version-D7bDI0PJ.js.map +1 -0
  33. package/dist/{column-plan-helpers-D_V4oaZh.js → column-plan-helpers-IG6uFb1s.js} +2 -2
  34. package/dist/{column-plan-helpers-D_V4oaZh.js.map → column-plan-helpers-IG6uFb1s.js.map} +1 -1
  35. package/dist/{connection-C938nR3E.js → connection-czvI7TZL.js} +57 -10
  36. package/dist/connection-czvI7TZL.js.map +1 -0
  37. package/dist/{databasePoolManager-Yqdw14wY.js → databasePoolManager-3stMNFL-.js} +4 -6
  38. package/dist/databasePoolManager-3stMNFL-.js.map +1 -0
  39. package/dist/db-command-line.d.ts +14 -0
  40. package/dist/db-subcommands.d.ts +11 -0
  41. package/dist/{deferred-index-build-Cis_HoGn.js → deferred-index-build-CqaOv1Xx.js} +8 -8
  42. package/dist/{deferred-index-build-Cis_HoGn.js.map → deferred-index-build-CqaOv1Xx.js.map} +1 -1
  43. package/dist/{doctor-DvJH-IQG.js → doctor-DW_mlTzz.js} +186 -42
  44. package/dist/doctor-DW_mlTzz.js.map +1 -0
  45. package/dist/{ensure-collection-policies-CCqayoUz.js → ensure-collection-policies-DLWgabQ2.js} +13 -10
  46. package/dist/ensure-collection-policies-DLWgabQ2.js.map +1 -0
  47. package/dist/{ensure-collection-tables-DvvImXDe.js → ensure-collection-tables-CFIRq8ni.js} +9 -9
  48. package/dist/{ensure-collection-tables-DvvImXDe.js.map → ensure-collection-tables-CFIRq8ni.js.map} +1 -1
  49. package/dist/{ensure-tables-Dpgwx5sy.js → ensure-tables-4nA-tfwi.js} +5 -5
  50. package/dist/{ensure-tables-Dpgwx5sy.js.map → ensure-tables-4nA-tfwi.js.map} +1 -1
  51. package/dist/{enum-labels-kept-CUlUlRkO.js → enum-labels-kept-PcPW65xy.js} +3 -3
  52. package/dist/{enum-labels-kept-CUlUlRkO.js.map → enum-labels-kept-PcPW65xy.js.map} +1 -1
  53. package/dist/{generate-drizzle-schema-C3EAP9HE.js → generate-drizzle-schema-DC0BOUpn.js} +3 -3
  54. package/dist/{generate-drizzle-schema-C3EAP9HE.js.map → generate-drizzle-schema-DC0BOUpn.js.map} +1 -1
  55. package/dist/{generate-drizzle-schema-logic-DA3zM8zc.js → generate-drizzle-schema-logic-CPzCRD-8.js} +4 -4
  56. package/dist/{generate-drizzle-schema-logic-DA3zM8zc.js.map → generate-drizzle-schema-logic-CPzCRD-8.js.map} +1 -1
  57. package/dist/{generate-files-ClmOUHXj.js → generate-files-BP-4W_gm.js} +6 -6
  58. package/dist/{generate-files-ClmOUHXj.js.map → generate-files-BP-4W_gm.js.map} +1 -1
  59. package/dist/{generate-next-step-DCeS4LrJ.js → generate-next-step-DgK5BlBn.js} +2 -2
  60. package/dist/{generate-next-step-DCeS4LrJ.js.map → generate-next-step-DgK5BlBn.js.map} +1 -1
  61. package/dist/{generate-postgres-ddl-logic-4eUP4t8w.js → generate-postgres-ddl-logic-DPl1oH_z.js} +4 -4
  62. package/dist/{generate-postgres-ddl-logic-4eUP4t8w.js.map → generate-postgres-ddl-logic-DPl1oH_z.js.map} +1 -1
  63. package/dist/generated-schema-diff-eZCklRZQ.js +1025 -0
  64. package/dist/generated-schema-diff-eZCklRZQ.js.map +1 -0
  65. package/dist/{generated-schema-staleness-FlxM2i4i.js → generated-schema-staleness-BvNF3i-s.js} +2 -2
  66. package/dist/{generated-schema-staleness-FlxM2i4i.js.map → generated-schema-staleness-BvNF3i-s.js.map} +1 -1
  67. package/dist/history/HistoryService.d.ts +7 -0
  68. package/dist/index.d.ts +21 -0
  69. package/dist/index.es.js +288 -11
  70. package/dist/index.es.js.map +1 -1
  71. package/dist/{introspect-db-logic-CI5CU_n0.js → introspect-db-logic-DgQVzccW.js} +2 -2
  72. package/dist/{introspect-db-logic-CI5CU_n0.js.map → introspect-db-logic-DgQVzccW.js.map} +1 -1
  73. package/dist/{rls-bootstrap-sql-Bd-hJk08.js → migrate-baseline-B-2Ef4Mv.js} +718 -41
  74. package/dist/migrate-baseline-B-2Ef4Mv.js.map +1 -0
  75. package/dist/migrate-policy-stamps-BQtFHApx.js +89 -0
  76. package/dist/migrate-policy-stamps-BQtFHApx.js.map +1 -0
  77. package/dist/{open-rebase-BKA7Nyoe.js → open-rebase-C8jQ6s5a.js} +324 -1047
  78. package/dist/open-rebase-C8jQ6s5a.js.map +1 -0
  79. package/dist/open-rebase.d.ts +9 -1
  80. package/dist/{pg-error-utils-Bv5n2PLn.js → pg-error-utils-DhiUTlVx.js} +2 -2
  81. package/dist/{pg-error-utils-Bv5n2PLn.js.map → pg-error-utils-DhiUTlVx.js.map} +1 -1
  82. package/dist/{plan-schema-CXOucCw-.js → plan-schema-Czf3q4-Q.js} +4 -4
  83. package/dist/{plan-schema-CXOucCw-.js.map → plan-schema-Czf3q4-Q.js.map} +1 -1
  84. package/dist/{policy-drift-vm0BcvcE.js → policy-drift-X4A-xAzv.js} +3 -3
  85. package/dist/{policy-drift-vm0BcvcE.js.map → policy-drift-X4A-xAzv.js.map} +1 -1
  86. package/dist/pool-disconnects.d.ts +28 -0
  87. package/dist/{push-index-prebuild-DIequ4bV.js → push-index-prebuild-UTvB5pqH.js} +4 -4
  88. package/dist/{push-index-prebuild-DIequ4bV.js.map → push-index-prebuild-UTvB5pqH.js.map} +1 -1
  89. package/dist/push-kept-defaults-BGOlOqRQ.js +137 -0
  90. package/dist/push-kept-defaults-BGOlOqRQ.js.map +1 -0
  91. package/dist/{push-legacy-renames-BqJut4F3.js → push-legacy-renames-BwaKi8xF.js} +4 -4
  92. package/dist/{push-legacy-renames-BqJut4F3.js.map → push-legacy-renames-BwaKi8xF.js.map} +1 -1
  93. package/dist/{push-policy-plan-CvX8hiPb.js → push-policy-plan-DQ2tWceD.js} +5 -5
  94. package/dist/{push-policy-plan-CvX8hiPb.js.map → push-policy-plan-DQ2tWceD.js.map} +1 -1
  95. package/dist/{render-ddl-CQNwZdse.js → render-ddl-4v88y-Gv.js} +4 -4
  96. package/dist/{render-ddl-CQNwZdse.js.map → render-ddl-4v88y-Gv.js.map} +1 -1
  97. package/dist/{rls-enforcement-D7P4-ZYX.js → rls-enforcement-BOHuHVlc.js} +43 -4
  98. package/dist/rls-enforcement-BOHuHVlc.js.map +1 -0
  99. package/dist/schema/destructive-sql.d.ts +16 -0
  100. package/dist/schema/doctor-cli.js +5 -5
  101. package/dist/schema/doctor.d.ts +20 -2
  102. package/dist/schema/ensure-collection-policies.d.ts +4 -1
  103. package/dist/schema/generate-drizzle-schema.js +1 -1
  104. package/dist/schema/generate-postgres-ddl.js +2 -2
  105. package/dist/schema/generated-schema-diff.d.ts +21 -0
  106. package/dist/schema/introspect-db.js +5 -6
  107. package/dist/schema/introspect-db.js.map +1 -1
  108. package/dist/schema/migrate-policy-stamps.d.ts +23 -0
  109. package/dist/schema/migration-freshness.d.ts +69 -0
  110. package/dist/schema/push-kept-defaults.d.ts +57 -0
  111. package/dist/schema/push-policy-plan.d.ts +5 -0
  112. package/dist/schema/rls-bootstrap-sql.d.ts +47 -10
  113. package/dist/security/rls-enforcement.d.ts +18 -0
  114. package/dist/services/BranchService.d.ts +20 -2
  115. package/dist/services/FetchService.d.ts +12 -0
  116. package/dist/services/channel-presence.d.ts +3 -1
  117. package/dist/services/nested-path.d.ts +16 -0
  118. package/dist/services/pg-notify-listener.d.ts +2 -0
  119. package/dist/services/realtimeService.d.ts +18 -1
  120. package/dist/{source-Bv5KPeIx.js → source-fZb92pN8.js} +2 -2
  121. package/dist/{source-Bv5KPeIx.js.map → source-fZb92pN8.js.map} +1 -1
  122. package/dist/{vector-index-BFhyEaiz.js → vector-index-DsQ3V2d2.js} +2 -2
  123. package/dist/{vector-index-BFhyEaiz.js.map → vector-index-DsQ3V2d2.js.map} +1 -1
  124. package/dist/{websocket-MC0zTBar.js → websocket-CKYc3V4N.js} +56 -14
  125. package/dist/websocket-CKYc3V4N.js.map +1 -0
  126. package/package.json +7 -7
  127. package/dist/BranchService-iXXZeVYD.js.map +0 -1
  128. package/dist/backup-cli-B2CAn9fR.js +0 -647
  129. package/dist/backup-cli-B2CAn9fR.js.map +0 -1
  130. package/dist/backup-service-Bb39plam.js.map +0 -1
  131. package/dist/cli-console-DQ_K-sdM.js.map +0 -1
  132. package/dist/cli-errors-DwQnNATs.js.map +0 -1
  133. package/dist/cli-flags-D-b0qL9T.js +0 -206
  134. package/dist/cli-flags-D-b0qL9T.js.map +0 -1
  135. package/dist/collections-schema-version-T6cGvrDi.js.map +0 -1
  136. package/dist/connection-C938nR3E.js.map +0 -1
  137. package/dist/databasePoolManager-Yqdw14wY.js.map +0 -1
  138. package/dist/doctor-DvJH-IQG.js.map +0 -1
  139. package/dist/ensure-collection-policies-CCqayoUz.js.map +0 -1
  140. package/dist/open-rebase-BKA7Nyoe.js.map +0 -1
  141. package/dist/rls-bootstrap-sql-Bd-hJk08.js.map +0 -1
  142. package/dist/rls-enforcement-D7P4-ZYX.js.map +0 -1
  143. package/dist/rolldown-runtime-V7rFbMRe.js +0 -39
  144. package/dist/websocket-MC0zTBar.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backup-cli-PoRG-zEq.js","names":[],"sources":["../src/backup/pg-tools.ts","../src/backup/retention.ts","../src/backup/pg-binary.ts","../src/backup/backup-logic.ts","../src/backup/backup-service.ts","../src/backup/backup-cli.ts"],"sourcesContent":["/**\n * Pure helpers for the backup/restore commands.\n *\n * Everything in this file is side-effect free so it can be unit-tested\n * without a live Postgres server, matching the constraint that CI must\n * not require a database.\n */\n\nimport { forLibpq } from \"../utils/connection-string\";\n\n/**\n * A parsed backup destination. `--out` (and the scheduled-backup config)\n * accepts either a local filesystem path or an object-storage URL.\n */\nexport type BackupDestination =\n | { kind: \"local\"; path: string }\n | { kind: \"s3\"; bucket: string; prefix: string }\n | { kind: \"gcs\"; bucket: string; prefix: string };\n\n/**\n * Extract the database name from a Postgres connection string.\n * Returns `null` when the URL has no database path (e.g. bare host).\n */\nexport function parseDbNameFromUrl(connectionString: string): string | null {\n try {\n const parsed = new URL(connectionString);\n const name = parsed.pathname.replace(/^\\//, \"\").trim();\n return name.length > 0 ? name : null;\n } catch {\n // Fall back to a permissive regex for non-URL DSNs.\n const match = connectionString.match(/\\/([^/?]+)(\\?|$)/);\n return match && match[1] ? match[1] : null;\n }\n}\n\n/**\n * Swap the database name in a connection string, preserving credentials,\n * host, port and query params. Used by `--target-db` / `--create-db` so a\n * restore can target a fresh database instead of clobbering the live one.\n */\nexport function withDatabaseName(connectionString: string, dbName: string): string {\n try {\n const parsed = new URL(connectionString);\n parsed.pathname = `/${dbName}`;\n return parsed.toString();\n } catch {\n return connectionString.replace(/\\/([^/?]+)(\\?|$)/, `/${dbName}$2`);\n }\n}\n\n/**\n * Parse the major version out of `pg_dump --version` / `pg_restore --version`\n * output, e.g. `\"pg_dump (PostgreSQL) 16.2\"` → `16`. Handles the pre-10\n * `9.6.x` scheme (returns `9`) and beta strings like `\"17beta1\"`.\n */\nexport function parsePgToolMajor(versionOutput: string): number | null {\n const match = versionOutput.match(/(\\d+)(?:\\.(\\d+))?/);\n if (!match) return null;\n const major = Number(match[1]);\n if (!Number.isFinite(major)) return null;\n // Postgres 9.x used the first two numbers as the major (9.6, 9.4…).\n if (major === 9 && match[2] !== undefined) {\n return 9;\n }\n return major;\n}\n\n/**\n * Convert `SELECT current_setting('server_version_num')` (e.g. `160002`)\n * into a major version (`16`). Also accepts pre-10 encodings like `90603`\n * → `9`.\n */\nexport function serverVersionNumToMajor(versionNum: number | string): number | null {\n const num = typeof versionNum === \"string\" ? Number(versionNum) : versionNum;\n if (!Number.isFinite(num) || num <= 0) return null;\n if (num < 100000) {\n // 9.x scheme: 90603 = 9.6.3\n return Math.floor(num / 10000);\n }\n return Math.floor(num / 10000);\n}\n\nexport interface VersionCompatibility {\n compatible: boolean;\n reason?: string;\n}\n\n/**\n * pg_dump / pg_restore must be **at least** as new as the server they talk\n * to. A newer client against an older server is supported; an older client\n * against a newer server is not and produces corrupt or rejected output.\n */\nexport function checkToolServerCompatibility(\n toolMajor: number | null,\n serverMajor: number | null\n): VersionCompatibility {\n if (toolMajor === null) {\n return { compatible: false, reason: \"Could not determine the client tool version.\" };\n }\n if (serverMajor === null) {\n return { compatible: false, reason: \"Could not determine the Postgres server version.\" };\n }\n if (toolMajor < serverMajor) {\n return {\n compatible: false,\n reason:\n `Client tool is Postgres ${toolMajor} but the server is Postgres ${serverMajor}. ` +\n `pg_dump/pg_restore must be the same major version as the server or newer. ` +\n `Install Postgres ${serverMajor} client tools.`\n };\n }\n return { compatible: true };\n}\n\n/**\n * Build a deterministic, sortable backup file name:\n * `rebase-<db>-<YYYYMMDD>T<HHMMSS>Z.dump`\n *\n * The UTC timestamp is embedded so retention pruning can recover the\n * creation time from the object key alone, without extra metadata.\n */\nexport function buildBackupFilename(dbName: string, date: Date = new Date()): string {\n const iso = date.toISOString(); // 2026-07-14T09:12:03.123Z\n const stamp = iso.replace(/\\.\\d+Z$/, \"Z\").replace(/[-:]/g, \"\");\n const safeDb = dbName.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n return `rebase-${safeDb}-${stamp}.dump`;\n}\n\n/**\n * Recover the creation timestamp encoded in a backup file name by\n * {@link buildBackupFilename}. Returns `null` for names that don't match,\n * so foreign objects in a shared prefix are never pruned.\n */\nexport function parseBackupTimestamp(fileName: string): Date | null {\n const base = fileName.split(\"/\").pop() ?? fileName;\n const match = base.match(/-(\\d{8})T(\\d{6})Z\\.dump$/);\n if (!match) return null;\n const [, ymd, hms] = match;\n const iso =\n `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}` +\n `T${hms.slice(0, 2)}:${hms.slice(2, 4)}:${hms.slice(4, 6)}Z`;\n const date = new Date(iso);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\n/**\n * Parse a destination string into a structured {@link BackupDestination}.\n * `s3://bucket/prefix` and `gs://bucket/prefix` map to object storage;\n * anything else is treated as a local path.\n */\nexport function parseBackupDestination(out: string): BackupDestination {\n const s3 = out.match(/^s3:\\/\\/([^/]+)\\/?(.*)$/);\n if (s3) {\n return { kind: \"s3\", bucket: s3[1], prefix: stripTrailingSlash(s3[2]) };\n }\n const gcs = out.match(/^gs:\\/\\/([^/]+)\\/?(.*)$/);\n if (gcs) {\n return { kind: \"gcs\", bucket: gcs[1], prefix: stripTrailingSlash(gcs[2]) };\n }\n return { kind: \"local\", path: out };\n}\n\nfunction stripTrailingSlash(s: string): string {\n return s.replace(/\\/+$/, \"\");\n}\n\n/**\n * Join a storage prefix and a file name without producing a leading or\n * doubled slash.\n */\nexport function joinStorageKey(prefix: string, fileName: string): string {\n const clean = prefix.replace(/^\\/+|\\/+$/g, \"\");\n return clean.length > 0 ? `${clean}/${fileName}` : fileName;\n}\n\n/**\n * The identity `pg_dump` reads rows as, when row security is left on.\n *\n * Not optional, and that is the whole design. `pg_dump --enable-row-security`\n * on its own is the dangerous command in this file: it turns the \"query would\n * be affected by row-level security policy\" *error* into a dump that exits 0\n * and is silently missing every row the dumping role's policies exclude. A\n * backup that looks fine and restores most of your data is worse than one that\n * refused to run.\n *\n * So the flag is unreachable without a subject to evaluate the policies\n * against. Rebase's generated policies read `app.uid` and `app.user_roles`;\n * supplying an admin role satisfies the `admin_full_access` rule and the dump\n * sees everything that rule sees.\n */\nexport interface RowSecurityIdentity {\n /** Written to `app.uid`. Any non-empty value — it is only an audit trail. */\n uid: string;\n /** Written to `app.user_roles`. Must include a role the policies admit. */\n roles: string[];\n}\n\n/**\n * `PGOPTIONS` carrying an identity, for a libpq tool that has no other way to\n * set a GUC.\n *\n * A backslash escape rather than quoting, which is what libpq's `-c` parsing\n * takes: a space inside a value ends the option otherwise, so a role list is\n * comma-joined and never spaced.\n */\nexport function buildRowSecurityPgOptions(identity: RowSecurityIdentity): string {\n const escape = (value: string) => value.replace(/([\\\\ ])/g, \"\\\\$1\");\n return [\n `-c app.uid=${escape(identity.uid)}`,\n `-c app.user_id=${escape(identity.uid)}`,\n `-c app.user_roles=${escape(identity.roles.join(\",\"))}`\n ].join(\" \");\n}\n\n/**\n * Assemble the `pg_dump` argument vector. Uses the custom format (`-Fc`),\n * which is compressed and restorable selectively via `pg_restore`.\n */\nexport function buildPgDumpArgs(opts: {\n connectionString: string;\n outFile: string;\n /** Extra schemas/tables to exclude, e.g. Atlas revision tables. */\n excludeSchemas?: string[];\n /** Number of parallel jobs (directory format only; ignored for -Fc). */\n noOwner?: boolean;\n /**\n * Dump with row security on, as this identity. Omit — which is the default\n * — and `pg_dump` errors rather than skipping rows it cannot see.\n */\n rowSecurity?: RowSecurityIdentity;\n}): string[] {\n const args = [\"--format=custom\", \"--no-password\", `--file=${opts.outFile}`];\n if (opts.noOwner) {\n args.push(\"--no-owner\");\n }\n if (opts.rowSecurity) {\n args.push(\"--enable-row-security\");\n }\n for (const schema of opts.excludeSchemas ?? []) {\n args.push(`--exclude-schema=${schema}`);\n }\n args.push(forLibpq(opts.connectionString));\n return args;\n}\n\n/**\n * Whether a `pg_dump` failure is the row-security one, and what to do about it.\n *\n * The error text names the table and nothing else, so the first read of it is\n * \"why would a backup be affected by RLS at all?\" — the answer being that the\n * dumping role is not the tables' owner and has no `BYPASSRLS`, which is the\n * normal state of the `postgres` user on Cloud SQL, RDS and every other managed\n * Postgres. Nothing about that is visible from the message.\n *\n * Returns `null` for any other failure, so the caller reports it unchanged.\n */\nexport function diagnoseRowSecurityDumpFailure(error: unknown): string | null {\n const text = [\n (error as { stderr?: unknown })?.stderr,\n (error as { message?: unknown })?.message\n ].map(part => (typeof part === \"string\" ? part : \"\")).join(\"\\n\");\n\n if (!/row-level security policy/i.test(text)) return null;\n\n const table = text.match(/for table \"([^\"]+)\"/)?.[1];\n\n return [\n `pg_dump cannot read ${table ? `\"${table}\"` : \"one of the tables\"} because row-level security applies to it.`,\n \"\",\n \" The dumping role is neither the table's owner nor `BYPASSRLS`, which is the normal\",\n \" state of the `postgres` user on Cloud SQL, RDS and other managed Postgres — there is\",\n \" no superuser to hand out.\",\n \"\",\n \" Two ways out:\",\n \"\",\n \" • Grant the dumping role BYPASSRLS, or make it the owner, and run this again. The\",\n \" dump then contains every row, which is what a backup should mean.\",\n \"\",\n \" • Re-run with --enable-row-security to dump as an admin subject instead. Rebase\",\n \" sets `app.uid`/`app.user_roles` so the generated `admin_full_access` policy\",\n \" admits the dump. Read the warning it prints: the result contains exactly the\",\n \" rows those policies admit, and any table whose policies do not include an\",\n \" admin rule comes out short — with no error.\",\n \"\",\n \" Do not reach for a bare `pg_dump --enable-row-security` by hand. Without the\",\n \" settings above it succeeds and silently omits rows.\"\n ].join(\"\\n\");\n}\n\n/**\n * Assemble the `pg_restore` argument vector for a custom-format dump.\n */\nexport function buildPgRestoreArgs(opts: {\n connectionString: string;\n inputFile: string;\n /** Drop objects before recreating them (destructive but idempotent). */\n clean?: boolean;\n /**\n * Abort on the first error instead of logging and continuing. Defaults\n * ON: a restore that silently skips failed GRANT/RLS statements (because\n * a role is missing) \"succeeds\" with RLS un-enforced — a security hole.\n * Fail loudly instead so the operator knows the restore is incomplete.\n */\n exitOnError?: boolean;\n noOwner?: boolean;\n}): string[] {\n const args = [\"--format=custom\", \"--no-password\", `--dbname=${forLibpq(opts.connectionString)}`];\n if (opts.clean) {\n args.push(\"--clean\", \"--if-exists\");\n }\n if (opts.noOwner) {\n args.push(\"--no-owner\");\n }\n // Default to --exit-on-error unless explicitly disabled.\n if (opts.exitOnError !== false) {\n args.push(\"--exit-on-error\");\n }\n args.push(opts.inputFile);\n return args;\n}\n\n/**\n * Assemble the `pg_restore --list` argument vector. Reading a dump's table\n * of contents parses the whole archive without touching a database, so it is\n * a cheap integrity check that the file isn't truncated or corrupt.\n */\nexport function buildPgRestoreListArgs(inputFile: string): string[] {\n return [\"--list\", inputFile];\n}\n\n/** The schemas and tables a dump creates, read off its table of contents. */\nexport interface DumpObjects {\n schemas: string[];\n tables: { schema: string; table: string }[];\n /**\n * Every relation it creates — tables, views, materialized views, foreign\n * tables and sequences — by schema and name: what `restore --clean` can\n * tell apart from what the target holds besides.\n */\n relations: { schema: string; name: string }[];\n /** Every function, procedure and aggregate it creates, by schema and name: an overloaded name once for each. */\n routines: { schema: string; name: string }[];\n /** Every type it creates — enum, composite, range — and every domain, by schema and name. */\n types: { schema: string; name: string }[];\n}\n\n/** `<id>; <catalog oid> <oid> <description> <namespace> <tag…> <owner>`, the shape of a TOC entry. */\nconst TOC_ENTRY = /^\\d+;\\s+\\d+\\s+\\d+\\s+(SCHEMA|TABLE)\\s+(?!DATA\\s)(\\S+)\\s+(.+)\\s+(\\S+)$/;\n\n/** A TOC entry for a relation of any kind. `TABLE DATA`, `SEQUENCE SET` and `SEQUENCE OWNED BY` are not relations. */\nconst TOC_RELATION = /^\\d+;\\s+\\d+\\s+\\d+\\s+(?:FOREIGN TABLE|MATERIALIZED VIEW|TABLE|VIEW|SEQUENCE)\\s+(?!DATA\\s|SET\\s|OWNED BY\\s)(\\S+)\\s+(.+)\\s+(\\S+)$/;\n\n/** A function's TOC entry: its tag is the name and the argument types, `two(integer, text)`. */\nconst TOC_ROUTINE = /^\\d+;\\s+\\d+\\s+\\d+\\s+(?:FUNCTION|PROCEDURE|AGGREGATE)\\s+(\\S+)\\s+(.+?)\\(.*\\)\\s+\\S+$/;\n\n/** A type's or a domain's TOC entry. */\nconst TOC_TYPE = /^\\d+;\\s+\\d+\\s+\\d+\\s+(?:TYPE|DOMAIN)\\s+(\\S+)\\s+(.+)\\s+(\\S+)$/;\n\n/**\n * The schemas and tables in `pg_restore --list` output: the objects a\n * restore without `--clean` fails on when the target already has them.\n *\n * A TOC line ends in the object's owner, after its namespace and its name;\n * a schema's namespace is `-`. The name is what lies between the two, so a\n * name with a space in it (`Odd Name`) reads whole. `TABLE DATA` and every\n * other kind of entry are not objects of their own here. Its relations,\n * functions and types are read too, for what `restore --clean` would drop\n * that the dump does not hold (`findCleanExtras`).\n */\nexport function parseDumpObjects(list: string): DumpObjects {\n const objects: DumpObjects = { schemas: [], tables: [], relations: [], routines: [], types: [] };\n for (const line of list.split(\"\\n\")) {\n const trimmed = line.trim();\n const relation = TOC_RELATION.exec(trimmed);\n if (relation) objects.relations.push({ schema: relation[1], name: relation[2] });\n const routine = TOC_ROUTINE.exec(trimmed);\n if (routine) objects.routines.push({ schema: routine[1], name: routine[2] });\n const type = TOC_TYPE.exec(trimmed);\n if (type) objects.types.push({ schema: type[1], name: type[2] });\n const entry = TOC_ENTRY.exec(trimmed);\n if (!entry) continue;\n const [, kind, namespace, name] = entry;\n if (kind === \"SCHEMA\") objects.schemas.push(name);\n else objects.tables.push({ schema: namespace, table: name });\n }\n return objects;\n}\n\n/** A Postgres identifier, double-quoted. */\nfunction quoteIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\n/**\n * How long `restore --clean` waits for a lock before it gives up.\n *\n * A `rebase dev` serving from the database holds connections, and one inside a\n * transaction would otherwise make the restore wait without a word. The dump's\n * own script sets `lock_timeout = 0` after this, for the objects it creates.\n */\nexport const CLEAN_LOCK_TIMEOUT = \"15s\";\n\n/**\n * What `restore --clean` runs first, in the transaction the restore runs in:\n * every schema the dump creates, dropped with `CASCADE`, and every table it\n * creates in a schema it does not (`public`), the same.\n *\n * `CASCADE`, which `pg_restore --clean` never uses: a table the backup lacks\n * in one of its schemas — `rebase.atlas_schema_revisions` from `rebase db\n * migrate`, a table a newer runtime added — is exactly what stopped its plain\n * `DROP SCHEMA rebase`, and a table that references one of the backup's is what\n * stops a plain `DROP TABLE`. The dump's script follows, with its own `DROP …\n * IF EXISTS` for everything else it creates.\n */\nexport function cleanRestorePrelude(objects: DumpObjects): string[] {\n const schemas = objects.schemas.filter((schema) => schema !== \"public\");\n const dropped = new Set(schemas);\n const tables = objects.tables.filter((table) => !dropped.has(table.schema));\n return [\n \"SET client_min_messages = warning\",\n `SET lock_timeout = '${CLEAN_LOCK_TIMEOUT}'`,\n ...schemas.map((schema) => `DROP SCHEMA IF EXISTS ${quoteIdentifier(schema)} CASCADE`),\n ...tables.map((table) => `DROP TABLE IF EXISTS ${quoteIdentifier(table.schema)}.${quoteIdentifier(table.table)} CASCADE`)\n ];\n}\n\n/**\n * `pg_restore` writing the dump as a SQL script on stdout, with the `DROP …\n * IF EXISTS` that `--clean` adds, for `psql` to run. See {@link buildPsqlScriptArgs}.\n */\nexport function buildPgRestoreScriptArgs(opts: { inputFile: string; noOwner?: boolean }): string[] {\n return [\n \"--format=custom\",\n \"--clean\",\n \"--if-exists\",\n ...(opts.noOwner ? [\"--no-owner\"] : []),\n \"--file=-\",\n opts.inputFile\n ];\n}\n\n/**\n * `psql` running a script read from stdin, stopping at its first error.\n *\n * `-X`, so no `.psqlrc` changes what runs; `-q`, so it prints errors and\n * warnings, not a command tag per statement. The transaction is the script's\n * own: `restore --clean` writes the `BEGIN`, and the `COMMIT` only once\n * `pg_restore` has written the whole dump.\n */\nexport function buildPsqlScriptArgs(connectionString: string): string[] {\n return [\"-X\", \"-q\", \"--no-password\", \"-v\", \"ON_ERROR_STOP=1\", `--dbname=${forLibpq(connectionString)}`, \"--file=-\"];\n}\n\n/**\n * Assemble the `pg_dumpall --globals-only` argument vector. Roles (and other\n * cluster-wide objects) live outside any single database, so a per-database\n * `pg_dump` omits them. Without the `rebase_user` role the RLS GRANT\n * statements in the main dump fail on restore and RLS is silently lost — so\n * every backup captures the globals into a sidecar `.globals.sql`.\n *\n * `--no-role-passwords` keeps role secrets out of the artifact (backups may\n * be shipped off-box); roles are recreated password-less and re-secured by\n * the operator.\n */\nexport function buildPgDumpallGlobalsArgs(opts: {\n connectionString: string;\n outFile: string;\n}): string[] {\n return [\n \"--globals-only\",\n \"--no-role-passwords\",\n \"--no-password\",\n `--file=${opts.outFile}`,\n `--dbname=${forLibpq(opts.connectionString)}`\n ];\n}\n\n/**\n * Derive the globals sidecar path/key for a given `.dump` file. Keeps the\n * two artifacts adjacent so listing, uploading and pruning can find one from\n * the other. A name that doesn't end in `.dump` is returned unchanged with a\n * `.globals.sql` suffix appended.\n */\nexport function globalsFileForDump(dumpPath: string): string {\n return dumpPath.endsWith(\".dump\")\n ? dumpPath.slice(0, -\".dump\".length) + \".globals.sql\"\n : dumpPath + \".globals.sql\";\n}\n\n/**\n * Split a `pg_dumpall --globals-only` script into individual statements.\n * Used when replaying globals on restore so each `CREATE ROLE` / `GRANT`\n * can run independently and a benign \"role already exists\" on one doesn't\n * abort the rest. Drops `--` comment lines and blank statements.\n */\nexport function splitGlobalsStatements(sql: string): string[] {\n const withoutComments = sql\n .split(\"\\n\")\n // `--` comments, and psql meta-commands. pg_dumpall 15+ wraps its output\n // in `\\restrict <token>` / `\\unrestrict <token>`, which are instructions\n // to psql, not SQL. This replay sends statements over a connection\n // instead, so they arrived at the server as `\\restrict …` and came back\n // as `syntax error at or near \"\\\"` — reported to the user as two skipped\n // globals per restore, which reads like roles failed to apply when\n // nothing did. They carry no state worth replaying: dropping them is\n // exactly what a SQL-level consumer should do.\n .filter((line) => {\n const trimmed = line.trim();\n return !trimmed.startsWith(\"--\") && !trimmed.startsWith(\"\\\\\");\n })\n .join(\"\\n\");\n return withoutComments\n .split(\";\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n}\n\n/**\n * Resolve the Postgres connection string the backup commands should use,\n * mirroring the precedence the branch command already relies on.\n */\nexport function resolveConnectionString(\n env: Record<string, string | undefined>\n): string | null {\n return env.DATABASE_URL || env.ADMIN_CONNECTION_STRING || null;\n}\n","/**\n * Retention pruning for scheduled backups. Pure logic — no I/O — so it can\n * be exhaustively unit-tested without touching a storage backend.\n */\nimport { parseBackupTimestamp } from \"./pg-tools\";\n\nexport interface BackupObject {\n /** Storage key / file name. */\n key: string;\n /**\n * Creation time. Optional — when absent it is recovered from the\n * timestamp encoded in the key by `buildBackupFilename`.\n */\n createdAt?: Date;\n /**\n * Size on disk, when the lister knows it (local destinations always do).\n *\n * Reported so an empty artifact cannot masquerade as a backup in\n * `rebase db backups list`. Deliberately NOT consulted by\n * {@link selectBackupsToPrune}: retention decides by age, and a rule that\n * silently skipped small files would make a genuinely tiny dump immortal.\n * Visibility is the fix here; the artifacts themselves are now removed at\n * the point of failure by `discardPartialDump`.\n */\n sizeBytes?: number;\n}\n\nexport interface RetentionOptions {\n /** Delete backups older than this many days. `0`/negative disables age pruning. */\n retentionDays?: number;\n /**\n * Always keep at least this many of the most recent backups, even if\n * they are older than `retentionDays`. Guards against wiping every\n * backup after a long outage. Default: 0 (no minimum).\n */\n keepMinimum?: number;\n /** Reference \"now\" — injectable for deterministic tests. */\n now?: Date;\n}\n\n/**\n * Decide which backups to delete under the given retention policy.\n *\n * Rules, applied in order:\n * 1. Objects whose key isn't a recognised rebase backup (no parseable\n * timestamp and no `createdAt`) are never selected — foreign files in a\n * shared bucket are left untouched.\n * 2. The `keepMinimum` newest backups are always retained.\n * 3. Of the remainder, any older than `retentionDays` are selected for\n * deletion.\n *\n * Returns the keys to delete, oldest first.\n */\nexport function selectBackupsToPrune(\n backups: BackupObject[],\n options: RetentionOptions\n): string[] {\n const retentionDays = options.retentionDays ?? 0;\n const keepMinimum = Math.max(0, options.keepMinimum ?? 0);\n const now = options.now ?? new Date();\n\n if (retentionDays <= 0) {\n return [];\n }\n\n // Resolve a timestamp for every object; drop the ones we can't date.\n const dated = backups\n .map((b) => {\n const createdAt = b.createdAt ?? parseBackupTimestamp(b.key);\n return createdAt ? { key: b.key, createdAt } : null;\n })\n .filter((b): b is { key: string; createdAt: Date } => b !== null);\n\n // Newest first so the first `keepMinimum` are the protected ones.\n dated.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n const cutoff = now.getTime() - retentionDays * 24 * 60 * 60 * 1000;\n\n const toDelete = dated\n .slice(keepMinimum)\n .filter((b) => b.createdAt.getTime() < cutoff);\n\n // Return oldest first for predictable, readable logs.\n toDelete.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n return toDelete.map((b) => b.key);\n}\n","/**\n * Where the PostgreSQL client tools are, without spawning them.\n *\n * Kept apart from `backup-service.ts`, which pulls in `execa` (ESM-only), so\n * `createBackupCron` can check for the tools when it is registered.\n */\nimport fs from \"fs\";\nimport { resolveLocalBin } from \"../cli-helpers\";\n\nexport type PgTool = \"pg_dump\" | \"pg_restore\" | \"pg_dumpall\" | \"psql\";\n\nconst OVERRIDE_VARIABLE: Record<PgTool, string> = {\n pg_dump: \"PG_DUMP_PATH\",\n pg_restore: \"PG_RESTORE_PATH\",\n pg_dumpall: \"PG_DUMPALL_PATH\",\n psql: \"PSQL_PATH\"\n};\n\n/** The variable that points at `tool` when it is not on the PATH. */\nexport function pgToolVariable(tool: PgTool): string {\n return OVERRIDE_VARIABLE[tool];\n}\n\n/** Locate `pg_dump` / `pg_restore` / `pg_dumpall` / `psql`, honouring an env override. */\nexport function resolvePgBinary(\n tool: PgTool,\n env: Record<string, string | undefined> = process.env\n): string | null {\n const override = env[OVERRIDE_VARIABLE[tool]];\n if (override && fs.existsSync(override)) return override;\n return resolveLocalBin(tool);\n}\n","/**\n * Pure-ish orchestration for the backup/restore paths, kept free of `execa`\n * and `pg` value imports so it can be unit-tested under jest (the impure\n * edges — spawning processes, opening connections — live in\n * `backup-service.ts`, which is vitest/runtime only).\n *\n * The functions here take their side-effecting dependency as an argument\n * (a statement runner, an object deleter) so tests can inject fakes.\n */\nimport { globalsFileForDump, splitGlobalsStatements } from \"./pg-tools\";\n\n/**\n * Replay a `pg_dumpall --globals-only` script one statement at a time,\n * tolerating per-statement failures. On a same-cluster restore the roles\n * usually already exist (`CREATE ROLE` → \"already exists\") and on a managed\n * provider an `ALTER ROLE <superuser>` may be refused; neither should abort\n * recreation of the roles that *are* missing. Returns how many statements\n * applied vs were skipped.\n *\n * `runStatement` executes one SQL statement and rejects on error.\n */\nexport async function applyGlobalsWith(\n runStatement: (sql: string) => Promise<void>,\n globalsSql: string,\n log: (message: string) => void = () => {}\n): Promise<{ applied: number; skipped: number }> {\n let applied = 0;\n let skipped = 0;\n for (const statement of splitGlobalsStatements(globalsSql)) {\n try {\n await runStatement(statement);\n applied++;\n } catch (err) {\n skipped++;\n const firstLine = statement.split(\"\\n\")[0].slice(0, 80);\n log(` • Skipped global: ${firstLine} (${err instanceof Error ? err.message : String(err)})`);\n }\n }\n return { applied, skipped };\n}\n\n/**\n * Delete each pruned dump together with its `.globals.sql` roles sidecar, so\n * pruning never orphans the roles file. The sidecar is best-effort — older\n * backups predate it, so a missing-sidecar failure is swallowed while a\n * failure deleting the dump itself propagates.\n *\n * `deleteObject` removes one key and rejects if it cannot (e.g. not found).\n */\nexport async function pruneWith(\n keys: string[],\n deleteObject: (key: string) => Promise<void>\n): Promise<void> {\n for (const key of keys) {\n await deleteObject(key);\n try {\n await deleteObject(globalsFileForDump(key));\n } catch {\n // Sidecar may not exist for older backups — ignore.\n }\n }\n}\n\n/**\n * Remove a dump artifact abandoned by a failed tool run.\n *\n * `pg_dump` creates its `--file=` target before it finishes connecting, so any\n * failure — a URL libpq rejects, a dropped connection, a full disk — leaves a\n * 0-byte file behind. That corpse is not inert: `rebase db backups list` used\n * to show it as an ordinary entry, and `selectBackupsToPrune` ranks by\n * timestamp alone, so it occupies a protected `keepMinimum` slot and can push\n * a real backup out of retention.\n *\n * Best-effort on purpose: the caller is already throwing, and a failed unlink\n * must not replace the real diagnosis with an ENOENT/EPERM from the cleanup.\n *\n * Lives here rather than in `backup-service.ts` for the reason at the top of\n * this file — that module's top-level `execa` import makes it unloadable under\n * jest, so anything placed there cannot be unit-tested.\n *\n * `remove` deletes one file and throws if it cannot; `exists` reports presence.\n */\nexport function discardPartialDumpWith(\n exists: (file: string) => boolean,\n remove: (file: string) => void,\n file: string\n): void {\n try {\n if (exists(file)) remove(file);\n } catch {\n // Ignored: see above.\n }\n}\n","/**\n * Backup / restore orchestration: thin, well-typed wrappers around\n * `pg_dump` and `pg_restore`, plus binary detection, version pre-flight,\n * and upload/prune against a storage backend.\n *\n * The pure argument- and policy-logic lives in `pg-tools.ts` and\n * `retention.ts`; this module is the impure edge (spawns processes, talks\n * to Postgres and storage) and is intentionally kept small.\n */\nimport fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport type { StorageController } from \"@rebasepro/server\";\nimport { pgToolVariable, resolvePgBinary } from \"./pg-binary\";\nimport {\n BackupDestination,\n buildBackupFilename,\n buildPgDumpArgs,\n buildPgDumpallGlobalsArgs,\n buildRowSecurityPgOptions,\n diagnoseRowSecurityDumpFailure,\n type RowSecurityIdentity,\n buildPgRestoreArgs,\n buildPgRestoreListArgs,\n buildPgRestoreScriptArgs,\n buildPsqlScriptArgs,\n cleanRestorePrelude,\n checkToolServerCompatibility,\n type DumpObjects,\n globalsFileForDump,\n joinStorageKey,\n parsePgToolMajor,\n parseBackupTimestamp,\n parseDumpObjects,\n serverVersionNumToMajor,\n VersionCompatibility\n} from \"./pg-tools\";\nimport { BackupObject, RetentionOptions, selectBackupsToPrune } from \"./retention\";\nimport { applyGlobalsWith, discardPartialDumpWith, pruneWith } from \"./backup-logic\";\nimport { splitPassword } from \"../utils/connection-string\";\n\n/**\n * How a libpq tool is invoked for a connection string: the URL its command\n * line carries, and the environment it runs in.\n *\n * The password goes in `PGPASSWORD`, never on the command line, where every\n * process listing could read it and every failure printed it back (execa's\n * error repeats the command). See {@link splitPassword}.\n */\nfunction libpqInvocation(\n connectionString: string,\n env: Record<string, string | undefined>\n): { connectionString: string; env: Record<string, string> } {\n const split = splitPassword(connectionString);\n const toolEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (value !== undefined) toolEnv[key] = value;\n }\n if (split.password !== null) toolEnv.PGPASSWORD = split.password;\n return { connectionString: split.connectionString, env: toolEnv };\n}\n\n/**\n * Remove a dump artifact abandoned by a failed tool run. See\n * {@link discardPartialDumpWith} for why this exists and why the logic lives\n * in the execa-free module.\n */\nexport function discardPartialDump(file: string): void {\n discardPartialDumpWith(\n (f) => fs.existsSync(f),\n (f) => fs.unlinkSync(f),\n file\n );\n}\n\nexport class BackupToolError extends Error {\n constructor(message: string, readonly hint?: string) {\n super(message);\n this.name = \"BackupToolError\";\n }\n}\n\nexport { resolvePgBinary };\n\n/** Run `<bin> --version` and extract the major version. */\nexport async function detectToolMajor(bin: string): Promise<number | null> {\n try {\n const { stdout } = await execa(bin, [\"--version\"]);\n return parsePgToolMajor(stdout);\n } catch {\n return null;\n }\n}\n\n/** Query the server for its major version via `server_version_num`. */\nexport async function getServerVersionMajor(connectionString: string): Promise<number | null> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n await client.connect();\n try {\n const res = await client.query(\"SHOW server_version_num\");\n const raw = res.rows?.[0]?.server_version_num;\n return serverVersionNumToMajor(raw);\n } finally {\n await client.end();\n }\n}\n\n/** PGlite names itself in `version()`: `PostgreSQL 18.3 (PGlite 0.5.6) on wasm32-…`. */\nconst SHARED_SESSION_ENGINE = /\\(PGlite\\b/i;\n\n/**\n * Put back what a client tool left set on a database that is one session\n * every connection shares, and do nothing on any other.\n *\n * The managed development database is PGlite: one session behind a socket\n * server, so what `pg_dump` sets for itself — `search_path` emptied,\n * `row_security` off, `PREPARE dumpEnumType …` — stays set for every client\n * after it, a running `rebase dev` included. One `rebase db backup` there left\n * every API request answering 500 \"table does not exist\", a restart did not\n * help (the database outlives `rebase dev`), and the next backup failed on\n * `prepared statement \"dumpenumtype\" already exists`.\n *\n * `RESET ALL` and `DEALLOCATE ALL`, not `DISCARD ALL`: that would also drop\n * the `LISTEN` a running `rebase dev`'s realtime holds on the same session.\n * Best effort: it runs after the tool, whose own outcome is what the caller\n * reports.\n */\nexport async function resetSharedSession(connectionString: string): Promise<void> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString, connectionTimeoutMillis: 10_000, query_timeout: 15_000 });\n client.on(\"error\", () => undefined);\n try {\n await client.connect();\n const { rows } = await client.query<{ version: string }>(\"SELECT version() AS version\");\n if (!SHARED_SESSION_ENGINE.test(rows[0]?.version ?? \"\")) return;\n await client.query(\"RESET ALL\");\n await client.query(\"DEALLOCATE ALL\");\n } catch {\n // Nothing to add to the tool's own result; see above.\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n\nexport interface PreflightResult extends VersionCompatibility {\n bin: string;\n toolMajor: number | null;\n serverMajor: number | null;\n}\n\n/**\n * Verify the requested client tool exists and its major version is\n * compatible with the live server. Throws {@link BackupToolError} — with a\n * doctor-style hint — when the binary is missing.\n */\nexport async function preflight(\n tool: \"pg_dump\" | \"pg_restore\",\n connectionString: string,\n env: Record<string, string | undefined> = process.env\n): Promise<PreflightResult> {\n const bin = resolvePgBinary(tool, env);\n if (!bin) {\n throw new BackupToolError(\n `Could not find the '${tool}' binary.`,\n `Install the PostgreSQL client tools (e.g. 'brew install libpq' or 'apt-get install postgresql-client'), ` +\n `or set ${tool === \"pg_dump\" ? \"PG_DUMP_PATH\" : \"PG_RESTORE_PATH\"} to its full path.`\n );\n }\n const [toolMajor, serverMajor] = await Promise.all([\n detectToolMajor(bin),\n getServerVersionMajor(connectionString)\n ]);\n const compat = checkToolServerCompatibility(toolMajor, serverMajor);\n return { bin, toolMajor, serverMajor, ...compat };\n}\n\nexport interface BackupResult {\n /** Absolute path of the produced dump file on local disk. */\n localFile: string;\n fileName: string;\n sizeBytes: number;\n /**\n * Absolute path of the `.globals.sql` sidecar holding cluster-wide roles\n * (present unless globals capture was disabled or unavailable).\n */\n globalsFile?: string;\n globalsSizeBytes?: number;\n}\n\n/**\n * Produce a custom-format dump on local disk. When `outDir` is omitted the\n * file is written to the OS temp directory (used by the upload path, which\n * cleans it up afterwards).\n *\n * Alongside the `-Fc` dump it writes a `<name>.globals.sql` sidecar via\n * `pg_dumpall --globals-only` so the roles the dump's GRANT/RLS statements\n * depend on can be recreated on restore. Set `includeGlobals: false` to skip\n * it (e.g. when the caller has no privilege to read cluster globals).\n */\nexport async function createDump(opts: {\n connectionString: string;\n dbName: string;\n outDir?: string;\n fileName?: string;\n excludeSchemas?: string[];\n noOwner?: boolean;\n inheritStdio?: boolean;\n includeGlobals?: boolean;\n env?: Record<string, string | undefined>;\n /**\n * Dump with row security left on, reading as this identity.\n *\n * The escape hatch for a managed Postgres, where the dumping role owns\n * nothing and has no `BYPASSRLS`. Off by default, and deliberately so: with\n * row security on, `pg_dump` stops erroring on rows it cannot see and\n * simply omits them. See {@link RowSecurityIdentity}.\n */\n rowSecurity?: RowSecurityIdentity;\n}): Promise<BackupResult> {\n const env = opts.env ?? process.env;\n const bin = resolvePgBinary(\"pg_dump\", env);\n if (!bin) {\n throw new BackupToolError(\n \"Could not find the 'pg_dump' binary.\",\n \"Install the PostgreSQL client tools or set PG_DUMP_PATH.\"\n );\n }\n\n const fileName = opts.fileName ?? buildBackupFilename(opts.dbName);\n const outDir = opts.outDir ?? fs.mkdtempSync(path.join(os.tmpdir(), \"rebase-backup-\"));\n fs.mkdirSync(outDir, { recursive: true });\n const localFile = path.join(outDir, fileName);\n createOwnerOnly(localFile);\n\n const tool = libpqInvocation(opts.connectionString, env);\n const args = buildPgDumpArgs({\n connectionString: tool.connectionString,\n outFile: localFile,\n excludeSchemas: opts.excludeSchemas,\n noOwner: opts.noOwner,\n rowSecurity: opts.rowSecurity\n });\n\n // `PGOPTIONS` is the only way to set a GUC on a tool that takes no SQL.\n // Built from the same object that added `--enable-row-security`, so the\n // flag cannot travel without the identity that makes it safe.\n const dumpEnv: Record<string, string> = { ...tool.env };\n if (opts.rowSecurity) {\n dumpEnv.PGOPTIONS = [env.PGOPTIONS, buildRowSecurityPgOptions(opts.rowSecurity)]\n .filter(Boolean).join(\" \");\n }\n\n try {\n try {\n await execa(bin, args, {\n stdio: opts.inheritStdio ? \"inherit\" : \"pipe\",\n env: dumpEnv\n });\n } finally {\n await resetSharedSession(opts.connectionString);\n }\n } catch (error) {\n // pg_dump creates its `--file=` target before it finishes connecting,\n // so any failure here — a URL libpq rejects, a dropped connection, a\n // full disk — leaves a 0-byte file behind that nothing else removed.\n // That corpse is not inert: `rebase db backups list` shows it as an\n // ordinary entry, and `selectBackupsToPrune` ranks by timestamp alone,\n // so it occupies a protected `keepMinimum` slot and can push a real\n // backup out of retention. A missing backup is honest; an empty file\n // that reads as a backup is not.\n discardPartialDump(localFile);\n // The RLS failure names a table and no cause. Replace it with the\n // cause and the two ways out; anything else is re-thrown untouched.\n const diagnosis = diagnoseRowSecurityDumpFailure(error);\n if (!diagnosis) throw error;\n throw new BackupToolError(\n diagnosis,\n \"Run `rebase db backup --help` for the flag, and read what it says about partial dumps.\"\n );\n }\n\n const sizeBytes = fs.existsSync(localFile) ? fs.statSync(localFile).size : 0;\n\n const result: BackupResult = { localFile, fileName, sizeBytes };\n\n if (opts.includeGlobals !== false) {\n const dumpallBin = resolvePgBinary(\"pg_dumpall\", env);\n if (!dumpallBin) {\n throw new BackupToolError(\n \"Could not find the 'pg_dumpall' binary needed to capture cluster roles.\",\n \"Install the PostgreSQL client tools or set PG_DUMPALL_PATH. \" +\n \"To take a role-incomplete backup anyway, pass includeGlobals: false.\"\n );\n }\n const globalsFile = globalsFileForDump(localFile);\n createOwnerOnly(globalsFile);\n try {\n try {\n await execa(\n dumpallBin,\n buildPgDumpallGlobalsArgs({ connectionString: tool.connectionString, outFile: globalsFile }),\n { stdio: opts.inheritStdio ? \"inherit\" : \"pipe\", env: tool.env }\n );\n } finally {\n await resetSharedSession(opts.connectionString);\n }\n } catch (error) {\n // Same reasoning as the pg_dump catch above, and the dump goes with\n // it: the pair is uploaded and pruned together, so a dump whose\n // roles sidecar is missing restores without the roles its GRANT and\n // RLS statements need — the exact failure the sidecar exists to\n // prevent. Leaving half a pair on disk would look like a backup.\n discardPartialDump(globalsFile);\n discardPartialDump(localFile);\n throw error;\n }\n result.globalsFile = globalsFile;\n result.globalsSizeBytes = fs.existsSync(globalsFile) ? fs.statSync(globalsFile).size : 0;\n }\n\n return result;\n}\n\n/**\n * Create `file` empty and readable by its owner only, before a tool writes it.\n *\n * A dump holds every row, and the `.globals.sql` sidecar every role's password\n * hash. pg_dump and pg_dumpall create their `--file=` target with the\n * process's umask — 0644 on most machines, readable by every user — and keep\n * the mode of a file that is already there. Created 0600 first, the file is\n * never readable by anyone else, not even while the dump runs; chmod-ing it\n * afterwards would leave it open for as long as that takes. A file that\n * already existed is narrowed too.\n */\nfunction createOwnerOnly(file: string): void {\n fs.closeSync(fs.openSync(file, \"w\", 0o600));\n fs.chmodSync(file, 0o600);\n}\n\n/**\n * Cheap integrity check on a freshly written dump: it must be non-empty and\n * `pg_restore --list` must parse its table of contents without error. Used\n * before pruning older backups so a corrupt-but-exit-0 dump never becomes\n * the reason the last good backup is deleted.\n */\nexport async function validateDump(\n localFile: string,\n env: Record<string, string | undefined> = process.env\n): Promise<{ ok: boolean; reason?: string }> {\n if (!fs.existsSync(localFile)) {\n return { ok: false, reason: `Dump file does not exist: ${localFile}` };\n }\n if (fs.statSync(localFile).size === 0) {\n return { ok: false, reason: \"Dump file is empty (0 bytes).\" };\n }\n const bin = resolvePgBinary(\"pg_restore\", env);\n if (!bin) {\n // Can't verify without pg_restore; treat as inconclusive-but-fail so\n // pruning doesn't proceed on an unverified dump.\n return { ok: false, reason: \"Could not find 'pg_restore' to verify the dump.\" };\n }\n try {\n await execa(bin, buildPgRestoreListArgs(localFile), {\n stdio: \"pipe\",\n env: { ...(env as Record<string, string>) }\n });\n return { ok: true };\n } catch (err) {\n return { ok: false, reason: `pg_restore --list failed: ${err instanceof Error ? err.message : String(err)}` };\n }\n}\n\n/**\n * Replay a `pg_dumpall --globals-only` script to recreate cluster roles\n * before a restore, so the dump's GRANT/RLS statements (which reference\n * `rebase_user` and any owner roles) actually apply. Runs statement by\n * statement and tolerates per-statement failures — on a same-cluster restore\n * the roles usually already exist (`CREATE ROLE` → \"already exists\"), and on\n * a managed provider an `ALTER ROLE <superuser>` may be refused; neither\n * should abort role recreation. Returns how many statements applied vs were\n * skipped.\n */\nexport async function applyGlobals(\n connectionString: string,\n globalsSql: string,\n log: (message: string) => void = () => {}\n): Promise<{ applied: number; skipped: number }> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n await client.connect();\n try {\n return await applyGlobalsWith(\n async (sql) => { await client.query(sql); },\n globalsSql,\n log\n );\n } finally {\n await client.end();\n }\n}\n\n/**\n * Restore a custom-format dump into the database named by\n * `connectionString`. Destructive when `clean` is set (drops objects\n * first). Never called automatically — the CLI gates it behind explicit\n * confirmation.\n *\n * Runs with `--exit-on-error` by default: a restore that logs-and-continues\n * past a failed GRANT (because a role was missing) reports success with RLS\n * un-enforced. Callers should recreate roles first (see {@link applyGlobals})\n * and only set `exitOnError: false` deliberately.\n */\nexport async function restoreDump(opts: {\n connectionString: string;\n inputFile: string;\n clean?: boolean;\n noOwner?: boolean;\n exitOnError?: boolean;\n inheritStdio?: boolean;\n env?: Record<string, string | undefined>;\n}): Promise<void> {\n const env = opts.env ?? process.env;\n const bin = resolvePgBinary(\"pg_restore\", env);\n if (!bin) {\n throw new BackupToolError(\n \"Could not find the 'pg_restore' binary.\",\n \"Install the PostgreSQL client tools or set PG_RESTORE_PATH.\"\n );\n }\n const tool = libpqInvocation(opts.connectionString, env);\n const args = buildPgRestoreArgs({\n connectionString: tool.connectionString,\n inputFile: opts.inputFile,\n clean: opts.clean,\n noOwner: opts.noOwner,\n exitOnError: opts.exitOnError\n });\n try {\n await execa(bin, args, {\n stdio: opts.inheritStdio ? \"inherit\" : \"pipe\",\n env: tool.env\n });\n } finally {\n await resetSharedSession(opts.connectionString);\n }\n}\n\n/**\n * A `restore --clean` that stopped, and so was rolled back whole.\n *\n * `tool` is the one that stopped it: `pg_restore`, writing the dump's script,\n * or `psql`, running it. `lockTimeout` when what `psql` stopped on was the\n * wait for a lock — `CLEAN_LOCK_TIMEOUT` in `pg-tools.ts`.\n */\nexport class CleanRestoreFailed extends Error {\n constructor(\n readonly tool: \"pg_restore\" | \"psql\",\n readonly exitCode: number | undefined,\n readonly lockTimeout: boolean\n ) {\n super(`${tool} exited with code ${exitCode ?? \"unknown\"}`);\n this.name = \"CleanRestoreFailed\";\n }\n}\n\n/**\n * Restore a dump over what the database holds, as one transaction:\n * {@link cleanRestorePrelude} first, then the dump as `pg_restore` writes it\n * for `psql`, and the `COMMIT` only after the last of it.\n *\n * One unit, so it either replaces what the dump holds or changes nothing:\n * `pg_restore --clean` runs each statement on its own, so the drops it starts\n * with had all happened when a later one failed — and its plain `DROP SCHEMA\n * rebase` fails on any table the backup lacks, which left a database with\n * every table dropped and nothing restored. Here a failure anywhere —\n * `pg_restore` cannot read the archive, a statement fails, the connection\n * drops — ends the transaction without a `COMMIT`, and Postgres rolls it back.\n *\n * Throws {@link CleanRestoreFailed} when it did not commit.\n */\nexport async function restoreDumpReplacing(opts: {\n connectionString: string;\n inputFile: string;\n objects: DumpObjects;\n noOwner?: boolean;\n inheritStdio?: boolean;\n env?: Record<string, string | undefined>;\n}): Promise<void> {\n const env = opts.env ?? process.env;\n const restoreBin = resolvePgBinary(\"pg_restore\", env);\n const psqlBin = resolvePgBinary(\"psql\", env);\n if (!restoreBin || !psqlBin) {\n const tool = restoreBin ? \"psql\" : \"pg_restore\";\n throw new BackupToolError(\n `Could not find the '${tool}' binary${tool === \"psql\" ? \", which runs a --clean restore as one transaction\" : \"\"}.`,\n `Install the PostgreSQL client tools or set ${pgToolVariable(tool)}.`\n );\n }\n const tool = libpqInvocation(opts.connectionString, env);\n\n const script = execa(restoreBin, buildPgRestoreScriptArgs({ inputFile: opts.inputFile, noOwner: opts.noOwner }), {\n stdin: \"ignore\",\n stdout: \"pipe\",\n stderr: opts.inheritStdio ? \"inherit\" : \"ignore\",\n buffer: false,\n reject: false,\n env: tool.env\n });\n // stdout is the rows of the script's own `SELECT`s (`set_config`,\n // `setval`), which say nothing. stderr is shown as it arrives and kept, to\n // tell a lock timeout from anything else.\n const apply = execa(psqlBin, buildPsqlScriptArgs(tool.connectionString), {\n stdin: \"pipe\",\n stdout: \"ignore\",\n stderr: opts.inheritStdio ? [\"pipe\", \"inherit\"] : \"pipe\",\n reject: false,\n env: tool.env\n });\n\n const sink = apply.stdin;\n const source = script.stdout;\n if (!sink || !source) throw new BackupToolError(\"Could not connect pg_restore to psql.\");\n // psql stops reading at its first error, and the script behind it must not\n // wait on a pipe nobody drains.\n sink.on(\"error\", () => undefined);\n apply.once(\"exit\", () => {\n source.unpipe(sink);\n source.resume();\n script.kill();\n });\n\n sink.write([\"BEGIN\", ...cleanRestorePrelude(opts.objects)].map((statement) => `${statement};\\n`).join(\"\"));\n source.pipe(sink, { end: false });\n\n const written = await script;\n const committed = written.exitCode === 0 && sink.writable;\n sink.end(committed ? \"COMMIT;\\n\" : undefined);\n const applied = await apply;\n await resetSharedSession(opts.connectionString);\n\n if (applied.exitCode !== 0) {\n const stderr = typeof applied.stderr === \"string\" ? applied.stderr : \"\";\n throw new CleanRestoreFailed(\"psql\", applied.exitCode, /lock timeout/i.test(stderr));\n }\n if (!committed) throw new CleanRestoreFailed(\"pg_restore\", written.exitCode, false);\n}\n\n/**\n * What `restore --clean` drops that the backup does not hold, so it can say\n * so before it runs: what a schema the backup replaces whole holds that it has\n * no copy of — tables, views, sequences, functions, procedures, aggregates,\n * types and domains — and the views and foreign keys elsewhere that reference\n * one of the relations it replaces. As `<kind> <name>`.\n *\n * A function is matched by its name, so an overload the backup lacks beside\n * one it holds is not named. Sequences a column owns go with their table,\n * and what an extension owns with the extension, so neither is named.\n *\n * None for a database that does not exist yet.\n */\nexport async function findCleanExtras(connectionString: string, objects: DumpObjects): Promise<string[]> {\n const schemas = objects.schemas.filter((schema) => schema !== \"public\");\n if (schemas.length === 0 && objects.relations.length === 0) return [];\n const { routines, types } = objects;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n try {\n await client.connect();\n } catch (err) {\n // 3D000: the database does not exist yet, as `--create-db` finds it.\n if (err instanceof Error && \"code\" in err && err.code === \"3D000\") return [];\n throw err;\n }\n try {\n const { rows } = await client.query<{ kind: string; name: string }>(\n `WITH dumped AS (\n SELECT c.oid\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN unnest($2::text[], $3::text[]) AS d(schema_name, rel_name)\n ON d.schema_name = n.nspname AND d.rel_name = c.relname\n )\n SELECT kind, name FROM (\n SELECT CASE c.relkind WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view'\n WHEN 'f' THEN 'foreign table' WHEN 'S' THEN 'sequence' ELSE 'table' END AS kind,\n n.nspname || '.' || c.relname AS name\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY($1::text[])\n AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')\n AND c.oid NOT IN (SELECT oid FROM dumped)\n AND NOT (c.relkind = 'S' AND EXISTS (\n SELECT 1 FROM pg_depend owner\n WHERE owner.classid = 'pg_class'::regclass AND owner.objid = c.oid\n AND owner.deptype IN ('a', 'i')))\n UNION\n SELECT CASE p.prokind WHEN 'p' THEN 'procedure' WHEN 'a' THEN 'aggregate' ELSE 'function' END,\n n.nspname || '.' || p.proname\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = ANY($1::text[])\n AND (n.nspname, p.proname) NOT IN (SELECT * FROM unnest($4::text[], $5::text[]))\n AND NOT EXISTS (\n SELECT 1 FROM pg_depend owner\n WHERE owner.classid = 'pg_proc'::regclass AND owner.objid = p.oid\n AND owner.deptype IN ('e', 'i'))\n UNION\n SELECT CASE t.typtype WHEN 'd' THEN 'domain' ELSE 'type' END,\n n.nspname || '.' || t.typname\n FROM pg_type t\n JOIN pg_namespace n ON n.oid = t.typnamespace\n WHERE n.nspname = ANY($1::text[])\n AND (t.typtype IN ('e', 'd', 'r')\n OR (t.typtype = 'c' AND EXISTS (\n SELECT 1 FROM pg_class tc WHERE tc.oid = t.typrelid AND tc.relkind = 'c')))\n AND (n.nspname, t.typname) NOT IN (SELECT * FROM unnest($6::text[], $7::text[]))\n AND NOT EXISTS (\n SELECT 1 FROM pg_depend owner\n WHERE owner.classid = 'pg_type'::regclass AND owner.objid = t.oid\n AND owner.deptype = 'e')\n UNION\n SELECT 'view', vn.nspname || '.' || v.relname\n FROM pg_depend dep\n JOIN pg_rewrite r ON r.oid = dep.objid AND dep.classid = 'pg_rewrite'::regclass\n JOIN pg_class v ON v.oid = r.ev_class\n JOIN pg_namespace vn ON vn.oid = v.relnamespace\n WHERE dep.refobjid IN (SELECT oid FROM dumped)\n AND v.oid NOT IN (SELECT oid FROM dumped)\n AND NOT vn.nspname = ANY($1::text[])\n UNION\n SELECT 'foreign key', con.conname || ' on ' || cn.nspname || '.' || cr.relname\n FROM pg_constraint con\n JOIN pg_class cr ON cr.oid = con.conrelid\n JOIN pg_namespace cn ON cn.oid = cr.relnamespace\n WHERE con.contype = 'f'\n AND con.confrelid IN (SELECT oid FROM dumped)\n AND con.conrelid NOT IN (SELECT oid FROM dumped)\n AND NOT cn.nspname = ANY($1::text[])\n ) extra\n ORDER BY name`,\n [\n schemas,\n objects.relations.map((r) => r.schema), objects.relations.map((r) => r.name),\n routines.map((r) => r.schema), routines.map((r) => r.name),\n types.map((t) => t.schema), types.map((t) => t.name)\n ]\n );\n return rows.map((row) => `${row.kind} ${row.name}`);\n } finally {\n await client.end();\n }\n}\n\n/** The schemas and tables a dump creates, from `pg_restore --list`. See {@link parseDumpObjects}. */\nexport async function readDumpObjects(\n inputFile: string,\n env: Record<string, string | undefined> = process.env\n): Promise<DumpObjects> {\n const bin = resolvePgBinary(\"pg_restore\", env);\n if (!bin) {\n throw new BackupToolError(\n \"Could not find the 'pg_restore' binary.\",\n \"Install the PostgreSQL client tools or set PG_RESTORE_PATH.\"\n );\n }\n const toolEnv = Object.fromEntries(\n Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined)\n );\n let listed: string;\n try {\n ({ stdout: listed } = await execa(bin, buildPgRestoreListArgs(inputFile), { stdio: \"pipe\", env: toolEnv }));\n } catch (err) {\n // execa's message is the command line and pg_restore's stderr, which\n // tells the reader neither what is wrong with the file nor that\n // nothing has happened yet.\n const stderr = err instanceof Error && \"stderr\" in err && typeof err.stderr === \"string\" ? err.stderr : \"\";\n const { message, hint } = describeUnreadableDump(path.basename(inputFile), stderr);\n throw new BackupToolError(message, hint);\n }\n return parseDumpObjects(listed);\n}\n\n/**\n * What `db restore` says of a file whose table of contents pg_restore cannot\n * read: before anything is restored, so nothing has changed.\n *\n * `pgRestoreStderr` is what `pg_restore --list` printed. Its first error line\n * is quoted, so the reader sees the tool's own words too.\n */\nexport function describeUnreadableDump(file: string, pgRestoreStderr: string): { message: string; hint: string } {\n const said = pgRestoreStderr.split(\"\\n\")\n .map(line => line.replace(/^pg_restore:\\s*(?:error:\\s*)?/, \"\").trim())\n .find(line => line.length > 0);\n const quoted = said ? ` (pg_restore: ${said})` : \"\";\n const unchanged = \"Nothing was restored or changed.\";\n const elsewhere = \"Restore from another backup (`rebase db backups list` lists them), or copy this one again from where it came from.\";\n\n if (said && /unsupported version \\(([\\d.]+)\\) in file header/.test(said)) {\n return {\n message: `${file} was written by a newer pg_dump than this pg_restore reads${quoted}. ${unchanged}`,\n hint: \"Install the PostgreSQL client tools of the version that wrote it, or set PG_RESTORE_PATH to that pg_restore.\"\n };\n }\n if (said && /does not appear to be a valid archive/.test(said)) {\n return {\n message: `${file} is not a backup pg_restore can read${quoted}. \\`rebase db restore\\` takes the .dump files \\`rebase db backup\\` writes. ${unchanged}`,\n hint: elsewhere\n };\n }\n if (said && /end of file|too short/.test(said)) {\n return {\n message: `${file} is truncated: it ends before pg_restore can read what it holds${quoted}. ` +\n \"A copy or download that did not finish, or a disk that filled while it was written, leaves a file like this. \" +\n unchanged,\n hint: elsewhere\n };\n }\n return {\n message: `${file} cannot be read as a backup${quoted}: it is damaged, or not a pg_dump archive. ${unchanged}`,\n hint: elsewhere\n };\n}\n\n/**\n * Which of a dump's schemas and tables the target database already holds,\n * as `schema <name>` / `table <schema>.<name>`: what a restore without\n * `--clean` would stop on. `public` is left out of the schemas — every\n * database has it, and pg_restore does not create it. None for a database\n * that does not exist yet.\n */\nexport async function findRestoreConflicts(connectionString: string, objects: DumpObjects): Promise<string[]> {\n const schemas = objects.schemas.filter((schema) => schema !== \"public\");\n if (schemas.length === 0 && objects.tables.length === 0) return [];\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n try {\n await client.connect();\n } catch (err) {\n // 3D000: the database does not exist yet, as `--create-db` finds it.\n if (err instanceof Error && \"code\" in err && err.code === \"3D000\") return [];\n throw err;\n }\n try {\n const existingSchemas = await client.query<{ nspname: string }>(\n \"SELECT nspname FROM pg_namespace WHERE nspname = ANY($1::text[]) ORDER BY nspname\",\n [schemas]\n );\n const existingTables = await client.query<{ nspname: string; relname: string }>(\n `SELECT n.nspname, c.relname\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN unnest($1::text[], $2::text[]) AS d(schema_name, table_name)\n ON d.schema_name = n.nspname AND d.table_name = c.relname\n WHERE c.relkind IN ('r', 'p')\n ORDER BY n.nspname, c.relname`,\n [objects.tables.map((t) => t.schema), objects.tables.map((t) => t.table)]\n );\n return [\n ...existingSchemas.rows.map((row) => `schema ${row.nspname}`),\n ...existingTables.rows.map((row) => `table ${row.nspname}.${row.relname}`)\n ];\n } finally {\n await client.end();\n }\n}\n\n/**\n * Create a database (if absent) by connecting to the maintenance\n * `postgres` database. Used by `restore --create-db`.\n */\nexport async function ensureDatabaseExists(\n adminConnectionString: string,\n dbName: string\n): Promise<boolean> {\n const { Client } = await import(\"pg\");\n const parsed = new URL(adminConnectionString);\n parsed.pathname = \"/postgres\";\n const client = new Client({ connectionString: parsed.toString() });\n await client.connect();\n try {\n const existing = await client.query(\"SELECT 1 FROM pg_database WHERE datname = $1\", [dbName]);\n if (existing.rowCount && existing.rowCount > 0) {\n return false;\n }\n // Identifier can't be parameterised; guard against injection.\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(dbName)) {\n throw new BackupToolError(`Invalid database name: \"${dbName}\"`);\n }\n await client.query(`CREATE DATABASE \"${dbName}\"`);\n return true;\n } finally {\n await client.end();\n }\n}\n\n/**\n * Upload a local dump to object storage under the destination's prefix.\n * Backups may contain secrets/PII, so the object is written with a\n * private/octet-stream content type; bucket-level ACLs must stay private.\n */\nexport async function uploadBackup(\n storage: StorageController,\n localFile: string,\n dest: Extract<BackupDestination, { kind: \"s3\" | \"gcs\" }>\n): Promise<{ key: string; storageUrl: string }> {\n const fileName = path.basename(localFile);\n const key = joinStorageKey(dest.prefix, fileName);\n // Backed by the dump on disk, not read into memory: the built-in\n // controllers write it a chunk (S3: a multipart part) at a time. Read with\n // `readFileSync` and copied into a `File`, a dump was held three or four\n // times over in the process running the cron, and one over 2 GiB could\n // not be read at all (`ERR_FS_FILE_TOO_LARGE`), so it never uploaded.\n const file = new File([await fs.openAsBlob(localFile)], fileName, { type: \"application/octet-stream\" });\n // Not held to the controller's upload limits: `maxFileSize` (50 MB unless\n // set) and `allowedMimeTypes` say what a user may upload, and the CLI and\n // the documented cron build their controller without either. Held to\n // them, every dump over 50 MB failed with PAYLOAD_TOO_LARGE.\n const result = await storage.putObject({\n file,\n key,\n bucket: dest.bucket,\n metadata: { \"rebase-backup\": \"1\" }\n }, { uploadLimits: false });\n return { key, storageUrl: result.storageUrl };\n}\n\n/** Stats in flight at once while listing a local backup folder. */\nconst LOCAL_STAT_CONCURRENCY = 32;\n\n/** `fn` over `items`, at most `limit` at a time; results in input order. */\nasync function mapBounded<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const worker = async () => {\n while (next < items.length) {\n const i = next++;\n results[i] = await fn(items[i]);\n }\n };\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));\n return results;\n}\n\n/**\n * List existing backups at a destination. For local destinations reads the\n * directory; for object storage lists the prefix via the controller.\n */\nexport async function listBackups(\n dest: BackupDestination,\n storage?: StorageController\n): Promise<BackupObject[]> {\n if (dest.kind === \"local\") {\n // Asynchronous throughout, a few stats at a time: retention lists the\n // folder after every scheduled backup, inside the server process, and\n // a year of hourly backups is 8,760 dumps stat'ed one by one.\n const stat = await fs.promises.stat(dest.path).catch(() => null);\n if (!stat) return [];\n const dir = stat.isDirectory() ? dest.path : path.dirname(dest.path);\n const dumps = (await fs.promises.readdir(dir)).filter((f) => f.endsWith(\".dump\"));\n const stats = await mapBounded(dumps, LOCAL_STAT_CONCURRENCY, (f) => fs.promises.stat(path.join(dir, f)));\n return dumps\n .map((f, i) => {\n const createdAt = parseBackupTimestamp(f) ?? stats[i].mtime;\n return { key: path.join(dir, f), createdAt, sizeBytes: stats[i].size };\n })\n .sort((a, b) => (b.createdAt?.getTime() ?? 0) - (a.createdAt?.getTime() ?? 0));\n }\n\n if (!storage) {\n throw new BackupToolError(\n `Listing ${dest.kind} backups requires a configured storage backend.`\n );\n }\n // The server's lister, not a second copy of it: a listing is paged, in\n // ascending key order, and this one read a single page of 1,000 — the\n // OLDEST backups — so `rebase db backups list` stopped showing new ones,\n // and retention ranked a page that held none of the newest. The two copies\n // had already drifted apart once (over the roles sidecar).\n const { listBackupObjects } = await import(\"@rebasepro/server\");\n const listed = await listBackupObjects(dest, storage);\n return listed.map((info) => ({\n key: info.key,\n createdAt: info.createdAt ? new Date(info.createdAt) : undefined\n }));\n}\n\n/**\n * Apply a retention policy to a destination, deleting the backups selected\n * by {@link selectBackupsToPrune}. Returns the keys that were removed.\n */\nexport async function pruneBackups(\n dest: BackupDestination,\n options: RetentionOptions,\n storage?: StorageController\n): Promise<string[]> {\n const backups = await listBackups(dest, storage);\n const toDelete = selectBackupsToPrune(backups, options);\n\n // Delete each dump together with its `.globals.sql` sidecar (pruneWith\n // handles the pairing + best-effort sidecar). The deleter rejects on a\n // missing key so pruneWith can swallow an absent sidecar.\n const deleteObject =\n dest.kind === \"local\"\n ? async (key: string) => {\n if (!fs.existsSync(key)) throw new Error(`not found: ${key}`);\n fs.unlinkSync(key);\n }\n : async (key: string) => {\n if (!storage) throw new BackupToolError(\"Storage backend required to prune object backups.\");\n await storage.deleteObject(key, dest.bucket);\n };\n\n await pruneWith(toDelete, deleteObject);\n return toDelete;\n}\n","/**\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 { closestWord, 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 CleanRestoreFailed,\n createDump,\n discardPartialDump,\n ensureDatabaseExists,\n findCleanExtras,\n findRestoreConflicts,\n listBackups,\n preflight,\n readDumpObjects,\n restoreDump,\n restoreDumpReplacing,\n uploadBackup,\n validateDump\n} from \"./backup-service\";\nimport { resolvePgBinary } from \"./pg-binary\";\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 [typed] = args._;\n if (typed !== undefined) {\n const stray = redactConnectionPasswords(typed);\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 const dropsRebase = (args[\"--exclude-schema\"] ?? []).find(excludesRebaseSchema);\n if (dropsRebase !== undefined) throw new Error(excludesRebaseMessage(dropsRebase));\n return args;\n}\n\n/**\n * A `pg_dump --exclude-schema` pattern as the regular expression pg_dump\n * hands the server, by pg_dump's own rules (`patternToSQLRegex` in\n * PostgreSQL's `fe_utils/string_utils.c`):\n *\n * - outside double quotes, an upper-case letter is folded to lower case, `*`\n * is `.*`, `?` is `.`, and every other character, regular-expression syntax\n * included (`[r]`, `(a|b)`, `+`), passes through as it is;\n * - inside double quotes, case is kept and every special character is\n * matched literally; `\"\"` is one quote;\n * - `$` is always literal, and `[]` is always the two characters;\n * - an unquoted `.` separates a database from the schema, so `shop.rebase`\n * is matched on `rebase`.\n *\n * The result is anchored, as pg_dump anchors it: `^(…)$`.\n */\nexport function schemaPatternRegex(pattern: string): string {\n let regex = \"\";\n let inQuotes = false;\n for (let index = 0; index < pattern.length; index += 1) {\n const char = pattern[index];\n if (char === \"\\\"\") {\n if (inQuotes && pattern[index + 1] === \"\\\"\") {\n regex += \"\\\"\";\n index += 1;\n } else {\n inQuotes = !inQuotes;\n }\n } else if (!inQuotes && char >= \"A\" && char <= \"Z\") {\n regex += char.toLowerCase();\n } else if (!inQuotes && char === \"*\") {\n regex += \".*\";\n } else if (!inQuotes && char === \"?\") {\n regex += \".\";\n } else if (!inQuotes && char === \".\") {\n // What came before was the database: the schema is what follows.\n regex = \"\";\n } else if (char === \"$\") {\n regex += \"\\\\$\";\n } else if (inQuotes && \"|*+?()[]{}.^$\\\\\".includes(char)) {\n regex += `\\\\${char}`;\n } else if (char === \"[\" && pattern[index + 1] === \"]\") {\n regex += \"\\\\[\";\n } else {\n regex += char;\n }\n }\n return `^(${regex})$`;\n}\n\n/**\n * Whether a `pg_dump --exclude-schema` pattern matches the `rebase` schema, by\n * pg_dump's own rules (see {@link schemaPatternRegex}).\n *\n * Evaluated here with JavaScript's regular expressions, which read the syntax\n * people write in a pattern (`[r]ebase`, `(rebase|x)`, `reb.+`) as the\n * server does. The server's engine has syntax JavaScript reads otherwise\n * (`[[:alpha:]]`, `\\m`), so `db backup` asks the server too before it dumps\n * (see `backupCommand`); this check is the one that answers before anything\n * connects. A pattern JavaScript cannot compile is left to that one.\n */\nexport function excludesRebaseSchema(pattern: string): boolean {\n try {\n return new RegExp(schemaPatternRegex(pattern)).test(\"rebase\");\n } catch {\n return false;\n }\n}\n\n/**\n * Whether the server's regular-expression engine matches `name` with `regex`,\n * the way pg_dump's own query matches a schema pattern\n * (`nspname OPERATOR(pg_catalog.~) '^(…)$' COLLATE pg_catalog.default`).\n *\n * A regex the server will not compile matches nothing here; pg_dump then\n * refuses it in its own words.\n */\nasync function serverRegexMatches(connectionString: string, regex: string, name: string): Promise<boolean> {\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString });\n await client.connect();\n try {\n const { rows } = await client.query<{ matches: boolean }>(\n \"SELECT $1::text OPERATOR(pg_catalog.~) $2::text COLLATE pg_catalog.default AS matches\",\n [name, regex]\n );\n return rows[0]?.matches === true;\n } catch (err) {\n // 2201B: invalid_regular_expression.\n if (err instanceof Error && \"code\" in err && err.code === \"2201B\") return false;\n throw err;\n } finally {\n await client.end();\n }\n}\n\n/** The refusal for a pattern that leaves out the rebase schema. */\nfunction excludesRebaseMessage(pattern: string): string {\n return `--exclude-schema ${pattern} leaves out the rebase schema, and a backup without it cannot be restored: ` +\n \"it holds the users, roles and the functions every policy calls. Nothing was run.\";\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 // The server's word on each pattern, in the engine pg_dump's own query\n // runs it in. `parseBackupLine` has answered for the syntax JavaScript\n // reads the same way; this catches the rest (`[[:alpha:]]+`, `\\mrebase`)\n // before pg_dump writes a dump that cannot be restored.\n for (const pattern of args[\"--exclude-schema\"] ?? []) {\n if (await serverRegexMatches(connectionString, schemaPatternRegex(pattern), \"rebase\")) {\n outError(chalk.red(` ✗ ${excludesRebaseMessage(pattern)}`));\n process.exit(1);\n }\n }\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 => `\"${redactConnectionPasswords(word)}\"`).join(\", \")}. Nothing was run.`\n );\n }\n return args;\n}\n\n/**\n * The restore's one question, asked before anything can change.\n *\n * `--yes` skips it. On a terminal it asks for a typed 'yes'. With no terminal\n * nobody can answer, and the refusal says to pass `--yes`, as `db reset`,\n * `db pull` and `db branch prune` do: \"Aborted. No changes were made.\" alone\n * read as though someone had answered no.\n *\n * @returns whether to go on. When not, it has said why.\n */\nexport async function confirmRestore(opts: {\n target: string;\n yes: boolean;\n interactive: boolean;\n ask: (question: string) => Promise<boolean>;\n}): Promise<boolean> {\n if (opts.yes) return true;\n outWarn(chalk.yellow(` ⚠️ This will restore into \"${opts.target}\" and may overwrite existing data.`));\n if (!opts.interactive) {\n outError(chalk.red(\" ✗ Nothing was restored: there is no terminal to confirm on.\"));\n outError(chalk.gray(` Re-run with --yes to restore into \"${opts.target}\".`));\n return false;\n }\n const confirmed = await opts.ask(chalk.yellow(\" Type 'yes' to continue: \"));\n if (!confirmed) print(chalk.gray(\" Aborted. No changes were made.\"));\n return confirmed;\n}\n\n/** How many of the conflicting objects a refusal names before counting the rest. */\nconst CONFLICTS_NAMED = 5;\n\n/**\n * What `db restore` says when the target already holds what the backup\n * creates, and the two ways round it: `--clean` replaces them with the\n * backup's copy, a new database restores beside them.\n *\n * `line` is the rest of what the user typed — the database it names, `--yes`,\n * `--no-owner` — which both commands keep, so the one copied runs against the\n * same database and does not stop again to ask. `--target-db` goes on the\n * `--clean` one only: the other names a new database.\n */\nexport function describeRestoreConflict(\n target: string,\n backupArg: string,\n conflicts: readonly string[],\n line: { targetDb?: string; carried?: readonly string[] } = {}\n): { message: string; hint: string } {\n const named = conflicts.slice(0, CONFLICTS_NAMED).join(\", \");\n const more = conflicts.length > CONFLICTS_NAMED ? `, and ${conflicts.length - CONFLICTS_NAMED} more` : \"\";\n const carried = line.carried?.length ? ` ${line.carried.join(\" \")}` : \"\";\n const sameTarget = line.targetDb ? ` --target-db ${line.targetDb}` : \"\";\n return {\n message: `\"${target}\" already holds ${named}${more}, which this backup creates. ` +\n \"Without --clean, pg_restore stops at the first of them. Nothing was restored or changed.\",\n hint: [\n `To replace them with the backup's copy: rebase db restore ${backupArg}${sameTarget} --clean${carried}`,\n `To restore beside them, in a new database: rebase db restore ${backupArg} --create-db --target-db <new name>${carried}`\n ].join(\"\\n \")\n };\n}\n\n/** How many of the objects `--clean` drops beyond the backup's own it names before counting the rest. */\nconst EXTRAS_NAMED = 10;\n\n/**\n * What `restore --clean` says, before it asks, about what it drops that the\n * backup does not hold — see `findCleanExtras`. Nothing when there is none.\n */\nexport function describeCleanExtras(schemas: readonly string[], extras: readonly string[]): string[] {\n if (extras.length === 0) return [];\n const replaced = schemas.filter((schema) => schema !== \"public\");\n const lead = replaced.length > 0\n ? `--clean replaces ${replaced.length === 1 ? \"schema\" : \"schemas\"} ${replaced.join(\", \")} whole, so it also drops what this backup does not hold:`\n : \"--clean also drops what this backup does not hold:\";\n return [\n lead,\n ...extras.slice(0, EXTRAS_NAMED).map((extra) => ` ${extra}`),\n ...(extras.length > EXTRAS_NAMED ? [` and ${extras.length - EXTRAS_NAMED} more`] : [])\n ];\n}\n\n/**\n * What a `restore --clean` that stopped says: it ran as one transaction, so\n * nothing changed. The cluster roles the sidecar recreated are the exception,\n * and are said to be.\n */\nexport function describeCleanRestoreFailure(\n target: string,\n failure: { tool: \"pg_restore\" | \"psql\"; lockTimeout: boolean },\n rolesApplied: number\n): { message: string; hint?: string } {\n const why = failure.tool === \"pg_restore\"\n ? \"pg_restore could not read the whole backup\"\n : failure.lockTimeout\n ? `it waited too long for a lock on \"${target}\"`\n : \"a statement failed\";\n const hints = [\n ...(failure.lockTimeout\n ? [\"Something holds a lock on it — usually a `rebase dev` serving from it. Stop that, then restore again.\"]\n : []),\n ...(rolesApplied > 0\n ? [`The ${rolesApplied} cluster role(s) recreated from the backup's sidecar before it stay.`]\n : [])\n ];\n return {\n message: `Nothing was restored or changed: the restore ran as one transaction, and it was rolled back when ${why} (above). ` +\n `\"${target}\" holds what it held before.`,\n hint: hints.length > 0 ? hints.join(\"\\n \") : undefined\n };\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)) throw new BackupToolError(`Backup file not found: ${localFile}`);\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 // Thrown, not exited, from here down: an exit skipped the `finally`\n // that removes a dump downloaded from object storage.\n const pf = await preflight(\"pg_restore\", baseConnection);\n if (!pf.compatible) throw new BackupToolError(pf.reason ?? \"pg_restore cannot restore into this server.\");\n\n // `--create-db` needs a name before anything else can be decided.\n if (args[\"--create-db\"] && !targetDb) {\n throw new BackupToolError(\"--create-db requires a resolvable target database name (use --target-db).\");\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 // Before the question and before anything is applied, roles included:\n // without --clean, pg_restore stops at the first object the target\n // already has, and said so in its own words and execa's, after the\n // roles had run. A target that does not exist yet holds nothing.\n const objects = await readDumpObjects(localFile);\n if (!args[\"--clean\"]) {\n const conflicts = await findRestoreConflicts(targetConnection, objects);\n if (conflicts.length > 0) {\n const { message, hint } = describeRestoreConflict(targetDb ?? \"the target database\", backupArg, conflicts, {\n targetDb: args[\"--target-db\"],\n carried: [\n ...(args[\"--database-url\"] ? [\"--database-url\", `\"${args[\"--database-url\"]}\"`] : []),\n ...(args[\"--docker\"] ? [\"--docker\"] : []),\n ...(args[\"--no-owner\"] ? [\"--no-owner\"] : []),\n ...(args[\"--yes\"] ? [\"--yes\"] : [])\n ]\n });\n throw new BackupToolError(message, hint);\n }\n }\n\n // `--clean` replaces the backup's schemas whole, in one transaction\n // with the restore — see `restoreDumpReplacing`. `--continue-on-error`\n // asks for the opposite of one transaction, and gets pg_restore's own\n // `--clean`, statement by statement, as it asked.\n const replacing = args[\"--clean\"] === true && args[\"--continue-on-error\"] !== true;\n if (replacing) {\n if (!resolvePgBinary(\"psql\")) {\n throw new BackupToolError(\n \"Could not find the 'psql' binary, which runs a --clean restore as one transaction. Nothing was restored or changed.\",\n \"Install the PostgreSQL client tools (they ship psql beside pg_restore), or set PSQL_PATH to its full path.\"\n );\n }\n const extras = describeCleanExtras(objects.schemas, await findCleanExtras(targetConnection, objects));\n if (extras.length > 0) {\n outWarn(chalk.yellow(` ⚠️ ${extras[0]}`));\n for (const extra of extras.slice(1)) outWarn(chalk.yellow(` ${extra}`));\n }\n }\n\n const confirmed = await confirmRestore({\n target: targetDb ?? \"the target database\",\n yes: args[\"--yes\"] === true,\n interactive: process.stdin.isTTY === true,\n ask: promptConfirm\n });\n if (!confirmed) {\n // An exit code, so the `finally` still removes a downloaded dump.\n process.exitCode = 1;\n return;\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 let rolesApplied = 0;\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 rolesApplied = applied;\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 try {\n if (replacing) {\n await restoreDumpReplacing({\n connectionString: targetConnection,\n inputFile: localFile,\n objects,\n noOwner: args[\"--no-owner\"],\n inheritStdio: true\n });\n } else {\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 } catch (err) {\n if (err instanceof BackupToolError) throw err;\n if (err instanceof CleanRestoreFailed) {\n const { message, hint } = describeCleanRestoreFailure(targetDb ?? \"the target database\", err, rolesApplied);\n throw new BackupToolError(message, hint);\n }\n // pg_restore has printed its own error above; execa's repeats the\n // command line, which says nothing the reader can act on.\n throw new BackupToolError(\n `pg_restore stopped on the error above. What it restored before that stays in \"${targetDb ?? \"the target database\"}\".`,\n rolesApplied > 0\n ? `The ${rolesApplied} cluster role(s) recreated from the backup's sidecar before it stay too.`\n : undefined\n );\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// ─────────────────────────────────────────────────────────────────────────\nconst BACKUPS_ACTIONS = [\"list\"] as const;\n\nconst BACKUPS_LIST_FLAGS = { \"--out\": String, \"--output\": \"--out\", \"-o\": \"--out\" } satisfies arg.Spec;\n\n/**\n * Parse a `rebase db backups list …` line, or its `rebase db backup list …`\n * spelling: the flags start after `list`, the third word of either.\n */\nexport function parseBackupsListLine(rawArgs: readonly string[]) {\n return parseCommandFlags(BACKUPS_LIST_FLAGS, rawArgs.slice(3), \"db backups list\");\n}\n\n/** What `db backups <action>` says of an action it does not have: the sentence every `db` command says. */\nexport function unknownBackupsAction(action: string): string {\n const near = closestWord(action, BACKUPS_ACTIONS);\n return near\n ? `Unknown db backups command \"${action}\" — did you mean \\`${near}\\`? Run \\`rebase db backups --help\\` for the rest.`\n : `Unknown db backups command \"${action}\". Run \\`rebase db backups --help\\` for the ones there are.`;\n}\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(`✗ ${unknownBackupsAction(action)}`));\n process.exit(1);\n }\n\n const args = parseBackupsListLine(rawArgs);\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). Never rebase: a backup\n without it cannot be restored\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\")} Replace what the backup holds, in one transaction with\n the restore (runs the dump through psql)\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 asks for a typed 'yes' on a terminal, and with no terminal to ask on it\n refuses. Prefer --create-db/--target-db to restore into a fresh database\n rather than overwriting a live one. Into a database that already holds\n what the backup creates, it needs --clean, and refuses before changing\n anything without it. --clean drops each schema the backup creates whole,\n with what it holds that the backup does not (it names those first), and\n restores in the same transaction: a restore that stops changes nothing.\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>] ${chalk.gray(\"(the same thing)\")}\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mBAAmB,kBAAyC;CACxE,IAAI;EAEA,MAAM,OAAO,IADM,IAAI,gBACV,CAAA,CAAO,SAAS,QAAQ,OAAO,EAAE,CAAC,CAAC,KAAK;EACrD,OAAO,KAAK,SAAS,IAAI,OAAO;CACpC,QAAQ;EAEJ,MAAM,QAAQ,iBAAiB,MAAM,kBAAkB;EACvD,OAAO,SAAS,MAAM,KAAK,MAAM,KAAK;CAC1C;AACJ;;;;;;AAOA,SAAgB,iBAAiB,kBAA0B,QAAwB;CAC/E,IAAI;EACA,MAAM,SAAS,IAAI,IAAI,gBAAgB;EACvC,OAAO,WAAW,IAAI;EACtB,OAAO,OAAO,SAAS;CAC3B,QAAQ;EACJ,OAAO,iBAAiB,QAAQ,oBAAoB,IAAI,OAAO,GAAG;CACtE;AACJ;;;;;;AAOA,SAAgB,iBAAiB,eAAsC;CACnE,MAAM,QAAQ,cAAc,MAAM,mBAAmB;CACrD,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,QAAQ,OAAO,MAAM,EAAE;CAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO;CAEpC,IAAI,UAAU,KAAK,MAAM,OAAO,KAAA,GAC5B,OAAO;CAEX,OAAO;AACX;;;;;;AAOA,SAAgB,wBAAwB,YAA4C;CAChF,MAAM,MAAM,OAAO,eAAe,WAAW,OAAO,UAAU,IAAI;CAClE,IAAI,CAAC,OAAO,SAAS,GA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BAAyB;CAC9B,IAAM;EACR,MAAM,KAAK,mBAAmB,EAAE;;EAEhC,MAAM,MAAM,KAAK,OAAO,EAAE;;+DAEmC,MAAM,KAAK,kBAAkB,EAAE;CAC7F;AACD"}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  __createRequire(import.meta.url);
3
- import { n as __exportAll } from "./rolldown-runtime-V7rFbMRe.js";
4
- import { n as extractPgError } from "./pg-error-utils-Bv5n2PLn.js";
3
+ import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
4
+ import { n as extractPgError } from "./pg-error-utils-DhiUTlVx.js";
5
5
  //#region src/schema/boot-ddl.ts
6
6
  /**
7
7
  * How boot DDL waits for a table lock, and how it applies several statements as
@@ -102,4 +102,4 @@ var sleep = (ms) => ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) :
102
102
  //#endregion
103
103
  export { isLockTimeout as a, resolveBootLockOptions as c, boot_ddl_exports as i, sleep as l, BOOT_LOCK_TIMEOUT_MS as n, isMultiStatementRefusal as o, atomicBatch as r, joinStatements as s, BOOT_LOCK_RETRY_BUDGET_MS as t };
104
104
 
105
- //# sourceMappingURL=boot-ddl-s_3Hkz94.js.map
105
+ //# sourceMappingURL=boot-ddl-EsgqDkx0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"boot-ddl-s_3Hkz94.js","names":[],"sources":["../src/schema/boot-ddl.ts"],"sourcesContent":["/**\n * How boot DDL waits for a table lock, and how it applies several statements as\n * one.\n *\n * ## Why boot DDL has a lock budget at all\n *\n * Every statement that changes a table — `ALTER TABLE`, `CREATE`/`DROP POLICY`,\n * `DROP TRIGGER` — needs a lock that conflicts with readers. While it *waits*\n * for that lock it sits in the table's lock queue, and every query that arrives\n * after it queues behind it, however short. A boot that happened to start while\n * a report, a long transaction or a `pg_dump` held a table stalled every live\n * read of that table for as long as it waited — up to the pool's\n * `statement_timeout` (30 s), per statement, one table after another.\n *\n * `lock_timeout` turns that wait into a short, bounded attempt. Measured on\n * Postgres 18: a reader holding one table for 5 s held a live `SELECT\n * count(*)` behind the boot for 4.4 s; with the budget below it is held for at\n * most {@link BOOT_LOCK_TIMEOUT_MS}, and the queue drains between attempts.\n *\n * ## The budget\n *\n * 1 s per attempt. An uncontended `ACCESS EXCLUSIVE` on a healthy table is\n * granted in well under a millisecond — the wait is for the statements already\n * running on it to finish — so a second is three orders of magnitude of\n * headroom and never fires on a database that is merely busy. It fires only\n * when something holds the table for longer than any interactive query should,\n * and then the cost to live traffic is one second, which sits inside every\n * client timeout this framework ships with. Longer budgets buy nothing a retry\n * does not buy better: the queue behind a waiting lock grows for as long as it\n * waits, and drains as soon as it gives up.\n *\n * ## Applying several statements as one\n *\n * {@link atomicBatch} joins statements into one simple-protocol query string.\n * Postgres runs a multi-statement query as a single implicit transaction: every\n * statement commits or none does, the `SET LOCAL` applies to that transaction\n * only, and a failure rolls it back on its own — the connection goes back to the\n * pool clean, which an explicit `BEGIN` in the string would not guarantee. It is\n * one round trip and one commit instead of one of each per statement.\n *\n * A handle that speaks only the extended protocol (PGlite in-process, used by\n * tests) refuses the string before running any of it; {@link\n * isMultiStatementRefusal} recognises that so the caller can fall back to one\n * statement at a time.\n */\nimport { extractPgError } from \"../utils/pg-error-utils\";\n\n/** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */\nexport const BOOT_LOCK_TIMEOUT_MS = 1_000;\n\n/** Attempts per table, including the first, before a contended table is given up on. */\nexport const BOOT_LOCK_ATTEMPTS = 3;\n\n/**\n * The most lock waiting one boot step spends on *retries*, in total.\n *\n * Without a cap, a holder that covers the whole database — a `pg_dump` takes\n * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs\n * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the\n * holder that is about to finish (a report, a transaction), and ten seconds is\n * plenty to wait that out; past it, waiting longer only delays the boot.\n */\nexport const BOOT_LOCK_RETRY_BUDGET_MS = 10_000;\n\nexport interface BootLockOptions {\n /** Per-attempt `lock_timeout`, ms. Default {@link BOOT_LOCK_TIMEOUT_MS}. */\n lockTimeoutMs?: number;\n /** Attempts per table, including the first. Default {@link BOOT_LOCK_ATTEMPTS}. */\n attempts?: number;\n /** Total retry waiting per step, ms. Default {@link BOOT_LOCK_RETRY_BUDGET_MS}. */\n retryBudgetMs?: number;\n /** Pause before retry round `round` (1-based), ms. Default: jittered, growing. */\n backoffMs?: (round: number) => number;\n}\n\nexport interface ResolvedBootLockOptions {\n lockTimeoutMs: number;\n attempts: number;\n retryBudgetMs: number;\n backoffMs: (round: number) => number;\n}\n\nexport const resolveBootLockOptions = (options: BootLockOptions = {}): ResolvedBootLockOptions => ({\n lockTimeoutMs: options.lockTimeoutMs ?? BOOT_LOCK_TIMEOUT_MS,\n attempts: Math.max(1, options.attempts ?? BOOT_LOCK_ATTEMPTS),\n retryBudgetMs: options.retryBudgetMs ?? BOOT_LOCK_RETRY_BUDGET_MS,\n // Jittered so two replicas booting together do not retry in lockstep.\n backoffMs: options.backoffMs ?? (round => 500 * round * (1 + Math.random()))\n});\n\n/** `55P03 lock_not_available` — what `lock_timeout` raises. */\nexport const isLockTimeout = (err: unknown): boolean => extractPgError(err)?.code === \"55P03\";\n\n/**\n * `42601` \"cannot insert multiple commands into a prepared statement\": the\n * handle runs every query over the extended protocol, which carries exactly one\n * statement. Raised before anything runs, so nothing needs undoing.\n */\nexport const isMultiStatementRefusal = (err: unknown): boolean => {\n const pg = extractPgError(err);\n return pg?.code === \"42601\" && /multiple commands/i.test(pg.message ?? \"\");\n};\n\n/**\n * `SET LOCAL lock_timeout`, then the statements: one string, one implicit\n * transaction. See the module comment for why this and not `BEGIN … COMMIT`.\n */\nexport const atomicBatch = (statements: readonly string[], lockTimeoutMs: number): string =>\n `SET LOCAL lock_timeout = '${Math.max(1, Math.round(lockTimeoutMs))}ms';\\n${joinStatements(statements)}`;\n\n/** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */\nexport const joinStatements = (statements: readonly string[]): string =>\n statements\n .map(statement => {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n })\n .join(\"\\n\");\n\nexport const sleep = (ms: number): Promise<void> =>\n ms > 0 ? new Promise(resolve => setTimeout(resolve, ms)) : Promise.resolve();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,uBAAuB;;;;;;;;;;AAcpC,IAAa,4BAA4B;AAoBzC,IAAa,0BAA0B,UAA2B,CAAC,OAAgC;CAC/F,eAAe,QAAQ,iBAAA;CACvB,UAAU,KAAK,IAAI,GAAG,QAAQ,YAAA,CAA8B;CAC5D,eAAe,QAAQ,iBAAA;CAEvB,WAAW,QAAQ,eAAc,UAAS,MAAM,SAAS,IAAI,KAAK,OAAO;AAC7E;;AAGA,IAAa,iBAAiB,QAA0B,eAAe,GAAG,CAAC,EAAE,SAAS;;;;;;AAOtF,IAAa,2BAA2B,QAA0B;CAC9D,MAAM,KAAK,eAAe,GAAG;CAC7B,OAAO,IAAI,SAAS,WAAW,qBAAqB,KAAK,GAAG,WAAW,EAAE;AAC7E;;;;;AAMA,IAAa,eAAe,YAA+B,kBACvD,6BAA6B,KAAK,IAAI,GAAG,KAAK,MAAM,aAAa,CAAC,EAAE,QAAQ,eAAe,UAAU;;AAGzG,IAAa,kBAAkB,eAC3B,WACK,KAAI,cAAa;CACd,MAAM,UAAU,UAAU,KAAK;CAC/B,OAAO,QAAQ,SAAS,GAAG,IAAI,UAAU,GAAG,QAAQ;AACxD,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,IAAa,SAAS,OAClB,KAAK,IAAI,IAAI,SAAQ,YAAW,WAAW,SAAS,EAAE,CAAC,IAAI,QAAQ,QAAQ"}
1
+ {"version":3,"file":"boot-ddl-EsgqDkx0.js","names":[],"sources":["../src/schema/boot-ddl.ts"],"sourcesContent":["/**\n * How boot DDL waits for a table lock, and how it applies several statements as\n * one.\n *\n * ## Why boot DDL has a lock budget at all\n *\n * Every statement that changes a table — `ALTER TABLE`, `CREATE`/`DROP POLICY`,\n * `DROP TRIGGER` — needs a lock that conflicts with readers. While it *waits*\n * for that lock it sits in the table's lock queue, and every query that arrives\n * after it queues behind it, however short. A boot that happened to start while\n * a report, a long transaction or a `pg_dump` held a table stalled every live\n * read of that table for as long as it waited — up to the pool's\n * `statement_timeout` (30 s), per statement, one table after another.\n *\n * `lock_timeout` turns that wait into a short, bounded attempt. Measured on\n * Postgres 18: a reader holding one table for 5 s held a live `SELECT\n * count(*)` behind the boot for 4.4 s; with the budget below it is held for at\n * most {@link BOOT_LOCK_TIMEOUT_MS}, and the queue drains between attempts.\n *\n * ## The budget\n *\n * 1 s per attempt. An uncontended `ACCESS EXCLUSIVE` on a healthy table is\n * granted in well under a millisecond — the wait is for the statements already\n * running on it to finish — so a second is three orders of magnitude of\n * headroom and never fires on a database that is merely busy. It fires only\n * when something holds the table for longer than any interactive query should,\n * and then the cost to live traffic is one second, which sits inside every\n * client timeout this framework ships with. Longer budgets buy nothing a retry\n * does not buy better: the queue behind a waiting lock grows for as long as it\n * waits, and drains as soon as it gives up.\n *\n * ## Applying several statements as one\n *\n * {@link atomicBatch} joins statements into one simple-protocol query string.\n * Postgres runs a multi-statement query as a single implicit transaction: every\n * statement commits or none does, the `SET LOCAL` applies to that transaction\n * only, and a failure rolls it back on its own — the connection goes back to the\n * pool clean, which an explicit `BEGIN` in the string would not guarantee. It is\n * one round trip and one commit instead of one of each per statement.\n *\n * A handle that speaks only the extended protocol (PGlite in-process, used by\n * tests) refuses the string before running any of it; {@link\n * isMultiStatementRefusal} recognises that so the caller can fall back to one\n * statement at a time.\n */\nimport { extractPgError } from \"../utils/pg-error-utils\";\n\n/** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */\nexport const BOOT_LOCK_TIMEOUT_MS = 1_000;\n\n/** Attempts per table, including the first, before a contended table is given up on. */\nexport const BOOT_LOCK_ATTEMPTS = 3;\n\n/**\n * The most lock waiting one boot step spends on *retries*, in total.\n *\n * Without a cap, a holder that covers the whole database — a `pg_dump` takes\n * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs\n * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the\n * holder that is about to finish (a report, a transaction), and ten seconds is\n * plenty to wait that out; past it, waiting longer only delays the boot.\n */\nexport const BOOT_LOCK_RETRY_BUDGET_MS = 10_000;\n\nexport interface BootLockOptions {\n /** Per-attempt `lock_timeout`, ms. Default {@link BOOT_LOCK_TIMEOUT_MS}. */\n lockTimeoutMs?: number;\n /** Attempts per table, including the first. Default {@link BOOT_LOCK_ATTEMPTS}. */\n attempts?: number;\n /** Total retry waiting per step, ms. Default {@link BOOT_LOCK_RETRY_BUDGET_MS}. */\n retryBudgetMs?: number;\n /** Pause before retry round `round` (1-based), ms. Default: jittered, growing. */\n backoffMs?: (round: number) => number;\n}\n\nexport interface ResolvedBootLockOptions {\n lockTimeoutMs: number;\n attempts: number;\n retryBudgetMs: number;\n backoffMs: (round: number) => number;\n}\n\nexport const resolveBootLockOptions = (options: BootLockOptions = {}): ResolvedBootLockOptions => ({\n lockTimeoutMs: options.lockTimeoutMs ?? BOOT_LOCK_TIMEOUT_MS,\n attempts: Math.max(1, options.attempts ?? BOOT_LOCK_ATTEMPTS),\n retryBudgetMs: options.retryBudgetMs ?? BOOT_LOCK_RETRY_BUDGET_MS,\n // Jittered so two replicas booting together do not retry in lockstep.\n backoffMs: options.backoffMs ?? (round => 500 * round * (1 + Math.random()))\n});\n\n/** `55P03 lock_not_available` — what `lock_timeout` raises. */\nexport const isLockTimeout = (err: unknown): boolean => extractPgError(err)?.code === \"55P03\";\n\n/**\n * `42601` \"cannot insert multiple commands into a prepared statement\": the\n * handle runs every query over the extended protocol, which carries exactly one\n * statement. Raised before anything runs, so nothing needs undoing.\n */\nexport const isMultiStatementRefusal = (err: unknown): boolean => {\n const pg = extractPgError(err);\n return pg?.code === \"42601\" && /multiple commands/i.test(pg.message ?? \"\");\n};\n\n/**\n * `SET LOCAL lock_timeout`, then the statements: one string, one implicit\n * transaction. See the module comment for why this and not `BEGIN … COMMIT`.\n */\nexport const atomicBatch = (statements: readonly string[], lockTimeoutMs: number): string =>\n `SET LOCAL lock_timeout = '${Math.max(1, Math.round(lockTimeoutMs))}ms';\\n${joinStatements(statements)}`;\n\n/** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */\nexport const joinStatements = (statements: readonly string[]): string =>\n statements\n .map(statement => {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n })\n .join(\"\\n\");\n\nexport const sleep = (ms: number): Promise<void> =>\n ms > 0 ? new Promise(resolve => setTimeout(resolve, ms)) : Promise.resolve();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,uBAAuB;;;;;;;;;;AAcpC,IAAa,4BAA4B;AAoBzC,IAAa,0BAA0B,UAA2B,CAAC,OAAgC;CAC/F,eAAe,QAAQ,iBAAA;CACvB,UAAU,KAAK,IAAI,GAAG,QAAQ,YAAA,CAA8B;CAC5D,eAAe,QAAQ,iBAAA;CAEvB,WAAW,QAAQ,eAAc,UAAS,MAAM,SAAS,IAAI,KAAK,OAAO;AAC7E;;AAGA,IAAa,iBAAiB,QAA0B,eAAe,GAAG,CAAC,EAAE,SAAS;;;;;;AAOtF,IAAa,2BAA2B,QAA0B;CAC9D,MAAM,KAAK,eAAe,GAAG;CAC7B,OAAO,IAAI,SAAS,WAAW,qBAAqB,KAAK,GAAG,WAAW,EAAE;AAC7E;;;;;AAMA,IAAa,eAAe,YAA+B,kBACvD,6BAA6B,KAAK,IAAI,GAAG,KAAK,MAAM,aAAa,CAAC,EAAE,QAAQ,eAAe,UAAU;;AAGzG,IAAa,kBAAkB,eAC3B,WACK,KAAI,cAAa;CACd,MAAM,UAAU,UAAU,KAAK;CAC/B,OAAO,QAAQ,SAAS,GAAG,IAAI,UAAU,GAAG,QAAQ;AACxD,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,IAAa,SAAS,OAClB,KAAK,IAAI,IAAI,SAAQ,YAAW,WAAW,SAAS,EAAE,CAAC,IAAI,QAAQ,QAAQ"}
@@ -16,6 +16,21 @@ import arg from "arg";
16
16
  * not exist in its own words.
17
17
  */
18
18
  export declare const BRANCH_ACTION_FLAGS: Record<string, arg.Spec>;
19
+ /**
20
+ * Refuse a flag `action` does not take, naming the one it was probably meant
21
+ * to be — the same sentence `db backup` and `db restore` say.
22
+ *
23
+ * Throws: the driver's entry turns a thrown error into one red line and exit 1,
24
+ * and this runs before anything connects.
25
+ */
26
+ export declare function assertKnownBranchFlags(action: string, rest: readonly string[]): void;
27
+ /**
28
+ * A `db branch` line, `["db", "branch", <action>, …]`, with its switches'
29
+ * values resolved against the action's flags (see `resolveSwitchValues`):
30
+ * what the branch dispatch reads, so `prune --yes=false` is not a yes. An
31
+ * action the table does not list comes back as it was.
32
+ */
33
+ export declare function resolveBranchSwitches(rawArgs: readonly string[]): string[];
19
34
  /**
20
35
  * Words on a `db branch` command line that no argument accounts for.
21
36
  *