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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +16 -0
  2. package/dist/{BranchService-DGPL6G_C.js → BranchService-UgKa416x.js} +47 -19
  3. package/dist/BranchService-UgKa416x.js.map +1 -0
  4. package/dist/PostgresBackendDriver.d.ts +187 -13
  5. package/dist/PostgresBootstrapper.d.ts +101 -2
  6. package/dist/auth/ensure-tables.d.ts +12 -0
  7. package/dist/auth/services.d.ts +78 -14
  8. package/dist/{auth-users-columns-D2LBFrMH.js → auth-users-columns-C72EMoDJ.js} +17 -1
  9. package/dist/{auth-users-columns-D2LBFrMH.js.map → auth-users-columns-C72EMoDJ.js.map} +1 -1
  10. package/dist/backup/backup-cli.d.ts +75 -2
  11. package/dist/backup/backup-service.d.ts +2 -2
  12. package/dist/backup/pg-binary.d.ts +5 -0
  13. package/dist/{backup-cli-24v4OlSp.js → backup-cli-yiKd1GsC.js} +168 -75
  14. package/dist/backup-cli-yiKd1GsC.js.map +1 -0
  15. package/dist/{backup-service-HQ9GC4tN.js → backup-service-AZWc2wvI.js} +104 -35
  16. package/dist/backup-service-AZWc2wvI.js.map +1 -0
  17. package/dist/boot-ddl-B9ZmBJ75.js +105 -0
  18. package/dist/boot-ddl-B9ZmBJ75.js.map +1 -0
  19. package/dist/cli-console-DGee3Zl7.js +225 -0
  20. package/dist/cli-console-DGee3Zl7.js.map +1 -0
  21. package/dist/cli-console.d.ts +39 -0
  22. package/dist/cli-errors-oVUuD8k0.js +2180 -0
  23. package/dist/cli-errors-oVUuD8k0.js.map +1 -0
  24. package/dist/cli-errors.d.ts +133 -9
  25. package/dist/{cli-flags-BglvpjHv.js → cli-flags-DnPHXjRH.js} +56 -6
  26. package/dist/cli-flags-DnPHXjRH.js.map +1 -0
  27. package/dist/cli-flags.d.ts +15 -0
  28. package/dist/cli-helpers.d.ts +88 -34
  29. package/dist/cli-output.d.ts +16 -28
  30. package/dist/{arg-Dni7MzLB.js → cli-prompt-egtNKkZl.js} +49 -3
  31. package/dist/cli-prompt-egtNKkZl.js.map +1 -0
  32. package/dist/cli-prompt.d.ts +19 -0
  33. package/dist/cli-push.d.ts +87 -0
  34. package/dist/cli-scratch-database.d.ts +33 -8
  35. package/dist/cli.js +826 -230
  36. package/dist/cli.js.map +1 -1
  37. package/dist/{column-plan-helpers-DF-8dTVa.js → column-plan-helpers-D_V4oaZh.js} +43 -27
  38. package/dist/column-plan-helpers-D_V4oaZh.js.map +1 -0
  39. package/dist/{databasePoolManager-Bj5FbeAs.js → connection-C938nR3E.js} +25 -113
  40. package/dist/connection-C938nR3E.js.map +1 -0
  41. package/dist/connection.d.ts +13 -2
  42. package/dist/data-transformer.d.ts +0 -8
  43. package/dist/databasePoolManager-DZgnBOgj.js +119 -0
  44. package/dist/databasePoolManager-DZgnBOgj.js.map +1 -0
  45. package/dist/deferred-index-build-BqmEHGaD.js +1051 -0
  46. package/dist/deferred-index-build-BqmEHGaD.js.map +1 -0
  47. package/dist/{doctor-Cb2thZ8s.js → doctor-CUAAOFZm.js} +281 -89
  48. package/dist/doctor-CUAAOFZm.js.map +1 -0
  49. package/dist/ensure-collection-policies-Bb51V2OV.js +541 -0
  50. package/dist/ensure-collection-policies-Bb51V2OV.js.map +1 -0
  51. package/dist/ensure-collection-tables-egjGBjhv.js +532 -0
  52. package/dist/ensure-collection-tables-egjGBjhv.js.map +1 -0
  53. package/dist/{ensure-tables-Dhn9KM3B.js → ensure-tables-DMPWhJ6R.js} +180 -77
  54. package/dist/ensure-tables-DMPWhJ6R.js.map +1 -0
  55. package/dist/enum-labels-kept-Msq5gMcb.js +56 -0
  56. package/dist/enum-labels-kept-Msq5gMcb.js.map +1 -0
  57. package/dist/generate-drizzle-schema-DrA-YgXv.js +57 -0
  58. package/dist/generate-drizzle-schema-DrA-YgXv.js.map +1 -0
  59. package/dist/{generate-drizzle-schema-logic-BfzK7UQd.js → generate-drizzle-schema-logic-BaT0H7Gq.js} +29 -11
  60. package/dist/generate-drizzle-schema-logic-BaT0H7Gq.js.map +1 -0
  61. package/dist/generate-files-OoRJLEdk.js +199 -0
  62. package/dist/generate-files-OoRJLEdk.js.map +1 -0
  63. package/dist/generate-postgres-ddl-logic-B4k9djAV.js +152 -0
  64. package/dist/generate-postgres-ddl-logic-B4k9djAV.js.map +1 -0
  65. package/dist/{generated-schema-staleness-Di9c4ZxN.js → generated-schema-staleness-BWN_PsMi.js} +2 -2
  66. package/dist/{generated-schema-staleness-Di9c4ZxN.js.map → generated-schema-staleness-BWN_PsMi.js.map} +1 -1
  67. package/dist/generated-sql.d.ts +34 -0
  68. package/dist/history/HistoryService.d.ts +64 -5
  69. package/dist/history/ensure-history-table.d.ts +63 -4
  70. package/dist/index.d.ts +1 -0
  71. package/dist/index.es.js +139 -16738
  72. package/dist/index.es.js.map +1 -1
  73. package/dist/{introspect-db-logic-WMuAfxvw.js → introspect-db-logic-BCc1Jym2.js} +654 -353
  74. package/dist/introspect-db-logic-BCc1Jym2.js.map +1 -0
  75. package/dist/introspect-db-queries-BhhJg0b8.js +364 -0
  76. package/dist/introspect-db-queries-BhhJg0b8.js.map +1 -0
  77. package/dist/open-rebase-CAjWpPjs.js +20895 -0
  78. package/dist/open-rebase-CAjWpPjs.js.map +1 -0
  79. package/dist/open-rebase.d.ts +94 -0
  80. package/dist/pg-error-utils-Bs_Ue4wn.js +395 -0
  81. package/dist/pg-error-utils-Bs_Ue4wn.js.map +1 -0
  82. package/dist/{plan-schema-C0fxM8dY.js → plan-schema-CsNgK0qi.js} +279 -534
  83. package/dist/plan-schema-CsNgK0qi.js.map +1 -0
  84. package/dist/{policy-drift-DljYdrpW.js → policy-drift-BKC50y2p.js} +33 -9
  85. package/dist/policy-drift-BKC50y2p.js.map +1 -0
  86. package/dist/push-index-prebuild-C_qhyoJa.js +45 -0
  87. package/dist/push-index-prebuild-C_qhyoJa.js.map +1 -0
  88. package/dist/push-legacy-renames-5g9h3HOa.js +34 -0
  89. package/dist/push-legacy-renames-5g9h3HOa.js.map +1 -0
  90. package/dist/{generate-postgres-ddl-logic-Bt2d2mRH.js → render-ddl-CrfEe__B.js} +24 -157
  91. package/dist/render-ddl-CrfEe__B.js.map +1 -0
  92. package/dist/{rls-bootstrap-sql-B8EclDyM.js → rls-bootstrap-sql-Bd-hJk08.js} +125 -1101
  93. package/dist/rls-bootstrap-sql-Bd-hJk08.js.map +1 -0
  94. package/dist/{rls-enforcement-C6Xk0lA6.js → rls-enforcement-D7P4-ZYX.js} +138 -18
  95. package/dist/rls-enforcement-D7P4-ZYX.js.map +1 -0
  96. package/dist/{__vite-browser-external-BnuHet1e.js → rolldown-runtime-V7rFbMRe.js} +1 -8
  97. package/dist/schema/atlas-exclude.d.ts +42 -0
  98. package/dist/schema/auth-schema.d.ts +172 -2
  99. package/dist/schema/boot-ddl.d.ts +47 -0
  100. package/dist/schema/carved-out-migration.d.ts +5 -4
  101. package/dist/schema/classify-change.d.ts +29 -1
  102. package/dist/schema/collection-index.d.ts +45 -0
  103. package/dist/schema/column-plan-helpers.d.ts +38 -21
  104. package/dist/schema/deferred-index-build.d.ts +131 -0
  105. package/dist/schema/destructive-sql.d.ts +50 -2
  106. package/dist/schema/doctor-cli.js +110 -6
  107. package/dist/schema/doctor-cli.js.map +1 -1
  108. package/dist/schema/doctor-search-scale.d.ts +45 -0
  109. package/dist/schema/doctor.d.ts +53 -1
  110. package/dist/schema/ensure-collection-policies.d.ts +95 -35
  111. package/dist/schema/ensure-collection-tables.d.ts +56 -3
  112. package/dist/schema/enum-labels-kept.d.ts +26 -0
  113. package/dist/schema/generate-drizzle-schema.js +1 -1
  114. package/dist/schema/generate-files.d.ts +44 -0
  115. package/dist/schema/generate-next-step.d.ts +0 -13
  116. package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
  117. package/dist/schema/generate-postgres-ddl.js +10 -81
  118. package/dist/schema/generate-postgres-ddl.js.map +1 -1
  119. package/dist/schema/generate-schema-commit.d.ts +12 -0
  120. package/dist/schema/generated-schema-diff.d.ts +7 -0
  121. package/dist/schema/introspect-db-logic.d.ts +63 -0
  122. package/dist/schema/introspect-db-queries.d.ts +21 -2
  123. package/dist/schema/introspect-db-search.d.ts +22 -0
  124. package/dist/schema/introspect-db-storage.d.ts +83 -0
  125. package/dist/schema/introspect-db-structure.d.ts +10 -0
  126. package/dist/schema/introspect-db.js +29 -21
  127. package/dist/schema/introspect-db.js.map +1 -1
  128. package/dist/schema/migrate-baseline.d.ts +33 -0
  129. package/dist/schema/migration-post-process.d.ts +34 -0
  130. package/dist/schema/plan/diff-plan.d.ts +127 -1
  131. package/dist/schema/plan/plan-schema.d.ts +16 -8
  132. package/dist/schema/plan/render-ddl.d.ts +8 -1
  133. package/dist/schema/plan/types.d.ts +45 -11
  134. package/dist/schema/push-index-prebuild.d.ts +25 -0
  135. package/dist/schema/push-legacy-renames.d.ts +20 -0
  136. package/dist/schema/rls-bootstrap-sql.d.ts +15 -0
  137. package/dist/schema/undeclarable-constraints.d.ts +59 -0
  138. package/dist/search-column-BM-GV6vH.js +442 -0
  139. package/dist/search-column-BM-GV6vH.js.map +1 -0
  140. package/dist/security/policy-drift.d.ts +1 -1
  141. package/dist/security/rls-enforcement.d.ts +39 -4
  142. package/dist/services/BranchService.d.ts +29 -1
  143. package/dist/services/FetchService.d.ts +63 -12
  144. package/dist/services/PersistService.d.ts +15 -0
  145. package/dist/services/RelationService.d.ts +106 -3
  146. package/dist/services/cdc/CdcListener.d.ts +26 -10
  147. package/dist/services/cdc/identity-columns.d.ts +19 -0
  148. package/dist/services/cdc/trigger-cdc.d.ts +180 -18
  149. package/dist/services/channel-bus/PostgresChannelBus.d.ts +12 -7
  150. package/dist/services/channel-bus/index.d.ts +1 -1
  151. package/dist/services/channel-history.d.ts +32 -5
  152. package/dist/services/collection-helpers.d.ts +26 -1
  153. package/dist/services/field-viewer.d.ts +15 -1
  154. package/dist/services/pg-notify-listener.d.ts +95 -6
  155. package/dist/services/realtimeService.d.ts +467 -53
  156. package/dist/services/row-pipeline.d.ts +16 -9
  157. package/dist/services/socket-liveness.d.ts +85 -0
  158. package/dist/services/soft-delete.d.ts +12 -0
  159. package/dist/services/sql-script.d.ts +275 -0
  160. package/dist/services/vector-iterative-scan.d.ts +40 -0
  161. package/dist/services/write-depth.d.ts +22 -0
  162. package/dist/services/write-transaction-scope.d.ts +15 -3
  163. package/dist/socket-opt-ins.d.ts +64 -0
  164. package/dist/source-DB6xJv3p.js +873 -0
  165. package/dist/source-DB6xJv3p.js.map +1 -0
  166. package/dist/tsx-loader.d.ts +14 -0
  167. package/dist/utils/connection-string.d.ts +31 -0
  168. package/dist/utils/drizzle-conditions.d.ts +63 -3
  169. package/dist/utils/error-cause.d.ts +7 -0
  170. package/dist/utils/pg-error-utils.d.ts +2 -4
  171. package/dist/utils/result-rows.d.ts +10 -0
  172. package/dist/{vector-index-CMJKb3C9.js → vector-index-BFhyEaiz.js} +2 -2
  173. package/dist/{vector-index-CMJKb3C9.js.map → vector-index-BFhyEaiz.js.map} +1 -1
  174. package/dist/websocket-DUiiwQd2.js +1632 -0
  175. package/dist/websocket-DUiiwQd2.js.map +1 -0
  176. package/dist/websocket.d.ts +63 -18
  177. package/package.json +7 -7
  178. package/dist/BranchService-DGPL6G_C.js.map +0 -1
  179. package/dist/__vite-browser-external-BnuHet1e.js.map +0 -1
  180. package/dist/arg-Dni7MzLB.js.map +0 -1
  181. package/dist/backup-cli-24v4OlSp.js.map +0 -1
  182. package/dist/backup-service-HQ9GC4tN.js.map +0 -1
  183. package/dist/cli-errors-B8qHg02P.js +0 -798
  184. package/dist/cli-errors-B8qHg02P.js.map +0 -1
  185. package/dist/cli-flags-BglvpjHv.js.map +0 -1
  186. package/dist/cli-output-CNdMql-L.js +0 -47
  187. package/dist/cli-output-CNdMql-L.js.map +0 -1
  188. package/dist/collection-index-DdnsxiJ_.js +0 -286
  189. package/dist/collection-index-DdnsxiJ_.js.map +0 -1
  190. package/dist/column-plan-helpers-DF-8dTVa.js.map +0 -1
  191. package/dist/databasePoolManager-Bj5FbeAs.js.map +0 -1
  192. package/dist/doctor-Cb2thZ8s.js.map +0 -1
  193. package/dist/ensure-collection-policies-RHUcEp4v.js +0 -105
  194. package/dist/ensure-collection-policies-RHUcEp4v.js.map +0 -1
  195. package/dist/ensure-collection-tables-BEEjn5cn.js +0 -857
  196. package/dist/ensure-collection-tables-BEEjn5cn.js.map +0 -1
  197. package/dist/ensure-tables-Dhn9KM3B.js.map +0 -1
  198. package/dist/generate-drizzle-schema-logic-BfzK7UQd.js.map +0 -1
  199. package/dist/generate-drizzle-schema-yzY_BLhr.js +0 -123
  200. package/dist/generate-drizzle-schema-yzY_BLhr.js.map +0 -1
  201. package/dist/generate-postgres-ddl-logic-Bt2d2mRH.js.map +0 -1
  202. package/dist/introspect-db-logic-WMuAfxvw.js.map +0 -1
  203. package/dist/plan-schema-C0fxM8dY.js.map +0 -1
  204. package/dist/policy-drift-DljYdrpW.js.map +0 -1
  205. package/dist/rls-bootstrap-sql-B8EclDyM.js.map +0 -1
  206. package/dist/rls-enforcement-C6Xk0lA6.js.map +0 -1
  207. package/dist/source-Br7L7GOI.js +0 -410
  208. package/dist/source-Br7L7GOI.js.map +0 -1
@@ -0,0 +1,2180 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { a as outWarn, i as outError, m as isRebaseIndexName, o as atlasExcludePattern, r as out, s as excludePatternParts, t as chalk } from "./source-DB6xJv3p.js";
4
+ import path from "path";
5
+ import fs from "fs";
6
+ import { fileURLToPath, pathToFileURL } from "url";
7
+ import { execSync } from "child_process";
8
+ import { createRequire } from "module";
9
+ //#region src/utils/error-cause.ts
10
+ /**
11
+ * Walk the error cause chain and return the deepest meaningful message.
12
+ *
13
+ * A leaf module, imported by the driver CLI: `pg-error-utils.ts`, where it used
14
+ * to live, imports `@rebasepro/server`, and the CLI must start without it.
15
+ */
16
+ function extractCauseMessage(error) {
17
+ if (!error || typeof error !== "object") return null;
18
+ if (!(error instanceof Error)) return null;
19
+ if (error.cause && typeof error.cause === "object") {
20
+ const deeper = extractCauseMessage(error.cause);
21
+ if (deeper) return deeper;
22
+ if (error.cause instanceof Error && error.cause.message) return error.cause.message;
23
+ }
24
+ return null;
25
+ }
26
+ //#endregion
27
+ //#region src/utils/connection-string.ts
28
+ /**
29
+ * Connection-string rewrites for the tools Rebase shells out to.
30
+ *
31
+ * Pure and dependency-free: `pg-tools` builds argument vectors without a live
32
+ * server, and these have to be usable from there.
33
+ */
34
+ /**
35
+ * The `sslmode` values libpq accepts. `no-verify` is conspicuously not one.
36
+ */
37
+ var LIBPQ_SSLMODES = /* @__PURE__ */ new Set([
38
+ "disable",
39
+ "allow",
40
+ "prefer",
41
+ "require",
42
+ "verify-ca",
43
+ "verify-full"
44
+ ]);
45
+ /**
46
+ * Make a connection string safe to hand to a libpq program.
47
+ *
48
+ * `sslmode=no-verify` is a node-postgres convention — encrypt, but do not check
49
+ * the certificate — and libpq does not have it. It does not degrade or warn:
50
+ *
51
+ * psql: error: invalid sslmode value: "no-verify"
52
+ *
53
+ * which means a `DATABASE_URL` that works perfectly for the app makes `psql`,
54
+ * `pg_dump`, `pg_restore` and Atlas all refuse to start, with an error that
55
+ * points at the value rather than at the convention it comes from. It has cost
56
+ * this project time more than once.
57
+ *
58
+ * `require` is the honest translation: libpq's `require` encrypts and does not
59
+ * verify the certificate either, which is exactly what `no-verify` asks for.
60
+ * Nothing is relaxed by the rewrite — `verify-ca` and `verify-full` are left
61
+ * alone, so a connection string that asked for verification still gets it.
62
+ *
63
+ * Only `sslmode` is touched, and only when it is a value libpq would reject.
64
+ * Anything unparseable is returned as given: a connection that works
65
+ * unverified beats one this corrupted.
66
+ */
67
+ function forLibpq(connectionString) {
68
+ let url;
69
+ try {
70
+ url = new URL(connectionString);
71
+ } catch {
72
+ return connectionString;
73
+ }
74
+ if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") return connectionString;
75
+ const sslmode = url.searchParams.get("sslmode");
76
+ if (sslmode === null || LIBPQ_SSLMODES.has(sslmode)) return connectionString;
77
+ url.searchParams.set("sslmode", "require");
78
+ url.search = Array.from(url.searchParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
79
+ return url.toString();
80
+ }
81
+ /**
82
+ * A connection string with its password taken out, and the password.
83
+ *
84
+ * For a libpq program: the URL goes on its command line, and the password goes
85
+ * in `PGPASSWORD`. On the command line it was readable by anyone who can list
86
+ * processes, and it came back verbatim in every failure, because execa's error
87
+ * message repeats the command: `Command failed with exit code 1: pg_restore
88
+ * '--dbname=postgresql://app:s3cret@…'`, in a terminal, a CI log and the
89
+ * scheduled backup's run history.
90
+ *
91
+ * libpq takes the password from the URL's user info or a `password` parameter,
92
+ * so both are removed. The value is percent-decoded, because `PGPASSWORD` is
93
+ * read literally. Anything that is not a URL is returned as given, with no
94
+ * password: a key/value DSN keeps its own.
95
+ */
96
+ function splitPassword(connectionString) {
97
+ let url;
98
+ try {
99
+ url = new URL(connectionString);
100
+ } catch {
101
+ return {
102
+ connectionString,
103
+ password: null
104
+ };
105
+ }
106
+ if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") return {
107
+ connectionString,
108
+ password: null
109
+ };
110
+ const fromUserInfo = url.password ? decodePercent(url.password) : null;
111
+ const fromParameter = url.searchParams.get("password");
112
+ if (fromUserInfo === null && fromParameter === null) return {
113
+ connectionString,
114
+ password: null
115
+ };
116
+ url.password = "";
117
+ if (fromParameter !== null) {
118
+ url.searchParams.delete("password");
119
+ url.search = Array.from(url.searchParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
120
+ }
121
+ return {
122
+ connectionString: url.toString(),
123
+ password: fromUserInfo ?? fromParameter
124
+ };
125
+ }
126
+ function decodePercent(value) {
127
+ try {
128
+ return decodeURIComponent(value);
129
+ } catch {
130
+ return value;
131
+ }
132
+ }
133
+ /**
134
+ * Every password a line of text carries in a connection string, replaced with
135
+ * `***`.
136
+ *
137
+ * For whatever is about to be printed or logged and may have a connection
138
+ * string in it: an error a client tool or a driver raised, a message that
139
+ * quotes a command line. Covers the URL user-info form (`scheme://user:pass@`,
140
+ * any scheme, a password with a raw `@` in it included) and `password=` in a
141
+ * query string or a key/value DSN. The user, host and database stay, because
142
+ * they are what a reader needs to tell which database it was.
143
+ */
144
+ function redactConnectionPasswords(text) {
145
+ return text.replace(/(\b[a-z][a-z0-9+.-]*:\/\/[^\s/?#@'"]*):[^\s/?#'"]*@/gi, "$1:***@").replace(/(\bpassword\s*=\s*)('[^']*'|[^\s&'"]+)/gi, "$1***");
146
+ }
147
+ //#endregion
148
+ //#region src/schema/destructive-sql.ts
149
+ /**
150
+ * SQL fragments that destroy data or data-bearing objects. Matched
151
+ * case-insensitively against each statement of the plan. `IF EXISTS` /
152
+ * whitespace variations are tolerated by the regexes below.
153
+ */
154
+ var DESTRUCTIVE_PATTERNS = [
155
+ {
156
+ label: "DROP TABLE",
157
+ re: /\bDROP\s+TABLE\b/i
158
+ },
159
+ {
160
+ label: "DROP COLUMN",
161
+ re: /\bDROP\s+COLUMN\b/i
162
+ },
163
+ {
164
+ label: "DROP SCHEMA",
165
+ re: /\bDROP\s+SCHEMA\b/i
166
+ },
167
+ {
168
+ label: "DROP VIEW",
169
+ re: /\bDROP\s+(MATERIALIZED\s+)?VIEW\b/i
170
+ },
171
+ {
172
+ label: "DROP TYPE",
173
+ re: /\bDROP\s+TYPE\b/i
174
+ },
175
+ {
176
+ label: "TRUNCATE",
177
+ re: /\bTRUNCATE\b/i
178
+ }
179
+ ];
180
+ /**
181
+ * Split a SQL script into individual statements, dropping blank lines and
182
+ * `--` comment lines. Deliberately simple: Atlas emits one plain statement
183
+ * per `;`, without string literals that contain semicolons in a schema DDL
184
+ * plan, so a naive split is safe and keeps this dependency-free.
185
+ */
186
+ function splitSqlStatements(sql) {
187
+ return sql.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").split(";").map((s) => s.trim()).filter((s) => s.length > 0);
188
+ }
189
+ /** `->`, the marker Atlas prints in front of the first line of every statement. */
190
+ var PLAN_MARKER_RE = /^\s*->\s?/;
191
+ /** `-------`, both the rule between sections and the one above a summary. */
192
+ var PLAN_RULE_RE = /^\s*-{5,}\s*$/;
193
+ /** `Planning migration statements (3 in total):` — and the count it announces. */
194
+ var PLAN_HEADING_RE = /^Planning migration statements \((\d+) in total\):/m;
195
+ /**
196
+ * What Atlas prints, and nothing else, when there is nothing to plan — from
197
+ * `schema apply`, or from `migrate apply` with no file pending.
198
+ */
199
+ var PLAN_SYNCED_RE = /^\s*(?:Schema is synced, no changes to be made|No migration files to execute)\s*$/;
200
+ /**
201
+ * Read the statements out of whatever Atlas printed.
202
+ *
203
+ * `atlas schema apply --dry-run` does not print SQL. It prints a report, and
204
+ * the same statements appear in it twice:
205
+ *
206
+ * Planning migration statements (2 in total):
207
+ *
208
+ * -- modify "people" table:
209
+ * -> ALTER TABLE "public"."people" ALTER COLUMN "rating" TYPE numeric(4,1);
210
+ * -- create "notes" table:
211
+ * -> CREATE TABLE "public"."notes" (
212
+ * "body" text NULL DEFAULT 'a;b',
213
+ * …
214
+ * );
215
+ *
216
+ * -------------------------------------------
217
+ *
218
+ * Analyzing planned statements (2 in total):
219
+ * …
220
+ * Running dry-run migration (2 statements in total):
221
+ * -- modify "people" table
222
+ * -> ALTER TABLE …; ← the same statement, again
223
+ * -- ok (19µs)
224
+ *
225
+ * Splitting that on `;` is how the push gate went blind: the heading has no
226
+ * `;` and does not start with `--`, so it became the first line of the first
227
+ * statement, and an `ALTER TABLE` parse anchored at the start of a statement
228
+ * read nothing — every narrowing type change applied without a prompt. Reading
229
+ * both sections was a second bug, counting every destructive statement twice.
230
+ *
231
+ * So the report is read as a report: a statement is a `->` line and the lines
232
+ * indented under it, up to the next `--` heading, `->`, blank line or rule;
233
+ * only the first section that holds a `->` is read; and `;` plays no part,
234
+ * because a default like `'a;b'` contains one.
235
+ *
236
+ * Plain SQL — a migration file, or an Atlas that printed SQL — has no `->`
237
+ * and is split the old way.
238
+ */
239
+ function readPlan(plan) {
240
+ if (PLAN_SYNCED_RE.test(plan)) return { statements: [] };
241
+ const lines = plan.split(/\r?\n/);
242
+ if (!lines.some((line) => PLAN_MARKER_RE.test(line))) return { statements: splitSqlStatements(plan) };
243
+ const heading = PLAN_HEADING_RE.exec(plan);
244
+ const statements = [];
245
+ let current = null;
246
+ const flush = () => {
247
+ if (current) statements.push(current.join("\n").trim().replace(/;\s*$/, "").trimEnd());
248
+ current = null;
249
+ };
250
+ for (const line of lines) {
251
+ if (PLAN_MARKER_RE.test(line)) {
252
+ flush();
253
+ current = [line.replace(PLAN_MARKER_RE, "")];
254
+ continue;
255
+ }
256
+ if (PLAN_RULE_RE.test(line) || /^\S/.test(line) && !line.startsWith("--")) {
257
+ flush();
258
+ if (statements.length > 0) break;
259
+ continue;
260
+ }
261
+ if (!current) continue;
262
+ if (line.trim() === "" || line.trim().startsWith("--")) {
263
+ flush();
264
+ continue;
265
+ }
266
+ current.push(line);
267
+ }
268
+ flush();
269
+ return {
270
+ statements,
271
+ announced: heading ? Number(heading[1]) : void 0
272
+ };
273
+ }
274
+ /**
275
+ * The statements of an Atlas plan, each exactly once, without Atlas's
276
+ * rendering and without the trailing `;`. See {@link readPlan} for the shape
277
+ * it reads; `test/fixtures/atlas-dry-run/` holds real captures of it.
278
+ */
279
+ function extractPlanStatements(plan) {
280
+ return readPlan(plan).statements;
281
+ }
282
+ /**
283
+ * Whether Atlas answered the dry-run with "Schema is synced" and nothing else.
284
+ *
285
+ * Positive evidence only: an empty or unreadable report also yields no
286
+ * statements, and is not the same answer.
287
+ */
288
+ function isSyncedPlan(plan) {
289
+ return PLAN_SYNCED_RE.test(plan);
290
+ }
291
+ /**
292
+ * Every column of every ordinary table outside the system schemas, with its
293
+ * type. What {@link detectDestructiveStatements} compares a planned type
294
+ * change against; `format_type` because it carries the modifier (`(255)`,
295
+ * `(10,2)`) that decides whether a change widens or narrows.
296
+ */
297
+ var COLUMN_TYPES_SQL = `
298
+ SELECT n.nspname AS "schema",
299
+ c.relname AS "table",
300
+ a.attname AS "column",
301
+ format_type(a.atttypid, a.atttypmod) AS "type"
302
+ FROM pg_attribute a
303
+ JOIN pg_class c ON c.oid = a.attrelid
304
+ JOIN pg_namespace n ON n.oid = c.relnamespace
305
+ WHERE c.relkind IN ('r', 'p')
306
+ AND a.attnum > 0
307
+ AND NOT a.attisdropped
308
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
309
+ AND n.nspname NOT LIKE 'pg\\_%'
310
+ `;
311
+ /**
312
+ * Scan an Atlas plan (the SQL printed by `schema apply --dry-run`) and return
313
+ * the statements that would destroy data. An empty array means the plan is
314
+ * safe to auto-approve.
315
+ *
316
+ * `columnTypes` is what the database holds now. A type change to a column it
317
+ * does not list is flagged: not knowing what a column is means not knowing
318
+ * whether the change keeps its values.
319
+ *
320
+ * `constraints` are the CHECK and EXCLUDE constraints the database holds now.
321
+ * A `DROP CONSTRAINT` of one of them is flagged; of any other constraint (a
322
+ * foreign key, a `UNIQUE`) it is not, as before.
323
+ */
324
+ function detectDestructiveStatements(planSql, columnTypes = [], constraints = []) {
325
+ const found = [];
326
+ const { statements, announced } = readPlan(planSql);
327
+ if (announced !== void 0 && announced !== statements.length) found.push({
328
+ statement: `Planning migration statements (${announced} in total)`,
329
+ kind: "UNREADABLE PLAN",
330
+ detail: `Atlas announced ${announced} statement(s) and ${statements.length} could be read — read the plan yourself before allowing it`
331
+ });
332
+ for (const statement of statements) {
333
+ const dropped = DESTRUCTIVE_PATTERNS.find(({ re }) => re.test(statement));
334
+ const rekeyed = describePrimaryKeyChange(statement);
335
+ const lossy = parseColumnTypeChanges(statement).map((change) => ({
336
+ change,
337
+ from: currentTypeOf(change, columnTypes)
338
+ })).filter(({ change, from }) => from === void 0 || !isLosslessTypeChange(from, change.to)).map(({ change, from }) => `"${change.column}" ${from ?? "(current type unknown)"} → ${change.to}`).join("; ");
339
+ const unenforced = describeConstraintDrops(statement, constraints);
340
+ const kind = dropped?.label ?? (rekeyed ? "PRIMARY KEY CHANGE" : lossy ? "ALTER COLUMN TYPE" : unenforced ? "DROP CONSTRAINT" : void 0);
341
+ if (!kind) continue;
342
+ const detail = [
343
+ rekeyed,
344
+ lossy,
345
+ unenforced
346
+ ].filter(Boolean).join("; ");
347
+ found.push(detail ? {
348
+ statement,
349
+ kind,
350
+ detail
351
+ } : {
352
+ statement,
353
+ kind
354
+ });
355
+ }
356
+ return found;
357
+ }
358
+ var IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`;
359
+ var ALTER_TABLE_RE = new RegExp(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(${IDENT})(?:\.(${IDENT}))?\s+([\s\S]*)$`, "i");
360
+ var TYPE_CLAUSE_RE = new RegExp(String.raw`^ALTER\s+(?:COLUMN\s+)?(${IDENT})\s+(?:SET\s+DATA\s+)?TYPE\s+([\s\S]+)$`, "i");
361
+ var unquote = (ident) => ident.startsWith("\"") ? ident.slice(1, -1).replace(/""/g, "\"") : ident;
362
+ /**
363
+ * Split an `ALTER TABLE`'s clause list on its top-level commas — the ones
364
+ * outside parentheses and quotes, so `TYPE numeric(10, 2)` stays one clause.
365
+ */
366
+ function splitClauses(body) {
367
+ const clauses = [];
368
+ let depth = 0;
369
+ let quote;
370
+ let start = 0;
371
+ for (let i = 0; i < body.length; i++) {
372
+ const ch = body[i];
373
+ if (quote) {
374
+ if (ch === quote) quote = void 0;
375
+ } else if (ch === "\"" || ch === "'") quote = ch;
376
+ else if (ch === "(") depth++;
377
+ else if (ch === ")") depth--;
378
+ else if (ch === "," && depth === 0) {
379
+ clauses.push(body.slice(start, i).trim());
380
+ start = i + 1;
381
+ }
382
+ }
383
+ clauses.push(body.slice(start).trim());
384
+ return clauses.filter((clause) => clause.length > 0);
385
+ }
386
+ /**
387
+ * The statement from its `ALTER TABLE` on, wherever on a line that starts.
388
+ *
389
+ * {@link readPlan} hands over clean statements. This is the second line of
390
+ * defence for text it could not clean — a rendering it does not know yet —
391
+ * where a line of prose above the statement must not hide the statement, which
392
+ * is exactly how an anchored match once read Atlas's whole plan as safe.
393
+ */
394
+ function fromAlterTable(statement) {
395
+ const start = /(?:^|\n)[ \t]*(?:->[ \t]*)?(ALTER\s+TABLE\b)/i.exec(statement);
396
+ return start ? statement.slice(start.index + start[0].length - start[1].length).trim() : statement.trim();
397
+ }
398
+ /**
399
+ * Every `ALTER COLUMN … [SET DATA] TYPE` in one statement. Atlas prints its
400
+ * dry-run statements under a `-> ` marker and puts several clauses in one
401
+ * `ALTER TABLE`, so both are handled.
402
+ */
403
+ function parseColumnTypeChanges(statement) {
404
+ const table = ALTER_TABLE_RE.exec(fromAlterTable(statement));
405
+ if (!table) return [];
406
+ const [schema, name] = table[2] ? [unquote(table[1]), unquote(table[2])] : [void 0, unquote(table[1])];
407
+ const changes = [];
408
+ for (const clause of splitClauses(table[3])) {
409
+ const match = TYPE_CLAUSE_RE.exec(clause);
410
+ if (!match) continue;
411
+ const to = match[2].split(/\s+(?:USING|COLLATE)\s/i)[0].trim();
412
+ changes.push({
413
+ schema,
414
+ table: name,
415
+ column: unquote(match[1]),
416
+ to
417
+ });
418
+ }
419
+ return changes;
420
+ }
421
+ /** `ADD [CONSTRAINT "x"] PRIMARY KEY ("a", "b")`, one clause of an `ALTER TABLE`. */
422
+ var ADD_PRIMARY_KEY_RE = new RegExp(String.raw`^ADD\s+(?:CONSTRAINT\s+${IDENT}\s+)?PRIMARY\s+KEY\b\s*(?:\(([^)]*)\))?`, "i");
423
+ /** `DROP CONSTRAINT [IF EXISTS] "x"`, one clause of an `ALTER TABLE`. */
424
+ var DROP_CONSTRAINT_RE = new RegExp(String.raw`^DROP\s+CONSTRAINT\s+(?:IF\s+EXISTS\s+)?(${IDENT})`, "i");
425
+ /** What a row loses when the columns that address it change. */
426
+ var ROW_ADDRESS_LOST = "every row's id changes, so anything that refers to a row by its id — a URL, a foreign key, an id stored elsewhere — stops finding it";
427
+ /**
428
+ * What an `ALTER TABLE` does to the table's primary key, in a sentence — or
429
+ * `undefined` when it leaves the key alone.
430
+ *
431
+ * The key is a row's address: Rebase reads, links and routes every row by it.
432
+ * Atlas plans a key change as `DROP CONSTRAINT "<table>_pkey", ADD PRIMARY KEY
433
+ * (…)` — one routine-looking statement that names no DROP of data — so moving
434
+ * a collection from `(id)` to `(id, locale)` re-keyed a populated table with
435
+ * no prompt. A `CREATE TABLE`'s own `PRIMARY KEY` is not a change and is never
436
+ * read here: only an `ALTER TABLE`'s clauses are. A dropped constraint counts
437
+ * as the key when it carries Postgres's default name for one, `<table>_pkey`;
438
+ * a key under another name is caught by the `ADD PRIMARY KEY` that replaces it.
439
+ */
440
+ function describePrimaryKeyChange(statement) {
441
+ const alter = ALTER_TABLE_RE.exec(fromAlterTable(statement));
442
+ if (!alter) return void 0;
443
+ const table = alter[2] ? `${alter[1]}.${alter[2]}` : alter[1];
444
+ let added;
445
+ let dropped;
446
+ for (const clause of splitClauses(alter[3])) {
447
+ const add = ADD_PRIMARY_KEY_RE.exec(clause);
448
+ if (add) {
449
+ added = add[1] === void 0 ? "a new key" : `(${add[1].split(",").map((c) => c.trim()).join(", ")})`;
450
+ continue;
451
+ }
452
+ const drop = DROP_CONSTRAINT_RE.exec(clause);
453
+ if (drop && unquote(drop[1]).endsWith("_pkey")) dropped = drop[1];
454
+ }
455
+ if (added && dropped) return `${table} is re-keyed on ${added}: ${ROW_ADDRESS_LOST}`;
456
+ if (added) return `${table} gets the primary key ${added}: rows are addressed by it from now on, and the push fails if two rows share a value`;
457
+ if (dropped) return `${table} loses its primary key ${dropped}: ${ROW_ADDRESS_LOST}`;
458
+ }
459
+ /**
460
+ * The CHECK and EXCLUDE constraints an `ALTER TABLE` drops, in a sentence — or
461
+ * `undefined` when it drops none.
462
+ *
463
+ * Matched by name on the statement's table, in its schema when the plan names
464
+ * one (Atlas always does). A constraint the catalogue does not list as a CHECK
465
+ * or an EXCLUDE — a foreign key, a `UNIQUE`, the primary key — is not this.
466
+ */
467
+ function describeConstraintDrops(statement, constraints) {
468
+ if (constraints.length === 0) return void 0;
469
+ const alter = ALTER_TABLE_RE.exec(fromAlterTable(statement));
470
+ if (!alter) return void 0;
471
+ const [schema, table] = alter[2] ? [unquote(alter[1]), unquote(alter[2])] : [void 0, unquote(alter[1])];
472
+ const lost = [];
473
+ for (const clause of splitClauses(alter[3])) {
474
+ const drop = DROP_CONSTRAINT_RE.exec(clause);
475
+ if (!drop) continue;
476
+ const name = unquote(drop[1]);
477
+ const constraint = constraints.find((c) => c.table === table && c.name === name && (schema === void 0 || c.schema === schema));
478
+ if (constraint) lost.push(`${constraint.kind === "check" ? "CHECK" : "EXCLUDE"} "${name}"`);
479
+ }
480
+ if (lost.length === 0) return void 0;
481
+ return `${schema ? `${schema}.${table}` : table} loses ${lost.join(", ")}: no row is lost, and the database accepts every row ${lost.length === 1 ? "it refuses" : "they refuse"} today`;
482
+ }
483
+ /**
484
+ * The column's current type. A table named without its schema matches in any
485
+ * schema, but only when every match agrees — two same-named tables with
486
+ * different types leave the answer unknown.
487
+ */
488
+ function currentTypeOf(change, columnTypes) {
489
+ const types = new Set(columnTypes.filter((col) => col.table === change.table && col.column === change.column && (change.schema === void 0 || col.schema === change.schema)).map((col) => col.type));
490
+ return types.size === 1 ? [...types][0] : void 0;
491
+ }
492
+ /** Spellings of one type, mapped to one name. Anything absent compares verbatim. */
493
+ var TYPE_ALIASES = {
494
+ "int": "integer",
495
+ "int4": "integer",
496
+ "int2": "smallint",
497
+ "int8": "bigint",
498
+ "character varying": "varchar",
499
+ "decimal": "numeric",
500
+ "timestamp without time zone": "timestamp",
501
+ "timestamp with time zone": "timestamptz",
502
+ "time without time zone": "time",
503
+ "time with time zone": "timetz",
504
+ "bool": "boolean",
505
+ "float4": "real",
506
+ "float8": "double precision",
507
+ "character": "bpchar",
508
+ "char": "bpchar"
509
+ };
510
+ /** Decimal digits each integer type holds, which is what a `numeric` must hold too. */
511
+ var INTEGER_DIGITS = {
512
+ smallint: 5,
513
+ integer: 10,
514
+ bigint: 19
515
+ };
516
+ /** Types whose modifier is a fractional-seconds precision, 6 when absent. */
517
+ var SECONDS_PRECISION = /* @__PURE__ */ new Set([
518
+ "timestamp",
519
+ "timestamptz",
520
+ "time",
521
+ "timetz"
522
+ ]);
523
+ function parseType(raw) {
524
+ let text = raw.trim().replace(/\s+/g, " ");
525
+ let dims = 0;
526
+ for (let suffix = /\s*\[\d*\]$/.exec(text); suffix; suffix = /\s*\[\d*\]$/.exec(text)) {
527
+ dims++;
528
+ text = text.slice(0, suffix.index);
529
+ }
530
+ if (text.includes("\"")) return {
531
+ base: text,
532
+ dims
533
+ };
534
+ text = text.toLowerCase().replace(/^pg_catalog\./, "");
535
+ let args;
536
+ const modifier = /\(([^)]*)\)/.exec(text);
537
+ if (modifier) {
538
+ args = modifier[1].split(",").map((part) => Number(part.trim()));
539
+ text = `${text.slice(0, modifier.index)} ${text.slice(modifier.index + modifier[0].length)}`.replace(/\s+/g, " ").trim();
540
+ }
541
+ return {
542
+ base: TYPE_ALIASES[text] ?? text,
543
+ args,
544
+ dims
545
+ };
546
+ }
547
+ /** Does moving from one modifier to another, on the same type, keep every value? */
548
+ function modifierWidens(base, from, to) {
549
+ if (JSON.stringify(from) === JSON.stringify(to)) return true;
550
+ if (base === "varchar") return to === void 0 || from !== void 0 && to[0] >= from[0];
551
+ if (base === "numeric") {
552
+ if (to === void 0) return true;
553
+ if (from === void 0) return false;
554
+ const [p1, s1 = 0] = from;
555
+ const [p2, s2 = 0] = to;
556
+ return s2 >= s1 && p2 - s2 >= p1 - s1;
557
+ }
558
+ if (SECONDS_PRECISION.has(base)) return (to?.[0] ?? 6) >= (from?.[0] ?? 6);
559
+ return false;
560
+ }
561
+ /**
562
+ * Is `ALTER COLUMN … TYPE to` a widening, one that keeps every value exactly
563
+ * as it was?
564
+ *
565
+ * Deliberately short. Everything not listed needs a confirmation, including
566
+ * changes that are usually harmless: `timestamp` → `timestamptz` reads each
567
+ * value in the session's time zone, `json` → `jsonb` drops duplicate keys,
568
+ * `real` → `double precision` prints 0.1 as 0.100000001490116, and `integer` →
569
+ * `text` keeps the digits but changes what the column is.
570
+ *
571
+ * - the same type, with a modifier at least as wide (`varchar(100)` →
572
+ * `varchar(255)`, `numeric(10,2)` → `numeric(12,2)` or unbounded,
573
+ * `timestamptz(3)` → `timestamptz`);
574
+ * - `smallint` → `integer` → `bigint`, and any of them to a `numeric` with
575
+ * room for all their digits;
576
+ * - `varchar(n)` → `text`, and `text` → an unbounded `varchar`.
577
+ *
578
+ * Arrays follow their element type, and never gain or lose a dimension.
579
+ */
580
+ function isLosslessTypeChange(from, to) {
581
+ const a = parseType(from);
582
+ const b = parseType(to);
583
+ if (a.dims !== b.dims) return false;
584
+ if (a.args?.some(Number.isNaN) || b.args?.some(Number.isNaN)) return false;
585
+ if (a.base === b.base) return modifierWidens(a.base, a.args, b.args);
586
+ const fromDigits = INTEGER_DIGITS[a.base];
587
+ if (fromDigits !== void 0) {
588
+ const toDigits = INTEGER_DIGITS[b.base];
589
+ if (toDigits !== void 0) return toDigits >= fromDigits;
590
+ if (b.base === "numeric") return b.args === void 0 || b.args[0] - (b.args[1] ?? 0) >= fromDigits;
591
+ return false;
592
+ }
593
+ if (a.base === "varchar" && b.base === "text") return true;
594
+ if (a.base === "text" && b.base === "varchar") return b.args === void 0;
595
+ return false;
596
+ }
597
+ /**
598
+ * The flag that opted a push into destructive changes, as it was given —
599
+ * `--allow-destructive`, or its alias `--yes` / `-y` — or `undefined` for
600
+ * none. The line that says why a destructive push went ahead names the one
601
+ * the user typed: "because --allow-destructive was passed" to someone who
602
+ * typed `--yes` reads like a flag they never set.
603
+ */
604
+ function destructiveOptInFlag(args) {
605
+ if (args["--allow-destructive"] === true) return "--allow-destructive";
606
+ if (args["--yes"] === true) return "--yes";
607
+ }
608
+ /**
609
+ * Decide how `db push` should proceed given the plan's destructiveness and
610
+ * the invocation context.
611
+ *
612
+ * - No destructive statements → `apply` (safe to auto-approve).
613
+ * - Destructive + `--allow-destructive` → `apply` (operator opted in).
614
+ * - Destructive + interactive TTY → `confirm` (prompt before applying).
615
+ * - Destructive + non-interactive → `refuse` (never silently drop data in
616
+ * CI / scripts / agents).
617
+ */
618
+ function decidePushSafety(opts) {
619
+ if (opts.destructiveCount === 0) return "apply";
620
+ if (opts.allowDestructive) return "apply";
621
+ return opts.interactive ? "confirm" : "refuse";
622
+ }
623
+ //#endregion
624
+ //#region src/schema/undeclarable-constraints.ts
625
+ /**
626
+ * The constraints a collection cannot declare, and how `db push` keeps Atlas
627
+ * from dropping them.
628
+ *
629
+ * `db push` is declarative: Atlas makes each managed table match `schema.sql`,
630
+ * and anything on the table that `schema.sql` does not mention is planned as a
631
+ * drop. The collection model declares a table's primary key, its columns'
632
+ * `NOT NULL`, `UNIQUE` and foreign keys, and nothing else. So a hand-written
633
+ * `CHECK (total >= 0)` — or one an adopted database arrived with, which
634
+ * `schema introspect` reads as `validation.min: 0` — was dropped by the first
635
+ * push, in the same `ALTER TABLE` as whatever else the push changed, with no
636
+ * prompt. From then on the database accepted every row the constraint used to
637
+ * refuse, while the form still enforced the rule and so hid that it had gone.
638
+ *
639
+ * EXCLUDE constraints are the same case: Atlas inspects them and plans their
640
+ * drop the same way. Triggers and functions are not: Atlas's free tier does
641
+ * not inspect either, so it never plans a drop for one. Measured on the pinned
642
+ * atlas 1.2.3 against PG 18; `introspect-check-constraints-e2e` pins all four.
643
+ *
644
+ * Ownership, as with indexes (`getForeignIndexExcludes` in `cli-helpers.ts`)
645
+ * and policies: a constraint the desired state declares is
646
+ * Atlas's to manage, and every other CHECK or EXCLUDE is somebody else's and is
647
+ * kept out of the plan with `--exclude`. Today the desired state declares
648
+ * neither kind, so every one is kept. A rule nobody wants any more is dropped
649
+ * by hand (`ALTER TABLE … DROP CONSTRAINT …`), which is the only statement that
650
+ * can say so.
651
+ *
652
+ * Side-effect free, so it is unit-tested without Atlas or a database.
653
+ */
654
+ /**
655
+ * Every CHECK and EXCLUDE constraint on an ordinary or partitioned table
656
+ * outside the system schemas.
657
+ *
658
+ * `contype` `c` and `x` only. A primary key (`p`), `UNIQUE` (`u`), foreign key
659
+ * (`f`) and, from PG 18, a catalogued `NOT NULL` (`n`) are what a collection
660
+ * declares, so Atlas keeps managing them.
661
+ */
662
+ var UNDECLARABLE_CONSTRAINTS_SQL = `
663
+ SELECT n.nspname AS "schema",
664
+ c.relname AS "table",
665
+ con.conname AS "name",
666
+ CASE con.contype WHEN 'c' THEN 'check' ELSE 'exclude' END AS "kind"
667
+ FROM pg_constraint con
668
+ JOIN pg_class c ON c.oid = con.conrelid
669
+ JOIN pg_namespace n ON n.oid = c.relnamespace
670
+ WHERE con.contype IN ('c', 'x')
671
+ AND c.relkind IN ('r', 'p')
672
+ AND n.nspname NOT IN ('pg_catalog', 'information_schema')
673
+ AND n.nspname NOT LIKE 'pg\\_%'
674
+ `;
675
+ var DECLARED_CONSTRAINT_RE = /\bCONSTRAINT\s+"((?:[^"]|"")+)"\s+(?:CHECK|EXCLUDE)\b/gi;
676
+ /**
677
+ * The CHECK and EXCLUDE constraint names a desired state (`schema.sql`)
678
+ * declares — Atlas's to manage, and so never excluded.
679
+ */
680
+ function declaredConstraintNames(desiredSql) {
681
+ const names = /* @__PURE__ */ new Set();
682
+ for (const match of desiredSql.matchAll(DECLARED_CONSTRAINT_RE)) names.add(match[1].replace(/""/g, "\""));
683
+ return names;
684
+ }
685
+ /**
686
+ * The `--exclude` patterns that keep Atlas from dropping the CHECK and EXCLUDE
687
+ * constraints the desired state does not declare. Three-part
688
+ * `schema.table.constraint`, which is what Atlas matches a constraint by: a
689
+ * two-part pattern reads as a table, matches nothing, and reports no error.
690
+ */
691
+ function undeclaredConstraintExcludes(existing, desiredSql) {
692
+ const declared = declaredConstraintNames(desiredSql);
693
+ return existing.filter((constraint) => !declared.has(constraint.name)).map((constraint) => atlasExcludePattern(constraint.schema, constraint.table, constraint.name));
694
+ }
695
+ //#endregion
696
+ //#region src/module-dir.ts
697
+ var moduleDir = path.dirname(fileURLToPath(import.meta.url));
698
+ //#endregion
699
+ //#region src/generated-sql.ts
700
+ /**
701
+ * Where `db push` and `db generate` put the SQL they render from the collections.
702
+ *
703
+ * Five files — `schema.sql` (Atlas's desired state), `policies.sql`,
704
+ * `search.sql`, `vector.sql` and `triggers.sql` — and every one of them is
705
+ * scratch. Both commands regenerate all five before reading any of them, and
706
+ * nothing else reads them at all. They used to be written into `drizzle/`, beside
707
+ * the migrations, and committed: a copy nobody read, which every collection
708
+ * change rewrote in the diff and every two branches touching collections
709
+ * conflicted on.
710
+ *
711
+ * Relative to the directory the command runs in (the backend), like the
712
+ * migrations are.
713
+ */
714
+ /** The directory, relative to the working directory. POSIX, because it is also a URL path. */
715
+ var GENERATED_SQL_DIR = ".rebase/sql";
716
+ /**
717
+ * `schema.sql` as Atlas takes it. Relative on purpose, like the
718
+ * `file://drizzle/migrations` beside it: Atlas joins the URL's host and path, so
719
+ * `.rebase` is read as the first path segment, measured against the pinned 1.2.3.
720
+ */
721
+ var DESIRED_STATE_URL = `file://${GENERATED_SQL_DIR}/schema.sql`;
722
+ /** The files the DDL generator writes, all of them derived from the collections. */
723
+ var GENERATED_SQL_FILES = [
724
+ "schema.sql",
725
+ "policies.sql",
726
+ "search.sql",
727
+ "vector.sql",
728
+ "triggers.sql"
729
+ ];
730
+ /** The absolute directory, for the working directory the command runs in. */
731
+ function generatedSqlDir(cwd = process.cwd()) {
732
+ return path.resolve(cwd, GENERATED_SQL_DIR);
733
+ }
734
+ /**
735
+ * The first line of every file the generator writes, in every release that
736
+ * wrote them into `drizzle/`. Matching it is what makes removing the old copy
737
+ * safe: a file there under one of these names that does not open this way was
738
+ * written by a person, and is left alone.
739
+ */
740
+ var GENERATED_HEADER = /^-- This file (is auto-generated by the Rebase DDL generator|contains RLS policies generated by Rebase)\./;
741
+ /**
742
+ * Get the directory ready to be written, and retire the copies an older release
743
+ * committed.
744
+ *
745
+ * The directory ignores itself, rather than relying on the project's
746
+ * `.gitignore`: a scaffold ignores `.rebase/`, but a project created before it
747
+ * did would otherwise start committing these files from their new home.
748
+ *
749
+ * The old copies in `drizzle/` are deleted, not left behind. Nothing writes them
750
+ * any more, so from the first push after an upgrade they only fall further
751
+ * behind — and a stale `policies.sql` in the repository is exactly what someone
752
+ * reviewing the project's RLS would read.
753
+ *
754
+ * With `retire: false` (`db push --dry-run`, which writes nothing of the
755
+ * project's) the old copies are only found, not removed.
756
+ *
757
+ * @returns the old files it removed — or, with `retire: false`, would remove —
758
+ * relative to the working directory.
759
+ */
760
+ function prepareGeneratedSqlDir(cwd = process.cwd(), options = {}) {
761
+ const dir = generatedSqlDir(cwd);
762
+ fs.mkdirSync(dir, { recursive: true });
763
+ const ignore = path.join(dir, ".gitignore");
764
+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, "# Generated by `rebase db push` / `rebase db generate` from the collections.\n*\n");
765
+ const removed = [];
766
+ for (const name of GENERATED_SQL_FILES) {
767
+ const legacy = path.join(cwd, "drizzle", name);
768
+ if (!fs.existsSync(legacy)) continue;
769
+ const firstLine = fs.readFileSync(legacy, "utf-8").split("\n", 1)[0];
770
+ if (!GENERATED_HEADER.test(firstLine)) continue;
771
+ if (options.retire !== false) fs.rmSync(legacy);
772
+ removed.push(path.posix.join("drizzle", name));
773
+ }
774
+ return removed;
775
+ }
776
+ //#endregion
777
+ //#region src/cli-helpers.ts
778
+ /**
779
+ * Which package manager installed this project, read off its lockfile.
780
+ *
781
+ * Every remedy for a blocked build script is package-manager specific, and
782
+ * naming the wrong one is the same failure as naming none: `pnpm approve-builds`
783
+ * is not a thing an npm user can run, and `pnpm.onlyBuiltDependencies` is a key
784
+ * npm does not read. This existed as a pnpm-only message for long enough that
785
+ * npm 12 — which blocks dependency lifecycle scripts by default, the way pnpm 10
786
+ * does — could ship and leave every npm reader three unfollowable commands deep.
787
+ *
788
+ * The lockfile, not `npm_config_user_agent`: the question is how the project's
789
+ * `node_modules` was built, not which binary happens to be invoking us. Walks up
790
+ * because commands run from `backend/` in a scaffolded project, and the lockfile
791
+ * is at the workspace root.
792
+ */
793
+ function detectProjectPackageManager(startDir = process.cwd()) {
794
+ const lockfiles = [
795
+ ["pnpm-lock.yaml", "pnpm"],
796
+ ["bun.lock", "bun"],
797
+ ["bun.lockb", "bun"],
798
+ ["yarn.lock", "yarn"],
799
+ ["package-lock.json", "npm"]
800
+ ];
801
+ let dir = path.resolve(startDir);
802
+ while (true) {
803
+ for (const [file, manager] of lockfiles) if (fs.existsSync(path.join(dir, file))) return manager;
804
+ const parent = path.dirname(dir);
805
+ if (parent === dir) return "unknown";
806
+ dir = parent;
807
+ }
808
+ }
809
+ /**
810
+ * How to let `@ariga/atlas` run its `preinstall`, in the reader's own package
811
+ * manager.
812
+ *
813
+ * Returns the lines to print after "the binary is missing but the package is
814
+ * installed". Kept next to {@link detectProjectPackageManager} so the two move
815
+ * together, and returned rather than printed so it can be asserted on.
816
+ */
817
+ function describeBuildScriptRemedy(packageName, manager = detectProjectPackageManager()) {
818
+ switch (manager) {
819
+ case "npm": return [
820
+ ` npm install-scripts approve ${packageName}`,
821
+ "",
822
+ " or, to record it in the project (what `rebase init` scaffolds):",
823
+ "",
824
+ " // package.json",
825
+ ` "allowScripts": { "${packageName}": true }`,
826
+ "",
827
+ " Then re-run `npm install`."
828
+ ];
829
+ case "yarn": return [
830
+ " // .yarnrc.yml",
831
+ " enableScripts: true",
832
+ "",
833
+ " Then re-run `yarn install`."
834
+ ];
835
+ case "bun": return [
836
+ " // package.json",
837
+ ` "trustedDependencies": ["${packageName}"]`,
838
+ "",
839
+ " Then re-run `bun install`."
840
+ ];
841
+ default: return [
842
+ " pnpm approve-builds",
843
+ "",
844
+ " or, to record it in the project (what `rebase init` scaffolds):",
845
+ "",
846
+ " // package.json",
847
+ ` "pnpm": { "onlyBuiltDependencies": ["${packageName}"] }`,
848
+ "",
849
+ " Then re-run `pnpm install`."
850
+ ];
851
+ }
852
+ }
853
+ /**
854
+ * "Install again, from scratch", in the reader's own package manager.
855
+ *
856
+ * For the `bin-link-missing` state: the tree is half-written, and re-resolving
857
+ * it is what recreates the `.bin` shim. `--force` on pnpm is what makes it
858
+ * relink rather than decide the tree is already up to date.
859
+ */
860
+ function describeReinstallCommand(manager = detectProjectPackageManager()) {
861
+ switch (manager) {
862
+ case "npm": return "rm -rf node_modules && npm install";
863
+ case "yarn": return "yarn install --force";
864
+ case "bun": return "rm -rf node_modules && bun install";
865
+ default: return "pnpm install --force";
866
+ }
867
+ }
868
+ /** `add <pkg>` as a dev dependency, in the reader's own package manager. */
869
+ function describeDevAddCommand(packageName, manager = detectProjectPackageManager()) {
870
+ switch (manager) {
871
+ case "npm": return `npm install -D ${packageName}`;
872
+ case "yarn": return `yarn add -D ${packageName}`;
873
+ case "bun": return `bun add -d ${packageName}`;
874
+ default: return `pnpm add -D ${packageName}`;
875
+ }
876
+ }
877
+ /**
878
+ * Where a package's own manifest lives, or null if it is not installed here.
879
+ *
880
+ * `package.json` rather than the package root: a package with an `exports` map
881
+ * that omits `.` is unresolvable by name even when it is perfectly installed,
882
+ * which would misreport it as absent.
883
+ */
884
+ function resolvePackageManifest(packageName) {
885
+ const bases = [pathToFileURL(path.join(process.cwd(), "package.json")), pathToFileURL(path.join(moduleDir, "package.json"))];
886
+ for (const base of bases) try {
887
+ return createRequire(base).resolve(`${packageName}/package.json`);
888
+ } catch {}
889
+ return null;
890
+ }
891
+ /**
892
+ * The binaries a package's own manifest declares, as absolute paths.
893
+ *
894
+ * `bin` is a string for a single binary named after the package, or a map.
895
+ * Both forms appear in the wild and `@ariga/atlas` uses the map.
896
+ */
897
+ function declaredBinaries(manifestPath) {
898
+ let manifest;
899
+ try {
900
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
901
+ } catch {
902
+ return [];
903
+ }
904
+ const dir = path.dirname(manifestPath);
905
+ if (typeof manifest.bin === "string") return [path.resolve(dir, manifest.bin)];
906
+ if (manifest.bin && typeof manifest.bin === "object") return Object.values(manifest.bin).filter((target) => typeof target === "string").map((target) => path.resolve(dir, target));
907
+ return [];
908
+ }
909
+ function diagnoseMissingBin(packageName) {
910
+ const manifestPath = resolvePackageManifest(packageName);
911
+ if (!manifestPath) return "not-installed";
912
+ const binaries = declaredBinaries(manifestPath);
913
+ if (binaries.length === 0) return "build-script-blocked";
914
+ return binaries.some((file) => fs.existsSync(file)) ? "bin-link-missing" : "build-script-blocked";
915
+ }
916
+ function resolveLocalBin(binName) {
917
+ let dir = moduleDir;
918
+ while (true) {
919
+ const candidate = path.join(dir, "node_modules", ".bin", binName);
920
+ if (fs.existsSync(candidate)) return candidate;
921
+ const parent = path.dirname(dir);
922
+ if (parent === dir) break;
923
+ dir = parent;
924
+ }
925
+ let cwd = process.cwd();
926
+ while (true) {
927
+ const candidate = path.join(cwd, "node_modules", ".bin", binName);
928
+ if (fs.existsSync(candidate)) return candidate;
929
+ const parent = path.dirname(cwd);
930
+ if (parent === cwd) break;
931
+ cwd = parent;
932
+ }
933
+ try {
934
+ const globalPath = execSync(process.platform === "win32" ? `where ${binName}` : `which ${binName}`, { encoding: "utf-8" }).trim().split("\n")[0].trim();
935
+ if (globalPath && fs.existsSync(globalPath)) return globalPath;
936
+ } catch {}
937
+ return null;
938
+ }
939
+ async function getTableIncludesFromCollections(allCollections) {
940
+ const { getTableName, relationalCollections, resolveJunctionSpecs } = await import("@rebasepro/common");
941
+ const { isPostgresCollectionConfig } = await import("@rebasepro/types");
942
+ const collections = relationalCollections(allCollections);
943
+ const includes = [];
944
+ for (const col of collections) {
945
+ const tableName = getTableName(col);
946
+ const schema = isPostgresCollectionConfig(col) && col.schema ? col.schema : "public";
947
+ if (tableName) includes.push(`${schema}.${tableName}`);
948
+ }
949
+ for (const junction of resolveJunctionSpecs(collections).values()) includes.push(`${junction.schema}.${junction.table}`);
950
+ return Array.from(new Set(includes));
951
+ }
952
+ async function getTableIncludes(collectionsPath) {
953
+ return getTableIncludesFromCollections(await loadCollectionsForCli(collectionsPath));
954
+ }
955
+ /**
956
+ * Load a project's collections the way the Atlas-facing commands need them.
957
+ *
958
+ * Deliberately forgiving — a file that fails to import is skipped rather than
959
+ * fatal — because the callers use this to *narrow* what Atlas may touch, and a
960
+ * hard failure here would block a push over an unrelated broken file. Callers
961
+ * that cannot tolerate a partial answer (the table excludes, which fail closed)
962
+ * check the result themselves.
963
+ */
964
+ /** Paths this process has already complained about. See {@link loadCollectionsForCli}. */
965
+ var warnedMissingCollectionsPaths = /* @__PURE__ */ new Set();
966
+ async function loadCollectionsForCli(collectionsPath) {
967
+ const resolvedPath = path.resolve(collectionsPath);
968
+ const collections = [];
969
+ if (!fs.existsSync(resolvedPath) && !warnedMissingCollectionsPaths.has(resolvedPath)) {
970
+ warnedMissingCollectionsPaths.add(resolvedPath);
971
+ outWarn(chalk.yellow(` ⚠ Collections path not found: "${collectionsPath}"\n Resolved to: ${resolvedPath}\n (relative to cwd: ${process.cwd()})\n Pass an absolute path, or a path relative to where you run the command.`));
972
+ }
973
+ if (fs.existsSync(resolvedPath)) {
974
+ if (fs.statSync(resolvedPath).isDirectory()) {
975
+ const files = fs.readdirSync(resolvedPath);
976
+ for (const file of files) if ((file.endsWith(".ts") || file.endsWith(".js")) && !file.includes(".test.") && !file.endsWith(".d.ts") && file !== "index.ts" && file !== "index.js") try {
977
+ const module = await import(pathToFileURL(path.join(resolvedPath, file)).href);
978
+ if (module && module.default) collections.push(module.default);
979
+ } catch {}
980
+ }
981
+ }
982
+ return collections;
983
+ }
984
+ /**
985
+ * The app database connections this process has open, by URL — one each.
986
+ *
987
+ * `rebase db push` used to open a connection per step: the auth bootstrap, the
988
+ * connectivity probe, each catalogue read behind the Atlas excludes, the
989
+ * column types, the generated-column edges, and then every post-step — RLS
990
+ * lock, auth tables, vector, search, triggers, policies, reconcile, role,
991
+ * legacy schema. 18 of them on a push that changed nothing. Locally each costs
992
+ * a few milliseconds; against a hosted Postgres over TLS a connect is four or
993
+ * five round trips (TCP, TLS 1.3, startup, SCRAM twice) — about 4 s of every
994
+ * push at 40 ms, and more on a serverless database that wakes per connection.
995
+ *
996
+ * Opened on first use and closed by {@link closeAppClients} when the command
997
+ * ends. The scratch database Atlas plans in is created and dropped through the
998
+ * `postgres` database, on a connection of its own: it is not this one.
999
+ */
1000
+ var appClients = /* @__PURE__ */ new Map();
1001
+ async function openAppClient(databaseUrl, connectionTimeoutMillis) {
1002
+ const open = appClients.get(databaseUrl);
1003
+ if (open) return open;
1004
+ const opening = (async () => {
1005
+ const { Client } = await import("pg");
1006
+ const client = new Client({
1007
+ connectionString: databaseUrl,
1008
+ ...connectionTimeoutMillis ? { connectionTimeoutMillis } : {}
1009
+ });
1010
+ const forget = () => {
1011
+ if (appClients.get(databaseUrl) === opening) appClients.delete(databaseUrl);
1012
+ };
1013
+ client.on("error", forget);
1014
+ client.on("end", forget);
1015
+ await client.connect();
1016
+ return client;
1017
+ })();
1018
+ appClients.set(databaseUrl, opening);
1019
+ try {
1020
+ return await opening;
1021
+ } catch (err) {
1022
+ appClients.delete(databaseUrl);
1023
+ throw err;
1024
+ }
1025
+ }
1026
+ /**
1027
+ * Run one step on this process's connection to the app database.
1028
+ *
1029
+ * Every step leaves the session as it found it, which is what a connection of
1030
+ * its own used to guarantee by being closed. None of them sets anything for
1031
+ * the session — `SET LOCAL` inside their own transaction, or `RESET` — and one
1032
+ * that fails part-way through a transaction it opened is rolled back here, so
1033
+ * the next step does not meet `current transaction is aborted`.
1034
+ *
1035
+ * @param options.connectionTimeoutMillis applies only when this call is the one
1036
+ * that connects.
1037
+ */
1038
+ async function withAppClient(databaseUrl, step, options = {}) {
1039
+ const client = await openAppClient(databaseUrl, options.connectionTimeoutMillis);
1040
+ try {
1041
+ return await step(client);
1042
+ } catch (err) {
1043
+ await client.query("ROLLBACK").catch(() => void 0);
1044
+ throw err;
1045
+ }
1046
+ }
1047
+ /** Close every connection {@link withAppClient} opened. Called once, as the command ends. */
1048
+ async function closeAppClients() {
1049
+ const open = [...appClients.values()];
1050
+ appClients.clear();
1051
+ await Promise.all(open.map(async (opening) => {
1052
+ try {
1053
+ await (await opening).end();
1054
+ } catch {}
1055
+ }));
1056
+ }
1057
+ /**
1058
+ * Names the empty database Atlas plans against, instead of `<db>_dev_diff`.
1059
+ *
1060
+ * The derived one is made with `CREATE DATABASE` beside the real database,
1061
+ * which assumes a server that holds more than one. PGlite — the managed
1062
+ * development database — serves exactly one: the CREATE succeeds and creates
1063
+ * nothing, so Atlas connected straight back to the database it was comparing
1064
+ * and refused it as "not clean". `rebase db push` on the managed database now
1065
+ * starts a second, throwaway PGlite and names it here. Anyone can name their
1066
+ * own the same way; a named database is neither created nor dropped.
1067
+ */
1068
+ var ATLAS_DEV_URL_ENV = "REBASE_ATLAS_DEV_URL";
1069
+ /**
1070
+ * The database Atlas replays the desired schema into: the one
1071
+ * {@link ATLAS_DEV_URL_ENV} names (`named: true` — not ours to create or
1072
+ * drop), else `<db>_dev_diff`.
1073
+ */
1074
+ function atlasDevDatabaseUrl(databaseUrl, env) {
1075
+ const named = env[ATLAS_DEV_URL_ENV]?.trim();
1076
+ if (!named) return {
1077
+ url: getDevDatabaseUrl(databaseUrl),
1078
+ named: false
1079
+ };
1080
+ if (named === databaseUrl.trim()) throw new Error(`${ATLAS_DEV_URL_ENV} names the same database as DATABASE_URL. It must be a separate, empty database that Atlas may fill and clear.`);
1081
+ return {
1082
+ url: named,
1083
+ named: true
1084
+ };
1085
+ }
1086
+ function getDevDatabaseUrl(databaseUrl) {
1087
+ try {
1088
+ const parsed = new URL(databaseUrl);
1089
+ parsed.pathname = `/${parsed.pathname.slice(1)}_dev_diff`;
1090
+ return parsed.toString();
1091
+ } catch {
1092
+ return databaseUrl + "_dev_diff";
1093
+ }
1094
+ }
1095
+ /**
1096
+ * Create the scratch database Atlas plans against, and say so when we cannot.
1097
+ *
1098
+ * Atlas needs a `--dev-url` — an empty database it can build the desired state
1099
+ * in — and this makes `<db>_dev_diff` next to the real one. The whole body used
1100
+ * to be wrapped in an empty catch commented "Ignore, let Atlas handle
1101
+ * connection failures", and Atlas's version of handling it is `postgres:
1102
+ * querying system variables: pq: database "app_dev_diff" does not exist
1103
+ * (3D000)` — the symptom, four frames downstream of the cause, with the cause
1104
+ * thrown away.
1105
+ *
1106
+ * The cause is almost always `42501`: `CREATE DATABASE` is a privilege managed
1107
+ * providers do not grant, so this is the first thing a hosted user hits and the
1108
+ * one they can do least with.
1109
+ *
1110
+ * @returns whether the scratch database was created by *this* call — the only
1111
+ * case in which dropping it afterwards is ours to do.
1112
+ */
1113
+ async function ensureDevDatabaseExists(databaseUrl, devDatabaseUrl) {
1114
+ let devDbName = "";
1115
+ try {
1116
+ const { Client } = await import("pg");
1117
+ const parsed = new URL(databaseUrl);
1118
+ devDbName = new URL(devDatabaseUrl).pathname.slice(1);
1119
+ parsed.pathname = "/postgres";
1120
+ const client = new Client({ connectionString: parsed.toString() });
1121
+ await client.connect();
1122
+ try {
1123
+ if ((await client.query("SELECT 1 FROM pg_database WHERE datname = $1", [devDbName])).rowCount === 0) {
1124
+ await client.query(`CREATE DATABASE "${devDbName}"`);
1125
+ out(chalk.gray(` ✓ Created validation database "${devDbName}"`));
1126
+ return true;
1127
+ }
1128
+ } finally {
1129
+ await client.end();
1130
+ }
1131
+ } catch (err) {
1132
+ outWarn(describeDevDatabaseFailure(err, devDbName || "<db>_dev_diff"));
1133
+ }
1134
+ return false;
1135
+ }
1136
+ /**
1137
+ * What went wrong creating the scratch database, and what to do about it.
1138
+ *
1139
+ * Exported for its test: the `42501` branch is the one that matters and it
1140
+ * cannot be provoked without a non-superuser role.
1141
+ */
1142
+ function describeDevDatabaseFailure(err, devDbName) {
1143
+ const code = err?.code;
1144
+ const message = err instanceof Error ? err.message : String(err);
1145
+ const lines = [chalk.yellow(` ⚠ Could not create the Atlas scratch database "${devDbName}": ${message}`)];
1146
+ if (code === "42501") lines.push(chalk.gray(` Atlas plans every change in a throwaway copy of the schema, and CREATE DATABASE
1147
+ is a privilege most managed providers withhold. Two ways forward:
1148
+ • GRANT the role CREATEDB: ALTER ROLE "<role>" CREATEDB;
1149
+ • or create it once by hand: CREATE DATABASE "${devDbName}";`));
1150
+ else lines.push(chalk.gray(" Atlas will fail next with `database \"" + devDbName + "\" does not exist (3D000)`, which is this."));
1151
+ return lines.join("\n");
1152
+ }
1153
+ /**
1154
+ * Drop the scratch database again, after the command that needed it succeeded.
1155
+ *
1156
+ * It is a full copy of the schema — no rows, but every table, type and index —
1157
+ * and it was left behind per target forever. The only notice anyone got was
1158
+ * `rebase db branch prune` reporting "3 Atlas scratch database(s) left over
1159
+ * from db push", and on a provider that bills per database it is a silent cost.
1160
+ *
1161
+ * Deliberately NOT called on the failure path: after a failed push the scratch
1162
+ * database holds the state Atlas was planning against, which is the one thing
1163
+ * worth inspecting.
1164
+ */
1165
+ async function dropDevDatabase(databaseUrl, devDatabaseUrl) {
1166
+ try {
1167
+ const { Client } = await import("pg");
1168
+ const parsed = new URL(databaseUrl);
1169
+ const devDbName = new URL(devDatabaseUrl).pathname.slice(1);
1170
+ parsed.pathname = "/postgres";
1171
+ const client = new Client({ connectionString: parsed.toString() });
1172
+ await client.connect();
1173
+ try {
1174
+ await client.query(`DROP DATABASE IF EXISTS "${devDbName}"`);
1175
+ out(chalk.gray(` ✓ Removed validation database "${devDbName}"`));
1176
+ } finally {
1177
+ await client.end();
1178
+ }
1179
+ } catch (err) {
1180
+ outWarn(chalk.gray(` ⚠ Could not remove the Atlas scratch database: ${err instanceof Error ? err.message : String(err)}\n \`rebase db branch prune --include-dev-diff\` clears them.`));
1181
+ }
1182
+ }
1183
+ /**
1184
+ * The generated SQL for the project's `search` blocks, if it has any.
1185
+ *
1186
+ * @param sqlDir directory holding the generated SQL. Defaults to
1187
+ * `.rebase/sql` under the working directory.
1188
+ */
1189
+ function readSearchDdl(sqlDir = generatedSqlDir()) {
1190
+ const searchFile = path.join(sqlDir, "search.sql");
1191
+ if (!fs.existsSync(searchFile)) return "";
1192
+ return fs.readFileSync(searchFile, "utf-8").trim();
1193
+ }
1194
+ /**
1195
+ * Bring the search column, its index and their helpers up to date.
1196
+ *
1197
+ * Runs *after* Atlas, not before: the statements are `ALTER TABLE ... ADD
1198
+ * COLUMN`, so the table has to exist. Atlas is told to ignore these objects
1199
+ * entirely (`getSearchExcludes`) — it cannot manage them, and left to itself it
1200
+ * would plan a `DROP COLUMN` for every one, since they are absent from the
1201
+ * desired state it was given.
1202
+ *
1203
+ * A no-op when no collection declared `search`. A failure is *not* swallowed:
1204
+ * silently pushing a schema whose search column never appeared is how a
1205
+ * collection ends up with search configured, no error anywhere, and no results.
1206
+ */
1207
+ async function applySearchDdl(databaseUrl, sqlDir = generatedSqlDir()) {
1208
+ const sql = readSearchDdl(sqlDir);
1209
+ if (!sql) return;
1210
+ await withAppClient(databaseUrl, (client) => client.query(sql));
1211
+ out(chalk.gray(" ✓ Applied full-text search columns and indexes"));
1212
+ }
1213
+ /**
1214
+ * Glob patterns keeping Atlas away from the search objects.
1215
+ *
1216
+ * Returns an empty list — and so changes nothing — for a project with no
1217
+ * `search` block, which is every project that has not opted in.
1218
+ */
1219
+ async function getSearchExcludes(collectionsPath) {
1220
+ const { searchExcludePatterns } = await import("./generate-postgres-ddl-logic-B4k9djAV.js").then((n) => n.o);
1221
+ return searchExcludePatterns(await loadCollectionsForCli(collectionsPath));
1222
+ }
1223
+ /**
1224
+ * Every `generated column → column it reads` edge in the database.
1225
+ *
1226
+ * Read from `pg_depend` rather than by matching names in the expression text:
1227
+ * a generated column's `pg_attrdef` row carries one `deptype = 'n'` dependency
1228
+ * per column its expression references, which is the catalogue's own answer and
1229
+ * cannot be fooled by a column name that also appears inside a string literal
1230
+ * or as part of a longer identifier.
1231
+ *
1232
+ * Used by `db push` to find what has to come out of the way before Atlas runs —
1233
+ * see `generated-column-conflicts.ts` for why that is necessary at all.
1234
+ */
1235
+ async function queryGeneratedColumnDependencies(databaseUrl) {
1236
+ return withAppClient(databaseUrl, async (client) => {
1237
+ return (await client.query(`
1238
+ SELECT n.nspname AS "schema",
1239
+ c.relname AS "table",
1240
+ gen.attname AS "column",
1241
+ dep.attname AS "dependsOn"
1242
+ FROM pg_attrdef ad
1243
+ JOIN pg_class c ON c.oid = ad.adrelid
1244
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1245
+ JOIN pg_attribute gen ON gen.attrelid = ad.adrelid AND gen.attnum = ad.adnum
1246
+ JOIN pg_depend d ON d.classid = 'pg_attrdef'::regclass
1247
+ AND d.objid = ad.oid
1248
+ AND d.refclassid = 'pg_class'::regclass
1249
+ AND d.refobjid = ad.adrelid
1250
+ AND d.deptype = 'n'
1251
+ JOIN pg_attribute dep ON dep.attrelid = ad.adrelid AND dep.attnum = d.refobjsubid
1252
+ WHERE gen.attgenerated <> ''
1253
+ AND NOT gen.attisdropped
1254
+ AND NOT dep.attisdropped;
1255
+ `)).rows;
1256
+ });
1257
+ }
1258
+ /**
1259
+ * Every column in the database with its current type, for the destructive
1260
+ * gate to tell a widening `ALTER COLUMN … TYPE` from one that loses data.
1261
+ */
1262
+ async function queryColumnTypes(databaseUrl) {
1263
+ return withAppClient(databaseUrl, async (client) => (await client.query(COLUMN_TYPES_SQL)).rows);
1264
+ }
1265
+ /**
1266
+ * Drop the generated columns standing in the way of an apply.
1267
+ *
1268
+ * Their indexes and their `COMMENT ON COLUMN` stamp go with them, which is
1269
+ * exactly right: `applySearchDdl` rebuilds all three from `search.sql` and a
1270
+ * surviving stamp would make the rebuilt column look like drift.
1271
+ */
1272
+ async function dropGeneratedColumns(databaseUrl, statements) {
1273
+ if (statements.length === 0) return;
1274
+ await withAppClient(databaseUrl, async (client) => {
1275
+ for (const statement of statements) await client.query(statement);
1276
+ });
1277
+ }
1278
+ /**
1279
+ * The generated SQL for the project's `vector` properties, if it has any.
1280
+ *
1281
+ * @param sqlDir directory holding the generated SQL. Defaults to
1282
+ * `.rebase/sql` under the working directory.
1283
+ */
1284
+ function readVectorDdl(sqlDir = generatedSqlDir()) {
1285
+ const vectorFile = path.join(sqlDir, "vector.sql");
1286
+ if (!fs.existsSync(vectorFile)) return "";
1287
+ return fs.readFileSync(vectorFile, "utf-8").trim();
1288
+ }
1289
+ /**
1290
+ * Install pgvector and bring the vector columns and their ANN indexes up to
1291
+ * date.
1292
+ *
1293
+ * Runs *after* Atlas, like {@link applySearchDdl} and for the same reason: the
1294
+ * statements are `ALTER TABLE … ADD COLUMN`, so the table has to exist. Atlas
1295
+ * is told to ignore these objects entirely ({@link getVectorExcludes}) — it
1296
+ * cannot manage a type its dev database is structurally incapable of having,
1297
+ * and left to itself it would plan a `DROP COLUMN` for every one.
1298
+ *
1299
+ * A no-op when no collection declares a `vector` property. A failure is *not*
1300
+ * swallowed: a push that reported success while the embedding column never
1301
+ * appeared is how a project ends up with vector search configured, no error
1302
+ * anywhere, and no results.
1303
+ */
1304
+ async function applyVectorDdl(databaseUrl, sqlDir = generatedSqlDir()) {
1305
+ const sql = readVectorDdl(sqlDir);
1306
+ if (!sql) return;
1307
+ const { vectorExtensionHint } = await import("./vector-index-BFhyEaiz.js").then((n) => n.f);
1308
+ try {
1309
+ await withAppClient(databaseUrl, (client) => client.query(sql));
1310
+ } catch (err) {
1311
+ const message = err instanceof Error ? err.message : String(err);
1312
+ const hint = vectorExtensionHint(message);
1313
+ if (!hint) throw err;
1314
+ throw new Error(`${message}${hint}`, { cause: err });
1315
+ }
1316
+ out(chalk.gray(" ✓ Applied vector columns and ANN indexes"));
1317
+ }
1318
+ /**
1319
+ * Glob patterns keeping Atlas away from the vector objects.
1320
+ *
1321
+ * Returns an empty list — and so changes nothing — for a project with no
1322
+ * `vector` property, which is every project that has not opted in.
1323
+ */
1324
+ async function getVectorExcludes(collectionsPath) {
1325
+ const { vectorExcludePatterns } = await import("./generate-postgres-ddl-logic-B4k9djAV.js").then((n) => n.o);
1326
+ return vectorExcludePatterns(await loadCollectionsForCli(collectionsPath));
1327
+ }
1328
+ /**
1329
+ * The generated SQL for the project's `autoValue: "on_update"` properties, if
1330
+ * it has any.
1331
+ *
1332
+ * @param sqlDir directory holding the generated SQL. Defaults to
1333
+ * `.rebase/sql` under the working directory.
1334
+ */
1335
+ function readTriggersDdl(sqlDir = generatedSqlDir()) {
1336
+ const triggersFile = path.join(sqlDir, "triggers.sql");
1337
+ if (!fs.existsSync(triggersFile)) return "";
1338
+ return fs.readFileSync(triggersFile, "utf-8").trim();
1339
+ }
1340
+ /**
1341
+ * Install the `updated_at` trigger function and bind it to every column that
1342
+ * asked for one.
1343
+ *
1344
+ * Runs *after* Atlas, like {@link applySearchDdl} and {@link applyVectorDdl}:
1345
+ * a trigger needs its table and its column to exist. Atlas is told to ignore
1346
+ * the triggers ({@link getTriggerExcludes}) because it cannot manage a function
1347
+ * at all — its free tier refuses to parse a desired state containing one.
1348
+ *
1349
+ * A no-op when no property declares `autoValue: "on_update"`. A failure is
1350
+ * *not* swallowed: a push that reported success while the trigger never
1351
+ * appeared is how `updated_at` ends up silently stale for every writer that is
1352
+ * not the driver, which is the whole reason the trigger exists.
1353
+ */
1354
+ async function applyTriggersDdl(databaseUrl, sqlDir = generatedSqlDir()) {
1355
+ const sql = readTriggersDdl(sqlDir);
1356
+ if (!sql) return;
1357
+ await withAppClient(databaseUrl, (client) => client.query(sql));
1358
+ out(chalk.gray(" ✓ Applied `updated_at` triggers"));
1359
+ }
1360
+ /** @see getSearchExcludes */
1361
+ async function getTriggerExcludes(collectionsPath) {
1362
+ const { triggerExcludePatterns } = await import("./generate-postgres-ddl-logic-B4k9djAV.js").then((n) => n.o);
1363
+ return triggerExcludePatterns(await loadCollectionsForCli(collectionsPath));
1364
+ }
1365
+ /**
1366
+ * Every index Postgres holds on a table, by its parts — never joined with `.`,
1367
+ * which a name may itself contain.
1368
+ *
1369
+ * Constraint-backed indexes are left out: a `PRIMARY KEY` or a `UNIQUE` is a
1370
+ * *constraint* to Atlas, diffed from the constraint declaration, and naming its
1371
+ * index in an exclude would shield the constraint itself.
1372
+ */
1373
+ async function queryExistingIndexes(databaseUrl) {
1374
+ return withAppClient(databaseUrl, async (client) => {
1375
+ return (await client.query(`
1376
+ SELECT n.nspname AS "schema", t.relname AS "table", i.relname AS "index"
1377
+ FROM pg_index x
1378
+ JOIN pg_class i ON i.oid = x.indexrelid
1379
+ JOIN pg_class t ON t.oid = x.indrelid
1380
+ JOIN pg_namespace n ON n.oid = t.relnamespace
1381
+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
1382
+ AND t.relkind IN ('r', 'p')
1383
+ AND NOT EXISTS (
1384
+ SELECT 1 FROM pg_constraint c WHERE c.conindid = i.oid
1385
+ );
1386
+ `)).rows;
1387
+ });
1388
+ }
1389
+ /**
1390
+ * Glob patterns keeping Atlas away from indexes that are not Rebase's.
1391
+ *
1392
+ * The problem this solves is live and predates the `indexes:` block. `db push`
1393
+ * is declarative, so an index on a managed table that is absent from
1394
+ * `schema.sql` is drift — and Atlas plans `DROP INDEX` for it. Verified
1395
+ * against atlas v1.2.3: create one by hand, re-run an unchanged push, and the
1396
+ * plan is a bare drop. `DROP INDEX` is not in `DESTRUCTIVE_PATTERNS`, so the
1397
+ * auto-approved apply took it without asking. Until now the only way to have
1398
+ * an index at all was to write it by hand, which made that the *only* outcome.
1399
+ *
1400
+ * Ownership rather than a prompt, because once indexes are declarable a drop
1401
+ * is usually correct: removing one from the config should remove it from the
1402
+ * database, quietly. What must never be dropped is an index Rebase never
1403
+ * created — a hand-written one, or one an introspected database arrived with.
1404
+ * {@link isRebaseIndexName} is the test, the same arrangement
1405
+ * `isGeneratedPolicyName` uses to let policy reconciliation drop only what it
1406
+ * generated.
1407
+ *
1408
+ * The named-in-the-desired-state check comes first and is what makes removal
1409
+ * work: a declared index that the author has just deleted still matches the
1410
+ * name pattern, is no longer in the plan, and so is *not* excluded — Atlas
1411
+ * drops it, as intended.
1412
+ *
1413
+ * Three-part `schema.table.index`, never two: a two-part pattern reads as a
1414
+ * *table* named `<index>` in a *schema* named `<table>`, matches nothing, and
1415
+ * reports no error — the trap already recorded for the search excludes. And
1416
+ * spelled by `atlasExcludePattern`: a raw `orders_idx[v1]` is a glob that
1417
+ * matches `orders_idxv`, so that index was dropped with no prompt.
1418
+ */
1419
+ async function getForeignIndexExcludes(databaseUrl, collectionsPath, deps = {}) {
1420
+ const queryIndexes = deps.queryExistingIndexes ?? queryExistingIndexes;
1421
+ const managed = await (deps.getManagedIndexNames ?? managedIndexNames)(collectionsPath);
1422
+ let existing;
1423
+ try {
1424
+ existing = await queryIndexes(databaseUrl);
1425
+ } catch (err) {
1426
+ throw new ExcludeIntrospectionError(`Failed to introspect the database for unmanaged indexes: ${err instanceof Error ? err.message : String(err)}`, err);
1427
+ }
1428
+ return existing.filter(({ index }) => {
1429
+ if (managed.has(index)) return false;
1430
+ return !isRebaseIndexName(index);
1431
+ }).map(({ schema, table, index }) => atlasExcludePattern(schema, table, index));
1432
+ }
1433
+ /**
1434
+ * The index names the current collections would create — search, vector and
1435
+ * declared alike. Anything Atlas would emit is by definition not foreign.
1436
+ */
1437
+ async function managedIndexNames(collectionsPath) {
1438
+ const collections = await loadCollectionsForCli(collectionsPath);
1439
+ const { searchExcludePatterns, vectorExcludePatterns } = await import("./generate-postgres-ddl-logic-B4k9djAV.js").then((n) => n.o);
1440
+ const { resolveColumnName } = await import("./column-plan-helpers-D_V4oaZh.js").then((n) => n.t);
1441
+ const { buildCollectionIndexPlan } = await import("./source-DB6xJv3p.js").then((n) => n.d);
1442
+ const names = new Set(buildCollectionIndexPlan(collections, resolveColumnName).map((spec) => spec.indexName));
1443
+ for (const pattern of [...searchExcludePatterns(collections), ...vectorExcludePatterns(collections)]) {
1444
+ const object = excludePatternParts(pattern)?.[2];
1445
+ if (object !== void 0) names.add(object);
1446
+ }
1447
+ return names;
1448
+ }
1449
+ /** Every CHECK and EXCLUDE constraint the database holds. @see UNDECLARABLE_CONSTRAINTS_SQL */
1450
+ async function queryUndeclarableConstraints(databaseUrl) {
1451
+ return withAppClient(databaseUrl, async (client) => (await client.query(UNDECLARABLE_CONSTRAINTS_SQL)).rows);
1452
+ }
1453
+ /**
1454
+ * Patterns keeping Atlas away from the CHECK and EXCLUDE constraints the
1455
+ * collections do not declare — which, since a collection cannot declare
1456
+ * either, is all of them. See `schema/undeclarable-constraints.ts`.
1457
+ *
1458
+ * Fails CLOSED, like {@link getTableExcludes}: without the catalogue nothing
1459
+ * says which constraints are there, and a partial list lets the push drop a
1460
+ * rule the database enforces. `desiredSql` is the `schema.sql` Atlas is about
1461
+ * to diff against; a constraint it declares is Atlas's to manage.
1462
+ */
1463
+ async function getUndeclaredConstraintExcludes(databaseUrl, desiredSql, deps = {}) {
1464
+ const queryConstraints = deps.queryConstraints ?? queryUndeclarableConstraints;
1465
+ let existing;
1466
+ try {
1467
+ existing = await queryConstraints(databaseUrl);
1468
+ } catch (err) {
1469
+ throw new ExcludeIntrospectionError(`Failed to introspect the database for CHECK and EXCLUDE constraints: ${err instanceof Error ? err.message : String(err)}`, err);
1470
+ }
1471
+ return undeclaredConstraintExcludes(existing, desiredSql);
1472
+ }
1473
+ async function queryExistingTables(databaseUrl) {
1474
+ return withAppClient(databaseUrl, async (client) => {
1475
+ return (await client.query(`
1476
+ SELECT table_schema AS "schema", table_name AS "table"
1477
+ FROM information_schema.tables
1478
+ WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
1479
+ AND table_type IN ('BASE TABLE', 'VIEW');
1480
+ `)).rows;
1481
+ });
1482
+ }
1483
+ /**
1484
+ * Raised when the exclude list could not be built. `db push` MUST abort on
1485
+ * this rather than continue: the exclude list is the only thing shielding
1486
+ * non-collection (user/system) tables from the auto-approved declarative
1487
+ * apply. A partial list — the old fail-open behaviour — meant a transient
1488
+ * introspection hiccup dropped every table not present in `schema.sql`.
1489
+ */
1490
+ var ExcludeIntrospectionError = class extends Error {
1491
+ cause;
1492
+ constructor(message, cause) {
1493
+ super(message);
1494
+ this.cause = cause;
1495
+ this.name = "ExcludeIntrospectionError";
1496
+ }
1497
+ };
1498
+ /**
1499
+ * Build the `--exclude` list that protects tables Rebase doesn't manage from
1500
+ * the declarative apply. Anything not backing a collection (or its M2M
1501
+ * junctions) is excluded so Atlas never drops it.
1502
+ *
1503
+ * Fails **closed**: if the database can't be introspected we cannot know
1504
+ * which tables to protect, so we throw {@link ExcludeIntrospectionError}
1505
+ * instead of returning a near-empty list and letting the caller drop
1506
+ * everything.
1507
+ *
1508
+ * `deps` is injectable for tests; production uses the real pg-backed queries.
1509
+ */
1510
+ async function getTableExcludes(databaseUrl, collectionsPath, deps = {}) {
1511
+ const getIncludes = deps.getIncludes ?? getTableIncludes;
1512
+ const queryTables = deps.queryExistingTables ?? queryExistingTables;
1513
+ const includes = await getIncludes(collectionsPath);
1514
+ const excludes = [
1515
+ "atlas_schema_revisions.*",
1516
+ "auth",
1517
+ "auth.*",
1518
+ "rebase",
1519
+ "rebase.*"
1520
+ ];
1521
+ let existingTables;
1522
+ try {
1523
+ existingTables = await queryTables(databaseUrl);
1524
+ } catch (err) {
1525
+ throw new ExcludeIntrospectionError(`Failed to introspect the database for unmapped tables: ${err instanceof Error ? err.message : String(err)}`, err);
1526
+ }
1527
+ for (const { schema, table } of existingTables) if (!includes.includes(`${schema}.${table}`)) excludes.push(atlasExcludePattern(schema, table));
1528
+ return excludes;
1529
+ }
1530
+ //#endregion
1531
+ //#region src/cli-errors.ts
1532
+ /**
1533
+ * Detect whether an error (or AggregateError wrapping multiple attempts)
1534
+ * represents an ECONNREFUSED — i.e. the database is simply not running.
1535
+ *
1536
+ * Handles:
1537
+ * - Direct `{ code: "ECONNREFUSED" }` errors from Node `net`
1538
+ * - `AggregateError` from dual-stack IPv4+IPv6 connection attempts
1539
+ * - Drizzle's `cause`-wrapped pg errors
1540
+ */
1541
+ function isEconnrefused(err) {
1542
+ if (!err || typeof err !== "object") return false;
1543
+ const e = err;
1544
+ if (e.code === "ECONNREFUSED") return true;
1545
+ if (Array.isArray(e.errors)) return e.errors.some((inner) => inner && typeof inner === "object" && inner.code === "ECONNREFUSED");
1546
+ if (e.cause && typeof e.cause === "object") return isEconnrefused(e.cause);
1547
+ return false;
1548
+ }
1549
+ /**
1550
+ * Detect PostgreSQL authentication failures.
1551
+ * PG error codes: 28P01 (invalid_password), 28000 (invalid_authorization_specification)
1552
+ */
1553
+ function isAuthFailure(err) {
1554
+ if (!err || typeof err !== "object") return false;
1555
+ const e = err;
1556
+ if (e.code === "28P01" || e.code === "28000") return true;
1557
+ if (e.cause && typeof e.cause === "object") return isAuthFailure(e.cause);
1558
+ if ("message" in e && typeof e.message === "string") {
1559
+ const msg = e.message.toLowerCase();
1560
+ if (msg.includes("password authentication failed") || msg.includes("no pg_hba.conf entry")) return true;
1561
+ }
1562
+ return false;
1563
+ }
1564
+ /**
1565
+ * Detect the "SSL is not enabled on the server" failure — the client attempted
1566
+ * an SSL handshake against a Postgres server that doesn't support it (common
1567
+ * with a plain local dev database). The fix is `?sslmode=disable` on the URL.
1568
+ */
1569
+ function isSslNotEnabled(err) {
1570
+ if (!err || typeof err !== "object") return false;
1571
+ const e = err;
1572
+ if (typeof e.message === "string" && e.message.toLowerCase().includes("ssl is not enabled on the server")) return true;
1573
+ if (e.cause && typeof e.cause === "object") return isSslNotEnabled(e.cause);
1574
+ return false;
1575
+ }
1576
+ /**
1577
+ * Detect PostgreSQL "cannot drop ... because other objects depend on it"
1578
+ * (error code 2BP01, dependent_objects_still_exist). This is the failure that
1579
+ * strands a declarative `db push` half-applied when a collection is removed but
1580
+ * an enum type it defined is still referenced by another object.
1581
+ */
1582
+ function isDependencyDropError(err) {
1583
+ if (!err || typeof err !== "object") return false;
1584
+ const e = err;
1585
+ if (e.code === "2BP01") return true;
1586
+ if (typeof e.message === "string") {
1587
+ const msg = e.message.toLowerCase();
1588
+ if (msg.includes("other objects depend on it") || msg.includes("cannot drop type")) return true;
1589
+ }
1590
+ if (e.cause && typeof e.cause === "object") return isDependencyDropError(e.cause);
1591
+ return false;
1592
+ }
1593
+ /**
1594
+ * Parse host:port from a DATABASE_URL for display purposes.
1595
+ *
1596
+ * Exported because every message about a connection has to name the thing it
1597
+ * could not reach, and the boot path needs the same rendering the CLI banners
1598
+ * use — including the same refusal to print the URL itself, which carries the
1599
+ * password.
1600
+ */
1601
+ function parseHostInfo(databaseUrl) {
1602
+ try {
1603
+ const parsed = new URL(databaseUrl);
1604
+ return `${parsed.hostname}:${parsed.port || 5432}`;
1605
+ } catch {
1606
+ return "unknown";
1607
+ }
1608
+ }
1609
+ /**
1610
+ * The sentence the operating system actually produced, dug out of the wrappers.
1611
+ *
1612
+ * `connect ECONNREFUSED 127.0.0.1:5432` is written by `net`, then wrapped by
1613
+ * `pg`, then wrapped again by Drizzle as `Failed query: …` — and on a
1614
+ * dual-stack host it is not in `.cause` at all but inside the
1615
+ * `AggregateError.errors` array of one attempt per resolved address. Printing
1616
+ * the banner without it loses the one token every search engine, runbook and
1617
+ * colleague recognises.
1618
+ */
1619
+ function deepestErrorMessage(err) {
1620
+ if (!err || typeof err !== "object") return null;
1621
+ const e = err;
1622
+ if (Array.isArray(e.errors)) for (const inner of e.errors) {
1623
+ const deeper = deepestErrorMessage(inner);
1624
+ if (deeper) return deeper;
1625
+ }
1626
+ if (e.cause) {
1627
+ const deeper = deepestErrorMessage(e.cause);
1628
+ if (deeper) return deeper;
1629
+ }
1630
+ if (typeof e.message === "string" && e.message && !e.message.startsWith("Failed query:")) return e.code ? `${e.message} (${e.code})` : e.message;
1631
+ return null;
1632
+ }
1633
+ /** One indented line naming the driver's own reason, or nothing. */
1634
+ function driverReasonLine(err) {
1635
+ const reason = err === void 0 ? null : deepestErrorMessage(err);
1636
+ return reason ? ` The driver said: ${reason}\n\n` : "";
1637
+ }
1638
+ /**
1639
+ * Format a diagnostic banner for ECONNREFUSED errors.
1640
+ */
1641
+ function formatConnectionRefusedBanner(databaseUrl, err) {
1642
+ return `
1643
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1644
+ ❌ Cannot connect to PostgreSQL at ${parseHostInfo(databaseUrl)}\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n` + driverReasonLine(err) + " The database server is not running or is not accepting\n connections. Common fixes:\n\n • docker compose up -d db (the service a Rebase scaffold ships)\n • brew services start postgresql@18\n • Verify DATABASE_URL in your .env file\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
1645
+ }
1646
+ /**
1647
+ * Format a diagnostic banner for authentication failures.
1648
+ */
1649
+ function formatAuthFailureBanner(databaseUrl, err) {
1650
+ const hostInfo = parseHostInfo(databaseUrl);
1651
+ let username = "unknown";
1652
+ try {
1653
+ username = new URL(databaseUrl).username || "unknown";
1654
+ } catch {}
1655
+ return `
1656
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1657
+ ❌ Authentication failed for user "${username}" at ${hostInfo}\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n` + driverReasonLine(err) + ` PostgreSQL rejected the credentials. Common fixes:
1658
+
1659
+ • Check the username and password in DATABASE_URL
1660
+ • Verify the user exists: psql -c "\\du"
1661
+ • Reset the password: ALTER USER ${username} PASSWORD 'new_password';\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
1662
+ }
1663
+ /**
1664
+ * Format a diagnostic banner for "SSL is not enabled on the server".
1665
+ */
1666
+ function formatSslNotEnabledBanner(databaseUrl) {
1667
+ const hostInfo = parseHostInfo(databaseUrl);
1668
+ const suggestion = databaseUrl.includes("?") ? "&sslmode=disable" : "?sslmode=disable";
1669
+ return `
1670
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1671
+ ❌ SSL is not enabled on the PostgreSQL server at ${hostInfo}\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n The client tried to connect over SSL, but the server does not\n support it. This is normal for a plain local dev database.\n\n Fix: append ${chalk.bold("sslmode=disable")} to DATABASE_URL, e.g.\n\n DATABASE_URL=...${suggestion}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
1672
+ }
1673
+ /**
1674
+ * Format a diagnostic banner for a dependency-drop failure during `db push`.
1675
+ * Explains that the database may be left partially migrated and how to recover.
1676
+ */
1677
+ function formatDependencyDropBanner() {
1678
+ return `
1679
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1680
+ ❌ Schema push failed: a type/table could not be dropped
1681
+ because other objects still depend on it.
1682
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1683
+
1684
+ ${chalk.yellow("The database may now be partially migrated.")} Atlas applies\n statements individually, so earlier changes in this push may\n already be committed while later ones failed.\n\n This commonly happens when a collection is removed but an enum\n type it defined is still referenced. To recover:\n\n 1. Inspect the leftover object named in the error above.\n 2. Drop it with CASCADE, e.g.:\n psql "$DATABASE_URL" -c 'DROP TYPE "<name>" CASCADE;'\n 3. Re-run: ${chalk.bold.green("rebase db push")}\n\n Prefer a safe, versioned workflow? Use ${chalk.bold("rebase db generate")}\n + ${chalk.bold("rebase db migrate")} instead of push for destructive changes.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
1685
+ }
1686
+ /**
1687
+ * Pre-flight check: verify that the database is reachable before running
1688
+ * a heavy subprocess (Atlas, migrations, etc.).
1689
+ *
1690
+ * Exits with code 1 and a friendly banner on known failure modes.
1691
+ * On unknown errors, logs a warning and allows the caller to proceed.
1692
+ */
1693
+ async function checkDatabaseConnectivity(databaseUrl) {
1694
+ try {
1695
+ await withAppClient(databaseUrl, (client) => client.query("SELECT 1"), { connectionTimeoutMillis: 5e3 });
1696
+ } catch (err) {
1697
+ if (isEconnrefused(err)) {
1698
+ outError(formatConnectionRefusedBanner(databaseUrl, err));
1699
+ process.exit(1);
1700
+ }
1701
+ if (isAuthFailure(err)) {
1702
+ outError(formatAuthFailureBanner(databaseUrl, err));
1703
+ process.exit(1);
1704
+ }
1705
+ if (isSslNotEnabled(err)) {
1706
+ outError(formatSslNotEnabledBanner(databaseUrl));
1707
+ process.exit(1);
1708
+ }
1709
+ outWarn(chalk.yellow(` ⚠ Could not verify database connectivity: ${err instanceof Error ? err.message : String(err)}`));
1710
+ outWarn(chalk.gray(" Proceeding anyway — the command may fail if the database is unreachable."));
1711
+ }
1712
+ }
1713
+ /**
1714
+ * Post-hoc error diagnosis for direct database operations (e.g. applyPolicies).
1715
+ * Returns a formatted diagnostic string if the error matches a known pattern,
1716
+ * or null if unrecognized.
1717
+ */
1718
+ function diagnoseDbError(err, databaseUrl) {
1719
+ if (isEconnrefused(err)) return formatConnectionRefusedBanner(databaseUrl || "", err);
1720
+ if (isAuthFailure(err)) return formatAuthFailureBanner(databaseUrl || "", err);
1721
+ if (isSslNotEnabled(err)) return formatSslNotEnabledBanner(databaseUrl || "");
1722
+ if (isDependencyDropError(err)) return formatDependencyDropBanner();
1723
+ return null;
1724
+ }
1725
+ /**
1726
+ * Say why the command failed, on the way out.
1727
+ *
1728
+ * The entry point below used to be `.catch(() => process.exit(1))`, which threw
1729
+ * the error away. Every message this file and its services raise — "Branch
1730
+ * \"x\" already exists.", "the source database has active connections", "Branch
1731
+ * name is too long" — was written, wrapped in the right PG error code, and then
1732
+ * discarded one frame before it reached a terminal. What a developer saw was a
1733
+ * header line, no error, and exit 1.
1734
+ *
1735
+ * Two shapes are deliberately kept quiet:
1736
+ *
1737
+ * - **A child process that already spoke.** Atlas, `pg_dump` and `psql` run
1738
+ * with inherited stdio, so their diagnosis is on the terminal already and
1739
+ * execa's wrapper adds only `Command failed with exit code 1: atlas …`.
1740
+ * `packages/cli` filters exactly these two phrasings one level up
1741
+ * (`runDbCommand`), and this is that filter, for the process that is actually
1742
+ * throwing.
1743
+ *
1744
+ * - **A message that is only a query.** Drizzle reports failures as
1745
+ * `Failed query: <sql> params:` and hides the real PostgreSQL error in
1746
+ * `cause`, so the wrapper alone tells a reader nothing they can act on. The
1747
+ * cause is appended when it says something the message does not.
1748
+ *
1749
+ * - **An error that has already printed its own diagnosis**, marked
1750
+ * `alreadyReported`. `CollectionsPathMissing` is one: it prints the path, what
1751
+ * it resolved to and the cwd it resolved against, and then throws so the entry
1752
+ * point owns the exit code. Repeating its one-line summary underneath would
1753
+ * undo the "printed once" this whole path exists for.
1754
+ *
1755
+ * Whatever is printed has its connection-string passwords replaced (see
1756
+ * `redactConnectionPasswords`): a driver or tool error can quote the URL it was
1757
+ * given, and this line lands in terminals and CI logs.
1758
+ */
1759
+ function reportCommandFailure(error) {
1760
+ const message = redactConnectionPasswords(error instanceof Error ? error.message : String(error ?? ""));
1761
+ if (error?.alreadyReported) return;
1762
+ if (!message || /Command failed|exited with code/i.test(message)) return;
1763
+ outError("");
1764
+ outError(chalk.red(` ✗ ${message}`));
1765
+ const rawCause = extractCauseMessage(error);
1766
+ const cause = rawCause ? redactConnectionPasswords(rawCause) : rawCause;
1767
+ if (cause && !message.includes(cause)) outError(chalk.gray(` ${cause}`));
1768
+ outError("");
1769
+ }
1770
+ /**
1771
+ * `migrate apply` refusing because the database already has the schema.
1772
+ *
1773
+ * `42710` (duplicate_object), `42P07` (duplicate_table), `42701`
1774
+ * (duplicate_column) and `42P06` (duplicate_schema) are what a migration hits
1775
+ * when boot-ensure — or a `db push` — has already provisioned the objects it
1776
+ * was going to create. Since boot-ensure provisions *every* production
1777
+ * database, this is the normal case rather than the exotic one, and the raw
1778
+ * failure (`pq: type "posts_status" already exists (42710)`, then `sql/migrate:
1779
+ * write revision: … current transaction is aborted`) names no way forward.
1780
+ *
1781
+ * `42701` is the everyday one in development: `rebase dev` adds a new
1782
+ * column at boot, `db generate` writes the migration that adds it, and
1783
+ * `db migrate` then finds it there. A column is named `table.column`.
1784
+ */
1785
+ function parseAlreadyProvisioned(text) {
1786
+ const column = /column "([^"]+)" of relation "([^"]+)" already exists/.exec(text);
1787
+ if (column && /42701/.test(text)) return {
1788
+ object: `${column[2]}.${column[1]}`,
1789
+ code: "42701"
1790
+ };
1791
+ const withCode = /(?:type|relation|constraint|schema) "([^"]+)" already exists \((42710|42P07|42P06)\)/.exec(text);
1792
+ if (withCode) return {
1793
+ object: withCode[1],
1794
+ code: withCode[2]
1795
+ };
1796
+ const bare = /(?:type|relation|constraint|schema) "([^"]+)" already exists/.exec(text);
1797
+ const code = /42P07|42P06|42710/.exec(text)?.[0];
1798
+ if (bare && code) return {
1799
+ object: bare[1],
1800
+ code
1801
+ };
1802
+ return null;
1803
+ }
1804
+ /**
1805
+ * The migration Atlas was running when it failed: `from version "<v>"` in
1806
+ * `sql/migrate: executing statement "…" from version "20261013201353": …`.
1807
+ */
1808
+ function parseFailedMigrationVersion(text) {
1809
+ return /from version "([^"]+)"/.exec(text)?.[1] ?? null;
1810
+ }
1811
+ /**
1812
+ * What to do about it: tell Atlas the database is already at a version.
1813
+ *
1814
+ * Atlas's own mechanism (`migrate apply --baseline <version>`), not a ledger of
1815
+ * ours — it writes the revision row Atlas reads, so every later `rebase db
1816
+ * migrate` is an ordinary one.
1817
+ */
1818
+ function formatBaselineRemedy(version, object, failedVersion) {
1819
+ const versionToken = version ?? "<version>";
1820
+ const onlyTheFailedOne = failedVersion && failedVersion !== version ? ` To mark only the migration that failed, and run the ones after it:
1821
+
1822
+ ${chalk.bold.green(`rebase db migrate --baseline ${failedVersion}`)}\n\n` : "";
1823
+ return "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n ❌ This database already has the schema this migration creates\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" + (object ? ` ${chalk.gray(`"${object}" is already there, so the migration cannot create it.`)}\n\n` : "") + ` Nothing is wrong with the migration — the database was provisioned\n another way. Every Rebase boot ensures the schema, and ${chalk.bold("rebase db push")}\n applies it directly, so a database that has ever run either one is\n ahead of the migrations recorded on it.\n\n Record where it already is, then migrate normally:\n\n ${chalk.bold.green(`rebase db migrate --baseline ${versionToken}`)}\n ${chalk.bold.green("rebase db migrate")}\n\n The baseline is the version already applied — the numeric prefix of\n the migration file describing what is in the database now. Migrations\n after it run; it and everything before it are marked done.\n\n` + onlyTheFailedOne + " On a database nothing has ever booted against, none of this is needed.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
1824
+ }
1825
+ /**
1826
+ * Atlas's whole report when a connection was closed before it answered:
1827
+ * `Error: EOF`, sometimes with the step in front (`Error: postgres: querying
1828
+ * system variables: EOF`). The line names neither the database nor the
1829
+ * connection, so on its own it reads like a crash.
1830
+ */
1831
+ function parseConnectionEof(text) {
1832
+ return /^Error: (?:.*: )?EOF\s*$/m.test(text);
1833
+ }
1834
+ /**
1835
+ * What a closed connection means, and that running the command again is safe.
1836
+ *
1837
+ * On the managed development database it is almost always the connection
1838
+ * limit. PGlite is one session behind a socket server that accepts only a few
1839
+ * connections; a running `rebase dev` holds some, `atlas schema apply` opens
1840
+ * two, and the one over the limit is closed unanswered. Measured: with the
1841
+ * daemon's limit of four and three held, `db push --dry-run` failed with a
1842
+ * bare `Error: EOF`; with two held it passed. The dev server's pool lets an
1843
+ * idle connection go after 30 seconds (`idleTimeoutMillis` in connection.ts),
1844
+ * which is why a later attempt usually works.
1845
+ */
1846
+ function formatConnectionEofBanner(managed) {
1847
+ const why = managed ? ` The managed development database accepts only a few connections at a\n time, and a running ${chalk.bold("rebase dev")} holds some of them. Atlas opened one more,\n and it was closed before the database answered.\n` : " The server, or a proxy or pooler in front of it, closed the connection:\n a restart, a connection limit, or a reaper for idle connections.\n";
1848
+ const next = managed ? ` Run the command again in a moment: it is safe to repeat, and the dev
1849
+ server lets an idle connection go after 30 seconds. If it keeps failing,
1850
+ stop ${chalk.bold("rebase dev")} while you run it.\n` : ` Run the command again: it is safe to repeat. If it keeps failing, check\n the server's connection limit and that it is up: ${chalk.bold("rebase doctor")}.\n`;
1851
+ return "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n ❌ Atlas lost its connection to the database (EOF)\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" + why + `\n` + next + "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
1852
+ }
1853
+ /** `ALTER TABLE … SET NOT NULL` on a table that already holds rows (23502). */
1854
+ function parseNotNullViolation(text) {
1855
+ const match = /column "([^"]+)" of relation "([^"]+)" contains null values/.exec(text);
1856
+ return match ? {
1857
+ table: match[2],
1858
+ column: match[1]
1859
+ } : null;
1860
+ }
1861
+ /**
1862
+ * Whether the column that refused NOT NULL was being added by this push, read
1863
+ * from the statement Atlas was running: `true` for `ADD COLUMN "<column>"`,
1864
+ * `false` for any other statement that names it (`ALTER COLUMN … SET NOT
1865
+ * NULL`), `null` when the error carried no statement.
1866
+ */
1867
+ function notNullColumnIsNew(stderr, column) {
1868
+ const statement = parseFailedStatement(stderr);
1869
+ if (!statement) return null;
1870
+ const quoted = column.replace(/"/g, "\"\"").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1871
+ return new RegExp(`ADD\\s+COLUMN\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?"${quoted}"`, "i").test(statement);
1872
+ }
1873
+ /**
1874
+ * The ways out, and only the ones that work for this column.
1875
+ *
1876
+ * A `defaultValue` backfills only a column the push is adding: PostgreSQL
1877
+ * fills `ADD COLUMN … NOT NULL DEFAULT …` for every existing row, but `ALTER
1878
+ * COLUMN … SET DEFAULT` touches no row that is already there, so for an
1879
+ * existing column that remedy fails exactly as before. When the error does not
1880
+ * say which it was (`isNew` null), the default is offered with that caveat.
1881
+ *
1882
+ * Boot-ensure handles this case — it adds the column nullable and sets NOT NULL
1883
+ * only when the table is empty — so a push that dies here is strictly worse
1884
+ * than the boot that would have run instead.
1885
+ */
1886
+ function formatNotNullViolationBanner(violation, rowCount, isNew = null) {
1887
+ const { table, column } = violation;
1888
+ const rows = rowCount === null ? ` "${table}" already holds rows, and none of them has a value for "${column}".\n` : ` "${table}" already holds ${rowCount} row${rowCount === 1 ? "" : "s"}, and they have no value for "${column}".\n`;
1889
+ const backfill = `Backfill by hand first, then push again:\n ${chalk.gray(`psql "$DATABASE_URL" -c 'UPDATE "${table}" SET "${column}" = … WHERE "${column}" IS NULL;'`)}\n`;
1890
+ const leaveOptional = `Leave it optional — take \`validation.required\` off the property.\n`;
1891
+ const defaultLine = (caveat) => `Give the property a default, so the push can backfill${caveat}:\n ${chalk.gray(`{ type: "string", defaultValue: "…", validation: { required: true } }`)}\n`;
1892
+ const remedies = isNew === false ? [backfill, leaveOptional] : isNew === true ? [
1893
+ defaultLine(""),
1894
+ backfill,
1895
+ leaveOptional
1896
+ ] : [
1897
+ backfill,
1898
+ defaultLine(" (only if this push adds the column — a default never fills rows that already exist)"),
1899
+ leaveOptional
1900
+ ];
1901
+ const count = [
1902
+ "",
1903
+ "One way",
1904
+ "Two ways",
1905
+ "Three ways"
1906
+ ][remedies.length];
1907
+ return `
1908
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1909
+ ❌ Cannot make "${table}"."${column}" required: existing rows are null\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n` + rows + ` PostgreSQL will not add the NOT NULL until every one of them does.
1910
+
1911
+ ${count} forward:\n\n` + remedies.map((r, i) => ` ${i + 1}. ${r}`).join("") + `\n ${chalk.gray("Nothing in this push was applied: Atlas applies it as one transaction.")}\n ${chalk.gray("`rebase dev` would have kept the column nullable instead:")}\n ${chalk.gray("boot sets NOT NULL only when it is safe.")}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
1912
+ }
1913
+ /** Atlas refusing to remove a label from an enum — a renamed `enum` option id. */
1914
+ function parseEnumLabelDrop(text) {
1915
+ const match = /dropping (?:enum )?value "([^"]+)" from enum "([^"]+)" is not supported/.exec(text);
1916
+ return match ? {
1917
+ label: match[1],
1918
+ enumType: match[2]
1919
+ } : null;
1920
+ }
1921
+ /**
1922
+ * Why the two paths disagree, and what retiring an option id actually costs.
1923
+ *
1924
+ * Boot-ensure adds enum labels and never removes one, so `rebase dev` accepts
1925
+ * the very edit that stops `db push` dead. PostgreSQL has no `ALTER TYPE …
1926
+ * DROP VALUE`: a label goes only by rewriting the type, which is a data
1927
+ * migration and not a schema push.
1928
+ */
1929
+ function formatEnumLabelDropBanner(drop) {
1930
+ const { label, enumType } = drop;
1931
+ return `
1932
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1933
+ ❌ "${label}" cannot be removed from the enum "${enumType}"\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n PostgreSQL has no ALTER TYPE … DROP VALUE. An option id can be added\n to an enum but never taken out of one, so renaming an id reads as a\n removal and a push cannot carry it.\n\n ${chalk.yellow("Nothing was applied.")} ${chalk.bold("rebase dev")} accepts this same edit — boot adds\n new labels and never removes one — so the two paths disagree by\n design, and the old label would simply have stayed behind, unused.\n\n To keep the id: put "${label}" back and change only its label text.\n\n To retire it for real, it is a data migration:\n\n 1. Add the new id alongside the old one, and push.\n 2. Move the rows: ${chalk.gray(`UPDATE … SET … = '<new>' WHERE … = '${label}';`)}\n 3. Rewrite the type, which is what actually drops the label:\n ${chalk.gray("rebase db generate retire_option && rebase db migrate")}\n ${chalk.gray("(a migration can CREATE TYPE …, ALTER TABLE … TYPE … USING, DROP TYPE)")}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
1934
+ }
1935
+ /**
1936
+ * The statement Atlas was running when it failed, unescaped.
1937
+ *
1938
+ * Two spellings, one per phase: the apply quotes it
1939
+ * (`executing statement "ALTER TABLE \"public\".\"people\" …;": pq: …`), and
1940
+ * the dry-run's analysis does not
1941
+ * (`analyzing plan: executing statement: ALTER TABLE "public"."people" …;: pq: …`).
1942
+ */
1943
+ function parseFailedStatement(text) {
1944
+ const quoted = /executing statement "((?:[^"\\]|\\.)*)"/.exec(text);
1945
+ if (quoted) return quoted[1].replace(/\\(.)/g, "$1");
1946
+ const bare = /executing statement: ([\s\S]*?;): pq:/.exec(text);
1947
+ return bare ? bare[1] : null;
1948
+ }
1949
+ /** `ALTER TABLE "public"."people" …` → `{ schema: "public", table: "people" }`. */
1950
+ function failedStatementTable(statement) {
1951
+ const ident = String.raw`(?:"((?:[^"]|"")+)"|([A-Za-z_][A-Za-z0-9_$]*))`;
1952
+ const match = new RegExp(String.raw`^\s*(?:ALTER\s+TABLE|CREATE\s+UNIQUE\s+INDEX\s+\S+\s+ON)\s+(?:ONLY\s+)?${ident}(?:\.${ident})?`, "i").exec(statement);
1953
+ if (!match) return null;
1954
+ const first = (match[1] ?? match[2]).replace(/""/g, "\"");
1955
+ const second = match[3] ?? match[4];
1956
+ return second === void 0 ? { table: first } : {
1957
+ schema: first,
1958
+ table: second.replace(/""/g, "\"")
1959
+ };
1960
+ }
1961
+ /**
1962
+ * PostgreSQL refusing to retype a column a `GENERATED ALWAYS AS … STORED`
1963
+ * expression reads (0A000). `db push` moves Rebase's own search columns out of
1964
+ * the way before the apply; this is what is left when it could not.
1965
+ */
1966
+ function parseGeneratedColumnRefusal(text) {
1967
+ if (!/cannot alter type of a column used by a generated column/.test(text)) return null;
1968
+ return { statement: parseFailedStatement(text) };
1969
+ }
1970
+ /**
1971
+ * Which generated columns read a column the failed statement retypes — read
1972
+ * from the catalogue, because PostgreSQL's DETAIL naming them does not survive
1973
+ * Atlas.
1974
+ */
1975
+ async function generatedColumnsBlocking(databaseUrl, statement) {
1976
+ if (!databaseUrl || !statement) return [];
1977
+ const target = failedStatementTable(statement);
1978
+ if (!target) return [];
1979
+ const retyped = [...statement.matchAll(/ALTER\s+(?:COLUMN\s+)?"((?:[^"]|"")+)"\s+(?:SET\s+DATA\s+)?TYPE\b/gi)].map((match) => match[1].replace(/""/g, "\""));
1980
+ if (retyped.length === 0) return [];
1981
+ try {
1982
+ const { Client } = await import("pg");
1983
+ const client = new Client({
1984
+ connectionString: databaseUrl,
1985
+ connectionTimeoutMillis: 5e3
1986
+ });
1987
+ await client.connect();
1988
+ try {
1989
+ return (await client.query(`
1990
+ SELECT n.nspname AS "schema", c.relname AS "table", gen.attname AS "column", dep.attname AS "reads"
1991
+ FROM pg_attrdef ad
1992
+ JOIN pg_class c ON c.oid = ad.adrelid
1993
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1994
+ JOIN pg_attribute gen ON gen.attrelid = ad.adrelid AND gen.attnum = ad.adnum
1995
+ JOIN pg_depend d ON d.classid = 'pg_attrdef'::regclass AND d.objid = ad.oid
1996
+ AND d.refclassid = 'pg_class'::regclass AND d.refobjid = ad.adrelid
1997
+ JOIN pg_attribute dep ON dep.attrelid = ad.adrelid AND dep.attnum = d.refobjsubid
1998
+ WHERE gen.attgenerated <> '' AND c.relname = $1
1999
+ AND ($2::text IS NULL OR n.nspname = $2) AND dep.attname = ANY($3::text[])
2000
+ ORDER BY 1, 2, 3, 4`, [
2001
+ target.table,
2002
+ target.schema ?? null,
2003
+ retyped
2004
+ ])).rows;
2005
+ } finally {
2006
+ await client.end();
2007
+ }
2008
+ } catch {
2009
+ return [];
2010
+ }
2011
+ }
2012
+ /**
2013
+ * What to do when a generated column stops a retype.
2014
+ *
2015
+ * A collection's own search column should never reach this — `db push` drops
2016
+ * it before the apply and rebuilds it after — so seeing one named here means
2017
+ * that machinery missed it, which is a bug worth a report. Any other generated
2018
+ * column is somebody's, with an expression Rebase holds no copy of.
2019
+ */
2020
+ function formatGeneratedColumnRefusalBanner(refusal, blockers) {
2021
+ const named = blockers.length > 0 ? blockers.map((b) => ` ${chalk.bold(`${b.schema}.${b.table}.${b.column}`)} reads "${b.reads}"`).join("\n") + "\n\n" : refusal.statement ? ` The statement:\n ${chalk.gray(refusal.statement.replace(/\s+/g, " "))}\n\n` : "";
2022
+ const first = blockers[0];
2023
+ const drop = first ? `ALTER TABLE "${first.schema}"."${first.table}" DROP COLUMN "${first.column}";` : "ALTER TABLE … DROP COLUMN <the generated column>;";
2024
+ return "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n ❌ A generated column reads a column this push retypes\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" + named + ` PostgreSQL will not retype a column while a GENERATED ALWAYS AS …
2025
+ STORED expression reads it, and Atlas applies a push as one
2026
+ transaction — ${chalk.yellow("nothing in this push was applied.")}\n\n A collection's ${chalk.bold("search")} column is dropped and rebuilt around the apply\n by the push itself. If that is the column named above, run the push\n again, and please report it: it should not have got this far.\n\n Any other generated column is yours. Drop it, push, and put it back\n with its original expression:\n\n ${chalk.gray(drop)}\n ${chalk.gray("rebase db push")}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
2027
+ }
2028
+ /**
2029
+ * PostgreSQL refusing a retype it has no implicit cast for (42804): `string` →
2030
+ * `number`, `time` → `date`, an array back to a string. Atlas reports it from
2031
+ * the dry-run's analysis as well as from the apply, so without this a
2032
+ * `--dry-run` died with the raw error and showed no plan at all.
2033
+ */
2034
+ function parseUncastableRetype(text) {
2035
+ const match = /column "((?:[^"]|"")+)" cannot be cast automatically to type ([^\n(]+?)\s*(?:\(42804\)|$|\n)/m.exec(text);
2036
+ if (!match) return null;
2037
+ return {
2038
+ column: match[1],
2039
+ type: match[2].trim(),
2040
+ statement: parseFailedStatement(text)
2041
+ };
2042
+ }
2043
+ /** The `ALTER … USING` a developer would run, and the other ways past it. Boot's drift report says the same. */
2044
+ function formatUncastableRetypeBanner(refusal) {
2045
+ const { column, type, statement } = refusal;
2046
+ const target = statement ? failedStatementTable(statement) : null;
2047
+ const table = target ? `${target.schema ? `"${target.schema}".` : ""}"${target.table}"` : "<table>";
2048
+ const quotedColumn = `"${column.replace(/"/g, "\"\"")}"`;
2049
+ return `
2050
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2051
+ ❌ ${table}.${quotedColumn} cannot be converted to ${type} automatically\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n The collection now declares this column as ${type}, and PostgreSQL has\n no implicit conversion from what the column holds today. Atlas stops\n at the first such statement — ${chalk.yellow("nothing in this push was applied")}, and a\n --dry-run cannot show the rest of the plan until this one is settled.\n\n Three ways forward:\n\n 1. Convert the values yourself, saying how, then push again:\n ${chalk.gray(`ALTER TABLE ${table} ALTER COLUMN ${quotedColumn} TYPE ${type} USING ${quotedColumn}::${type};`)}\n ${chalk.gray("(adjust the USING expression to whatever turns each old value into a new one)")}\n 2. Add a new property for the new type, copy the values over with an\n UPDATE, then remove the old property.\n 3. Keep the column as it is — put the property's type back, or pin the\n database type with ${chalk.bold("columnType")}.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
2052
+ }
2053
+ /**
2054
+ * A unique constraint or index PostgreSQL could not build because the rows
2055
+ * already repeat a value (23505). The DETAIL naming the value does not survive
2056
+ * Atlas, so the duplicates are read back from the table.
2057
+ */
2058
+ function parseUniqueBuildFailure(text) {
2059
+ const match = /could not create unique index "((?:[^"]|"")+)"/.exec(text);
2060
+ if (!match) return null;
2061
+ const statement = parseFailedStatement(text);
2062
+ let columns = [];
2063
+ if (statement) {
2064
+ const list = /UNIQUE\s*\(([^)]*)\)/i.exec(statement) ?? /\bON\s+(?:ONLY\s+)?(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*))?\s*(?:USING\s+\w+\s*)?\(([^)]*)\)/i.exec(statement);
2065
+ if (list) columns = [...list[1].matchAll(/"((?:[^"]|"")+)"|([A-Za-z_][\w$]*)/g)].map((m) => (m[1] ?? m[2]).replace(/""/g, "\""));
2066
+ }
2067
+ return {
2068
+ index: match[1],
2069
+ statement,
2070
+ columns
2071
+ };
2072
+ }
2073
+ /** Up to five repeated values, read from the database, or `[]` when we cannot say. */
2074
+ async function duplicateValues(databaseUrl, target, columns) {
2075
+ if (!databaseUrl || !target || columns.length === 0) return [];
2076
+ const ident = (name) => `"${name.replace(/"/g, "\"\"")}"`;
2077
+ const table = `${target.schema ? `${ident(target.schema)}.` : ""}${ident(target.table)}`;
2078
+ const cols = columns.map(ident).join(", ");
2079
+ try {
2080
+ const { Client } = await import("pg");
2081
+ const client = new Client({
2082
+ connectionString: databaseUrl,
2083
+ connectionTimeoutMillis: 5e3
2084
+ });
2085
+ await client.connect();
2086
+ try {
2087
+ return (await client.query(`SELECT concat_ws(', ', ${columns.map((c) => `${ident(c)}::text`).join(", ")}) AS "values", count(*)::int AS "count"
2088
+ FROM ${table} GROUP BY ${cols} HAVING count(*) > 1 ORDER BY count(*) DESC LIMIT 5`)).rows;
2089
+ } finally {
2090
+ await client.end();
2091
+ }
2092
+ } catch {
2093
+ return [];
2094
+ }
2095
+ }
2096
+ function formatUniqueBuildFailureBanner(failure, duplicates) {
2097
+ const target = failure.statement ? failedStatementTable(failure.statement) : null;
2098
+ const table = target ? `${target.schema ? `"${target.schema}".` : ""}"${target.table}"` : "<table>";
2099
+ const cols = failure.columns.length > 0 ? failure.columns.map((c) => `"${c}"`).join(", ") : "<column>";
2100
+ const listed = duplicates.length > 0 ? ` Repeated values:\n` + duplicates.map((d) => ` ${chalk.bold(d.values)} ${chalk.gray(`× ${d.count}`)}`).join("\n") + `\n\n` : "";
2101
+ return `
2102
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2103
+ ❌ Cannot make ${table} (${cols}) unique: rows already repeat a value\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n` + listed + ` PostgreSQL will not build "${failure.index}" while two rows share a\n value, and Atlas applies a push as one transaction — ${chalk.yellow("nothing in")}\n ${chalk.yellow("this push was applied.")}\n\n Find them:\n ${chalk.gray(`SELECT ${cols}, count(*) FROM ${table} GROUP BY ${cols} HAVING count(*) > 1;`)}\n\n Then change or delete the repeats and push again, or take ${chalk.bold("unique")} off\n the property.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
2104
+ }
2105
+ /** How many rows a table holds, or `null` when we cannot say. */
2106
+ async function countRows(databaseUrl, table) {
2107
+ if (!databaseUrl) return null;
2108
+ try {
2109
+ const { Client } = await import("pg");
2110
+ const client = new Client({
2111
+ connectionString: databaseUrl,
2112
+ connectionTimeoutMillis: 5e3
2113
+ });
2114
+ await client.connect();
2115
+ try {
2116
+ return (await client.query(`SELECT count(*)::int AS n FROM "${table.replace(/"/g, "\"\"")}"`)).rows[0]?.n ?? null;
2117
+ } finally {
2118
+ await client.end();
2119
+ }
2120
+ } catch {
2121
+ return null;
2122
+ }
2123
+ }
2124
+ /**
2125
+ * A hand-written generated column reading a column the plan wants to retype or
2126
+ * drop.
2127
+ *
2128
+ * Rebase's own generated columns are dropped and rebuilt around the apply — it
2129
+ * holds their definition in `search.sql`. This one it does not: PostgreSQL
2130
+ * stores a generated expression only in the catalogue, so dropping it to let
2131
+ * the apply through would destroy the only copy. Refuse instead, and say what
2132
+ * the operator can do about it.
2133
+ */
2134
+ function formatForeignGeneratedColumnBanner(conflicts) {
2135
+ const lines = conflicts.map((c) => {
2136
+ const reads = c.blocking.map((b) => `"${b.column}"`).join(", ");
2137
+ return ` ${chalk.bold(`${c.schema}.${c.table}.${c.column}`)} reads ${reads}`;
2138
+ });
2139
+ const first = conflicts[0];
2140
+ return "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n ❌ A generated column depends on a column this push changes\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" + lines.join("\n") + `
2141
+
2142
+ PostgreSQL refuses to retype or drop a column while a GENERATED
2143
+ ALWAYS AS … STORED expression reads it, and an Atlas apply is one
2144
+ transaction — so this refusal would roll back every other statement
2145
+ in the push with it.
2146
+
2147
+ ${chalk.yellow("Nothing was applied.")} Rebase rebuilds the generated columns it made\n itself (a collection's ${chalk.bold("search")} block) around the apply. It has no\n definition for this one, and a dropped generated expression is not\n recoverable from anywhere but your own migration.\n\n Drop it, push, and put it back:\n\n ${chalk.gray(`ALTER TABLE "${first.schema}"."${first.table}" DROP COLUMN "${first.column}";`)}\n ${chalk.gray("rebase db push")}\n ${chalk.gray("-- then re-create the column with its original expression")}\n\n Or declare it through a ${chalk.bold("search")} block, and Rebase will own it.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
2148
+ }
2149
+ /**
2150
+ * The remedy for an Atlas invocation that failed, or `null`.
2151
+ *
2152
+ * Scoped by the invocation, because the same database state means different
2153
+ * things to different subcommands: "already exists" under `migrate apply` wants
2154
+ * a baseline, while under `schema apply` it is a genuine conflict.
2155
+ */
2156
+ async function diagnoseAtlasFailure(context) {
2157
+ const { domain, args, stderr, databaseUrl } = context;
2158
+ if (parseConnectionEof(stderr)) return formatConnectionEofBanner(context.managedDatabase === true);
2159
+ if (domain === "migrate" && args.includes("apply")) {
2160
+ const provisioned = parseAlreadyProvisioned(stderr);
2161
+ if (provisioned) return formatBaselineRemedy(context.latestMigrationVersion ?? null, provisioned.object, parseFailedMigrationVersion(stderr));
2162
+ }
2163
+ if (domain === "schema" && args.includes("apply")) {
2164
+ const enumDrop = parseEnumLabelDrop(stderr);
2165
+ if (enumDrop) return formatEnumLabelDropBanner(enumDrop);
2166
+ const notNull = parseNotNullViolation(stderr);
2167
+ if (notNull) return formatNotNullViolationBanner(notNull, await countRows(databaseUrl, notNull.table), notNullColumnIsNew(stderr, notNull.column));
2168
+ const uncastable = parseUncastableRetype(stderr);
2169
+ if (uncastable) return formatUncastableRetypeBanner(uncastable);
2170
+ const unique = parseUniqueBuildFailure(stderr);
2171
+ if (unique) return formatUniqueBuildFailureBanner(unique, await duplicateValues(databaseUrl, unique.statement ? failedStatementTable(unique.statement) : null, unique.columns));
2172
+ const generated = parseGeneratedColumnRefusal(stderr);
2173
+ if (generated) return formatGeneratedColumnRefusalBanner(generated, await generatedColumnsBlocking(databaseUrl, generated.statement));
2174
+ }
2175
+ return null;
2176
+ }
2177
+ //#endregion
2178
+ export { queryColumnTypes as A, generatedSqlDir as B, getForeignIndexExcludes as C, getUndeclaredConstraintExcludes as D, getTriggerExcludes as E, readVectorDdl as F, extractPlanStatements as G, decidePushSafety as H, resolveLocalBin as I, forLibpq as J, fromAlterTable as K, withAppClient as L, queryUndeclarableConstraints as M, readSearchDdl as N, getVectorExcludes as O, readTriggersDdl as P, DESIRED_STATE_URL as R, ensureDevDatabaseExists as S, getTableExcludes as T, destructiveOptInFlag as U, prepareGeneratedSqlDir as V, detectDestructiveStatements as W, splitPassword as X, redactConnectionPasswords as Y, extractCauseMessage as Z, describeReinstallCommand as _, formatForeignGeneratedColumnBanner as a, dropDevDatabase as b, reportCommandFailure as c, applyTriggersDdl as d, applyVectorDdl as f, describeDevAddCommand as g, describeBuildScriptRemedy as h, diagnoseDbError as i, queryGeneratedColumnDependencies as j, loadCollectionsForCli as k, ExcludeIntrospectionError as l, closeAppClients as m, deepestErrorMessage as n, isEconnrefused as o, atlasDevDatabaseUrl as p, isSyncedPlan as q, diagnoseAtlasFailure as r, parseHostInfo as s, checkDatabaseConnectivity as t, applySearchDdl as u, detectProjectPackageManager as v, getSearchExcludes as w, dropGeneratedColumns as x, diagnoseMissingBin as y, GENERATED_SQL_DIR as z };
2179
+
2180
+ //# sourceMappingURL=cli-errors-oVUuD8k0.js.map