@rebasepro/server-postgres 0.17.3 → 0.18.1

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 (204) hide show
  1. package/LICENSE +0 -1
  2. package/README.md +31 -0
  3. package/dist/BranchService-ByLfM_Tt.js +360 -0
  4. package/dist/BranchService-ByLfM_Tt.js.map +1 -0
  5. package/dist/__vite-browser-external-BnuHet1e.js +46 -0
  6. package/dist/__vite-browser-external-BnuHet1e.js.map +1 -0
  7. package/dist/arg-Dni7MzLB.js +87 -0
  8. package/dist/arg-Dni7MzLB.js.map +1 -0
  9. package/dist/auth-users-columns-D2LBFrMH.js +116 -0
  10. package/dist/auth-users-columns-D2LBFrMH.js.map +1 -0
  11. package/dist/backup-argv.d.ts +19 -0
  12. package/dist/backup-cli-oM9WQVlV.js +408 -0
  13. package/dist/backup-cli-oM9WQVlV.js.map +1 -0
  14. package/dist/backup-service-Br3tqwsy.js +715 -0
  15. package/dist/backup-service-Br3tqwsy.js.map +1 -0
  16. package/dist/branch-argv.d.ts +28 -0
  17. package/dist/branch-prune.d.ts +77 -0
  18. package/dist/cli-collections-path.d.ts +31 -0
  19. package/dist/cli-errors-DxN4yzdH.js +657 -0
  20. package/dist/cli-errors-DxN4yzdH.js.map +1 -0
  21. package/dist/cli-errors.d.ts +123 -0
  22. package/dist/cli-flags.d.ts +101 -0
  23. package/dist/cli-helpers.d.ts +94 -10
  24. package/dist/cli-output-CNdMql-L.js +47 -0
  25. package/dist/cli-output-CNdMql-L.js.map +1 -0
  26. package/dist/cli.js +2020 -0
  27. package/dist/cli.js.map +1 -0
  28. package/dist/collection-index-BHgT_TKd.js +276 -0
  29. package/dist/collection-index-BHgT_TKd.js.map +1 -0
  30. package/dist/{collections-schema-version-BMeu3cgv.js → collections-schema-version-T6cGvrDi.js} +1 -2
  31. package/dist/{collections-schema-version-BMeu3cgv.js.map → collections-schema-version-T6cGvrDi.js.map} +1 -1
  32. package/dist/{connection-GOKU3Hu5.js → databasePoolManager-Bj5FbeAs.js} +112 -40
  33. package/dist/databasePoolManager-Bj5FbeAs.js.map +1 -0
  34. package/dist/databasePoolManager.d.ts +27 -0
  35. package/dist/doctor-D7HWmGzs.js +974 -0
  36. package/dist/doctor-D7HWmGzs.js.map +1 -0
  37. package/dist/{ensure-collection-policies-UCqgv_8c.js → ensure-collection-policies-2c2NV8zX.js} +7 -27
  38. package/dist/ensure-collection-policies-2c2NV8zX.js.map +1 -0
  39. package/dist/ensure-collection-tables-D4wJzM4y.js +820 -0
  40. package/dist/ensure-collection-tables-D4wJzM4y.js.map +1 -0
  41. package/dist/ensure-tables-CIojK-Rx.js +650 -0
  42. package/dist/ensure-tables-CIojK-Rx.js.map +1 -0
  43. package/dist/generate-drizzle-schema-CwEgVyjO.js +123 -0
  44. package/dist/generate-drizzle-schema-CwEgVyjO.js.map +1 -0
  45. package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +528 -0
  46. package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +1 -0
  47. package/dist/{ensure-collection-tables-DgVixhX3.js → generate-postgres-ddl-logic-CtnpIBVv.js} +126 -984
  48. package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +1 -0
  49. package/dist/generated-schema-staleness-DQdfJl2A.js +157 -0
  50. package/dist/generated-schema-staleness-DQdfJl2A.js.map +1 -0
  51. package/dist/index.d.ts +12 -0
  52. package/dist/index.es.js +7423 -1133
  53. package/dist/index.es.js.map +1 -1
  54. package/dist/introspect-db-logic-C6LQdTxj.js +1378 -0
  55. package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -0
  56. package/dist/policy-drift-kNJ6X2Uj.js +313 -0
  57. package/dist/policy-drift-kNJ6X2Uj.js.map +1 -0
  58. package/dist/{backup-service-DCk7KhhL.js → rls-bootstrap-sql-DLDnUjtx.js} +737 -2689
  59. package/dist/rls-bootstrap-sql-DLDnUjtx.js.map +1 -0
  60. package/dist/{rls-enforcement-DvAbL9YJ.js → rls-enforcement-DeYEjYLt.js} +65 -190
  61. package/dist/rls-enforcement-DeYEjYLt.js.map +1 -0
  62. package/dist/schema/bin/generate-drizzle-schema.d.ts +1 -0
  63. package/dist/schema/bin/generate-postgres-ddl.d.ts +1 -0
  64. package/dist/schema/column-type-drift.d.ts +79 -0
  65. package/dist/schema/doctor-cli.js +129 -0
  66. package/dist/schema/doctor-cli.js.map +1 -0
  67. package/dist/schema/doctor.d.ts +42 -0
  68. package/dist/schema/ensure-collection-tables.d.ts +90 -0
  69. package/dist/schema/generate-drizzle-schema.d.ts +1 -1
  70. package/dist/schema/generate-drizzle-schema.js +24 -0
  71. package/dist/schema/generate-drizzle-schema.js.map +1 -0
  72. package/dist/schema/generate-next-step.d.ts +30 -0
  73. package/dist/schema/generate-postgres-ddl-logic.d.ts +28 -0
  74. package/dist/schema/generate-postgres-ddl.d.ts +1 -1
  75. package/dist/schema/generate-postgres-ddl.js +138 -0
  76. package/dist/schema/generate-postgres-ddl.js.map +1 -0
  77. package/dist/schema/generated-schema-staleness.d.ts +37 -0
  78. package/dist/schema/introspect-db-queries.d.ts +34 -0
  79. package/dist/schema/introspect-db.js +866 -0
  80. package/dist/schema/introspect-db.js.map +1 -0
  81. package/dist/security/rls-enforcement.d.ts +63 -2
  82. package/dist/services/BranchService.d.ts +86 -1
  83. package/dist/services/collection-helpers.d.ts +1 -1
  84. package/dist/services/realtimeService.d.ts +30 -2
  85. package/dist/services/row-pipeline.d.ts +12 -1
  86. package/dist/source-Br7L7GOI.js +410 -0
  87. package/dist/source-Br7L7GOI.js.map +1 -0
  88. package/dist/utils/pg-error-utils.d.ts +3 -1
  89. package/dist/utils/pg-numeric-number-patch.d.ts +31 -0
  90. package/dist/vector-index-DkWxm2de.js +309 -0
  91. package/dist/vector-index-DkWxm2de.js.map +1 -0
  92. package/package.json +32 -27
  93. package/dist/backup-service-DCk7KhhL.js.map +0 -1
  94. package/dist/collection-index-BRUg10H5.js +0 -5690
  95. package/dist/collection-index-BRUg10H5.js.map +0 -1
  96. package/dist/connection-GOKU3Hu5.js.map +0 -1
  97. package/dist/ensure-collection-policies-UCqgv_8c.js.map +0 -1
  98. package/dist/ensure-collection-tables-DgVixhX3.js.map +0 -1
  99. package/dist/rls-bootstrap-sql-B5C9LoJ6.js +0 -244
  100. package/dist/rls-bootstrap-sql-B5C9LoJ6.js.map +0 -1
  101. package/dist/rls-enforcement-DvAbL9YJ.js.map +0 -1
  102. package/dist/src-DiB5RP2Z.js +0 -541
  103. package/dist/src-DiB5RP2Z.js.map +0 -1
  104. package/dist/websocket-BZ4H5wUz.js +0 -8198
  105. package/dist/websocket-BZ4H5wUz.js.map +0 -1
  106. package/src/PostgresAdapter.ts +0 -91
  107. package/src/PostgresBackendDriver.ts +0 -1857
  108. package/src/PostgresBootstrapper.ts +0 -1157
  109. package/src/auth/ensure-tables.ts +0 -896
  110. package/src/auth/schema-version.ts +0 -260
  111. package/src/auth/services.ts +0 -1610
  112. package/src/backup/backup-cli.ts +0 -520
  113. package/src/backup/backup-cron.ts +0 -212
  114. package/src/backup/backup-logic.ts +0 -93
  115. package/src/backup/backup-service.ts +0 -485
  116. package/src/backup/index.ts +0 -12
  117. package/src/backup/pg-tools.ts +0 -403
  118. package/src/backup/retention.ts +0 -86
  119. package/src/cli-errors.ts +0 -265
  120. package/src/cli-helpers.ts +0 -569
  121. package/src/cli-output.ts +0 -43
  122. package/src/cli.ts +0 -1339
  123. package/src/collections/PostgresCollectionRegistry.ts +0 -108
  124. package/src/collections/buildRegistry.ts +0 -68
  125. package/src/collections/validate-relations.ts +0 -402
  126. package/src/connection.ts +0 -333
  127. package/src/data-transformer.ts +0 -845
  128. package/src/databasePoolManager.ts +0 -95
  129. package/src/history/HistoryService.ts +0 -254
  130. package/src/history/ensure-history-table.ts +0 -53
  131. package/src/index.ts +0 -19
  132. package/src/interfaces.ts +0 -60
  133. package/src/module-dir.ts +0 -7
  134. package/src/schema/atlas-argv.ts +0 -94
  135. package/src/schema/auth-schema.ts +0 -298
  136. package/src/schema/auth-users-columns.ts +0 -131
  137. package/src/schema/carved-out-migration.ts +0 -404
  138. package/src/schema/classify-change.ts +0 -436
  139. package/src/schema/collection-index.ts +0 -427
  140. package/src/schema/collections-schema-version.ts +0 -103
  141. package/src/schema/destructive-sql.ts +0 -94
  142. package/src/schema/doctor-cli.ts +0 -66
  143. package/src/schema/doctor-policy-checks.ts +0 -105
  144. package/src/schema/doctor.ts +0 -837
  145. package/src/schema/drizzle-ddl.ts +0 -33
  146. package/src/schema/dynamic-tables.test.ts +0 -302
  147. package/src/schema/dynamic-tables.ts +0 -293
  148. package/src/schema/ensure-collection-policies.ts +0 -198
  149. package/src/schema/ensure-collection-tables.test.ts +0 -518
  150. package/src/schema/ensure-collection-tables.ts +0 -1267
  151. package/src/schema/generate-drizzle-schema-logic.ts +0 -957
  152. package/src/schema/generate-drizzle-schema.ts +0 -143
  153. package/src/schema/generate-postgres-ddl-logic.ts +0 -1339
  154. package/src/schema/generate-postgres-ddl.ts +0 -180
  155. package/src/schema/generate-schema-commit.ts +0 -267
  156. package/src/schema/generated-schema-staleness.ts +0 -284
  157. package/src/schema/introspect-db-constraints.ts +0 -385
  158. package/src/schema/introspect-db-inference.ts +0 -255
  159. package/src/schema/introspect-db-logic.ts +0 -1387
  160. package/src/schema/introspect-db-naming.ts +0 -15
  161. package/src/schema/introspect-db-project.ts +0 -78
  162. package/src/schema/introspect-db-queries.ts +0 -326
  163. package/src/schema/introspect-db-structure.ts +0 -670
  164. package/src/schema/introspect-db-types.ts +0 -56
  165. package/src/schema/introspect-db.ts +0 -257
  166. package/src/schema/introspect-runtime.test.ts +0 -260
  167. package/src/schema/introspect-runtime.ts +0 -327
  168. package/src/schema/non-sql-collections.test.ts +0 -131
  169. package/src/schema/rls-bootstrap-sql.ts +0 -288
  170. package/src/schema/search-column.ts +0 -643
  171. package/src/schema/test-schema.ts +0 -11
  172. package/src/schema/vector-index.ts +0 -491
  173. package/src/security/anonymous-grants.test.ts +0 -73
  174. package/src/security/policy-drift.test.ts +0 -435
  175. package/src/security/policy-drift.ts +0 -473
  176. package/src/security/rls-enforcement.ts +0 -505
  177. package/src/services/BranchService.ts +0 -326
  178. package/src/services/FetchService.ts +0 -2115
  179. package/src/services/PersistService.ts +0 -557
  180. package/src/services/RelationService.ts +0 -978
  181. package/src/services/RelationWriteService.ts +0 -653
  182. package/src/services/cdc/CdcListener.ts +0 -103
  183. package/src/services/cdc/junction-tables.ts +0 -91
  184. package/src/services/cdc/trigger-cdc.ts +0 -173
  185. package/src/services/channel-bus/ChannelBus.ts +0 -44
  186. package/src/services/channel-bus/PostgresChannelBus.ts +0 -299
  187. package/src/services/channel-bus/index.ts +0 -114
  188. package/src/services/channel-history.ts +0 -424
  189. package/src/services/channel-presence.ts +0 -185
  190. package/src/services/collection-helpers.ts +0 -420
  191. package/src/services/dataService.ts +0 -256
  192. package/src/services/index.ts +0 -14
  193. package/src/services/junction-writes.ts +0 -295
  194. package/src/services/nested-path.ts +0 -145
  195. package/src/services/pg-notify-listener.ts +0 -151
  196. package/src/services/realtimeService.ts +0 -2545
  197. package/src/services/row-pipeline.ts +0 -240
  198. package/src/services/write-denial.ts +0 -55
  199. package/src/types.ts +0 -4
  200. package/src/utils/connection-string.ts +0 -58
  201. package/src/utils/drizzle-conditions.ts +0 -2743
  202. package/src/utils/pg-array-null-patch.ts +0 -42
  203. package/src/utils/pg-error-utils.ts +0 -391
  204. package/src/websocket.ts +0 -855
@@ -0,0 +1,657 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ __createRequire(import.meta.url);
3
+ import { n as outError, r as outWarn } from "./cli-output-CNdMql-L.js";
4
+ import { t as chalk } from "./source-Br7L7GOI.js";
5
+ import { logger } from "@rebasepro/server";
6
+ //#region src/utils/pg-error-utils.ts
7
+ /**
8
+ * Shared PostgreSQL error extraction and user-friendly message formatting.
9
+ *
10
+ * Drizzle wraps native PG errors in a `.cause` chain. These utilities
11
+ * unwrap that chain to get the real PostgreSQL error (identified by a
12
+ * 5-character alphanumeric `code` such as `42P01`) and translate it into
13
+ * a message that is safe and helpful to show to end-users.
14
+ */
15
+ /**
16
+ * Return the error when it is a deliberate 4xx, otherwise null.
17
+ *
18
+ * A thrown `ApiError` is a decision the server made about the request, not a
19
+ * database failure: its message and code are already written for the client.
20
+ */
21
+ function asClientFacingError(error) {
22
+ if (!(error instanceof Error)) return null;
23
+ const e = error;
24
+ if (typeof e.statusCode !== "number" || e.statusCode < 400 || e.statusCode >= 500) return null;
25
+ return e;
26
+ }
27
+ /**
28
+ * Extract the underlying PostgreSQL error from a Drizzle wrapper.
29
+ * Drizzle wraps PG errors in a `cause` property — this function
30
+ * recursively walks the chain until it finds an object with a PG
31
+ * error code (5-char alphanumeric, e.g. `42P01`).
32
+ */
33
+ function extractPgError(error) {
34
+ if (!error || typeof error !== "object") return null;
35
+ if (!(error instanceof Error)) {
36
+ if ("cause" in error && error.cause && typeof error.cause === "object") return extractPgError(error.cause);
37
+ return null;
38
+ }
39
+ if ("code" in error && typeof error.code === "string" && /^[0-9A-Z]{5}$/.test(error.code)) return error;
40
+ if (error.cause && typeof error.cause === "object") return extractPgError(error.cause);
41
+ return null;
42
+ }
43
+ /**
44
+ * Whether the failure came back from Postgres rather than from building the
45
+ * query — which decides whether a fallback query is worth issuing.
46
+ *
47
+ * Reads here run inside a transaction (that is where `SET LOCAL ROLE` binds
48
+ * RLS). Once a statement raises, that transaction is aborted, and every later
49
+ * statement on it returns `25P02` — "current transaction is aborted, commands
50
+ * ignored until end of transaction block". So a retry after a database error
51
+ * cannot succeed, and it replaces a precise diagnosis ("invalid input syntax
52
+ * for type uuid") with a generic one. Rethrow instead.
53
+ *
54
+ * A query the driver could not even build — a missing reciprocal relation, say
55
+ * — never reached Postgres, leaves the transaction usable, and is exactly what
56
+ * the fallback paths exist for.
57
+ */
58
+ function reachedDatabase(error) {
59
+ return extractPgError(error) !== null;
60
+ }
61
+ /**
62
+ * Walk the error cause chain and return the deepest meaningful message.
63
+ */
64
+ function extractCauseMessage(error) {
65
+ if (!error || typeof error !== "object") return null;
66
+ if (!(error instanceof Error)) return null;
67
+ if (error.cause && typeof error.cause === "object") {
68
+ const deeper = extractCauseMessage(error.cause);
69
+ if (deeper) return deeper;
70
+ if (error.cause instanceof Error && error.cause.message) return error.cause.message;
71
+ }
72
+ return null;
73
+ }
74
+ /**
75
+ * Codes that mean "this connection will never work as configured".
76
+ *
77
+ * A wrong password or a database that does not exist is a settled fact about
78
+ * the connection string, not a transient fault — retrying produces the same
79
+ * answer forever.
80
+ */
81
+ var UNRECOVERABLE_CONNECT_CODES = /* @__PURE__ */ new Set([
82
+ "28P01",
83
+ "28000",
84
+ "3D000",
85
+ "42501"
86
+ ]);
87
+ /**
88
+ * Describe a failed connection attempt in terms a developer can act on.
89
+ *
90
+ * The error a caller catches is Drizzle's wrapper: its message is
91
+ * `Failed query: SELECT 1` and its stack runs through drizzle internals, while
92
+ * the sentence that says what is actually wrong — "password authentication
93
+ * failed for user …", "database … does not exist" — sits in `.cause`. Logging
94
+ * the wrapper, as the bootstrapper used to, tells a developer with a typo in
95
+ * their `DATABASE_URL` nothing at all.
96
+ */
97
+ function classifyConnectFailure(error) {
98
+ const pgError = extractPgError(error);
99
+ const reason = pgError?.message ?? extractCauseMessage(error) ?? (error instanceof Error ? error.message : String(error));
100
+ return {
101
+ fatal: Boolean(pgError?.code && UNRECOVERABLE_CONNECT_CODES.has(pgError.code)),
102
+ reason,
103
+ code: pgError?.code
104
+ };
105
+ }
106
+ /**
107
+ * Detect whether an error is specifically a role-switching permission failure
108
+ * (e.g. "permission denied to set role" or "must be member of role"),
109
+ * as opposed to a table-level permission denial.
110
+ *
111
+ * This is used by the backend driver to auto-disable role switching when the
112
+ * connection user lacks SET ROLE privileges, rather than surfacing a confusing
113
+ * error to the Studio SQL Editor user.
114
+ */
115
+ function isRoleSwitchingPermissionError(error) {
116
+ const pgError = extractPgError(error);
117
+ if (!pgError || pgError.code !== "42501") return false;
118
+ const msg = pgError.message.toLowerCase();
119
+ return msg.includes("set role") || msg.includes("member of role");
120
+ }
121
+ /**
122
+ * Was this `42501` the *caller* being refused by a policy, rather than the
123
+ * server lacking a privilege?
124
+ *
125
+ * Both arrive as `insufficient_privilege`, and they are opposite kinds of
126
+ * problem. A row-level-security refusal is a working access-control system
127
+ * doing its job: the caller asked for something their policies do not permit,
128
+ * which is a 403 and nobody's bug. A missing `GRANT` is the deployment being
129
+ * wrong — the connection role cannot touch the table at all, no policy is
130
+ * involved, and nothing the caller changes about the request will help.
131
+ *
132
+ * Postgres distinguishes them in the message, so this does too:
133
+ *
134
+ * new row violates row-level security policy for table "notes" → the caller
135
+ * permission denied for table notes → the server
136
+ *
137
+ * Only writes reach this. A read that RLS excludes is not an error — the rows
138
+ * are filtered and the caller gets an empty page — so the erroring case is
139
+ * specifically an `INSERT`/`UPDATE` whose row fails a policy's `WITH CHECK`.
140
+ *
141
+ * Matched on the message because that is the only thing carrying the
142
+ * distinction; the SQLSTATE is identical either way. Narrow by design: anything
143
+ * not naming row-level security stays the server's problem, since reporting a
144
+ * genuine privilege misconfiguration as "forbidden" would send an operator
145
+ * hunting for a policy bug that does not exist.
146
+ */
147
+ function isRowLevelSecurityDenial(error) {
148
+ const pgError = extractPgError(error);
149
+ if (!pgError || pgError.code !== "42501") return false;
150
+ return pgError.message.toLowerCase().includes("row-level security policy");
151
+ }
152
+ /**
153
+ * Translate a raw PostgreSQL error into a user-friendly message.
154
+ *
155
+ * @param pgError - The extracted PostgreSQL error (from {@link extractPgError})
156
+ * @param context - A human-readable context string (e.g. collection slug or path)
157
+ * @returns An object with a `message` safe for the client and the PG `code`.
158
+ */
159
+ function pgErrorToFriendlyMessage(pgError, context, options = {}) {
160
+ const verbose = options.verbose ?? process.env.NODE_ENV !== "production";
161
+ const detail = verbose ? pgError.detail : void 0;
162
+ const hint = verbose ? pgError.hint : void 0;
163
+ const constraint = pgError.constraint;
164
+ const column = pgError.column;
165
+ const table = pgError.table;
166
+ const dataType = verbose ? pgError.dataType : void 0;
167
+ const rawMessage = pgError.message || "Unknown database error";
168
+ const pgMessage = verbose ? rawMessage : "";
169
+ const code = pgError.code || "UNKNOWN";
170
+ const suffix = hint ? ` Hint: ${hint}` : "";
171
+ const tableRef = table ?? context;
172
+ /** `": <postgres said>"`, or nothing when the details are withheld. */
173
+ const said = pgMessage ? `: ${pgMessage}` : "";
174
+ switch (pgError.code) {
175
+ case "23503": return {
176
+ message: detail ? `Foreign key constraint violated: ${detail}${suffix}` : `Cannot complete operation: a foreign key constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
177
+ code
178
+ };
179
+ case "23505": return {
180
+ message: detail ? `Duplicate value: ${detail}${suffix}` : `Cannot complete operation: a unique constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
181
+ code
182
+ };
183
+ case "23502": return {
184
+ message: `Missing required field: "${column ?? "unknown"}" in "${tableRef}" cannot be empty.${suffix}`,
185
+ code
186
+ };
187
+ case "23514": return {
188
+ message: `Validation failed: a check constraint${constraint ? ` (${constraint})` : ""} was violated in "${context}".${suffix}`,
189
+ code
190
+ };
191
+ case "22P02": return {
192
+ message: `Invalid data format in "${context}"${said}.${suffix}`,
193
+ code
194
+ };
195
+ case "22001": return {
196
+ message: `Value too long for column "${column ?? "unknown"}" in "${tableRef}"${said}.${suffix}`,
197
+ code
198
+ };
199
+ case "22003": return {
200
+ message: `Numeric value out of range for column "${column ?? "unknown"}" in "${tableRef}"${said}.${suffix}`,
201
+ code
202
+ };
203
+ case "42703": return {
204
+ message: `Unknown column in "${tableRef}"${said}. Check if your schema is up to date (run migrations).${suffix}`,
205
+ code
206
+ };
207
+ case "42P01": return {
208
+ message: `Table not found for "${context}"${said}. Check if your schema is up to date (run migrations).${suffix}`,
209
+ code
210
+ };
211
+ case "42501": return rawMessage.toLowerCase().includes("row-level security policy") ? {
212
+ message: `Not permitted to write this row in "${tableRef}": it does not satisfy the row-level security policy.${suffix}`,
213
+ code
214
+ } : {
215
+ message: `Permission denied on "${tableRef}": the database role this server connects as lacks privileges on it.${suffix}`,
216
+ code
217
+ };
218
+ case "28000": return {
219
+ message: `Authorization failed for "${context}". Check your database credentials.${suffix}`,
220
+ code
221
+ };
222
+ default: {
223
+ const parts = [`Database error in "${context}" [${code}]${said}`];
224
+ if (detail) parts.push(`Detail: ${detail}`);
225
+ if (column) parts.push(`Column: ${column}`);
226
+ if (dataType) parts.push(`Data type: ${dataType}`);
227
+ if (constraint) parts.push(`Constraint: ${constraint}`);
228
+ if (hint) parts.push(`Hint: ${hint}`);
229
+ return {
230
+ message: parts.join(". "),
231
+ code
232
+ };
233
+ }
234
+ }
235
+ }
236
+ /**
237
+ * Sanitize any error into a message safe and helpful for the client.
238
+ *
239
+ * A deliberate 4xx (`ApiError`) passes through untouched — the server already
240
+ * decided what the client should read. Otherwise the PG error is extracted
241
+ * from the Drizzle cause chain, falling back to a generic message that
242
+ * doesn't leak SQL.
243
+ *
244
+ * @param error - The raw caught error
245
+ * @param context - A human-readable context string (e.g. collection path)
246
+ * @returns An object with `message` (user-friendly) and optional `code`
247
+ * (the `ApiError` code, or the PG SQLSTATE).
248
+ */
249
+ function sanitizeErrorForClient(error, context) {
250
+ const clientError = asClientFacingError(error);
251
+ if (clientError) {
252
+ const line = `[API ${clientError.statusCode} ${clientError.code ?? "BAD_REQUEST"}] in "${context}": ${clientError.message}`;
253
+ if (clientError.expected) logger.debug(line);
254
+ else logger.warn(`⚠️ ${line}`);
255
+ return {
256
+ message: clientError.message,
257
+ ...clientError.code && { code: clientError.code }
258
+ };
259
+ }
260
+ const pgError = extractPgError(error);
261
+ if (pgError) {
262
+ logger.error(`[PG ${pgError.code}] Error in "${context}"`, {
263
+ code: pgError.code,
264
+ message: pgError.message,
265
+ detail: pgError.detail,
266
+ hint: pgError.hint,
267
+ column: pgError.column,
268
+ table: pgError.table,
269
+ constraint: pgError.constraint,
270
+ dataType: pgError.dataType
271
+ });
272
+ return pgErrorToFriendlyMessage(pgError, context);
273
+ }
274
+ logger.error(`Database error in "${context}" (no PG error extracted)`, {
275
+ error: error instanceof Error ? error.message : String(error),
276
+ stack: error instanceof Error ? error.stack : void 0,
277
+ cause: error instanceof Error && error.cause ? error.cause instanceof Error ? error.cause.message : String(error.cause) : void 0
278
+ });
279
+ const causeMessage = extractCauseMessage(error);
280
+ if (causeMessage) return { message: `Database error in "${context}": ${causeMessage}` };
281
+ return { message: `Could not load data for "${context}". Check server logs for details.` };
282
+ }
283
+ //#endregion
284
+ //#region src/cli-errors.ts
285
+ /**
286
+ * Detect whether an error (or AggregateError wrapping multiple attempts)
287
+ * represents an ECONNREFUSED — i.e. the database is simply not running.
288
+ *
289
+ * Handles:
290
+ * - Direct `{ code: "ECONNREFUSED" }` errors from Node `net`
291
+ * - `AggregateError` from dual-stack IPv4+IPv6 connection attempts
292
+ * - Drizzle's `cause`-wrapped pg errors
293
+ */
294
+ function isEconnrefused(err) {
295
+ if (!err || typeof err !== "object") return false;
296
+ const e = err;
297
+ if (e.code === "ECONNREFUSED") return true;
298
+ if (Array.isArray(e.errors)) return e.errors.some((inner) => inner && typeof inner === "object" && inner.code === "ECONNREFUSED");
299
+ if (e.cause && typeof e.cause === "object") return isEconnrefused(e.cause);
300
+ return false;
301
+ }
302
+ /**
303
+ * Detect PostgreSQL authentication failures.
304
+ * PG error codes: 28P01 (invalid_password), 28000 (invalid_authorization_specification)
305
+ */
306
+ function isAuthFailure(err) {
307
+ if (!err || typeof err !== "object") return false;
308
+ const e = err;
309
+ if (e.code === "28P01" || e.code === "28000") return true;
310
+ if (e.cause && typeof e.cause === "object") return isAuthFailure(e.cause);
311
+ if ("message" in e && typeof e.message === "string") {
312
+ const msg = e.message.toLowerCase();
313
+ if (msg.includes("password authentication failed") || msg.includes("no pg_hba.conf entry")) return true;
314
+ }
315
+ return false;
316
+ }
317
+ /**
318
+ * Detect the "SSL is not enabled on the server" failure — the client attempted
319
+ * an SSL handshake against a Postgres server that doesn't support it (common
320
+ * with a plain local dev database). The fix is `?sslmode=disable` on the URL.
321
+ */
322
+ function isSslNotEnabled(err) {
323
+ if (!err || typeof err !== "object") return false;
324
+ const e = err;
325
+ if (typeof e.message === "string" && e.message.toLowerCase().includes("ssl is not enabled on the server")) return true;
326
+ if (e.cause && typeof e.cause === "object") return isSslNotEnabled(e.cause);
327
+ return false;
328
+ }
329
+ /**
330
+ * Detect PostgreSQL "cannot drop ... because other objects depend on it"
331
+ * (error code 2BP01, dependent_objects_still_exist). This is the failure that
332
+ * strands a declarative `db push` half-applied when a collection is removed but
333
+ * an enum type it defined is still referenced by another object.
334
+ */
335
+ function isDependencyDropError(err) {
336
+ if (!err || typeof err !== "object") return false;
337
+ const e = err;
338
+ if (e.code === "2BP01") return true;
339
+ if (typeof e.message === "string") {
340
+ const msg = e.message.toLowerCase();
341
+ if (msg.includes("other objects depend on it") || msg.includes("cannot drop type")) return true;
342
+ }
343
+ if (e.cause && typeof e.cause === "object") return isDependencyDropError(e.cause);
344
+ return false;
345
+ }
346
+ /**
347
+ * Parse host:port from a DATABASE_URL for display purposes.
348
+ *
349
+ * Exported because every message about a connection has to name the thing it
350
+ * could not reach, and the boot path needs the same rendering the CLI banners
351
+ * use — including the same refusal to print the URL itself, which carries the
352
+ * password.
353
+ */
354
+ function parseHostInfo(databaseUrl) {
355
+ try {
356
+ const parsed = new URL(databaseUrl);
357
+ return `${parsed.hostname}:${parsed.port || 5432}`;
358
+ } catch {
359
+ return "unknown";
360
+ }
361
+ }
362
+ /**
363
+ * The sentence the operating system actually produced, dug out of the wrappers.
364
+ *
365
+ * `connect ECONNREFUSED 127.0.0.1:5432` is written by `net`, then wrapped by
366
+ * `pg`, then wrapped again by Drizzle as `Failed query: …` — and on a
367
+ * dual-stack host it is not in `.cause` at all but inside the
368
+ * `AggregateError.errors` array of one attempt per resolved address. Printing
369
+ * the banner without it loses the one token every search engine, runbook and
370
+ * colleague recognises.
371
+ */
372
+ function deepestErrorMessage(err) {
373
+ if (!err || typeof err !== "object") return null;
374
+ const e = err;
375
+ if (Array.isArray(e.errors)) for (const inner of e.errors) {
376
+ const deeper = deepestErrorMessage(inner);
377
+ if (deeper) return deeper;
378
+ }
379
+ if (e.cause) {
380
+ const deeper = deepestErrorMessage(e.cause);
381
+ if (deeper) return deeper;
382
+ }
383
+ if (typeof e.message === "string" && e.message && !e.message.startsWith("Failed query:")) return e.code ? `${e.message} (${e.code})` : e.message;
384
+ return null;
385
+ }
386
+ /** One indented line naming the driver's own reason, or nothing. */
387
+ function driverReasonLine(err) {
388
+ const reason = err === void 0 ? null : deepestErrorMessage(err);
389
+ return reason ? ` The driver said: ${reason}\n\n` : "";
390
+ }
391
+ /**
392
+ * Format a diagnostic banner for ECONNREFUSED errors.
393
+ */
394
+ function formatConnectionRefusedBanner(databaseUrl, err) {
395
+ return `
396
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
397
+ ❌ 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";
398
+ }
399
+ /**
400
+ * Format a diagnostic banner for authentication failures.
401
+ */
402
+ function formatAuthFailureBanner(databaseUrl, err) {
403
+ const hostInfo = parseHostInfo(databaseUrl);
404
+ let username = "unknown";
405
+ try {
406
+ username = new URL(databaseUrl).username || "unknown";
407
+ } catch {}
408
+ return `
409
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
410
+ ❌ Authentication failed for user "${username}" at ${hostInfo}\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n` + driverReasonLine(err) + ` PostgreSQL rejected the credentials. Common fixes:
411
+
412
+ • Check the username and password in DATABASE_URL
413
+ • Verify the user exists: psql -c "\\du"
414
+ • Reset the password: ALTER USER ${username} PASSWORD 'new_password';\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
415
+ }
416
+ /**
417
+ * Format a diagnostic banner for "SSL is not enabled on the server".
418
+ */
419
+ function formatSslNotEnabledBanner(databaseUrl) {
420
+ const hostInfo = parseHostInfo(databaseUrl);
421
+ const suggestion = databaseUrl.includes("?") ? "&sslmode=disable" : "?sslmode=disable";
422
+ return `
423
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
424
+ ❌ 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`;
425
+ }
426
+ /**
427
+ * Format a diagnostic banner for a dependency-drop failure during `db push`.
428
+ * Explains that the database may be left partially migrated and how to recover.
429
+ */
430
+ function formatDependencyDropBanner() {
431
+ return `
432
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
433
+ ❌ Schema push failed: a type/table could not be dropped
434
+ because other objects still depend on it.
435
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
436
+
437
+ ${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`;
438
+ }
439
+ /**
440
+ * Pre-flight check: verify that the database is reachable before running
441
+ * a heavy subprocess (Atlas, migrations, etc.).
442
+ *
443
+ * Exits with code 1 and a friendly banner on known failure modes.
444
+ * On unknown errors, logs a warning and allows the caller to proceed.
445
+ */
446
+ async function checkDatabaseConnectivity(databaseUrl) {
447
+ let client;
448
+ try {
449
+ const { Client } = await import("pg");
450
+ client = new Client({
451
+ connectionString: databaseUrl,
452
+ connectionTimeoutMillis: 5e3
453
+ });
454
+ await client.connect();
455
+ await client.query("SELECT 1");
456
+ } catch (err) {
457
+ if (isEconnrefused(err)) {
458
+ outError(formatConnectionRefusedBanner(databaseUrl, err));
459
+ process.exit(1);
460
+ }
461
+ if (isAuthFailure(err)) {
462
+ outError(formatAuthFailureBanner(databaseUrl, err));
463
+ process.exit(1);
464
+ }
465
+ if (isSslNotEnabled(err)) {
466
+ outError(formatSslNotEnabledBanner(databaseUrl));
467
+ process.exit(1);
468
+ }
469
+ outWarn(chalk.yellow(` ⚠ Could not verify database connectivity: ${err instanceof Error ? err.message : String(err)}`));
470
+ outWarn(chalk.gray(" Proceeding anyway — the command may fail if the database is unreachable."));
471
+ } finally {
472
+ try {
473
+ await client?.end();
474
+ } catch {}
475
+ }
476
+ }
477
+ /**
478
+ * Post-hoc error diagnosis for direct database operations (e.g. applyPolicies).
479
+ * Returns a formatted diagnostic string if the error matches a known pattern,
480
+ * or null if unrecognized.
481
+ */
482
+ function diagnoseDbError(err, databaseUrl) {
483
+ if (isEconnrefused(err)) return formatConnectionRefusedBanner(databaseUrl || "", err);
484
+ if (isAuthFailure(err)) return formatAuthFailureBanner(databaseUrl || "", err);
485
+ if (isSslNotEnabled(err)) return formatSslNotEnabledBanner(databaseUrl || "");
486
+ if (isDependencyDropError(err)) return formatDependencyDropBanner();
487
+ return null;
488
+ }
489
+ /**
490
+ * Say why the command failed, on the way out.
491
+ *
492
+ * The entry point below used to be `.catch(() => process.exit(1))`, which threw
493
+ * the error away. Every message this file and its services raise — "Branch
494
+ * \"x\" already exists.", "the source database has active connections", "Branch
495
+ * name is too long" — was written, wrapped in the right PG error code, and then
496
+ * discarded one frame before it reached a terminal. What a developer saw was a
497
+ * header line, no error, and exit 1.
498
+ *
499
+ * Two shapes are deliberately kept quiet:
500
+ *
501
+ * - **A child process that already spoke.** Atlas, `pg_dump` and `psql` run
502
+ * with inherited stdio, so their diagnosis is on the terminal already and
503
+ * execa's wrapper adds only `Command failed with exit code 1: atlas …`.
504
+ * `packages/cli` filters exactly these two phrasings one level up
505
+ * (`runDbCommand`), and this is that filter, for the process that is actually
506
+ * throwing.
507
+ *
508
+ * - **A message that is only a query.** Drizzle reports failures as
509
+ * `Failed query: <sql> params:` and hides the real PostgreSQL error in
510
+ * `cause`, so the wrapper alone tells a reader nothing they can act on. The
511
+ * cause is appended when it says something the message does not.
512
+ *
513
+ * - **An error that has already printed its own diagnosis**, marked
514
+ * `alreadyReported`. `CollectionsPathMissing` is one: it prints the path, what
515
+ * it resolved to and the cwd it resolved against, and then throws so the entry
516
+ * point owns the exit code. Repeating its one-line summary underneath would
517
+ * undo the "printed once" this whole path exists for.
518
+ */
519
+ function reportCommandFailure(error) {
520
+ const message = error instanceof Error ? error.message : String(error ?? "");
521
+ if (error?.alreadyReported) return;
522
+ if (!message || /Command failed|exited with code/i.test(message)) return;
523
+ outError("");
524
+ outError(chalk.red(` ✗ ${message}`));
525
+ const cause = extractCauseMessage(error);
526
+ if (cause && !message.includes(cause)) outError(chalk.gray(` ${cause}`));
527
+ outError("");
528
+ }
529
+ /**
530
+ * `migrate apply` refusing because the database already has the schema.
531
+ *
532
+ * `42710` (duplicate_object) and `42P07` (duplicate_table) are what a migration
533
+ * hits when boot-ensure — or a `db push` — has already provisioned the objects
534
+ * it was going to create. Since boot-ensure provisions *every* production
535
+ * database, this is the normal case rather than the exotic one, and the raw
536
+ * failure (`pq: type "posts_status" already exists (42710)`, then `sql/migrate:
537
+ * write revision: … current transaction is aborted`) names no way forward.
538
+ */
539
+ function parseAlreadyProvisioned(text) {
540
+ const withCode = /(?:type|relation|constraint|schema) "([^"]+)" already exists \((42710|42P07)\)/.exec(text);
541
+ if (withCode) return {
542
+ object: withCode[1],
543
+ code: withCode[2]
544
+ };
545
+ const bare = /(?:type|relation|constraint|schema) "([^"]+)" already exists/.exec(text);
546
+ if (bare && /42710|42P07/.test(text)) return {
547
+ object: bare[1],
548
+ code: /42P07/.test(text) ? "42P07" : "42710"
549
+ };
550
+ return null;
551
+ }
552
+ /**
553
+ * What to do about it: tell Atlas the database is already at a version.
554
+ *
555
+ * Atlas's own mechanism (`migrate apply --baseline <version>`), not a ledger of
556
+ * ours — it writes the revision row Atlas reads, so every later `rebase db
557
+ * migrate` is an ordinary one.
558
+ */
559
+ function formatBaselineRemedy(version, object) {
560
+ const versionToken = version ?? "<version>";
561
+ 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 a migration history that was never recorded.\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 On a database nothing has ever booted against, none of this is needed.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
562
+ }
563
+ /** `ALTER TABLE … SET NOT NULL` on a table that already holds rows (23502). */
564
+ function parseNotNullViolation(text) {
565
+ const match = /column "([^"]+)" of relation "([^"]+)" contains null values/.exec(text);
566
+ return match ? {
567
+ table: match[2],
568
+ column: match[1]
569
+ } : null;
570
+ }
571
+ /**
572
+ * The three ways out, because there is no fourth.
573
+ *
574
+ * Boot-ensure handles this case — it adds the column nullable and sets NOT NULL
575
+ * only when the table is empty — so a push that dies here is strictly worse
576
+ * than the boot that would have run instead, and the developer deserves to be
577
+ * told which of the three they want rather than left with `pq: … contains null
578
+ * values (23502)` and no next step.
579
+ */
580
+ function formatNotNullViolationBanner(violation, rowCount) {
581
+ const { table, column } = violation;
582
+ 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`;
583
+ return `
584
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
585
+ ❌ 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.
586
+
587
+ Three ways forward:
588
+
589
+ 1. Give the property a default, so the push can backfill:
590
+ ${chalk.gray(`{ type: "string", defaultValue: "…", validation: { required: true } }`)}\n 2. Backfill by hand first, then push again:\n ${chalk.gray(`psql "$DATABASE_URL" -c 'UPDATE "${table}" SET "${column}" = … WHERE "${column}" IS NULL;'`)}\n 3. Leave it optional — take \`validation.required\` off the property.\n\n ${chalk.gray("Nothing was applied for this column. `rebase dev` would have added it")}\n ${chalk.gray("nullable instead: boot sets NOT NULL only when it is safe.")}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
591
+ }
592
+ /** Atlas refusing to remove a label from an enum — a renamed `enum` option id. */
593
+ function parseEnumLabelDrop(text) {
594
+ const match = /dropping (?:enum )?value "([^"]+)" from enum "([^"]+)" is not supported/.exec(text);
595
+ return match ? {
596
+ label: match[1],
597
+ enumType: match[2]
598
+ } : null;
599
+ }
600
+ /**
601
+ * Why the two paths disagree, and what retiring an option id actually costs.
602
+ *
603
+ * Boot-ensure adds enum labels and never removes one, so `rebase dev` accepts
604
+ * the very edit that stops `db push` dead. PostgreSQL has no `ALTER TYPE …
605
+ * DROP VALUE`: a label goes only by rewriting the type, which is a data
606
+ * migration and not a schema push.
607
+ */
608
+ function formatEnumLabelDropBanner(drop) {
609
+ const { label, enumType } = drop;
610
+ return `
611
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
612
+ ❌ "${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`;
613
+ }
614
+ /** How many rows a table holds, or `null` when we cannot say. */
615
+ async function countRows(databaseUrl, table) {
616
+ if (!databaseUrl) return null;
617
+ try {
618
+ const { Client } = await import("pg");
619
+ const client = new Client({
620
+ connectionString: databaseUrl,
621
+ connectionTimeoutMillis: 5e3
622
+ });
623
+ await client.connect();
624
+ try {
625
+ return (await client.query(`SELECT count(*)::int AS n FROM "${table.replace(/"/g, "\"\"")}"`)).rows[0]?.n ?? null;
626
+ } finally {
627
+ await client.end();
628
+ }
629
+ } catch {
630
+ return null;
631
+ }
632
+ }
633
+ /**
634
+ * The remedy for an Atlas invocation that failed, or `null`.
635
+ *
636
+ * Scoped by the invocation, because the same database state means different
637
+ * things to different subcommands: "already exists" under `migrate apply` wants
638
+ * a baseline, while under `schema apply` it is a genuine conflict.
639
+ */
640
+ async function diagnoseAtlasFailure(context) {
641
+ const { domain, args, stderr, databaseUrl } = context;
642
+ if (domain === "migrate" && args.includes("apply")) {
643
+ const provisioned = parseAlreadyProvisioned(stderr);
644
+ if (provisioned) return formatBaselineRemedy(context.latestMigrationVersion ?? null, provisioned.object);
645
+ }
646
+ if (domain === "schema" && args.includes("apply")) {
647
+ const enumDrop = parseEnumLabelDrop(stderr);
648
+ if (enumDrop) return formatEnumLabelDropBanner(enumDrop);
649
+ const notNull = parseNotNullViolation(stderr);
650
+ if (notNull) return formatNotNullViolationBanner(notNull, await countRows(databaseUrl, notNull.table));
651
+ }
652
+ return null;
653
+ }
654
+ //#endregion
655
+ export { isEconnrefused as a, classifyConnectFailure as c, isRoleSwitchingPermissionError as d, isRowLevelSecurityDenial as f, sanitizeErrorForClient as h, diagnoseDbError as i, extractCauseMessage as l, reachedDatabase as m, deepestErrorMessage as n, parseHostInfo as o, pgErrorToFriendlyMessage as p, diagnoseAtlasFailure as r, reportCommandFailure as s, checkDatabaseConnectivity as t, extractPgError as u };
656
+
657
+ //# sourceMappingURL=cli-errors-DxN4yzdH.js.map