express-file-cluster 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +3 -1
  2. package/dist/auth/index.d.cts +1 -1
  3. package/dist/auth/index.d.ts +1 -1
  4. package/dist/chunk-75O3WQKR.cjs +1386 -0
  5. package/dist/chunk-75O3WQKR.cjs.map +1 -0
  6. package/dist/{chunk-6OGOVV57.js → chunk-B2I7SYQ3.js} +100 -1261
  7. package/dist/chunk-B2I7SYQ3.js.map +1 -0
  8. package/dist/chunk-BBSZLGZW.js +113 -0
  9. package/dist/chunk-BBSZLGZW.js.map +1 -0
  10. package/dist/{chunk-AZYXQU3Z.cjs → chunk-FQFKHPLR.cjs} +217 -1378
  11. package/dist/chunk-FQFKHPLR.cjs.map +1 -0
  12. package/dist/chunk-OSES7ZQ5.js +1386 -0
  13. package/dist/chunk-OSES7ZQ5.js.map +1 -0
  14. package/dist/chunk-QL6EWT4B.cjs +113 -0
  15. package/dist/chunk-QL6EWT4B.cjs.map +1 -0
  16. package/dist/cli/db-runner.cjs +611 -26
  17. package/dist/cli/db-runner.cjs.map +1 -1
  18. package/dist/cli/db-runner.js +610 -25
  19. package/dist/cli/db-runner.js.map +1 -1
  20. package/dist/cli/index.cjs +1210 -12
  21. package/dist/cli/index.cjs.map +1 -1
  22. package/dist/cli/index.js +1221 -23
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/docs/api-reference/db.md +1 -0
  25. package/dist/docs/cli/add.md +136 -0
  26. package/dist/docs/cli/db.md +25 -2
  27. package/dist/docs/cli/index.md +10 -1
  28. package/dist/docs/core-concepts/middleware.md +1 -1
  29. package/dist/docs/getting-started/index.md +25 -18
  30. package/dist/docs/getting-started/project-structure.md +6 -7
  31. package/dist/docs/guides/authentication.md +3 -1
  32. package/dist/docs/guides/coming-from-prisma.md +75 -0
  33. package/dist/docs/guides/database.md +3 -2
  34. package/dist/docs/guides/generated-portals.md +36 -19
  35. package/dist/docs/guides/mailer.md +7 -10
  36. package/dist/docs/guides/migrations.md +114 -3
  37. package/dist/docs/guides/oauth.md +94 -0
  38. package/dist/docs/guides/rbac.md +5 -40
  39. package/dist/docs/index.md +5 -3
  40. package/dist/docs/skills/SKILL.md +3 -3
  41. package/dist/docs/skills/what-not-to-invent.md +22 -6
  42. package/dist/index.cjs +10 -8
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.cts +2 -2
  45. package/dist/index.d.ts +2 -2
  46. package/dist/index.js +8 -6
  47. package/dist/index.js.map +1 -1
  48. package/dist/registry/index.json +506 -0
  49. package/dist/registry/js-mongo/_base.json +1 -0
  50. package/dist/registry/js-mongo/account-security.json +1 -0
  51. package/dist/registry/js-mongo/account-settings.json +1 -0
  52. package/dist/registry/js-mongo/admin-admins.json +1 -0
  53. package/dist/registry/js-mongo/admin-analytics.json +1 -0
  54. package/dist/registry/js-mongo/admin-billing.json +1 -0
  55. package/dist/registry/js-mongo/admin-content.json +1 -0
  56. package/dist/registry/js-mongo/admin-logs.json +1 -0
  57. package/dist/registry/js-mongo/admin-support.json +1 -0
  58. package/dist/registry/js-mongo/admin-system.json +1 -0
  59. package/dist/registry/js-mongo/admin-users.json +1 -0
  60. package/dist/registry/js-mongo/admin.json +1 -0
  61. package/dist/registry/js-mongo/auth.json +1 -0
  62. package/dist/registry/js-mongo/auth@apple.json +1 -0
  63. package/dist/registry/js-mongo/auth@google.json +1 -0
  64. package/dist/registry/js-mongo/billing.json +1 -0
  65. package/dist/registry/js-mongo/email-client.json +1 -0
  66. package/dist/registry/js-mongo/email-verification.json +1 -0
  67. package/dist/registry/js-mongo/files.json +1 -0
  68. package/dist/registry/js-mongo/forgot-password.json +1 -0
  69. package/dist/registry/js-mongo/notifications.json +1 -0
  70. package/dist/registry/js-mongo/support.json +1 -0
  71. package/dist/registry/js-mongo/user-profile.json +1 -0
  72. package/dist/registry/js-pg-model/_base.json +1 -0
  73. package/dist/registry/js-pg-model/account-security.json +1 -0
  74. package/dist/registry/js-pg-model/account-settings.json +1 -0
  75. package/dist/registry/js-pg-model/admin-admins.json +1 -0
  76. package/dist/registry/js-pg-model/admin-analytics.json +1 -0
  77. package/dist/registry/js-pg-model/admin-billing.json +1 -0
  78. package/dist/registry/js-pg-model/admin-content.json +1 -0
  79. package/dist/registry/js-pg-model/admin-logs.json +1 -0
  80. package/dist/registry/js-pg-model/admin-support.json +1 -0
  81. package/dist/registry/js-pg-model/admin-system.json +1 -0
  82. package/dist/registry/js-pg-model/admin-users.json +1 -0
  83. package/dist/registry/js-pg-model/admin.json +1 -0
  84. package/dist/registry/js-pg-model/auth.json +1 -0
  85. package/dist/registry/js-pg-model/auth@apple.json +1 -0
  86. package/dist/registry/js-pg-model/auth@google.json +1 -0
  87. package/dist/registry/js-pg-model/billing.json +1 -0
  88. package/dist/registry/js-pg-model/email-client.json +1 -0
  89. package/dist/registry/js-pg-model/email-verification.json +1 -0
  90. package/dist/registry/js-pg-model/files.json +1 -0
  91. package/dist/registry/js-pg-model/forgot-password.json +1 -0
  92. package/dist/registry/js-pg-model/notifications.json +1 -0
  93. package/dist/registry/js-pg-model/support.json +1 -0
  94. package/dist/registry/js-pg-model/user-profile.json +1 -0
  95. package/dist/registry/js-pg-table/_base.json +1 -0
  96. package/dist/registry/js-pg-table/account-security.json +1 -0
  97. package/dist/registry/js-pg-table/account-settings.json +1 -0
  98. package/dist/registry/js-pg-table/admin-admins.json +1 -0
  99. package/dist/registry/js-pg-table/admin-analytics.json +1 -0
  100. package/dist/registry/js-pg-table/admin-billing.json +1 -0
  101. package/dist/registry/js-pg-table/admin-content.json +1 -0
  102. package/dist/registry/js-pg-table/admin-logs.json +1 -0
  103. package/dist/registry/js-pg-table/admin-support.json +1 -0
  104. package/dist/registry/js-pg-table/admin-system.json +1 -0
  105. package/dist/registry/js-pg-table/admin-users.json +1 -0
  106. package/dist/registry/js-pg-table/admin.json +1 -0
  107. package/dist/registry/js-pg-table/auth.json +1 -0
  108. package/dist/registry/js-pg-table/auth@apple.json +1 -0
  109. package/dist/registry/js-pg-table/auth@google.json +1 -0
  110. package/dist/registry/js-pg-table/billing.json +1 -0
  111. package/dist/registry/js-pg-table/email-client.json +1 -0
  112. package/dist/registry/js-pg-table/email-verification.json +1 -0
  113. package/dist/registry/js-pg-table/files.json +1 -0
  114. package/dist/registry/js-pg-table/forgot-password.json +1 -0
  115. package/dist/registry/js-pg-table/notifications.json +1 -0
  116. package/dist/registry/js-pg-table/support.json +1 -0
  117. package/dist/registry/js-pg-table/user-profile.json +1 -0
  118. package/dist/registry/ts-mongo/_base.json +1 -0
  119. package/dist/registry/ts-mongo/account-security.json +1 -0
  120. package/dist/registry/ts-mongo/account-settings.json +1 -0
  121. package/dist/registry/ts-mongo/admin-admins.json +1 -0
  122. package/dist/registry/ts-mongo/admin-analytics.json +1 -0
  123. package/dist/registry/ts-mongo/admin-billing.json +1 -0
  124. package/dist/registry/ts-mongo/admin-content.json +1 -0
  125. package/dist/registry/ts-mongo/admin-logs.json +1 -0
  126. package/dist/registry/ts-mongo/admin-support.json +1 -0
  127. package/dist/registry/ts-mongo/admin-system.json +1 -0
  128. package/dist/registry/ts-mongo/admin-users.json +1 -0
  129. package/dist/registry/ts-mongo/admin.json +1 -0
  130. package/dist/registry/ts-mongo/auth.json +1 -0
  131. package/dist/registry/ts-mongo/auth@apple.json +1 -0
  132. package/dist/registry/ts-mongo/auth@google.json +1 -0
  133. package/dist/registry/ts-mongo/billing.json +1 -0
  134. package/dist/registry/ts-mongo/email-client.json +1 -0
  135. package/dist/registry/ts-mongo/email-verification.json +1 -0
  136. package/dist/registry/ts-mongo/files.json +1 -0
  137. package/dist/registry/ts-mongo/forgot-password.json +1 -0
  138. package/dist/registry/ts-mongo/notifications.json +1 -0
  139. package/dist/registry/ts-mongo/support.json +1 -0
  140. package/dist/registry/ts-mongo/user-profile.json +1 -0
  141. package/dist/registry/ts-pg-model/_base.json +1 -0
  142. package/dist/registry/ts-pg-model/account-security.json +1 -0
  143. package/dist/registry/ts-pg-model/account-settings.json +1 -0
  144. package/dist/registry/ts-pg-model/admin-admins.json +1 -0
  145. package/dist/registry/ts-pg-model/admin-analytics.json +1 -0
  146. package/dist/registry/ts-pg-model/admin-billing.json +1 -0
  147. package/dist/registry/ts-pg-model/admin-content.json +1 -0
  148. package/dist/registry/ts-pg-model/admin-logs.json +1 -0
  149. package/dist/registry/ts-pg-model/admin-support.json +1 -0
  150. package/dist/registry/ts-pg-model/admin-system.json +1 -0
  151. package/dist/registry/ts-pg-model/admin-users.json +1 -0
  152. package/dist/registry/ts-pg-model/admin.json +1 -0
  153. package/dist/registry/ts-pg-model/auth.json +1 -0
  154. package/dist/registry/ts-pg-model/auth@apple.json +1 -0
  155. package/dist/registry/ts-pg-model/auth@google.json +1 -0
  156. package/dist/registry/ts-pg-model/billing.json +1 -0
  157. package/dist/registry/ts-pg-model/email-client.json +1 -0
  158. package/dist/registry/ts-pg-model/email-verification.json +1 -0
  159. package/dist/registry/ts-pg-model/files.json +1 -0
  160. package/dist/registry/ts-pg-model/forgot-password.json +1 -0
  161. package/dist/registry/ts-pg-model/notifications.json +1 -0
  162. package/dist/registry/ts-pg-model/support.json +1 -0
  163. package/dist/registry/ts-pg-model/user-profile.json +1 -0
  164. package/dist/registry/ts-pg-table/_base.json +1 -0
  165. package/dist/registry/ts-pg-table/account-security.json +1 -0
  166. package/dist/registry/ts-pg-table/account-settings.json +1 -0
  167. package/dist/registry/ts-pg-table/admin-admins.json +1 -0
  168. package/dist/registry/ts-pg-table/admin-analytics.json +1 -0
  169. package/dist/registry/ts-pg-table/admin-billing.json +1 -0
  170. package/dist/registry/ts-pg-table/admin-content.json +1 -0
  171. package/dist/registry/ts-pg-table/admin-logs.json +1 -0
  172. package/dist/registry/ts-pg-table/admin-support.json +1 -0
  173. package/dist/registry/ts-pg-table/admin-system.json +1 -0
  174. package/dist/registry/ts-pg-table/admin-users.json +1 -0
  175. package/dist/registry/ts-pg-table/admin.json +1 -0
  176. package/dist/registry/ts-pg-table/auth.json +1 -0
  177. package/dist/registry/ts-pg-table/auth@apple.json +1 -0
  178. package/dist/registry/ts-pg-table/auth@google.json +1 -0
  179. package/dist/registry/ts-pg-table/billing.json +1 -0
  180. package/dist/registry/ts-pg-table/email-client.json +1 -0
  181. package/dist/registry/ts-pg-table/email-verification.json +1 -0
  182. package/dist/registry/ts-pg-table/files.json +1 -0
  183. package/dist/registry/ts-pg-table/forgot-password.json +1 -0
  184. package/dist/registry/ts-pg-table/notifications.json +1 -0
  185. package/dist/registry/ts-pg-table/support.json +1 -0
  186. package/dist/registry/ts-pg-table/user-profile.json +1 -0
  187. package/dist/tasks/index.d.cts +1 -1
  188. package/dist/tasks/index.d.ts +1 -1
  189. package/dist/{types-B6lVw4bj.d.cts → types-B1tJoI4g.d.cts} +6 -0
  190. package/dist/{types-B6lVw4bj.d.ts → types-B1tJoI4g.d.ts} +6 -0
  191. package/package.json +11 -2
  192. package/dist/chunk-6OGOVV57.js.map +0 -1
  193. package/dist/chunk-AZYXQU3Z.cjs.map +0 -1
@@ -0,0 +1,1386 @@
1
+ import {
2
+ getOrm,
3
+ getPool
4
+ } from "./chunk-BUBXO7WU.js";
5
+ import {
6
+ getCurrentUser,
7
+ getLogger
8
+ } from "./chunk-277BSYVH.js";
9
+
10
+ // src/errors.ts
11
+ var HttpError = class _HttpError extends Error {
12
+ statusCode;
13
+ constructor(statusCode, message) {
14
+ super(message);
15
+ this.name = "HttpError";
16
+ this.statusCode = statusCode;
17
+ Error.captureStackTrace(this, _HttpError);
18
+ }
19
+ /**
20
+ * Wraps an unknown caught value into an `HttpError`.
21
+ * If the value is already an `HttpError`, it is returned as-is.
22
+ * Otherwise the `message` from the caught `Error` (or a fallback) is used.
23
+ *
24
+ * @example
25
+ * } catch (err) {
26
+ * throw HttpError.from(err, 500, 'Something went wrong');
27
+ * }
28
+ */
29
+ static from(err, statusCode = 500, fallback = "Internal Server Error") {
30
+ if (err instanceof _HttpError) return err;
31
+ const message = err instanceof Error ? err.message : fallback;
32
+ return new _HttpError(statusCode, message);
33
+ }
34
+ /** Returns a plain object representation suitable for JSON serialization. */
35
+ toJSON() {
36
+ return {
37
+ statusCode: this.statusCode,
38
+ error: this.name,
39
+ message: this.message
40
+ };
41
+ }
42
+ };
43
+ function isHttpError(value) {
44
+ return value instanceof HttpError;
45
+ }
46
+
47
+ // src/db/schema.ts
48
+ import { randomBytes, randomUUID } from "crypto";
49
+ var MODEL_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "object", "objectId", "array"]);
50
+ var TABLE_ONLY_TYPES = /* @__PURE__ */ new Set(["integer", "bigint", "decimal", "uuid", "json"]);
51
+ var TABLE_ONLY_OPTIONS = ["precision", "scale", "nativeEnum", "column", "onDelete"];
52
+ var REFERENTIAL_ACTIONS = /* @__PURE__ */ new Set(["restrict", "cascade", "setNull"]);
53
+ var FOREIGN_KEY_TYPES = /* @__PURE__ */ new Set(["objectId", "uuid", "integer", "bigint"]);
54
+ function isFieldDefinition(value) {
55
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
56
+ const type = value.type;
57
+ return typeof type === "string" && (MODEL_TYPES.has(type) || TABLE_ONLY_TYPES.has(type));
58
+ }
59
+ var untyped = () => ({ kind: "json", def: { type: "object" } });
60
+ var SchemaBuilder = class {
61
+ constructor(model, mode) {
62
+ this.model = model;
63
+ this.mode = mode;
64
+ }
65
+ model;
66
+ mode;
67
+ fail(path, message) {
68
+ throw new Error(`[EFC] ${this.model}.${path}: ${message}`);
69
+ }
70
+ checkType(type, path) {
71
+ if (this.mode === "model" && TABLE_ONLY_TYPES.has(type)) {
72
+ this.fail(path, `type '${type}' is PostgreSQL-only \u2014 use defineTable, or a portable type`);
73
+ }
74
+ }
75
+ checkDefinition(def, path, topLevel) {
76
+ this.checkType(def.type, path);
77
+ if (def.renamedFrom !== void 0 && !topLevel) {
78
+ this.fail(path, `'renamedFrom' only applies to top-level fields`);
79
+ }
80
+ if (this.mode === "model") {
81
+ for (const opt of TABLE_ONLY_OPTIONS) {
82
+ if (def[opt] !== void 0) this.fail(path, `'${opt}' is a defineTable option`);
83
+ }
84
+ return;
85
+ }
86
+ if ((def.precision !== void 0 || def.scale !== void 0) && def.type !== "decimal") {
87
+ this.fail(path, `'precision' / 'scale' only apply to decimal fields`);
88
+ }
89
+ if (def.scale !== void 0 && def.precision === void 0) {
90
+ this.fail(path, `'scale' needs 'precision'`);
91
+ }
92
+ if (def.nativeEnum && !(def.enum && def.enum.every((v) => typeof v === "string"))) {
93
+ this.fail(path, `'nativeEnum' needs a string 'enum'`);
94
+ }
95
+ if (def.column !== void 0 && !topLevel) {
96
+ this.fail(path, `'column' only applies to top-level fields`);
97
+ }
98
+ if (def.onDelete !== void 0) {
99
+ if (def.ref === void 0) this.fail(path, `'onDelete' needs 'ref'`);
100
+ if (!REFERENTIAL_ACTIONS.has(def.onDelete)) {
101
+ this.fail(path, `onDelete must be 'restrict', 'cascade' or 'setNull'`);
102
+ }
103
+ if (def.onDelete === "setNull" && def.required) {
104
+ this.fail(path, `onDelete: 'setNull' can't clear a required field`);
105
+ }
106
+ }
107
+ if (def.ref !== void 0) {
108
+ const many = def.type === "array";
109
+ if (!topLevel) this.fail(path, `'ref' only applies to top-level fields`);
110
+ if (!FOREIGN_KEY_TYPES.has(many ? String(def.of) : def.type)) {
111
+ this.fail(
112
+ path,
113
+ many ? `a many-to-many 'ref' needs of: objectId, uuid, integer or bigint` : `'ref' needs an id type: objectId, uuid, integer or bigint`
114
+ );
115
+ }
116
+ if (many && def.onDelete !== void 0) {
117
+ this.fail(
118
+ path,
119
+ `'onDelete' doesn't apply to many-to-many refs \u2014 links are always removed with either record`
120
+ );
121
+ }
122
+ if (many && (def.unique || def.index)) {
123
+ this.fail(path, `many-to-many refs are indexed already; 'unique' / 'index' don't apply`);
124
+ }
125
+ }
126
+ }
127
+ item(of, parent, path) {
128
+ if (of === void 0) return untyped();
129
+ if (typeof of === "string") {
130
+ this.checkType(of, path);
131
+ if (of === "object" || of === "json") return untyped();
132
+ const def = {
133
+ type: of,
134
+ ...parent.ref !== void 0 && { ref: parent.ref }
135
+ };
136
+ return { kind: "scalar", type: of, def };
137
+ }
138
+ return { kind: "object", fields: this.tree(of, `${path}.$`), def: { type: "object" } };
139
+ }
140
+ field(field, path, topLevel) {
141
+ if (Array.isArray(field)) {
142
+ const inner = field[0];
143
+ return {
144
+ kind: "array",
145
+ item: inner ? { kind: "object", fields: this.tree(inner, `${path}.$`), def: { type: "object" } } : untyped(),
146
+ def: { type: "array" }
147
+ };
148
+ }
149
+ if (!isFieldDefinition(field)) {
150
+ const type = field.type;
151
+ if (typeof type === "string") this.fail(path, `unknown field type '${type}'`);
152
+ return {
153
+ kind: "object",
154
+ fields: this.tree(field, path),
155
+ def: { type: "object" }
156
+ };
157
+ }
158
+ const def = field;
159
+ this.checkDefinition(def, path, topLevel);
160
+ if (def.type === "array") return { kind: "array", item: this.item(def.of, def, path), def };
161
+ if (def.type === "object") {
162
+ return def.fields ? { kind: "object", fields: this.tree(def.fields, path), def } : { kind: "json", def };
163
+ }
164
+ if (def.type === "json") return { kind: "json", def };
165
+ return { kind: "scalar", type: def.type, def };
166
+ }
167
+ tree(schema, prefix = "") {
168
+ const out = {};
169
+ for (const [key, field] of Object.entries(schema)) {
170
+ out[key] = this.field(field, prefix ? `${prefix}.${key}` : key, prefix === "");
171
+ }
172
+ return out;
173
+ }
174
+ };
175
+ function normalizeSchema(schema, mode = "model", model = "Model") {
176
+ return new SchemaBuilder(model, mode).tree(schema);
177
+ }
178
+ function timestampFields(options) {
179
+ const ts = options.timestamps ?? true;
180
+ if (ts === false) return {};
181
+ if (ts === true) return { createdAt: "createdAt", updatedAt: "updatedAt" };
182
+ const out = {};
183
+ if (ts.createdAt !== false) out.createdAt = ts.createdAt ?? "createdAt";
184
+ if (ts.updatedAt !== false) out.updatedAt = ts.updatedAt ?? "updatedAt";
185
+ return out;
186
+ }
187
+ var STATIC_DEFAULT_OPERATORS = {
188
+ $now: () => /* @__PURE__ */ new Date(),
189
+ $uuid: () => randomUUID(),
190
+ $timestamp: () => Date.now(),
191
+ $shortId: () => randomBytes(12).toString("base64url")
192
+ };
193
+ var FIXED_DEFAULT_OPERATORS = /* @__PURE__ */ new Set(["$now", "$uuid", "$objectId", "$timestamp", "$shortId"]);
194
+ function isCurrentUserOperator(value) {
195
+ return typeof value === "string" && (value === "$currentUser" || value.startsWith("$currentUser."));
196
+ }
197
+ function isDefaultOperator(value) {
198
+ return typeof value === "string" && FIXED_DEFAULT_OPERATORS.has(value) || isCurrentUserOperator(value);
199
+ }
200
+ function resolveDefault(value, objectId) {
201
+ if (!isDefaultOperator(value)) return value;
202
+ if (value === "$objectId") return objectId;
203
+ if (value === "$currentUser") return () => getCurrentUser();
204
+ if (isCurrentUserOperator(value)) {
205
+ const key = value.slice("$currentUser.".length);
206
+ return () => getCurrentUser()?.[key];
207
+ }
208
+ return STATIC_DEFAULT_OPERATORS[value];
209
+ }
210
+ function applyDefaults(tree, data, objectId) {
211
+ const out = { ...data };
212
+ for (const [key, node] of Object.entries(tree)) {
213
+ if (out[key] === void 0 && node.def.default !== void 0) {
214
+ const d = resolveDefault(node.def.default, objectId);
215
+ const value = typeof d === "function" ? d() : structuredClone(d);
216
+ if (value !== void 0) out[key] = value;
217
+ }
218
+ if (node.kind === "object" && out[key] != null && typeof out[key] === "object") {
219
+ out[key] = applyDefaults(node.fields, out[key], objectId);
220
+ }
221
+ if (node.kind === "array" && node.item.kind === "object" && Array.isArray(out[key])) {
222
+ const fields = node.item.fields;
223
+ out[key] = out[key].map(
224
+ (v) => v != null && typeof v === "object" ? applyDefaults(fields, v, objectId) : v
225
+ );
226
+ }
227
+ }
228
+ return out;
229
+ }
230
+ var ModelValidationError = class extends HttpError {
231
+ issues;
232
+ constructor(model, issues) {
233
+ super(
234
+ 400,
235
+ `${model} validation failed: ${issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`
236
+ );
237
+ this.name = "ModelValidationError";
238
+ this.issues = issues;
239
+ }
240
+ };
241
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
242
+ var INT4 = 2 ** 31;
243
+ var INT8_MIN = -(2n ** 63n);
244
+ var INT8_MAX = 2n ** 63n - 1n;
245
+ var DECIMAL_RE = /^[+-]?(\d+(\.\d*)?|\.\d+)$/;
246
+ function decimalDigits(value) {
247
+ const str = typeof value === "number" ? String(value) : value;
248
+ const [i = "", f = ""] = str.replace(/^[+-]/, "").split(".");
249
+ return { int: i.replace(/^0+/, "").length, frac: f.replace(/0+$/, "").length };
250
+ }
251
+ function typeError(type, def, value) {
252
+ switch (type) {
253
+ case "string":
254
+ return typeof value === "string" ? null : "must be a string";
255
+ case "number":
256
+ return typeof value === "number" && Number.isFinite(value) ? null : "must be a number";
257
+ case "integer":
258
+ return typeof value === "number" && Number.isInteger(value) && value >= -INT4 && value < INT4 ? null : "must be a 32-bit integer";
259
+ case "bigint": {
260
+ const big = typeof value === "bigint" ? value : typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : void 0;
261
+ return big !== void 0 && big >= INT8_MIN && big <= INT8_MAX ? null : "must be a 64-bit integer (bigint)";
262
+ }
263
+ case "decimal": {
264
+ const ok = typeof value === "number" && Number.isFinite(value) || typeof value === "string" && DECIMAL_RE.test(value);
265
+ if (!ok) return "must be a decimal number or numeric string";
266
+ if (def.precision !== void 0) {
267
+ const scale = def.scale ?? 0;
268
+ const { int, frac } = decimalDigits(value);
269
+ if (frac > scale) return `must have at most ${scale} decimal places`;
270
+ if (int > def.precision - scale)
271
+ return `must have at most ${def.precision - scale} digits before the decimal point`;
272
+ }
273
+ return null;
274
+ }
275
+ case "boolean":
276
+ return typeof value === "boolean" ? null : "must be a boolean";
277
+ case "date":
278
+ return !Number.isNaN(new Date(value).getTime()) ? null : "must be a date";
279
+ case "objectId":
280
+ return typeof value === "string" && UUID_RE.test(value) ? null : "must be a valid id";
281
+ case "uuid":
282
+ return typeof value === "string" && UUID_RE.test(value) ? null : "must be a UUID";
283
+ }
284
+ }
285
+ function compareBound(def, value, bound) {
286
+ if (def.type === "bigint") {
287
+ const a = BigInt(value);
288
+ const b = BigInt(bound instanceof Date ? bound.getTime() : bound);
289
+ return a < b ? -1 : a > b ? 1 : 0;
290
+ }
291
+ const num = (v) => v instanceof Date ? v.getTime() : def.type === "date" ? new Date(v).getTime() : Number(v);
292
+ return num(value) - num(bound);
293
+ }
294
+ async function checkRules(def, value, path, issues) {
295
+ if (def.enum && !def.enum.includes(value)) {
296
+ issues.push({ path, message: `must be one of: ${def.enum.join(", ")}` });
297
+ }
298
+ const ordered = typeof value === "number" || typeof value === "bigint" || value instanceof Date || def.type === "date" || def.type === "decimal" && typeof value === "string";
299
+ if (ordered) {
300
+ if (def.min !== void 0 && compareBound(def, value, def.min) < 0)
301
+ issues.push({ path, message: `must be >= ${String(def.min)}` });
302
+ if (def.max !== void 0 && compareBound(def, value, def.max) > 0)
303
+ issues.push({ path, message: `must be <= ${String(def.max)}` });
304
+ }
305
+ if (typeof value === "string" && def.type !== "decimal") {
306
+ if (def.minLength !== void 0 && value.length < def.minLength)
307
+ issues.push({ path, message: `must be at least ${def.minLength} characters` });
308
+ if (def.maxLength !== void 0 && value.length > def.maxLength)
309
+ issues.push({ path, message: `must be at most ${def.maxLength} characters` });
310
+ if (def.match && !def.match.test(value))
311
+ issues.push({ path, message: `must match ${String(def.match)}` });
312
+ }
313
+ if (def.validate) {
314
+ const result = await def.validate(value);
315
+ if (result !== true)
316
+ issues.push({ path, message: typeof result === "string" ? result : "is invalid" });
317
+ }
318
+ }
319
+ async function validateNode(node, value, path, issues, partial) {
320
+ if (value === void 0 || value === null) {
321
+ if (node.def.required && !partial) issues.push({ path, message: "is required" });
322
+ if (node.def.required && partial && value === null)
323
+ issues.push({ path, message: "is required" });
324
+ return;
325
+ }
326
+ switch (node.kind) {
327
+ case "scalar": {
328
+ const err = typeError(node.type, node.def, value);
329
+ if (err) {
330
+ issues.push({ path, message: err });
331
+ return;
332
+ }
333
+ await checkRules(node.def, value, path, issues);
334
+ return;
335
+ }
336
+ case "json":
337
+ await checkRules(node.def, value, path, issues);
338
+ return;
339
+ case "object":
340
+ if (typeof value !== "object" || Array.isArray(value)) {
341
+ issues.push({ path, message: "must be an object" });
342
+ return;
343
+ }
344
+ await validateTree(node.fields, value, issues, false, path);
345
+ await checkRules(node.def, value, path, issues);
346
+ return;
347
+ case "array":
348
+ if (!Array.isArray(value)) {
349
+ issues.push({ path, message: "must be an array" });
350
+ return;
351
+ }
352
+ for (let i = 0; i < value.length; i++) {
353
+ await validateNode(
354
+ { ...node.item, def: { ...node.item.def, required: true } },
355
+ value[i],
356
+ `${path}.${i}`,
357
+ issues,
358
+ false
359
+ );
360
+ }
361
+ await checkRules(node.def, value, path, issues);
362
+ }
363
+ }
364
+ async function validateTree(tree, data, issues, partial, prefix = "") {
365
+ for (const [key, node] of Object.entries(tree)) {
366
+ if (partial && !(key in data)) continue;
367
+ await validateNode(node, data[key], prefix ? `${prefix}.${key}` : key, issues, partial);
368
+ }
369
+ return issues;
370
+ }
371
+ function refFields(tree) {
372
+ const refs = /* @__PURE__ */ new Map();
373
+ for (const [key, node] of Object.entries(tree)) {
374
+ if (node.kind === "scalar" && node.type === "objectId" && node.def.ref) {
375
+ refs.set(key, { model: node.def.ref, many: false });
376
+ } else if (node.kind === "array" && node.item.kind === "scalar" && node.item.type === "objectId" && node.def.ref) {
377
+ refs.set(key, { model: node.def.ref, many: true });
378
+ }
379
+ }
380
+ return refs;
381
+ }
382
+ function sequenceFields(name, tree) {
383
+ const out = [];
384
+ for (const [path, node] of Object.entries(tree)) {
385
+ if (node.def.sequence) {
386
+ out.push({
387
+ path,
388
+ key: typeof node.def.sequence === "string" ? node.def.sequence : `${name}.${path}`
389
+ });
390
+ }
391
+ }
392
+ return out;
393
+ }
394
+ function nodeAt(tree, path) {
395
+ let node = tree[path[0]];
396
+ for (const part of path.slice(1)) {
397
+ if (!node) return void 0;
398
+ if (node.kind === "object") node = node.fields[part];
399
+ else if (node.kind === "array" && /^\d+$/.test(part)) node = node.item;
400
+ else if (node.kind === "json")
401
+ return node;
402
+ else return void 0;
403
+ }
404
+ return node;
405
+ }
406
+ async function validateAtPath(tree, dotted, value, issues) {
407
+ const node = nodeAt(tree, dotted.split("."));
408
+ if (!node) {
409
+ issues.push({ path: dotted, message: "unknown field" });
410
+ return;
411
+ }
412
+ await validateNode(node, value, dotted, issues, true);
413
+ }
414
+
415
+ // src/db/engine.ts
416
+ import { AsyncLocalStorage } from "async_hooks";
417
+ var engine;
418
+ function setDbEngine(value) {
419
+ engine = value;
420
+ }
421
+ function getDbEngine() {
422
+ return engine ?? "mongodb";
423
+ }
424
+ var autoSync = true;
425
+ function setAutoSync(value) {
426
+ autoSync = value;
427
+ }
428
+ function isAutoSync() {
429
+ return autoSync;
430
+ }
431
+ var syncSuppressed = false;
432
+ function setSyncSuppressed(value) {
433
+ syncSuppressed = value;
434
+ }
435
+ function isSyncSuppressed() {
436
+ return syncSuppressed;
437
+ }
438
+ var registry = /* @__PURE__ */ new Map();
439
+ function registerModel(model) {
440
+ registry.set(model.name, model);
441
+ }
442
+ function getRegisteredModel(name) {
443
+ return registry.get(name);
444
+ }
445
+ function registeredModels() {
446
+ return [...registry.values()];
447
+ }
448
+ var txStorage = new AsyncLocalStorage();
449
+ function currentTx() {
450
+ return txStorage.getStore();
451
+ }
452
+ function runInTx(handle, fn) {
453
+ return txStorage.run(handle, fn);
454
+ }
455
+
456
+ // src/db/pg-table.ts
457
+ import { randomUUID as randomUUID2 } from "crypto";
458
+ var drizzlePromise;
459
+ function loadDrizzle() {
460
+ drizzlePromise ??= Promise.all([import("drizzle-orm"), import("drizzle-orm/pg-core")]).then(([orm, pgCore]) => ({ sql: orm.sql, pgCore })).catch(() => {
461
+ drizzlePromise = void 0;
462
+ throw new Error("[EFC] drizzle-orm is not installed. Run: npm install pg drizzle-orm");
463
+ });
464
+ return drizzlePromise;
465
+ }
466
+ function tableNameFor(model) {
467
+ const lower = model.toLowerCase();
468
+ if (/[^aeiou]y$/.test(lower)) return lower.slice(0, -1) + "ies";
469
+ if (/(s|x|z|ch|sh)$/.test(lower)) return lower + "es";
470
+ return lower + "s";
471
+ }
472
+ var snakeCase = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
473
+ var q = (ident) => `"${ident.replace(/"/g, '""')}"`;
474
+ var sequenceName = (key) => `efc_seq_${key.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase()}`;
475
+ var literal = (v) => typeof v === "number" ? String(v) : `'${v.replace(/'/g, "''")}'`;
476
+ var syncing = /* @__PURE__ */ new Map();
477
+ var ACTION_SQL = {
478
+ restrict: "RESTRICT",
479
+ cascade: "CASCADE",
480
+ setNull: "SET NULL"
481
+ };
482
+ var ACTION_CODE = {
483
+ restrict: "r",
484
+ cascade: "c",
485
+ setNull: "n"
486
+ };
487
+ var ID_COLUMN = {
488
+ uuid: { kind: "uuid", type: "uuid" },
489
+ serial: { kind: "integer", type: "integer" },
490
+ bigserial: { kind: "bigint", type: "bigint" }
491
+ };
492
+ var modelOfTable = (table) => registeredModels().find((m) => {
493
+ try {
494
+ return m.pgTarget?.().table === table;
495
+ } catch {
496
+ return false;
497
+ }
498
+ })?.name ?? table;
499
+ function scalarSpec(type, def, native) {
500
+ switch (type) {
501
+ case "string":
502
+ if (native && def.maxLength !== void 0) {
503
+ return {
504
+ kind: "varchar",
505
+ ddl: `varchar(${def.maxLength})`,
506
+ formatted: `character varying(${def.maxLength})`,
507
+ length: def.maxLength
508
+ };
509
+ }
510
+ return { kind: "text", ddl: "text", formatted: "text" };
511
+ case "number":
512
+ return { kind: "double", ddl: "double precision", formatted: "double precision" };
513
+ case "integer":
514
+ return { kind: "integer", ddl: "integer", formatted: "integer" };
515
+ case "bigint":
516
+ return { kind: "bigint", ddl: "bigint", formatted: "bigint", bigintAs: "bigint" };
517
+ case "decimal": {
518
+ if (def.precision === void 0)
519
+ return { kind: "numeric", ddl: "numeric", formatted: "numeric" };
520
+ const t = `numeric(${def.precision},${def.scale ?? 0})`;
521
+ return {
522
+ kind: "numeric",
523
+ ddl: t,
524
+ formatted: t,
525
+ precision: def.precision,
526
+ scale: def.scale ?? 0
527
+ };
528
+ }
529
+ case "boolean":
530
+ return { kind: "boolean", ddl: "boolean", formatted: "boolean" };
531
+ case "date":
532
+ return { kind: "timestamptz", ddl: "timestamptz", formatted: "timestamp with time zone" };
533
+ case "objectId":
534
+ case "uuid":
535
+ return { kind: "uuid", ddl: "uuid", formatted: "uuid" };
536
+ }
537
+ }
538
+ function pgTable(name, tree, options, config) {
539
+ const snake = config.native && options.naming === "snake_case";
540
+ const table = options.collection ?? tableNameFor(snake ? snakeCase(name) : name);
541
+ const columnName = (field, def) => def?.column ?? (snake ? snakeCase(field) : field);
542
+ const idKind = config.native && options.id || "uuid";
543
+ if (tree["id"]) throw new Error(`[EFC] ${name}: "id" is the primary key \u2014 don't declare it`);
544
+ const ts = timestampFields(options);
545
+ const sequences = sequenceFields(name, tree);
546
+ const sequenceKeys = new Map(sequences.map((s) => [s.path, s.key]));
547
+ const refs = refFields(tree);
548
+ const columns = /* @__PURE__ */ new Map();
549
+ const joins = /* @__PURE__ */ new Map();
550
+ const idSpec = idKind === "uuid" ? { field: "id", column: "id", kind: "uuid", ddl: "uuid", formatted: "uuid" } : idKind === "serial" ? { field: "id", column: "id", kind: "integer", ddl: "integer", formatted: "integer" } : {
551
+ field: "id",
552
+ column: "id",
553
+ kind: "bigint",
554
+ ddl: "bigint",
555
+ formatted: "bigint",
556
+ bigintAs: "bigint"
557
+ };
558
+ columns.set("id", idSpec);
559
+ for (const [field, node] of Object.entries(tree)) {
560
+ const column = columnName(field, node.def);
561
+ const base = { field, column, node };
562
+ if (sequenceKeys.has(field)) {
563
+ columns.set(field, {
564
+ ...base,
565
+ kind: "bigint",
566
+ ddl: "bigint",
567
+ formatted: "bigint",
568
+ bigintAs: "number"
569
+ });
570
+ } else if (node.kind === "scalar") {
571
+ if (config.native && node.def.nativeEnum && node.def.enum) {
572
+ const enumType = `${table}_${column}_enum`;
573
+ columns.set(field, {
574
+ ...base,
575
+ kind: "enum",
576
+ ddl: q(enumType),
577
+ formatted: /^[a-z_][a-z0-9_]*$/.test(enumType) ? enumType : q(enumType),
578
+ enumType,
579
+ enumValues: node.def.enum.map(String)
580
+ });
581
+ } else {
582
+ columns.set(field, { ...base, ...scalarSpec(node.type, node.def, config.native) });
583
+ }
584
+ } else if (config.native && node.kind === "array" && node.item.kind === "scalar" && node.def.ref !== void 0) {
585
+ const item = scalarSpec(node.item.type, node.item.def, false).kind;
586
+ joins.set(field, {
587
+ field,
588
+ table: `${table}_${column}`,
589
+ legacyColumn: column,
590
+ target: node.def.ref,
591
+ item,
592
+ ddl: `${item}[]`,
593
+ node
594
+ });
595
+ } else if (config.native && node.kind === "array" && node.item.kind === "scalar") {
596
+ const item = scalarSpec(node.item.type, node.item.def, false);
597
+ columns.set(field, {
598
+ ...base,
599
+ ...item,
600
+ kind: "array",
601
+ item: item.kind,
602
+ ddl: `${item.ddl}[]`,
603
+ formatted: `${item.formatted}[]`
604
+ });
605
+ } else {
606
+ columns.set(field, { ...base, kind: "jsonb", ddl: "jsonb", formatted: "jsonb" });
607
+ }
608
+ }
609
+ for (const field of [ts.createdAt, ts.updatedAt]) {
610
+ if (field) {
611
+ columns.set(field, {
612
+ field,
613
+ column: columnName(field),
614
+ kind: "timestamptz",
615
+ ddl: "timestamptz",
616
+ formatted: "timestamp with time zone"
617
+ });
618
+ }
619
+ }
620
+ const byColumn = new Map([...columns.values()].map((c) => [c.column, c]));
621
+ const builder = (pgCore, kind, spec) => {
622
+ const c = spec.column;
623
+ switch (kind) {
624
+ case "varchar":
625
+ return pgCore.varchar(c, { length: spec.length });
626
+ case "double":
627
+ return pgCore.doublePrecision(c);
628
+ case "integer":
629
+ return pgCore.integer(c);
630
+ case "bigint":
631
+ return pgCore.bigint(c, { mode: spec.bigintAs ?? "bigint" });
632
+ case "numeric":
633
+ return pgCore.numeric(
634
+ c,
635
+ spec.precision !== void 0 ? { precision: spec.precision, scale: spec.scale } : {}
636
+ );
637
+ case "boolean":
638
+ return pgCore.boolean(c);
639
+ case "timestamptz":
640
+ return pgCore.timestamp(c, { withTimezone: true, mode: "date" });
641
+ case "uuid":
642
+ return pgCore.uuid(c);
643
+ default:
644
+ return pgCore.text(c);
645
+ }
646
+ };
647
+ let compiled;
648
+ const compile = () => compiled ??= loadDrizzle().then(({ sql, pgCore }) => {
649
+ const cols = {};
650
+ for (const [field, spec] of columns) {
651
+ let c;
652
+ if (spec.kind === "jsonb") c = pgCore.jsonb(spec.column);
653
+ else if (spec.kind === "array") c = builder(pgCore, spec.item, spec).array();
654
+ else c = builder(pgCore, spec.kind, spec);
655
+ if (field === "id") {
656
+ c = idKind === "uuid" ? c.primaryKey().defaultRandom() : c.primaryKey().generatedByDefaultAsIdentity();
657
+ }
658
+ cols[field] = c;
659
+ }
660
+ return { t: pgCore.pgTable(table, cols), sql };
661
+ });
662
+ let synced;
663
+ const ready = async () => {
664
+ const result = await compile();
665
+ if (isAutoSync()) {
666
+ synced ??= reconcile(false).then(
667
+ (changes) => {
668
+ if (changes.length)
669
+ getLogger().info({ table, changes: changes.length }, `Synced table ${table}`);
670
+ },
671
+ (err) => {
672
+ synced = void 0;
673
+ throw err;
674
+ }
675
+ );
676
+ await synced;
677
+ }
678
+ return result;
679
+ };
680
+ const client = () => {
681
+ const tx = currentTx();
682
+ return tx?.engine === "postgresql" ? tx.tx : getOrm();
683
+ };
684
+ const columnFor = (t, field) => {
685
+ if (!columns.has(field))
686
+ throw new ModelValidationError(name, [{ path: field, message: "unknown field" }]);
687
+ return t[field];
688
+ };
689
+ const scalarToDb = (kind, spec, v) => {
690
+ if (v == null) return v;
691
+ if (kind === "timestamptz") return v instanceof Date ? v : new Date(v);
692
+ if (kind === "bigint")
693
+ return spec.bigintAs === "number" ? Number(v) : BigInt(v);
694
+ if (kind === "numeric") return String(v);
695
+ return v;
696
+ };
697
+ const toDb = (field, value) => {
698
+ const spec = columns.get(field);
699
+ if (!spec || value == null) return value;
700
+ if (spec.kind === "array") {
701
+ return Array.isArray(value) ? value.map((v) => scalarToDb(spec.item, spec, v)) : value;
702
+ }
703
+ if (spec.kind === "jsonb") return value;
704
+ return scalarToDb(spec.kind, spec, value);
705
+ };
706
+ const revive = (node, value) => {
707
+ if (value == null) return value;
708
+ if (node.kind === "scalar") {
709
+ if (node.type === "date" && typeof value === "string") return new Date(value);
710
+ return value;
711
+ }
712
+ if (node.kind === "array" && Array.isArray(value))
713
+ return value.map((v) => revive(node.item, v));
714
+ if (node.kind === "object" && typeof value === "object" && !Array.isArray(value)) {
715
+ const out = { ...value };
716
+ for (const [k, child] of Object.entries(node.fields)) {
717
+ if (out[k] !== void 0) out[k] = revive(child, out[k]);
718
+ }
719
+ return out;
720
+ }
721
+ return value;
722
+ };
723
+ const hasNestedDate = (node) => node.kind === "scalar" ? node.type === "date" : node.kind === "array" ? hasNestedDate(node.item) : node.kind === "object" && Object.values(node.fields).some(hasNestedDate);
724
+ const datedJson = [...columns.values()].filter(
725
+ (c) => c.kind === "jsonb" && c.node && hasNestedDate(c.node)
726
+ );
727
+ const bigintCols = [...columns.values()].filter(
728
+ (c) => c.kind === "bigint" && c.bigintAs === "bigint" || c.kind === "array" && c.item === "bigint"
729
+ );
730
+ const fromRow = (row) => {
731
+ const out = {};
732
+ for (const [k, v] of Object.entries(row)) if (v !== null) out[k] = v;
733
+ for (const c of datedJson)
734
+ if (out[c.field] !== void 0) out[c.field] = revive(c.node, out[c.field]);
735
+ for (const c of bigintCols) {
736
+ const v = out[c.field];
737
+ if (typeof v === "string" || typeof v === "number") out[c.field] = BigInt(v);
738
+ else if (Array.isArray(v)) out[c.field] = v.map((x) => x == null ? x : BigInt(x));
739
+ }
740
+ return out;
741
+ };
742
+ const fromRawRow = (row) => {
743
+ const keyed = {};
744
+ for (const [col, v] of Object.entries(row)) {
745
+ const spec = byColumn.get(col);
746
+ if (!spec) continue;
747
+ keyed[spec.field] = v != null && spec.kind === "timestamptz" && !(v instanceof Date) ? new Date(v) : v;
748
+ }
749
+ return fromRow(keyed);
750
+ };
751
+ const validate = async (data, partial) => {
752
+ const issues = [];
753
+ const checkTree = {};
754
+ for (const [k, node] of Object.entries(tree)) {
755
+ checkTree[k] = sequenceKeys.has(k) ? { ...node, def: { ...node.def, required: false } } : node;
756
+ }
757
+ await validateTree(checkTree, data, issues, partial);
758
+ if (issues.length) throw new ModelValidationError(name, issues);
759
+ };
760
+ const known = (data) => Object.fromEntries(
761
+ Object.entries(data).filter(([k]) => {
762
+ const top = k.split(".")[0];
763
+ return columns.has(top) || joins.has(top);
764
+ })
765
+ );
766
+ const prepareInsert = async (input) => {
767
+ const { id, ...rest } = known(input);
768
+ for (const f of [ts.createdAt, ts.updatedAt]) if (f) delete rest[f];
769
+ const data = applyDefaults(tree, rest, randomUUID2);
770
+ await validate(data, false);
771
+ const now = /* @__PURE__ */ new Date();
772
+ if (ts.createdAt) data[ts.createdAt] = now;
773
+ if (ts.updatedAt) data[ts.updatedAt] = now;
774
+ if (id !== void 0) data["id"] = id;
775
+ for (const [k, v] of Object.entries(data)) data[k] = toDb(k, v);
776
+ return data;
777
+ };
778
+ const fieldOfColumn = (column) => byColumn.get(column)?.field ?? column;
779
+ const guard = async (fn) => {
780
+ try {
781
+ return await fn();
782
+ } catch (err) {
783
+ const e = err.cause ?? err;
784
+ if (e?.code === "42P01") {
785
+ throw new Error(
786
+ `[EFC] ${name}: table "${table}" does not exist \u2014 autoSync is off, so create it with a migration (Model.sync() / efc db sync)`
787
+ );
788
+ }
789
+ if (e?.code === "23505") {
790
+ const cols = /\(([^)]+)\)=/.exec(e.detail ?? "")?.[1] ?? "field";
791
+ const fields = cols.split(",").map((c) => fieldOfColumn(c.trim().replace(/"/g, ""))).join(", ");
792
+ throw new HttpError(409, `${name} with this ${fields} already exists`);
793
+ }
794
+ if (e?.code === "23503" || e?.code === "23001") {
795
+ const ref = /Key \(([^)]+)\)=\([^)]*\) is not present in table "([^"]+)"/.exec(
796
+ e.detail ?? ""
797
+ );
798
+ if (ref) {
799
+ throw new ModelValidationError(name, [
800
+ {
801
+ // In a join table: the many-to-many field it backs.
802
+ path: joinByTable.get(e.table ?? "") ?? fieldOfColumn(ref[1].replace(/"/g, "")),
803
+ message: `${modelOfTable(ref[2])} not found`
804
+ }
805
+ ]);
806
+ }
807
+ const by = /is (?:still )?referenced from table "([^"]+)"/.exec(e.detail ?? "")?.[1];
808
+ throw new HttpError(
809
+ 409,
810
+ `${name} is still referenced${by ? ` by ${modelOfTable(by)}` : ""} \u2014 delete or reassign those records first`
811
+ );
812
+ }
813
+ if (e?.code === "23502")
814
+ throw new ModelValidationError(name, [
815
+ { path: fieldOfColumn(e.column ?? ""), message: "is required" }
816
+ ]);
817
+ if (e?.code === "22P02" || e?.code === "22003" || e?.code === "23514")
818
+ throw new ModelValidationError(name, [{ path: "", message: "invalid value" }]);
819
+ throw err;
820
+ }
821
+ };
822
+ const JSONB_TO_ARRAY = "efc_jsonb_text_array";
823
+ const jsonbToArrayFn = `CREATE OR REPLACE FUNCTION ${JSONB_TO_ARRAY}(j jsonb) RETURNS text[] LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN j IS NULL OR jsonb_typeof(j) = 'null' THEN NULL WHEN jsonb_typeof(j) = 'array' THEN ARRAY(SELECT jsonb_array_elements_text(j)) ELSE ARRAY[j #>> '{}'] END $$`;
824
+ const castExpr = (spec, from) => {
825
+ const c = q(spec.column);
826
+ if (spec.kind === "jsonb") return `to_jsonb(${c})`;
827
+ if (spec.kind === "array") {
828
+ if (from === "jsonb") return `${JSONB_TO_ARRAY}(${c})::${spec.ddl}`;
829
+ if (from.endsWith("[]")) return `${c}::${spec.ddl}`;
830
+ return `CASE WHEN ${c} IS NULL THEN NULL ELSE ARRAY[${c}::text]::${spec.ddl} END`;
831
+ }
832
+ const scalar = from === "jsonb" ? `(${c} #>> '{}')` : c;
833
+ if (spec.kind === "enum") return `${scalar}::text::${spec.ddl}`;
834
+ if (spec.kind === "bigint" || spec.kind === "integer") {
835
+ return `round(${scalar}::numeric)::${spec.ddl}`;
836
+ }
837
+ return `${scalar}::${spec.ddl}`;
838
+ };
839
+ const needsTypeChange = (spec, existing) => {
840
+ if (existing === spec.formatted) return false;
841
+ if (spec.kind === "varchar") {
842
+ if (existing === "text") return false;
843
+ const m = /^character varying\((\d+)\)$/.exec(existing);
844
+ if (m && Number(m[1]) >= spec.length) return false;
845
+ }
846
+ return true;
847
+ };
848
+ const enumCheck = (column) => `${table}_${column}_enum`;
849
+ const fkName = (column) => `${table}_${column}_fkey`;
850
+ const isForeignKey = (spec) => config.native && spec.node?.kind === "scalar" && spec.node.def.ref !== void 0;
851
+ function resolveTarget(field, targetName, kind, many) {
852
+ const target = targetName === name ? { table, idKind } : getRegisteredModel(targetName)?.pgTarget?.();
853
+ if (!target) {
854
+ throw new Error(
855
+ `[EFC] ${name}.${field} references "${targetName}", which is not defined \u2014 import that model before using ${name}`
856
+ );
857
+ }
858
+ const want = ID_COLUMN[target.idKind];
859
+ if (kind !== want.kind) {
860
+ const hint = many ? `{ type: 'array', of: '${want.type}', ref: '${targetName}' }` : `{ type: '${want.type}', ref: '${targetName}' }`;
861
+ throw new Error(
862
+ `[EFC] ${name}.${field} references ${targetName}, whose id is ${want.type} (id: '${target.idKind}') \u2014 declare it ${hint}`
863
+ );
864
+ }
865
+ return target;
866
+ }
867
+ function foreignKeys() {
868
+ const out = [];
869
+ for (const spec of columns.values()) {
870
+ if (!isForeignKey(spec)) continue;
871
+ const def = spec.node.def;
872
+ const target = resolveTarget(spec.field, def.ref, spec.kind, false);
873
+ out.push({
874
+ field: spec.field,
875
+ onTable: table,
876
+ column: spec.column,
877
+ name: fkName(spec.column),
878
+ target: def.ref,
879
+ targetTable: target.table,
880
+ action: def.onDelete ?? "restrict"
881
+ });
882
+ }
883
+ for (const join of joins.values()) {
884
+ const target = resolveTarget(join.field, join.target, join.item, true);
885
+ const base = { field: join.field, onTable: join.table, action: "cascade" };
886
+ out.push(
887
+ {
888
+ ...base,
889
+ column: "owner_id",
890
+ name: `${join.table}_owner_id_fkey`,
891
+ target: name,
892
+ targetTable: table
893
+ },
894
+ {
895
+ ...base,
896
+ column: "ref_id",
897
+ name: `${join.table}_ref_id_fkey`,
898
+ target: join.target,
899
+ targetTable: target.table
900
+ }
901
+ );
902
+ }
903
+ return out;
904
+ }
905
+ const joinByTable = new Map([...joins.values()].map((j) => [j.table, j.field]));
906
+ const managedIndexName = /_(key|idx)$/;
907
+ function desiredIndexes() {
908
+ const out = /* @__PURE__ */ new Map();
909
+ for (const spec of columns.values()) {
910
+ const def = spec.node?.def;
911
+ if (!def) continue;
912
+ const col = spec.column;
913
+ if (def.unique) {
914
+ out.set(
915
+ `${table}_${col}_key`,
916
+ `CREATE UNIQUE INDEX ${q(`${table}_${col}_key`)} ON ${q(table)} (${q(col)})`
917
+ );
918
+ } else if (def.index || isForeignKey(spec) && def.index !== false) {
919
+ out.set(
920
+ `${table}_${col}_idx`,
921
+ `CREATE INDEX ${q(`${table}_${col}_idx`)} ON ${q(table)} (${q(col)})`
922
+ );
923
+ }
924
+ }
925
+ for (const idx of options.indexes ?? []) {
926
+ const fields = Object.entries(idx.fields).map(
927
+ ([f, d]) => [columns.get(f)?.column ?? f, d]
928
+ );
929
+ if (idx.expireAfterSeconds !== void 0) {
930
+ throw new Error(`[EFC] ${name}: TTL indexes (expireAfterSeconds) are MongoDB-only`);
931
+ }
932
+ const idxName = idx.name ?? `${table}_${fields.map(([f]) => f).join("_")}_${idx.unique ? "key" : "idx"}`;
933
+ if (fields.some(([, d]) => d === "text")) {
934
+ const doc = fields.map(([f]) => `coalesce(${q(f)}::text, '')`).join(` || ' ' || `);
935
+ out.set(
936
+ idxName,
937
+ `CREATE INDEX ${q(idxName)} ON ${q(table)} USING gin (to_tsvector('simple', ${doc}))`
938
+ );
939
+ } else {
940
+ const cols = fields.map(([f, d]) => `${q(f)} ${d === -1 ? "DESC" : "ASC"}`).join(", ");
941
+ out.set(
942
+ idxName,
943
+ `CREATE ${idx.unique ? "UNIQUE " : ""}INDEX ${q(idxName)} ON ${q(table)} (${cols})`
944
+ );
945
+ }
946
+ }
947
+ return out;
948
+ }
949
+ const tableExists = async (t) => (await getPool().query(
950
+ `SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
951
+ WHERE c.relname = $1 AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
952
+ [t]
953
+ )).rowCount > 0;
954
+ async function reconcile(dryRun) {
955
+ if (isSyncSuppressed()) return [];
956
+ const fks = foreignKeys();
957
+ if (dryRun) return statements(await reconcileTable({ dryRun: true }, fks, /* @__PURE__ */ new Set()));
958
+ let release;
959
+ const mine = new Promise((resolve) => release = resolve);
960
+ const prev = syncing.get(table);
961
+ syncing.set(table, mine);
962
+ try {
963
+ const deferred = /* @__PURE__ */ new Set();
964
+ const tx = currentTx();
965
+ if (tx?.engine === "postgresql" && fks.length) {
966
+ for (const fk of fks) deferred.add(fk.name);
967
+ tx.afterCommit.push(() => {
968
+ reconcile(false).catch(
969
+ (err) => getLogger().error({ err }, `${name}: adding foreign keys to "${table}" failed`)
970
+ );
971
+ });
972
+ }
973
+ for (const fk of fks) {
974
+ if (deferred.has(fk.name)) continue;
975
+ if (fk.targetTable === table || await tableExists(fk.targetTable)) continue;
976
+ const running = syncing.get(fk.targetTable);
977
+ if (running) {
978
+ deferred.add(fk.name);
979
+ void running.then(() => reconcile(false)).catch(
980
+ (err) => getLogger().error({ err }, `${name}: adding foreign keys to "${table}" failed`)
981
+ );
982
+ } else {
983
+ await getRegisteredModel(fk.target).sync();
984
+ }
985
+ }
986
+ return statements(await reconcileTable({ dryRun: false }, fks, deferred));
987
+ } finally {
988
+ release();
989
+ if (syncing.get(table) === mine) {
990
+ if (prev) syncing.set(table, prev);
991
+ else syncing.delete(table);
992
+ }
993
+ }
994
+ }
995
+ const statements = (steps) => steps.filter((s) => !s.check).map((s) => s.sql);
996
+ function plan(options2 = {}) {
997
+ return reconcileTable({ dryRun: true, plan: options2 }, foreignKeys(), /* @__PURE__ */ new Set());
998
+ }
999
+ async function reconcileTable(mode, fks, deferred) {
1000
+ const { dryRun } = mode;
1001
+ const generating = mode.plan !== void 0;
1002
+ const pool = getPool();
1003
+ const conn = await pool.connect();
1004
+ try {
1005
+ await conn.query("BEGIN");
1006
+ await conn.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`efc_sync:${table}`]);
1007
+ const existing = new Map(
1008
+ (await conn.query(
1009
+ `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable
1010
+ FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1011
+ WHERE c.relname = $1 AND n.nspname = current_schema() AND a.attnum > 0 AND NOT a.attisdropped`,
1012
+ [table]
1013
+ )).rows.map((r) => [r.name, { type: r.type, nullable: r.nullable }])
1014
+ );
1015
+ const checks = new Map(
1016
+ (await conn.query(
1017
+ `SELECT con.conname AS name, pg_get_constraintdef(con.oid) AS def, con.convalidated AS valid
1018
+ FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1019
+ WHERE c.relname = $1 AND n.nspname = current_schema() AND con.contype = 'c'`,
1020
+ [table]
1021
+ )).rows.map((r) => [r.name, { def: r.def, valid: r.valid }])
1022
+ );
1023
+ const indexes = new Map(
1024
+ (await conn.query(
1025
+ `SELECT indexname AS name, indexdef AS def FROM pg_indexes WHERE tablename = $1 AND schemaname = current_schema()`,
1026
+ [table]
1027
+ )).rows.map((r) => [r.name, r.def])
1028
+ );
1029
+ const liveFks = new Map(
1030
+ (await conn.query(
1031
+ `SELECT con.conname AS name, ft.relname AS target, con.confdeltype AS action, con.convalidated AS valid,
1032
+ pg_get_constraintdef(con.oid) AS def
1033
+ FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1034
+ JOIN pg_class ft ON ft.oid = con.confrelid
1035
+ WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND con.contype = 'f'`,
1036
+ [[table, ...joinByTable.keys()]]
1037
+ )).rows.map((r) => [r.name, r])
1038
+ );
1039
+ const liveJoinTables = new Set(
1040
+ (await conn.query(
1041
+ `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1042
+ WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
1043
+ [[...joinByTable.keys()]]
1044
+ )).rows.map((r) => r.name)
1045
+ );
1046
+ const steps = [];
1047
+ const add = (sql, extra = {}) => {
1048
+ if (!steps.some((s) => s.sql === sql)) steps.push({ phase: "main", ...extra, sql });
1049
+ };
1050
+ const columnExists = (column) => `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ${literal(table)} AND column_name = ${literal(column)}`;
1051
+ const wantedFks = new Map(fks.map((fk) => [fk.name, fk]));
1052
+ for (const [con, live] of liveFks) {
1053
+ const want = wantedFks.get(con);
1054
+ const ours = [...joinByTable.keys()].some((jt) => con.startsWith(`${jt}_`)) || [...columns.values()].some((c) => c.field !== "id" && fkName(c.column) === con);
1055
+ if (ours && (!want || live.target !== want.targetTable || live.action !== ACTION_CODE[want.action])) {
1056
+ const on = [...joinByTable.keys()].find((jt) => con.startsWith(`${jt}_`)) ?? table;
1057
+ add(`ALTER TABLE ${q(on)} DROP CONSTRAINT IF EXISTS ${q(con)}`, {
1058
+ down: `ALTER TABLE ${q(on)} ADD CONSTRAINT ${q(con)} ${live.def}`
1059
+ });
1060
+ liveFks.delete(con);
1061
+ }
1062
+ }
1063
+ for (const { key } of sequences) {
1064
+ const seq = sequenceName(key);
1065
+ const found = await conn.query(
1066
+ `SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1067
+ WHERE c.relkind = 'S' AND c.relname = $1 AND n.nspname = current_schema()`,
1068
+ [seq]
1069
+ );
1070
+ if (found.rowCount === 0)
1071
+ add(`CREATE SEQUENCE IF NOT EXISTS ${q(seq)}`, {
1072
+ down: `DROP SEQUENCE IF EXISTS ${q(seq)}`
1073
+ });
1074
+ }
1075
+ const enumSpecs = [...columns.values()].filter((c) => c.kind === "enum");
1076
+ if (enumSpecs.length) {
1077
+ const live = /* @__PURE__ */ new Map();
1078
+ for (const r of (await conn.query(
1079
+ `SELECT t.typname AS type, e.enumlabel AS label FROM pg_type t
1080
+ JOIN pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_enum e ON e.enumtypid = t.oid
1081
+ WHERE n.nspname = current_schema() AND t.typname = ANY($1)`,
1082
+ [enumSpecs.map((c) => c.enumType)]
1083
+ )).rows) {
1084
+ const set = live.get(r.type) ?? /* @__PURE__ */ new Set();
1085
+ if (r.label !== null) set.add(r.label);
1086
+ live.set(r.type, set);
1087
+ }
1088
+ for (const spec of enumSpecs) {
1089
+ const have = live.get(spec.enumType);
1090
+ if (!have) {
1091
+ add(`CREATE TYPE ${spec.ddl} AS ENUM (${spec.enumValues.map(literal).join(", ")})`, {
1092
+ down: `DROP TYPE IF EXISTS ${spec.ddl}`,
1093
+ skipIf: `SELECT 1 FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = current_schema() AND t.typname = ${literal(spec.enumType)}`
1094
+ });
1095
+ } else {
1096
+ for (const v of spec.enumValues) {
1097
+ if (!have.has(v)) add(`ALTER TYPE ${spec.ddl} ADD VALUE IF NOT EXISTS ${literal(v)}`);
1098
+ }
1099
+ }
1100
+ }
1101
+ }
1102
+ const columnSql = (spec) => {
1103
+ const seq = sequenceKeys.get(spec.field);
1104
+ return `${q(spec.column)} ${spec.ddl}${seq ? ` DEFAULT nextval('${sequenceName(seq)}')` : ""}`;
1105
+ };
1106
+ const idSql = idKind === "uuid" ? `${q("id")} uuid PRIMARY KEY DEFAULT gen_random_uuid()` : `${q("id")} ${idSpec.ddl} GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`;
1107
+ const isRequired = (spec) => spec.field !== "id" && spec.node?.kind !== void 0 && spec.node.def.required === true;
1108
+ if (existing.size === 0) {
1109
+ const defs = [...columns.values()].map(
1110
+ (spec) => spec.field === "id" ? idSql : columnSql(spec)
1111
+ );
1112
+ add(`CREATE TABLE IF NOT EXISTS ${q(table)} (
1113
+ ${defs.join(",\n ")}
1114
+ )`, {
1115
+ down: `DROP TABLE IF EXISTS ${q(table)}`
1116
+ });
1117
+ } else {
1118
+ for (const spec of columns.values()) {
1119
+ const old = spec.node?.def.renamedFrom;
1120
+ if (old === void 0 || existing.has(spec.column)) continue;
1121
+ const oldColumn = columnName(old);
1122
+ const col = existing.get(oldColumn);
1123
+ if (!col) continue;
1124
+ add(`ALTER TABLE ${q(table)} RENAME COLUMN ${q(oldColumn)} TO ${q(spec.column)}`, {
1125
+ down: `ALTER TABLE ${q(table)} RENAME COLUMN ${q(spec.column)} TO ${q(oldColumn)}`,
1126
+ skipIf: columnExists(spec.column)
1127
+ });
1128
+ existing.delete(oldColumn);
1129
+ existing.set(spec.column, col);
1130
+ }
1131
+ for (const spec of columns.values()) {
1132
+ const col = existing.get(spec.column);
1133
+ if (!col) {
1134
+ add(`ALTER TABLE ${q(table)} ADD COLUMN IF NOT EXISTS ${columnSql(spec)}`, {
1135
+ down: `ALTER TABLE ${q(table)} DROP COLUMN IF EXISTS ${q(spec.column)}`
1136
+ });
1137
+ } else if (spec.field !== "id" && needsTypeChange(spec, col.type)) {
1138
+ if (spec.kind === "array" && col.type === "jsonb") add(jsonbToArrayFn, { down: "" });
1139
+ const back = col.type === "jsonb" ? `to_jsonb(${q(spec.column)})` : `${q(spec.column)}::${col.type}`;
1140
+ add(
1141
+ `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${spec.ddl} USING ${castExpr(spec, col.type)}`,
1142
+ {
1143
+ down: `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${col.type} USING ${back}`,
1144
+ skipIf: `SELECT 1 FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = ${literal(table)} AND a.attname = ${literal(spec.column)} AND format_type(a.atttypid, a.atttypmod) = ${literal(spec.formatted)}`
1145
+ }
1146
+ );
1147
+ }
1148
+ }
1149
+ for (const [column, col] of existing) {
1150
+ const spec = byColumn.get(column);
1151
+ if (column !== "id" && !col.nullable && !(spec && isRequired(spec))) {
1152
+ add(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} DROP NOT NULL`, {
1153
+ down: `ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} SET NOT NULL`
1154
+ });
1155
+ }
1156
+ }
1157
+ }
1158
+ const wantedChecks = /* @__PURE__ */ new Map();
1159
+ for (const spec of columns.values()) {
1160
+ const def = spec.node?.def;
1161
+ if (spec.node?.kind === "scalar" && def?.enum && spec.kind !== "enum") {
1162
+ wantedChecks.set(
1163
+ enumCheck(spec.column),
1164
+ `CHECK (${q(spec.column)} IN (${def.enum.map(literal).join(", ")}))`
1165
+ );
1166
+ }
1167
+ }
1168
+ for (const [con, { def }] of checks) {
1169
+ const legacy = con.endsWith("_check") && con.startsWith(`${table}_`);
1170
+ const drop2 = () => {
1171
+ add(`ALTER TABLE ${q(table)} DROP CONSTRAINT IF EXISTS ${q(con)}`, {
1172
+ down: `ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def}`
1173
+ });
1174
+ checks.delete(con);
1175
+ };
1176
+ if (con.endsWith("_enum") && con.startsWith(`${table}_`) && !wantedChecks.has(con) || legacy) {
1177
+ drop2();
1178
+ } else if (wantedChecks.has(con)) {
1179
+ const want = wantedChecks.get(con);
1180
+ const values = (d) => [...d.matchAll(/'((?:[^']|'')*)'|(-?\d+(?:\.\d+)?)/g)].map((m) => m[1] ?? m[2]).sort().join("|");
1181
+ if (values(def) !== values(want)) drop2();
1182
+ }
1183
+ }
1184
+ for (const [con, def] of wantedChecks) {
1185
+ if (!checks.has(con))
1186
+ add(`ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def} NOT VALID`, {
1187
+ down: `ALTER TABLE ${q(table)} DROP CONSTRAINT IF EXISTS ${q(con)}`,
1188
+ skipIf: `SELECT 1 FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = ${literal(table)} AND con.conname = ${literal(con)}`
1189
+ });
1190
+ }
1191
+ const wantedIndexes = desiredIndexes();
1192
+ for (const [idx, def] of indexes) {
1193
+ if (idx !== `${table}_pkey` && idx.startsWith(`${table}_`) && managedIndexName.test(idx) && !wantedIndexes.has(idx)) {
1194
+ add(`DROP INDEX IF EXISTS ${q(idx)}`, { down: def });
1195
+ }
1196
+ }
1197
+ for (const [idx, create] of wantedIndexes)
1198
+ if (!indexes.has(idx))
1199
+ add(create.replace(/^CREATE (UNIQUE )?INDEX /, "CREATE $1INDEX IF NOT EXISTS "), {
1200
+ down: `DROP INDEX IF EXISTS ${q(idx)}`
1201
+ });
1202
+ const ownerDdl = idSpec.ddl;
1203
+ for (const join of joins.values()) {
1204
+ if (liveJoinTables.has(join.table)) continue;
1205
+ const refDdl = join.item;
1206
+ add(
1207
+ `CREATE TABLE IF NOT EXISTS ${q(join.table)} (
1208
+ ${q("owner_id")} ${ownerDdl} NOT NULL,
1209
+ ${q("ref_id")} ${refDdl} NOT NULL,
1210
+ ${q("position")} integer NOT NULL DEFAULT 0,
1211
+ PRIMARY KEY (${q("owner_id")}, ${q("ref_id")})
1212
+ )`,
1213
+ { down: `DROP TABLE IF EXISTS ${q(join.table)}` }
1214
+ );
1215
+ add(
1216
+ `CREATE INDEX IF NOT EXISTS ${q(`${join.table}_ref_id_idx`)} ON ${q(join.table)} (${q("ref_id")})`,
1217
+ { down: "" }
1218
+ // dropped with the table
1219
+ );
1220
+ const legacy = existing.get(join.legacyColumn)?.type;
1221
+ if (legacy === "jsonb" || legacy?.endsWith("[]")) {
1222
+ const c = `o.${q(join.legacyColumn)}`;
1223
+ const items = legacy === "jsonb" ? `jsonb_array_elements_text(CASE WHEN jsonb_typeof(${c}) = 'array' THEN ${c} ELSE '[]'::jsonb END)` : `unnest(${c}::text[])`;
1224
+ const valid = join.item === "uuid" ? `'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'` : `'^-?[0-9]{1,18}$'`;
1225
+ add(
1226
+ `INSERT INTO ${q(join.table)} (${q("owner_id")}, ${q("ref_id")}, ${q("position")}) SELECT o.${q("id")}, x.v::${refDdl}, x.n FROM ${q(table)} o, ${items} WITH ORDINALITY AS x(v, n) WHERE x.v ~ ${valid} ON CONFLICT DO NOTHING`,
1227
+ { down: "" }
1228
+ // the old column is kept
1229
+ );
1230
+ }
1231
+ }
1232
+ if (mode.plan?.tighten) {
1233
+ for (const spec of columns.values()) {
1234
+ if (!isRequired(spec) || existing.get(spec.column)?.nullable === false) continue;
1235
+ add(`SELECT count(*)::int AS n FROM ${q(table)} WHERE ${q(spec.column)} IS NULL`, {
1236
+ check: `${name}.${spec.field} is required, but %n row(s) of "${table}" have no value \u2014 fill them in, then run the migration again`
1237
+ });
1238
+ add(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} SET NOT NULL`, {
1239
+ down: `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} DROP NOT NULL`
1240
+ });
1241
+ }
1242
+ for (const [con, def] of wantedChecks) {
1243
+ if (checks.get(con)?.valid) continue;
1244
+ const spec = byColumn.get(con.slice(table.length + 1, -"_enum".length));
1245
+ const values = /IN \((.*)\)\)$/.exec(def)?.[1];
1246
+ if (spec && values) {
1247
+ add(
1248
+ `SELECT count(*)::int AS n FROM ${q(table)} WHERE ${q(spec.column)} IS NOT NULL AND ${q(spec.column)} NOT IN (${values})`,
1249
+ {
1250
+ check: `${name}.${spec.field}: %n row(s) of "${table}" hold a value outside its enum \u2014 fix them, then run the migration again`
1251
+ }
1252
+ );
1253
+ }
1254
+ add(`ALTER TABLE ${q(table)} VALIDATE CONSTRAINT ${q(con)}`, { down: "" });
1255
+ }
1256
+ }
1257
+ if (mode.plan?.allowDrop) {
1258
+ for (const [column, col] of existing) {
1259
+ if (byColumn.has(column)) continue;
1260
+ add(`ALTER TABLE ${q(table)} DROP COLUMN IF EXISTS ${q(column)}`, {
1261
+ down: `ALTER TABLE ${q(table)} ADD COLUMN IF NOT EXISTS ${q(column)} ${col.type} -- data is not restored`
1262
+ });
1263
+ }
1264
+ }
1265
+ const toValidate = [];
1266
+ for (const fk of fks) {
1267
+ if (deferred.has(fk.name)) continue;
1268
+ const live = liveFks.get(fk.name);
1269
+ if (!live) {
1270
+ add(
1271
+ `ALTER TABLE ${q(fk.onTable)} ADD CONSTRAINT ${q(fk.name)} FOREIGN KEY (${q(fk.column)}) REFERENCES ${q(fk.targetTable)} (${q("id")}) ON DELETE ${ACTION_SQL[fk.action]} NOT VALID`,
1272
+ {
1273
+ phase: "fk",
1274
+ down: `ALTER TABLE ${q(fk.onTable)} DROP CONSTRAINT IF EXISTS ${q(fk.name)}`,
1275
+ skipIf: `SELECT 1 FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = current_schema() AND c.relname = ${literal(fk.onTable)} AND con.conname = ${literal(fk.name)}`
1276
+ }
1277
+ );
1278
+ }
1279
+ if (!live?.valid) toValidate.push(fk);
1280
+ }
1281
+ const orphans = (fk) => `SELECT count(*)::int AS n FROM ${q(fk.onTable)} r WHERE ${q(fk.column)} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${q(fk.targetTable)} t WHERE t.${q("id")} = r.${q(fk.column)})`;
1282
+ const validations = toValidate.map(
1283
+ (fk) => `ALTER TABLE ${q(fk.onTable)} VALIDATE CONSTRAINT ${q(fk.name)}`
1284
+ );
1285
+ if (generating) {
1286
+ for (const [i, fk] of toValidate.entries()) {
1287
+ add(orphans(fk), {
1288
+ phase: "fk",
1289
+ check: `${name}.${fk.field}: %n row(s) reference a missing ${fk.target} \u2014 fix them, then run the migration again`
1290
+ });
1291
+ add(validations[i], { phase: "fk", down: "" });
1292
+ }
1293
+ }
1294
+ if (!dryRun) {
1295
+ for (const { sql: stmt } of steps) {
1296
+ try {
1297
+ await conn.query(stmt);
1298
+ } catch (err) {
1299
+ throw new Error(
1300
+ `[EFC] ${name}: syncing table "${table}" failed on: ${stmt}
1301
+ ${err.message}`
1302
+ );
1303
+ }
1304
+ }
1305
+ }
1306
+ await conn.query(dryRun ? "ROLLBACK" : "COMMIT");
1307
+ if (!dryRun) {
1308
+ for (const [i, fk] of toValidate.entries()) {
1309
+ try {
1310
+ await conn.query(validations[i]);
1311
+ } catch {
1312
+ const n = await conn.query(orphans(fk)).then((r) => r.rows[0]?.n ?? "?").catch(() => "?");
1313
+ getLogger().warn(
1314
+ { table, constraint: fk.name, orphans: Number(n) },
1315
+ `${name}.${fk.field}: ${n} row(s) reference a missing ${fk.target} \u2014 the foreign key applies to new writes; fix those rows, then run efc db sync to validate it`
1316
+ );
1317
+ }
1318
+ }
1319
+ }
1320
+ return generating ? steps : [...steps, ...validations.map((sql) => ({ sql, phase: "fk" }))];
1321
+ } catch (err) {
1322
+ await conn.query("ROLLBACK").catch(() => {
1323
+ });
1324
+ throw err;
1325
+ } finally {
1326
+ conn.release();
1327
+ }
1328
+ }
1329
+ async function drop() {
1330
+ const { sql } = await compile();
1331
+ await client().execute(sql.raw(`DROP TABLE IF EXISTS ${q(table)}`));
1332
+ }
1333
+ return {
1334
+ name,
1335
+ table,
1336
+ tree,
1337
+ idKind,
1338
+ columns,
1339
+ joins,
1340
+ ts,
1341
+ sequenceKeys,
1342
+ refs,
1343
+ compile,
1344
+ ready,
1345
+ client,
1346
+ columnFor,
1347
+ toDb,
1348
+ fromRow,
1349
+ fromRawRow,
1350
+ validate,
1351
+ known,
1352
+ prepareInsert,
1353
+ guard,
1354
+ reconcile,
1355
+ plan,
1356
+ drop
1357
+ };
1358
+ }
1359
+
1360
+ export {
1361
+ HttpError,
1362
+ isHttpError,
1363
+ normalizeSchema,
1364
+ timestampFields,
1365
+ resolveDefault,
1366
+ ModelValidationError,
1367
+ sequenceFields,
1368
+ nodeAt,
1369
+ validateAtPath,
1370
+ setDbEngine,
1371
+ getDbEngine,
1372
+ setAutoSync,
1373
+ isAutoSync,
1374
+ setSyncSuppressed,
1375
+ isSyncSuppressed,
1376
+ registerModel,
1377
+ getRegisteredModel,
1378
+ registeredModels,
1379
+ currentTx,
1380
+ runInTx,
1381
+ tableNameFor,
1382
+ snakeCase,
1383
+ q,
1384
+ pgTable
1385
+ };
1386
+ //# sourceMappingURL=chunk-OSES7ZQ5.js.map