express-file-cluster 0.3.15 → 0.7.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 (116) hide show
  1. package/README.md +71 -33
  2. package/dist/auth/index.cjs +12 -2
  3. package/dist/auth/index.cjs.map +1 -1
  4. package/dist/auth/index.d.cts +13 -2
  5. package/dist/auth/index.d.ts +13 -2
  6. package/dist/auth/index.js +12 -2
  7. package/dist/chunk-277BSYVH.js +127 -0
  8. package/dist/chunk-277BSYVH.js.map +1 -0
  9. package/dist/chunk-6OGOVV57.js +3847 -0
  10. package/dist/chunk-6OGOVV57.js.map +1 -0
  11. package/dist/chunk-7YEX4MQV.cjs +38 -0
  12. package/dist/chunk-7YEX4MQV.cjs.map +1 -0
  13. package/dist/chunk-AZYXQU3Z.cjs +3847 -0
  14. package/dist/chunk-AZYXQU3Z.cjs.map +1 -0
  15. package/dist/chunk-BUBXO7WU.js +170 -0
  16. package/dist/chunk-BUBXO7WU.js.map +1 -0
  17. package/dist/chunk-LJNSJFOL.js +38 -0
  18. package/dist/chunk-LJNSJFOL.js.map +1 -0
  19. package/dist/chunk-MGH4VDV3.cjs +170 -0
  20. package/dist/chunk-MGH4VDV3.cjs.map +1 -0
  21. package/dist/chunk-R34R7QPD.cjs +116 -0
  22. package/dist/chunk-R34R7QPD.cjs.map +1 -0
  23. package/dist/chunk-RS4MXCPW.js +116 -0
  24. package/dist/chunk-RS4MXCPW.js.map +1 -0
  25. package/dist/chunk-T4OHFU5T.cjs +154 -0
  26. package/dist/chunk-T4OHFU5T.cjs.map +1 -0
  27. package/dist/chunk-TI24L4XE.cjs.map +1 -1
  28. package/dist/chunk-TRC4DUZB.js +438 -0
  29. package/dist/chunk-TRC4DUZB.js.map +1 -0
  30. package/dist/chunk-TYR2GZZE.cjs +196 -0
  31. package/dist/chunk-TYR2GZZE.cjs.map +1 -0
  32. package/dist/chunk-UBQYQPBU.js +154 -0
  33. package/dist/chunk-UBQYQPBU.js.map +1 -0
  34. package/dist/chunk-UTM4PEVG.js +196 -0
  35. package/dist/chunk-UTM4PEVG.js.map +1 -0
  36. package/dist/chunk-YL37D6KM.cjs +127 -0
  37. package/dist/chunk-YL37D6KM.cjs.map +1 -0
  38. package/dist/chunk-ZDM5JHVK.cjs +438 -0
  39. package/dist/chunk-ZDM5JHVK.cjs.map +1 -0
  40. package/dist/cli/db-runner.cjs +497 -0
  41. package/dist/cli/db-runner.cjs.map +1 -0
  42. package/dist/cli/db-runner.d.cts +2 -0
  43. package/dist/cli/db-runner.d.ts +2 -0
  44. package/dist/cli/db-runner.js +497 -0
  45. package/dist/cli/db-runner.js.map +1 -0
  46. package/dist/cli/index.cjs +447 -69
  47. package/dist/cli/index.cjs.map +1 -1
  48. package/dist/cli/index.js +473 -95
  49. package/dist/cli/index.js.map +1 -1
  50. package/dist/docs/api-reference/auth.md +232 -0
  51. package/dist/docs/api-reference/compose.md +78 -0
  52. package/dist/docs/api-reference/db.md +351 -0
  53. package/dist/docs/api-reference/http-error.md +109 -0
  54. package/dist/docs/api-reference/ignite.md +326 -0
  55. package/dist/docs/api-reference/table.md +458 -0
  56. package/dist/docs/api-reference/tasks.md +140 -0
  57. package/dist/docs/cli/db.md +38 -0
  58. package/dist/docs/cli/diagnostics.md +145 -0
  59. package/dist/docs/cli/generate.md +120 -0
  60. package/dist/docs/cli/index.md +48 -0
  61. package/dist/docs/cli/start.md +112 -0
  62. package/dist/docs/contributing/index.md +139 -0
  63. package/dist/docs/core-concepts/background-tasks.md +228 -0
  64. package/dist/docs/core-concepts/clustering.md +114 -0
  65. package/dist/docs/core-concepts/file-based-routing.md +235 -0
  66. package/dist/docs/core-concepts/index.md +79 -0
  67. package/dist/docs/core-concepts/middleware.md +144 -0
  68. package/dist/docs/getting-started/index.md +91 -0
  69. package/dist/docs/getting-started/project-structure.md +154 -0
  70. package/dist/docs/guides/ai-agents.md +48 -0
  71. package/dist/docs/guides/authentication.md +196 -0
  72. package/dist/docs/guides/caching.md +124 -0
  73. package/dist/docs/guides/database.md +217 -0
  74. package/dist/docs/guides/deployment.md +171 -0
  75. package/dist/docs/guides/environment-variables.md +106 -0
  76. package/dist/docs/guides/error-handling.md +172 -0
  77. package/dist/docs/guides/generated-portals.md +115 -0
  78. package/dist/docs/guides/logging.md +108 -0
  79. package/dist/docs/guides/mailer.md +166 -0
  80. package/dist/docs/guides/migrations.md +106 -0
  81. package/dist/docs/guides/rbac.md +89 -0
  82. package/dist/docs/guides/validation.md +95 -0
  83. package/dist/docs/index.md +93 -0
  84. package/dist/docs/skills/SKILL.md +44 -0
  85. package/dist/docs/skills/api-surface.md +309 -0
  86. package/dist/docs/skills/auth-internals.md +141 -0
  87. package/dist/docs/skills/pre-flight.md +142 -0
  88. package/dist/docs/skills/routing-rules.md +114 -0
  89. package/dist/docs/skills/tasks-internals.md +172 -0
  90. package/dist/docs/skills/what-not-to-invent.md +251 -0
  91. package/dist/index.cjs +264 -391
  92. package/dist/index.cjs.map +1 -1
  93. package/dist/index.d.cts +699 -7
  94. package/dist/index.d.ts +699 -7
  95. package/dist/index.js +258 -385
  96. package/dist/index.js.map +1 -1
  97. package/dist/pgboss-backend-QKBXVJ6B.js +14 -0
  98. package/dist/pgboss-backend-QKBXVJ6B.js.map +1 -0
  99. package/dist/pgboss-backend-TCHI7CHM.cjs +14 -0
  100. package/dist/pgboss-backend-TCHI7CHM.cjs.map +1 -0
  101. package/dist/tasks/index.cjs.map +1 -1
  102. package/dist/tasks/index.d.cts +1 -1
  103. package/dist/tasks/index.d.ts +1 -1
  104. package/dist/types-B6lVw4bj.d.cts +588 -0
  105. package/dist/types-B6lVw4bj.d.ts +588 -0
  106. package/package.json +28 -5
  107. package/dist/chunk-6522HS2J.cjs +0 -99
  108. package/dist/chunk-6522HS2J.cjs.map +0 -1
  109. package/dist/chunk-DGVOJNR6.cjs +0 -55
  110. package/dist/chunk-DGVOJNR6.cjs.map +0 -1
  111. package/dist/chunk-KOHLLUN7.js +0 -55
  112. package/dist/chunk-KOHLLUN7.js.map +0 -1
  113. package/dist/chunk-VIP3PFWZ.js +0 -99
  114. package/dist/chunk-VIP3PFWZ.js.map +0 -1
  115. package/dist/types-BusbSenn.d.cts +0 -162
  116. package/dist/types-BusbSenn.d.ts +0 -162
@@ -0,0 +1,3847 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ var _chunkMGH4VDV3cjs = require('./chunk-MGH4VDV3.cjs');
10
+
11
+
12
+
13
+ var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
14
+
15
+ // src/errors.ts
16
+ var HttpError = class _HttpError extends Error {
17
+
18
+ constructor(statusCode, message) {
19
+ super(message);
20
+ this.name = "HttpError";
21
+ this.statusCode = statusCode;
22
+ Error.captureStackTrace(this, _HttpError);
23
+ }
24
+ /**
25
+ * Wraps an unknown caught value into an `HttpError`.
26
+ * If the value is already an `HttpError`, it is returned as-is.
27
+ * Otherwise the `message` from the caught `Error` (or a fallback) is used.
28
+ *
29
+ * @example
30
+ * } catch (err) {
31
+ * throw HttpError.from(err, 500, 'Something went wrong');
32
+ * }
33
+ */
34
+ static from(err, statusCode = 500, fallback = "Internal Server Error") {
35
+ if (err instanceof _HttpError) return err;
36
+ const message = err instanceof Error ? err.message : fallback;
37
+ return new _HttpError(statusCode, message);
38
+ }
39
+ /** Returns a plain object representation suitable for JSON serialization. */
40
+ toJSON() {
41
+ return {
42
+ statusCode: this.statusCode,
43
+ error: this.name,
44
+ message: this.message
45
+ };
46
+ }
47
+ };
48
+ function isHttpError(value) {
49
+ return value instanceof HttpError;
50
+ }
51
+
52
+ // src/db/schema.ts
53
+ var _crypto = require('crypto');
54
+ var MODEL_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "object", "objectId", "array"]);
55
+ var TABLE_ONLY_TYPES = /* @__PURE__ */ new Set(["integer", "bigint", "decimal", "uuid", "json"]);
56
+ var TABLE_ONLY_OPTIONS = ["precision", "scale", "nativeEnum", "column", "onDelete"];
57
+ var REFERENTIAL_ACTIONS = /* @__PURE__ */ new Set(["restrict", "cascade", "setNull"]);
58
+ var FOREIGN_KEY_TYPES = /* @__PURE__ */ new Set(["objectId", "uuid", "integer", "bigint"]);
59
+ function isFieldDefinition(value) {
60
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
61
+ const type = value.type;
62
+ return typeof type === "string" && (MODEL_TYPES.has(type) || TABLE_ONLY_TYPES.has(type));
63
+ }
64
+ var untyped = () => ({ kind: "json", def: { type: "object" } });
65
+ var SchemaBuilder = class {
66
+ constructor(model, mode) {
67
+ this.model = model;
68
+ this.mode = mode;
69
+ }
70
+
71
+
72
+ fail(path, message) {
73
+ throw new Error(`[EFC] ${this.model}.${path}: ${message}`);
74
+ }
75
+ checkType(type, path) {
76
+ if (this.mode === "model" && TABLE_ONLY_TYPES.has(type)) {
77
+ this.fail(path, `type '${type}' is PostgreSQL-only \u2014 use defineTable, or a portable type`);
78
+ }
79
+ }
80
+ checkDefinition(def, path, topLevel) {
81
+ this.checkType(def.type, path);
82
+ if (this.mode === "model") {
83
+ for (const opt of TABLE_ONLY_OPTIONS) {
84
+ if (def[opt] !== void 0) this.fail(path, `'${opt}' is a defineTable option`);
85
+ }
86
+ return;
87
+ }
88
+ if ((def.precision !== void 0 || def.scale !== void 0) && def.type !== "decimal") {
89
+ this.fail(path, `'precision' / 'scale' only apply to decimal fields`);
90
+ }
91
+ if (def.scale !== void 0 && def.precision === void 0) {
92
+ this.fail(path, `'scale' needs 'precision'`);
93
+ }
94
+ if (def.nativeEnum && !(def.enum && def.enum.every((v) => typeof v === "string"))) {
95
+ this.fail(path, `'nativeEnum' needs a string 'enum'`);
96
+ }
97
+ if (def.column !== void 0 && !topLevel) {
98
+ this.fail(path, `'column' only applies to top-level fields`);
99
+ }
100
+ if (def.onDelete !== void 0) {
101
+ if (def.ref === void 0) this.fail(path, `'onDelete' needs 'ref'`);
102
+ if (!REFERENTIAL_ACTIONS.has(def.onDelete)) {
103
+ this.fail(path, `onDelete must be 'restrict', 'cascade' or 'setNull'`);
104
+ }
105
+ if (def.onDelete === "setNull" && def.required) {
106
+ this.fail(path, `onDelete: 'setNull' can't clear a required field`);
107
+ }
108
+ }
109
+ if (def.ref !== void 0) {
110
+ const many = def.type === "array";
111
+ if (!topLevel) this.fail(path, `'ref' only applies to top-level fields`);
112
+ if (!FOREIGN_KEY_TYPES.has(many ? String(def.of) : def.type)) {
113
+ this.fail(
114
+ path,
115
+ many ? `a many-to-many 'ref' needs of: objectId, uuid, integer or bigint` : `'ref' needs an id type: objectId, uuid, integer or bigint`
116
+ );
117
+ }
118
+ if (many && def.onDelete !== void 0) {
119
+ this.fail(
120
+ path,
121
+ `'onDelete' doesn't apply to many-to-many refs \u2014 links are always removed with either record`
122
+ );
123
+ }
124
+ if (many && (def.unique || def.index)) {
125
+ this.fail(path, `many-to-many refs are indexed already; 'unique' / 'index' don't apply`);
126
+ }
127
+ }
128
+ }
129
+ item(of, parent, path) {
130
+ if (of === void 0) return untyped();
131
+ if (typeof of === "string") {
132
+ this.checkType(of, path);
133
+ if (of === "object" || of === "json") return untyped();
134
+ const def = {
135
+ type: of,
136
+ ...parent.ref !== void 0 && { ref: parent.ref }
137
+ };
138
+ return { kind: "scalar", type: of, def };
139
+ }
140
+ return { kind: "object", fields: this.tree(of, `${path}.$`), def: { type: "object" } };
141
+ }
142
+ field(field, path, topLevel) {
143
+ if (Array.isArray(field)) {
144
+ const inner = field[0];
145
+ return {
146
+ kind: "array",
147
+ item: inner ? { kind: "object", fields: this.tree(inner, `${path}.$`), def: { type: "object" } } : untyped(),
148
+ def: { type: "array" }
149
+ };
150
+ }
151
+ if (!isFieldDefinition(field)) {
152
+ const type = field.type;
153
+ if (typeof type === "string") this.fail(path, `unknown field type '${type}'`);
154
+ return {
155
+ kind: "object",
156
+ fields: this.tree(field, path),
157
+ def: { type: "object" }
158
+ };
159
+ }
160
+ const def = field;
161
+ this.checkDefinition(def, path, topLevel);
162
+ if (def.type === "array") return { kind: "array", item: this.item(def.of, def, path), def };
163
+ if (def.type === "object") {
164
+ return def.fields ? { kind: "object", fields: this.tree(def.fields, path), def } : { kind: "json", def };
165
+ }
166
+ if (def.type === "json") return { kind: "json", def };
167
+ return { kind: "scalar", type: def.type, def };
168
+ }
169
+ tree(schema, prefix = "") {
170
+ const out = {};
171
+ for (const [key, field] of Object.entries(schema)) {
172
+ out[key] = this.field(field, prefix ? `${prefix}.${key}` : key, prefix === "");
173
+ }
174
+ return out;
175
+ }
176
+ };
177
+ function normalizeSchema(schema, mode = "model", model = "Model") {
178
+ return new SchemaBuilder(model, mode).tree(schema);
179
+ }
180
+ function timestampFields(options) {
181
+ const ts = _nullishCoalesce(options.timestamps, () => ( true));
182
+ if (ts === false) return {};
183
+ if (ts === true) return { createdAt: "createdAt", updatedAt: "updatedAt" };
184
+ const out = {};
185
+ if (ts.createdAt !== false) out.createdAt = _nullishCoalesce(ts.createdAt, () => ( "createdAt"));
186
+ if (ts.updatedAt !== false) out.updatedAt = _nullishCoalesce(ts.updatedAt, () => ( "updatedAt"));
187
+ return out;
188
+ }
189
+ var STATIC_DEFAULT_OPERATORS = {
190
+ $now: () => /* @__PURE__ */ new Date(),
191
+ $uuid: () => _crypto.randomUUID.call(void 0, ),
192
+ $timestamp: () => Date.now(),
193
+ $shortId: () => _crypto.randomBytes.call(void 0, 12).toString("base64url")
194
+ };
195
+ var FIXED_DEFAULT_OPERATORS = /* @__PURE__ */ new Set(["$now", "$uuid", "$objectId", "$timestamp", "$shortId"]);
196
+ function isCurrentUserOperator(value) {
197
+ return typeof value === "string" && (value === "$currentUser" || value.startsWith("$currentUser."));
198
+ }
199
+ function isDefaultOperator(value) {
200
+ return typeof value === "string" && FIXED_DEFAULT_OPERATORS.has(value) || isCurrentUserOperator(value);
201
+ }
202
+ function resolveDefault(value, objectId) {
203
+ if (!isDefaultOperator(value)) return value;
204
+ if (value === "$objectId") return objectId;
205
+ if (value === "$currentUser") return () => _chunkYL37D6KMcjs.getCurrentUser.call(void 0, );
206
+ if (isCurrentUserOperator(value)) {
207
+ const key = value.slice("$currentUser.".length);
208
+ return () => _optionalChain([_chunkYL37D6KMcjs.getCurrentUser.call(void 0, ), 'optionalAccess', _ => _[key]]);
209
+ }
210
+ return STATIC_DEFAULT_OPERATORS[value];
211
+ }
212
+ function applyDefaults(tree, data, objectId) {
213
+ const out = { ...data };
214
+ for (const [key, node] of Object.entries(tree)) {
215
+ if (out[key] === void 0 && node.def.default !== void 0) {
216
+ const d = resolveDefault(node.def.default, objectId);
217
+ const value = typeof d === "function" ? d() : structuredClone(d);
218
+ if (value !== void 0) out[key] = value;
219
+ }
220
+ if (node.kind === "object" && out[key] != null && typeof out[key] === "object") {
221
+ out[key] = applyDefaults(node.fields, out[key], objectId);
222
+ }
223
+ if (node.kind === "array" && node.item.kind === "object" && Array.isArray(out[key])) {
224
+ const fields = node.item.fields;
225
+ out[key] = out[key].map(
226
+ (v) => v != null && typeof v === "object" ? applyDefaults(fields, v, objectId) : v
227
+ );
228
+ }
229
+ }
230
+ return out;
231
+ }
232
+ var ModelValidationError = class extends HttpError {
233
+
234
+ constructor(model, issues) {
235
+ super(
236
+ 400,
237
+ `${model} validation failed: ${issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`
238
+ );
239
+ this.name = "ModelValidationError";
240
+ this.issues = issues;
241
+ }
242
+ };
243
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
244
+ var INT4 = 2 ** 31;
245
+ var INT8_MIN = -(2n ** 63n);
246
+ var INT8_MAX = 2n ** 63n - 1n;
247
+ var DECIMAL_RE = /^[+-]?(\d+(\.\d*)?|\.\d+)$/;
248
+ function decimalDigits(value) {
249
+ const str = typeof value === "number" ? String(value) : value;
250
+ const [i = "", f = ""] = str.replace(/^[+-]/, "").split(".");
251
+ return { int: i.replace(/^0+/, "").length, frac: f.replace(/0+$/, "").length };
252
+ }
253
+ function typeError(type, def, value) {
254
+ switch (type) {
255
+ case "string":
256
+ return typeof value === "string" ? null : "must be a string";
257
+ case "number":
258
+ return typeof value === "number" && Number.isFinite(value) ? null : "must be a number";
259
+ case "integer":
260
+ return typeof value === "number" && Number.isInteger(value) && value >= -INT4 && value < INT4 ? null : "must be a 32-bit integer";
261
+ case "bigint": {
262
+ const big = typeof value === "bigint" ? value : typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : void 0;
263
+ return big !== void 0 && big >= INT8_MIN && big <= INT8_MAX ? null : "must be a 64-bit integer (bigint)";
264
+ }
265
+ case "decimal": {
266
+ const ok = typeof value === "number" && Number.isFinite(value) || typeof value === "string" && DECIMAL_RE.test(value);
267
+ if (!ok) return "must be a decimal number or numeric string";
268
+ if (def.precision !== void 0) {
269
+ const scale = _nullishCoalesce(def.scale, () => ( 0));
270
+ const { int, frac } = decimalDigits(value);
271
+ if (frac > scale) return `must have at most ${scale} decimal places`;
272
+ if (int > def.precision - scale)
273
+ return `must have at most ${def.precision - scale} digits before the decimal point`;
274
+ }
275
+ return null;
276
+ }
277
+ case "boolean":
278
+ return typeof value === "boolean" ? null : "must be a boolean";
279
+ case "date":
280
+ return !Number.isNaN(new Date(value).getTime()) ? null : "must be a date";
281
+ case "objectId":
282
+ return typeof value === "string" && UUID_RE.test(value) ? null : "must be a valid id";
283
+ case "uuid":
284
+ return typeof value === "string" && UUID_RE.test(value) ? null : "must be a UUID";
285
+ }
286
+ }
287
+ function compareBound(def, value, bound) {
288
+ if (def.type === "bigint") {
289
+ const a = BigInt(value);
290
+ const b = BigInt(bound instanceof Date ? bound.getTime() : bound);
291
+ return a < b ? -1 : a > b ? 1 : 0;
292
+ }
293
+ const num = (v) => v instanceof Date ? v.getTime() : def.type === "date" ? new Date(v).getTime() : Number(v);
294
+ return num(value) - num(bound);
295
+ }
296
+ async function checkRules(def, value, path, issues) {
297
+ if (def.enum && !def.enum.includes(value)) {
298
+ issues.push({ path, message: `must be one of: ${def.enum.join(", ")}` });
299
+ }
300
+ const ordered = typeof value === "number" || typeof value === "bigint" || value instanceof Date || def.type === "date" || def.type === "decimal" && typeof value === "string";
301
+ if (ordered) {
302
+ if (def.min !== void 0 && compareBound(def, value, def.min) < 0)
303
+ issues.push({ path, message: `must be >= ${String(def.min)}` });
304
+ if (def.max !== void 0 && compareBound(def, value, def.max) > 0)
305
+ issues.push({ path, message: `must be <= ${String(def.max)}` });
306
+ }
307
+ if (typeof value === "string" && def.type !== "decimal") {
308
+ if (def.minLength !== void 0 && value.length < def.minLength)
309
+ issues.push({ path, message: `must be at least ${def.minLength} characters` });
310
+ if (def.maxLength !== void 0 && value.length > def.maxLength)
311
+ issues.push({ path, message: `must be at most ${def.maxLength} characters` });
312
+ if (def.match && !def.match.test(value))
313
+ issues.push({ path, message: `must match ${String(def.match)}` });
314
+ }
315
+ if (def.validate) {
316
+ const result = await def.validate(value);
317
+ if (result !== true)
318
+ issues.push({ path, message: typeof result === "string" ? result : "is invalid" });
319
+ }
320
+ }
321
+ async function validateNode(node, value, path, issues, partial) {
322
+ if (value === void 0 || value === null) {
323
+ if (node.def.required && !partial) issues.push({ path, message: "is required" });
324
+ if (node.def.required && partial && value === null)
325
+ issues.push({ path, message: "is required" });
326
+ return;
327
+ }
328
+ switch (node.kind) {
329
+ case "scalar": {
330
+ const err = typeError(node.type, node.def, value);
331
+ if (err) {
332
+ issues.push({ path, message: err });
333
+ return;
334
+ }
335
+ await checkRules(node.def, value, path, issues);
336
+ return;
337
+ }
338
+ case "json":
339
+ await checkRules(node.def, value, path, issues);
340
+ return;
341
+ case "object":
342
+ if (typeof value !== "object" || Array.isArray(value)) {
343
+ issues.push({ path, message: "must be an object" });
344
+ return;
345
+ }
346
+ await validateTree(node.fields, value, issues, false, path);
347
+ await checkRules(node.def, value, path, issues);
348
+ return;
349
+ case "array":
350
+ if (!Array.isArray(value)) {
351
+ issues.push({ path, message: "must be an array" });
352
+ return;
353
+ }
354
+ for (let i = 0; i < value.length; i++) {
355
+ await validateNode(
356
+ { ...node.item, def: { ...node.item.def, required: true } },
357
+ value[i],
358
+ `${path}.${i}`,
359
+ issues,
360
+ false
361
+ );
362
+ }
363
+ await checkRules(node.def, value, path, issues);
364
+ }
365
+ }
366
+ async function validateTree(tree, data, issues, partial, prefix = "") {
367
+ for (const [key, node] of Object.entries(tree)) {
368
+ if (partial && !(key in data)) continue;
369
+ await validateNode(node, data[key], prefix ? `${prefix}.${key}` : key, issues, partial);
370
+ }
371
+ return issues;
372
+ }
373
+ function refFields(tree) {
374
+ const refs = /* @__PURE__ */ new Map();
375
+ for (const [key, node] of Object.entries(tree)) {
376
+ if (node.kind === "scalar" && node.type === "objectId" && node.def.ref) {
377
+ refs.set(key, { model: node.def.ref, many: false });
378
+ } else if (node.kind === "array" && node.item.kind === "scalar" && node.item.type === "objectId" && node.def.ref) {
379
+ refs.set(key, { model: node.def.ref, many: true });
380
+ }
381
+ }
382
+ return refs;
383
+ }
384
+ function sequenceFields(name, tree) {
385
+ const out = [];
386
+ for (const [path, node] of Object.entries(tree)) {
387
+ if (node.def.sequence) {
388
+ out.push({
389
+ path,
390
+ key: typeof node.def.sequence === "string" ? node.def.sequence : `${name}.${path}`
391
+ });
392
+ }
393
+ }
394
+ return out;
395
+ }
396
+ function nodeAt(tree, path) {
397
+ let node = tree[path[0]];
398
+ for (const part of path.slice(1)) {
399
+ if (!node) return void 0;
400
+ if (node.kind === "object") node = node.fields[part];
401
+ else if (node.kind === "array" && /^\d+$/.test(part)) node = node.item;
402
+ else if (node.kind === "json")
403
+ return node;
404
+ else return void 0;
405
+ }
406
+ return node;
407
+ }
408
+ async function validateAtPath(tree, dotted, value, issues) {
409
+ const node = nodeAt(tree, dotted.split("."));
410
+ if (!node) {
411
+ issues.push({ path: dotted, message: "unknown field" });
412
+ return;
413
+ }
414
+ await validateNode(node, value, dotted, issues, true);
415
+ }
416
+
417
+ // src/db/engine.ts
418
+ var _async_hooks = require('async_hooks');
419
+ var engine;
420
+ function setDbEngine(value) {
421
+ engine = value;
422
+ }
423
+ function getDbEngine() {
424
+ return _nullishCoalesce(engine, () => ( "mongodb"));
425
+ }
426
+ var autoSync = true;
427
+ function setAutoSync(value) {
428
+ autoSync = value;
429
+ }
430
+ function isAutoSync() {
431
+ return autoSync;
432
+ }
433
+ var registry = /* @__PURE__ */ new Map();
434
+ function registerModel(model) {
435
+ registry.set(model.name, model);
436
+ }
437
+ function getRegisteredModel(name) {
438
+ return registry.get(name);
439
+ }
440
+ function registeredModels() {
441
+ return [...registry.values()];
442
+ }
443
+ var txStorage = new (0, _async_hooks.AsyncLocalStorage)();
444
+ function currentTx() {
445
+ return txStorage.getStore();
446
+ }
447
+ function runInTx(handle, fn) {
448
+ return txStorage.run(handle, fn);
449
+ }
450
+
451
+ // src/db/mongo-model.ts
452
+ var mongoosePromise;
453
+ function loadMongoose() {
454
+ mongoosePromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("mongoose"))).then((mod) => _nullishCoalesce(mod.default, () => ( mod))).then((mg) => {
455
+ _chunkMGH4VDV3cjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkMGH4VDV3cjs.countStatement));
456
+ return mg;
457
+ }).catch((err) => {
458
+ mongoosePromise = void 0;
459
+ throw _chunkMGH4VDV3cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
460
+ });
461
+ return mongoosePromise;
462
+ }
463
+ function ctor(type, mg) {
464
+ switch (type) {
465
+ case "string":
466
+ return String;
467
+ case "number":
468
+ return Number;
469
+ case "boolean":
470
+ return Boolean;
471
+ case "date":
472
+ return Date;
473
+ case "objectId":
474
+ return mg.Schema.Types.ObjectId;
475
+ }
476
+ return mg.Schema.Types.Mixed;
477
+ }
478
+ function rules(node, mg) {
479
+ const d = node.def;
480
+ const entry = {};
481
+ if (d.required !== void 0) entry["required"] = d.required;
482
+ if (d.unique !== void 0) entry["unique"] = d.unique;
483
+ if (d.index !== void 0) entry["index"] = d.index;
484
+ if (d.default !== void 0)
485
+ entry["default"] = resolveDefault(d.default, () => new mg.Types.ObjectId());
486
+ if (d.enum !== void 0) entry["enum"] = d.enum;
487
+ if (d.min !== void 0) entry["min"] = d.min;
488
+ if (d.max !== void 0) entry["max"] = d.max;
489
+ if (d.minLength !== void 0) entry["minlength"] = d.minLength;
490
+ if (d.maxLength !== void 0) entry["maxlength"] = d.maxLength;
491
+ if (d.match !== void 0) entry["match"] = d.match;
492
+ if (d.validate !== void 0) {
493
+ const check = d.validate;
494
+ entry["validate"] = {
495
+ validator: async (v) => {
496
+ const result = await check(v);
497
+ if (result === true) return true;
498
+ throw new Error(typeof result === "string" ? result : "is invalid");
499
+ }
500
+ };
501
+ }
502
+ return entry;
503
+ }
504
+ function buildNode(node, mg) {
505
+ switch (node.kind) {
506
+ case "scalar": {
507
+ const entry = { type: ctor(node.type, mg), ...rules(node, mg) };
508
+ if (node.type === "objectId" && node.def.ref !== void 0) entry["ref"] = node.def.ref;
509
+ return entry;
510
+ }
511
+ case "json":
512
+ return { type: mg.Schema.Types.Mixed, ...rules(node, mg) };
513
+ case "object":
514
+ return {
515
+ type: new mg.Schema(buildTree(node.fields, mg), { _id: false }),
516
+ ...rules(node, mg)
517
+ };
518
+ case "array": {
519
+ let item;
520
+ if (node.item.kind === "object") item = new mg.Schema(buildTree(node.item.fields, mg));
521
+ else if (node.item.kind === "json") item = mg.Schema.Types.Mixed;
522
+ else item = buildNode(node.item, mg);
523
+ return { type: [item], ...rules(node, mg) };
524
+ }
525
+ }
526
+ }
527
+ function buildTree(tree, mg) {
528
+ const out = {};
529
+ for (const [key, node] of Object.entries(tree)) out[key] = buildNode(node, mg);
530
+ return out;
531
+ }
532
+ var COUNTER_MODEL_NAME = "__EFCCounter__";
533
+ function getCounterModel(mg) {
534
+ if (mg.models[COUNTER_MODEL_NAME])
535
+ return mg.models[COUNTER_MODEL_NAME];
536
+ const counterSchema = new mg.Schema(
537
+ { _id: { type: String, required: true }, seq: { type: Number, default: 0 } },
538
+ { collection: "efc_counters", versionKey: false }
539
+ );
540
+ return mg.model(COUNTER_MODEL_NAME, counterSchema);
541
+ }
542
+ async function nextSequence(mg, key) {
543
+ const doc = await getCounterModel(mg).findByIdAndUpdate(key, { $inc: { seq: 1 } }, { returnDocument: "after", upsert: true }).lean();
544
+ return doc.seq;
545
+ }
546
+ function normalise(value) {
547
+ if (Array.isArray(value)) return value.map(normalise);
548
+ if (value == null || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
549
+ return value;
550
+ }
551
+ const out = {};
552
+ for (const [k, v] of Object.entries(value)) out[k] = normalise(v);
553
+ if ("_id" in out) out["id"] = String(out["_id"]);
554
+ return out;
555
+ }
556
+ function translateError(model, err) {
557
+ const e = err;
558
+ if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "ValidationError" && e.errors) {
559
+ throw new ModelValidationError(
560
+ model,
561
+ Object.entries(e.errors).map(([path, v]) => ({
562
+ path,
563
+ message: v.message.replace(
564
+ /^Validator failed for path `[^`]+` with value `[^`]*`$/,
565
+ "is invalid"
566
+ )
567
+ }))
568
+ );
569
+ }
570
+ if (_optionalChain([e, 'optionalAccess', _3 => _3.name]) === "CastError") {
571
+ throw new ModelValidationError(model, [
572
+ { path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
573
+ ]);
574
+ }
575
+ if (_optionalChain([e, 'optionalAccess', _4 => _4.code]) === 11e3) {
576
+ const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
577
+ throw new HttpError(409, `${model} with this ${field} already exists`);
578
+ }
579
+ throw err;
580
+ }
581
+ function isCastErrorOnId(err) {
582
+ const e = err;
583
+ return _optionalChain([e, 'optionalAccess', _5 => _5.name]) === "CastError" && e.path === "_id";
584
+ }
585
+ function mapFilter(filter) {
586
+ if (!filter) return {};
587
+ const out = {};
588
+ for (const [k, v] of Object.entries(filter)) {
589
+ if (k === "$and" || k === "$or") out[k] = v.map(mapFilter);
590
+ else out[k === "id" ? "_id" : k] = v;
591
+ }
592
+ return out;
593
+ }
594
+ function mapSort(sort) {
595
+ if (!sort) return void 0;
596
+ const out = {};
597
+ for (const [k, v] of Object.entries(sort))
598
+ out[k === "id" ? "_id" : k] = v === -1 || v === "desc" ? -1 : 1;
599
+ return out;
600
+ }
601
+ function mongoModel(name, tree, options) {
602
+ let compiled;
603
+ const model = () => compiled ??= _chunkMGH4VDV3cjs.untracked.call(void 0,
604
+ () => loadMongoose().then(async (mg) => {
605
+ if (mg.models[name]) return mg.models[name];
606
+ const schema = new mg.Schema(buildTree(tree, mg), {
607
+ timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
608
+ // autoSync: false hands collection and index creation to migrations, on MongoDB too.
609
+ autoIndex: isAutoSync(),
610
+ autoCreate: isAutoSync(),
611
+ ...options.collection !== void 0 && { collection: options.collection }
612
+ });
613
+ for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
614
+ schema.index(idx.fields, {
615
+ ...idx.unique !== void 0 && { unique: idx.unique },
616
+ ...idx.expireAfterSeconds !== void 0 && {
617
+ expireAfterSeconds: idx.expireAfterSeconds
618
+ },
619
+ ...idx.name !== void 0 && { name: idx.name }
620
+ });
621
+ }
622
+ const sequences = sequenceFields(name, tree);
623
+ if (sequences.length > 0) {
624
+ schema.pre("validate", async function() {
625
+ if (!this.isNew) return;
626
+ for (const { path, key } of sequences) {
627
+ if (this.get(path) == null) this.set(path, await nextSequence(mg, key));
628
+ }
629
+ });
630
+ }
631
+ const M = mg.model(name, schema);
632
+ if (isAutoSync()) {
633
+ await M.init().catch((err) => {
634
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
635
+ { model: name, err: err.message },
636
+ `${name}: could not build its indexes \u2014 fix the data, then run efc db sync`
637
+ );
638
+ });
639
+ }
640
+ return M;
641
+ })
642
+ );
643
+ const session = () => {
644
+ const tx = currentTx();
645
+ return _optionalChain([tx, 'optionalAccess', _6 => _6.engine]) === "mongodb" ? { session: tx.session } : {};
646
+ };
647
+ const applyQueryOptions = (q2, opts) => {
648
+ if (_optionalChain([opts, 'optionalAccess', _7 => _7.populate])) q2.populate(opts.populate);
649
+ if (_optionalChain([opts, 'optionalAccess', _8 => _8.select])) q2.select(opts.select.join(" "));
650
+ const f = opts;
651
+ const sort = mapSort(_optionalChain([f, 'optionalAccess', _9 => _9.sort]));
652
+ if (sort) q2.sort(sort);
653
+ if (_optionalChain([f, 'optionalAccess', _10 => _10.skip]) !== void 0) q2.skip(f.skip);
654
+ if (_optionalChain([f, 'optionalAccess', _11 => _11.limit]) !== void 0) q2.limit(f.limit);
655
+ return q2;
656
+ };
657
+ const guard = async (fn) => {
658
+ try {
659
+ return await fn();
660
+ } catch (err) {
661
+ return translateError(name, err);
662
+ }
663
+ };
664
+ return {
665
+ find: (filter, opts) => guard(async () => {
666
+ const M = await model();
667
+ const docs = await applyQueryOptions(
668
+ M.find(mapFilter(filter), null, session()),
669
+ opts
670
+ ).lean();
671
+ return normalise(docs);
672
+ }),
673
+ async findById(id, opts) {
674
+ try {
675
+ const M = await model();
676
+ const doc = await applyQueryOptions(M.findById(id, null, session()), opts).lean();
677
+ return doc ? normalise(doc) : null;
678
+ } catch (err) {
679
+ if (isCastErrorOnId(err)) return null;
680
+ return translateError(name, err);
681
+ }
682
+ },
683
+ findOne: (filter, opts) => guard(async () => {
684
+ const M = await model();
685
+ const doc = await applyQueryOptions(
686
+ M.findOne(mapFilter(filter), null, session()),
687
+ opts
688
+ ).lean();
689
+ return doc ? normalise(doc) : null;
690
+ }),
691
+ create: (data) => guard(async () => {
692
+ const M = await model();
693
+ const [doc] = await M.create([data], session());
694
+ return normalise(doc.toObject());
695
+ }),
696
+ exists: (filter) => guard(async () => {
697
+ const M = await model();
698
+ return await M.exists(mapFilter(filter)).session(_nullishCoalesce(session().session, () => ( null))) !== null;
699
+ }),
700
+ distinct: (field, filter) => guard(async () => {
701
+ const mg = await loadMongoose();
702
+ const M = await model();
703
+ const values = await M.distinct(
704
+ field === "id" ? "_id" : field,
705
+ mapFilter(filter)
706
+ ).session(_nullishCoalesce(session().session, () => ( null)));
707
+ return values.map((v) => v instanceof mg.Types.ObjectId ? String(v) : v);
708
+ }),
709
+ createMany: (data) => guard(async () => {
710
+ const M = await model();
711
+ if (data.length === 0) return [];
712
+ const docs = await M.create(data, { ...session(), ordered: true });
713
+ return docs.map((d) => normalise(d.toObject()));
714
+ }),
715
+ async update(id, data) {
716
+ try {
717
+ const M = await model();
718
+ const doc = await M.findByIdAndUpdate(id, data, {
719
+ returnDocument: "after",
720
+ runValidators: true,
721
+ ...session()
722
+ }).lean();
723
+ return doc ? normalise(doc) : null;
724
+ } catch (err) {
725
+ if (isCastErrorOnId(err)) return null;
726
+ return translateError(name, err);
727
+ }
728
+ },
729
+ updateOne: (filter, data) => guard(async () => {
730
+ const M = await model();
731
+ const doc = await M.findOneAndUpdate(mapFilter(filter), data, {
732
+ returnDocument: "after",
733
+ runValidators: true,
734
+ ...session()
735
+ }).lean();
736
+ return doc ? normalise(doc) : null;
737
+ }),
738
+ updateMany: (filter, data) => guard(async () => {
739
+ const M = await model();
740
+ const r = await M.updateMany(mapFilter(filter), data, {
741
+ runValidators: true,
742
+ ...session()
743
+ });
744
+ return r.modifiedCount;
745
+ }),
746
+ async delete(id) {
747
+ try {
748
+ const M = await model();
749
+ await M.findByIdAndDelete(id, session());
750
+ } catch (err) {
751
+ if (isCastErrorOnId(err)) return;
752
+ translateError(name, err);
753
+ }
754
+ },
755
+ deleteOne: (filter) => guard(async () => {
756
+ const M = await model();
757
+ const doc = await M.findOneAndDelete(mapFilter(filter), session()).lean();
758
+ return doc ? normalise(doc) : null;
759
+ }),
760
+ deleteMany: (filter) => guard(async () => {
761
+ const M = await model();
762
+ const r = await M.deleteMany(mapFilter(filter), session());
763
+ return r.deletedCount;
764
+ }),
765
+ count: (filter) => guard(async () => {
766
+ const M = await model();
767
+ return M.countDocuments(mapFilter(filter), session());
768
+ }),
769
+ aggregate: (pipeline) => guard(async () => {
770
+ const M = await model();
771
+ const agg = M.aggregate(pipeline);
772
+ const s = session().session;
773
+ if (s) agg.session(s);
774
+ return await agg;
775
+ }),
776
+ raw: () => model(),
777
+ async sync(opts) {
778
+ const M = await model();
779
+ const changes = [];
780
+ const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
781
+ if (!exists) changes.push(`createCollection ${M.collection.collectionName}`);
782
+ const diff = await M.diffIndexes().catch(() => ({ toDrop: [], toCreate: [] }));
783
+ for (const idx of diff.toDrop) changes.push(`dropIndex ${String(idx)}`);
784
+ for (const idx of diff.toCreate) changes.push(`createIndex ${JSON.stringify(idx)}`);
785
+ if (_optionalChain([opts, 'optionalAccess', _12 => _12.dryRun])) return changes;
786
+ if (!exists) {
787
+ await M.createCollection().catch((err) => {
788
+ if (_optionalChain([err, 'optionalAccess', _13 => _13.code]) !== 48) throw err;
789
+ });
790
+ }
791
+ await M.syncIndexes();
792
+ return changes;
793
+ },
794
+ async drop() {
795
+ const M = await model();
796
+ await M.collection.drop().catch((err) => {
797
+ if (_optionalChain([err, 'optionalAccess', _14 => _14.code]) !== 26) throw err;
798
+ });
799
+ }
800
+ };
801
+ }
802
+
803
+ // src/db/mongo.ts
804
+ async function connectMongo(url) {
805
+ const mg = await loadMongoose();
806
+ await mg.connect(url);
807
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).info("MongoDB connected");
808
+ return mg.connection;
809
+ }
810
+
811
+ // src/db/pg-table.ts
812
+
813
+ var drizzlePromise;
814
+ function loadDrizzle() {
815
+ drizzlePromise ??= Promise.all([Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm"))), Promise.resolve().then(() => _interopRequireWildcard(require("drizzle-orm/pg-core")))]).then(([orm, pgCore]) => ({ sql: orm.sql, pgCore })).catch(() => {
816
+ drizzlePromise = void 0;
817
+ throw new Error("[EFC] drizzle-orm is not installed. Run: npm install pg drizzle-orm");
818
+ });
819
+ return drizzlePromise;
820
+ }
821
+ function tableNameFor(model) {
822
+ const lower = model.toLowerCase();
823
+ if (/[^aeiou]y$/.test(lower)) return lower.slice(0, -1) + "ies";
824
+ if (/(s|x|z|ch|sh)$/.test(lower)) return lower + "es";
825
+ return lower + "s";
826
+ }
827
+ var snakeCase = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
828
+ var q = (ident) => `"${ident.replace(/"/g, '""')}"`;
829
+ var sequenceName = (key) => `efc_seq_${key.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase()}`;
830
+ var literal = (v) => typeof v === "number" ? String(v) : `'${v.replace(/'/g, "''")}'`;
831
+ var syncing = /* @__PURE__ */ new Map();
832
+ var ACTION_SQL = {
833
+ restrict: "RESTRICT",
834
+ cascade: "CASCADE",
835
+ setNull: "SET NULL"
836
+ };
837
+ var ACTION_CODE = {
838
+ restrict: "r",
839
+ cascade: "c",
840
+ setNull: "n"
841
+ };
842
+ var ID_COLUMN = {
843
+ uuid: { kind: "uuid", type: "uuid" },
844
+ serial: { kind: "integer", type: "integer" },
845
+ bigserial: { kind: "bigint", type: "bigint" }
846
+ };
847
+ var modelOfTable = (table) => _nullishCoalesce(_optionalChain([registeredModels, 'call', _15 => _15(), 'access', _16 => _16.find, 'call', _17 => _17((m) => {
848
+ try {
849
+ return _optionalChain([m, 'access', _18 => _18.pgTarget, 'optionalCall', _19 => _19(), 'access', _20 => _20.table]) === table;
850
+ } catch (e2) {
851
+ return false;
852
+ }
853
+ }), 'optionalAccess', _21 => _21.name]), () => ( table));
854
+ function scalarSpec(type, def, native) {
855
+ switch (type) {
856
+ case "string":
857
+ if (native && def.maxLength !== void 0) {
858
+ return {
859
+ kind: "varchar",
860
+ ddl: `varchar(${def.maxLength})`,
861
+ formatted: `character varying(${def.maxLength})`,
862
+ length: def.maxLength
863
+ };
864
+ }
865
+ return { kind: "text", ddl: "text", formatted: "text" };
866
+ case "number":
867
+ return { kind: "double", ddl: "double precision", formatted: "double precision" };
868
+ case "integer":
869
+ return { kind: "integer", ddl: "integer", formatted: "integer" };
870
+ case "bigint":
871
+ return { kind: "bigint", ddl: "bigint", formatted: "bigint", bigintAs: "bigint" };
872
+ case "decimal": {
873
+ if (def.precision === void 0)
874
+ return { kind: "numeric", ddl: "numeric", formatted: "numeric" };
875
+ const t = `numeric(${def.precision},${_nullishCoalesce(def.scale, () => ( 0))})`;
876
+ return {
877
+ kind: "numeric",
878
+ ddl: t,
879
+ formatted: t,
880
+ precision: def.precision,
881
+ scale: _nullishCoalesce(def.scale, () => ( 0))
882
+ };
883
+ }
884
+ case "boolean":
885
+ return { kind: "boolean", ddl: "boolean", formatted: "boolean" };
886
+ case "date":
887
+ return { kind: "timestamptz", ddl: "timestamptz", formatted: "timestamp with time zone" };
888
+ case "objectId":
889
+ case "uuid":
890
+ return { kind: "uuid", ddl: "uuid", formatted: "uuid" };
891
+ }
892
+ }
893
+ function pgTable(name, tree, options, config) {
894
+ const snake = config.native && options.naming === "snake_case";
895
+ const table = _nullishCoalesce(options.collection, () => ( tableNameFor(snake ? snakeCase(name) : name)));
896
+ const columnName = (field, def) => _nullishCoalesce(_optionalChain([def, 'optionalAccess', _22 => _22.column]), () => ( (snake ? snakeCase(field) : field)));
897
+ const idKind = config.native && options.id || "uuid";
898
+ if (tree["id"]) throw new Error(`[EFC] ${name}: "id" is the primary key \u2014 don't declare it`);
899
+ const ts = timestampFields(options);
900
+ const sequences = sequenceFields(name, tree);
901
+ const sequenceKeys = new Map(sequences.map((s) => [s.path, s.key]));
902
+ const refs = refFields(tree);
903
+ const columns = /* @__PURE__ */ new Map();
904
+ const joins = /* @__PURE__ */ new Map();
905
+ 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" } : {
906
+ field: "id",
907
+ column: "id",
908
+ kind: "bigint",
909
+ ddl: "bigint",
910
+ formatted: "bigint",
911
+ bigintAs: "bigint"
912
+ };
913
+ columns.set("id", idSpec);
914
+ for (const [field, node] of Object.entries(tree)) {
915
+ const column = columnName(field, node.def);
916
+ const base = { field, column, node };
917
+ if (sequenceKeys.has(field)) {
918
+ columns.set(field, {
919
+ ...base,
920
+ kind: "bigint",
921
+ ddl: "bigint",
922
+ formatted: "bigint",
923
+ bigintAs: "number"
924
+ });
925
+ } else if (node.kind === "scalar") {
926
+ if (config.native && node.def.nativeEnum && node.def.enum) {
927
+ const enumType = `${table}_${column}_enum`;
928
+ columns.set(field, {
929
+ ...base,
930
+ kind: "enum",
931
+ ddl: q(enumType),
932
+ formatted: /^[a-z_][a-z0-9_]*$/.test(enumType) ? enumType : q(enumType),
933
+ enumType,
934
+ enumValues: node.def.enum.map(String)
935
+ });
936
+ } else {
937
+ columns.set(field, { ...base, ...scalarSpec(node.type, node.def, config.native) });
938
+ }
939
+ } else if (config.native && node.kind === "array" && node.item.kind === "scalar" && node.def.ref !== void 0) {
940
+ const item = scalarSpec(node.item.type, node.item.def, false).kind;
941
+ joins.set(field, {
942
+ field,
943
+ table: `${table}_${column}`,
944
+ legacyColumn: column,
945
+ target: node.def.ref,
946
+ item,
947
+ ddl: `${item}[]`,
948
+ node
949
+ });
950
+ } else if (config.native && node.kind === "array" && node.item.kind === "scalar") {
951
+ const item = scalarSpec(node.item.type, node.item.def, false);
952
+ columns.set(field, {
953
+ ...base,
954
+ ...item,
955
+ kind: "array",
956
+ item: item.kind,
957
+ ddl: `${item.ddl}[]`,
958
+ formatted: `${item.formatted}[]`
959
+ });
960
+ } else {
961
+ columns.set(field, { ...base, kind: "jsonb", ddl: "jsonb", formatted: "jsonb" });
962
+ }
963
+ }
964
+ for (const field of [ts.createdAt, ts.updatedAt]) {
965
+ if (field) {
966
+ columns.set(field, {
967
+ field,
968
+ column: columnName(field),
969
+ kind: "timestamptz",
970
+ ddl: "timestamptz",
971
+ formatted: "timestamp with time zone"
972
+ });
973
+ }
974
+ }
975
+ const byColumn = new Map([...columns.values()].map((c) => [c.column, c]));
976
+ const builder = (pgCore, kind, spec) => {
977
+ const c = spec.column;
978
+ switch (kind) {
979
+ case "varchar":
980
+ return pgCore.varchar(c, { length: spec.length });
981
+ case "double":
982
+ return pgCore.doublePrecision(c);
983
+ case "integer":
984
+ return pgCore.integer(c);
985
+ case "bigint":
986
+ return pgCore.bigint(c, { mode: _nullishCoalesce(spec.bigintAs, () => ( "bigint")) });
987
+ case "numeric":
988
+ return pgCore.numeric(
989
+ c,
990
+ spec.precision !== void 0 ? { precision: spec.precision, scale: spec.scale } : {}
991
+ );
992
+ case "boolean":
993
+ return pgCore.boolean(c);
994
+ case "timestamptz":
995
+ return pgCore.timestamp(c, { withTimezone: true, mode: "date" });
996
+ case "uuid":
997
+ return pgCore.uuid(c);
998
+ default:
999
+ return pgCore.text(c);
1000
+ }
1001
+ };
1002
+ let compiled;
1003
+ const compile = () => compiled ??= loadDrizzle().then(({ sql, pgCore }) => {
1004
+ const cols = {};
1005
+ for (const [field, spec] of columns) {
1006
+ let c;
1007
+ if (spec.kind === "jsonb") c = pgCore.jsonb(spec.column);
1008
+ else if (spec.kind === "array") c = builder(pgCore, spec.item, spec).array();
1009
+ else c = builder(pgCore, spec.kind, spec);
1010
+ if (field === "id") {
1011
+ c = idKind === "uuid" ? c.primaryKey().defaultRandom() : c.primaryKey().generatedByDefaultAsIdentity();
1012
+ }
1013
+ cols[field] = c;
1014
+ }
1015
+ return { t: pgCore.pgTable(table, cols), sql };
1016
+ });
1017
+ let synced;
1018
+ const ready = async () => {
1019
+ const result = await compile();
1020
+ if (isAutoSync()) {
1021
+ synced ??= reconcile(false).then(
1022
+ (changes) => {
1023
+ if (changes.length)
1024
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).info({ table, changes: changes.length }, `Synced table ${table}`);
1025
+ },
1026
+ (err) => {
1027
+ synced = void 0;
1028
+ throw err;
1029
+ }
1030
+ );
1031
+ await synced;
1032
+ }
1033
+ return result;
1034
+ };
1035
+ const client = () => {
1036
+ const tx = currentTx();
1037
+ return _optionalChain([tx, 'optionalAccess', _23 => _23.engine]) === "postgresql" ? tx.tx : _chunkMGH4VDV3cjs.getOrm.call(void 0, );
1038
+ };
1039
+ const columnFor = (t, field) => {
1040
+ if (!columns.has(field))
1041
+ throw new ModelValidationError(name, [{ path: field, message: "unknown field" }]);
1042
+ return t[field];
1043
+ };
1044
+ const scalarToDb = (kind, spec, v) => {
1045
+ if (v == null) return v;
1046
+ if (kind === "timestamptz") return v instanceof Date ? v : new Date(v);
1047
+ if (kind === "bigint")
1048
+ return spec.bigintAs === "number" ? Number(v) : BigInt(v);
1049
+ if (kind === "numeric") return String(v);
1050
+ return v;
1051
+ };
1052
+ const toDb = (field, value) => {
1053
+ const spec = columns.get(field);
1054
+ if (!spec || value == null) return value;
1055
+ if (spec.kind === "array") {
1056
+ return Array.isArray(value) ? value.map((v) => scalarToDb(spec.item, spec, v)) : value;
1057
+ }
1058
+ if (spec.kind === "jsonb") return value;
1059
+ return scalarToDb(spec.kind, spec, value);
1060
+ };
1061
+ const revive = (node, value) => {
1062
+ if (value == null) return value;
1063
+ if (node.kind === "scalar") {
1064
+ if (node.type === "date" && typeof value === "string") return new Date(value);
1065
+ return value;
1066
+ }
1067
+ if (node.kind === "array" && Array.isArray(value))
1068
+ return value.map((v) => revive(node.item, v));
1069
+ if (node.kind === "object" && typeof value === "object" && !Array.isArray(value)) {
1070
+ const out = { ...value };
1071
+ for (const [k, child] of Object.entries(node.fields)) {
1072
+ if (out[k] !== void 0) out[k] = revive(child, out[k]);
1073
+ }
1074
+ return out;
1075
+ }
1076
+ return value;
1077
+ };
1078
+ const hasNestedDate = (node) => node.kind === "scalar" ? node.type === "date" : node.kind === "array" ? hasNestedDate(node.item) : node.kind === "object" && Object.values(node.fields).some(hasNestedDate);
1079
+ const datedJson = [...columns.values()].filter(
1080
+ (c) => c.kind === "jsonb" && c.node && hasNestedDate(c.node)
1081
+ );
1082
+ const bigintCols = [...columns.values()].filter(
1083
+ (c) => c.kind === "bigint" && c.bigintAs === "bigint" || c.kind === "array" && c.item === "bigint"
1084
+ );
1085
+ const fromRow = (row) => {
1086
+ const out = {};
1087
+ for (const [k, v] of Object.entries(row)) if (v !== null) out[k] = v;
1088
+ for (const c of datedJson)
1089
+ if (out[c.field] !== void 0) out[c.field] = revive(c.node, out[c.field]);
1090
+ for (const c of bigintCols) {
1091
+ const v = out[c.field];
1092
+ if (typeof v === "string" || typeof v === "number") out[c.field] = BigInt(v);
1093
+ else if (Array.isArray(v)) out[c.field] = v.map((x) => x == null ? x : BigInt(x));
1094
+ }
1095
+ return out;
1096
+ };
1097
+ const fromRawRow = (row) => {
1098
+ const keyed = {};
1099
+ for (const [col, v] of Object.entries(row)) {
1100
+ const spec = byColumn.get(col);
1101
+ if (!spec) continue;
1102
+ keyed[spec.field] = v != null && spec.kind === "timestamptz" && !(v instanceof Date) ? new Date(v) : v;
1103
+ }
1104
+ return fromRow(keyed);
1105
+ };
1106
+ const validate = async (data, partial) => {
1107
+ const issues = [];
1108
+ const checkTree = {};
1109
+ for (const [k, node] of Object.entries(tree)) {
1110
+ checkTree[k] = sequenceKeys.has(k) ? { ...node, def: { ...node.def, required: false } } : node;
1111
+ }
1112
+ await validateTree(checkTree, data, issues, partial);
1113
+ if (issues.length) throw new ModelValidationError(name, issues);
1114
+ };
1115
+ const known = (data) => Object.fromEntries(
1116
+ Object.entries(data).filter(([k]) => {
1117
+ const top = k.split(".")[0];
1118
+ return columns.has(top) || joins.has(top);
1119
+ })
1120
+ );
1121
+ const prepareInsert = async (input) => {
1122
+ const { id, ...rest } = known(input);
1123
+ for (const f of [ts.createdAt, ts.updatedAt]) if (f) delete rest[f];
1124
+ const data = applyDefaults(tree, rest, _crypto.randomUUID);
1125
+ await validate(data, false);
1126
+ const now = /* @__PURE__ */ new Date();
1127
+ if (ts.createdAt) data[ts.createdAt] = now;
1128
+ if (ts.updatedAt) data[ts.updatedAt] = now;
1129
+ if (id !== void 0) data["id"] = id;
1130
+ for (const [k, v] of Object.entries(data)) data[k] = toDb(k, v);
1131
+ return data;
1132
+ };
1133
+ const fieldOfColumn = (column) => _nullishCoalesce(_optionalChain([byColumn, 'access', _24 => _24.get, 'call', _25 => _25(column), 'optionalAccess', _26 => _26.field]), () => ( column));
1134
+ const guard = async (fn) => {
1135
+ try {
1136
+ return await fn();
1137
+ } catch (err) {
1138
+ const e = _nullishCoalesce(err.cause, () => ( err));
1139
+ if (_optionalChain([e, 'optionalAccess', _27 => _27.code]) === "42P01") {
1140
+ throw new Error(
1141
+ `[EFC] ${name}: table "${table}" does not exist \u2014 autoSync is off, so create it with a migration (Model.sync() / efc db sync)`
1142
+ );
1143
+ }
1144
+ if (_optionalChain([e, 'optionalAccess', _28 => _28.code]) === "23505") {
1145
+ const cols = _nullishCoalesce(_optionalChain([/\(([^)]+)\)=/, 'access', _29 => _29.exec, 'call', _30 => _30(_nullishCoalesce(e.detail, () => ( ""))), 'optionalAccess', _31 => _31[1]]), () => ( "field"));
1146
+ const fields = cols.split(",").map((c) => fieldOfColumn(c.trim().replace(/"/g, ""))).join(", ");
1147
+ throw new HttpError(409, `${name} with this ${fields} already exists`);
1148
+ }
1149
+ if (_optionalChain([e, 'optionalAccess', _32 => _32.code]) === "23503" || _optionalChain([e, 'optionalAccess', _33 => _33.code]) === "23001") {
1150
+ const ref = /Key \(([^)]+)\)=\([^)]*\) is not present in table "([^"]+)"/.exec(
1151
+ _nullishCoalesce(e.detail, () => ( ""))
1152
+ );
1153
+ if (ref) {
1154
+ throw new ModelValidationError(name, [
1155
+ {
1156
+ // In a join table: the many-to-many field it backs.
1157
+ path: _nullishCoalesce(joinByTable.get(_nullishCoalesce(e.table, () => ( ""))), () => ( fieldOfColumn(ref[1].replace(/"/g, "")))),
1158
+ message: `${modelOfTable(ref[2])} not found`
1159
+ }
1160
+ ]);
1161
+ }
1162
+ const by = _optionalChain([/is (?:still )?referenced from table "([^"]+)"/, 'access', _34 => _34.exec, 'call', _35 => _35(_nullishCoalesce(e.detail, () => ( ""))), 'optionalAccess', _36 => _36[1]]);
1163
+ throw new HttpError(
1164
+ 409,
1165
+ `${name} is still referenced${by ? ` by ${modelOfTable(by)}` : ""} \u2014 delete or reassign those records first`
1166
+ );
1167
+ }
1168
+ if (_optionalChain([e, 'optionalAccess', _37 => _37.code]) === "23502")
1169
+ throw new ModelValidationError(name, [
1170
+ { path: fieldOfColumn(_nullishCoalesce(e.column, () => ( ""))), message: "is required" }
1171
+ ]);
1172
+ if (_optionalChain([e, 'optionalAccess', _38 => _38.code]) === "22P02" || _optionalChain([e, 'optionalAccess', _39 => _39.code]) === "22003" || _optionalChain([e, 'optionalAccess', _40 => _40.code]) === "23514")
1173
+ throw new ModelValidationError(name, [{ path: "", message: "invalid value" }]);
1174
+ throw err;
1175
+ }
1176
+ };
1177
+ const JSONB_TO_ARRAY = "efc_jsonb_text_array";
1178
+ 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 $$`;
1179
+ const castExpr = (spec, from) => {
1180
+ const c = q(spec.column);
1181
+ if (spec.kind === "jsonb") return `to_jsonb(${c})`;
1182
+ if (spec.kind === "array") {
1183
+ if (from === "jsonb") return `${JSONB_TO_ARRAY}(${c})::${spec.ddl}`;
1184
+ if (from.endsWith("[]")) return `${c}::${spec.ddl}`;
1185
+ return `CASE WHEN ${c} IS NULL THEN NULL ELSE ARRAY[${c}::text]::${spec.ddl} END`;
1186
+ }
1187
+ const scalar = from === "jsonb" ? `(${c} #>> '{}')` : c;
1188
+ if (spec.kind === "enum") return `${scalar}::text::${spec.ddl}`;
1189
+ if (spec.kind === "bigint" || spec.kind === "integer") {
1190
+ return `round(${scalar}::numeric)::${spec.ddl}`;
1191
+ }
1192
+ return `${scalar}::${spec.ddl}`;
1193
+ };
1194
+ const needsTypeChange = (spec, existing) => {
1195
+ if (existing === spec.formatted) return false;
1196
+ if (spec.kind === "varchar") {
1197
+ if (existing === "text") return false;
1198
+ const m = /^character varying\((\d+)\)$/.exec(existing);
1199
+ if (m && Number(m[1]) >= spec.length) return false;
1200
+ }
1201
+ return true;
1202
+ };
1203
+ const enumCheck = (column) => `${table}_${column}_enum`;
1204
+ const fkName = (column) => `${table}_${column}_fkey`;
1205
+ const isForeignKey = (spec) => config.native && _optionalChain([spec, 'access', _41 => _41.node, 'optionalAccess', _42 => _42.kind]) === "scalar" && spec.node.def.ref !== void 0;
1206
+ function resolveTarget(field, targetName, kind, many) {
1207
+ const target = targetName === name ? { table, idKind } : _optionalChain([getRegisteredModel, 'call', _43 => _43(targetName), 'optionalAccess', _44 => _44.pgTarget, 'optionalCall', _45 => _45()]);
1208
+ if (!target) {
1209
+ throw new Error(
1210
+ `[EFC] ${name}.${field} references "${targetName}", which is not defined \u2014 import that model before using ${name}`
1211
+ );
1212
+ }
1213
+ const want = ID_COLUMN[target.idKind];
1214
+ if (kind !== want.kind) {
1215
+ const hint = many ? `{ type: 'array', of: '${want.type}', ref: '${targetName}' }` : `{ type: '${want.type}', ref: '${targetName}' }`;
1216
+ throw new Error(
1217
+ `[EFC] ${name}.${field} references ${targetName}, whose id is ${want.type} (id: '${target.idKind}') \u2014 declare it ${hint}`
1218
+ );
1219
+ }
1220
+ return target;
1221
+ }
1222
+ function foreignKeys() {
1223
+ const out = [];
1224
+ for (const spec of columns.values()) {
1225
+ if (!isForeignKey(spec)) continue;
1226
+ const def = spec.node.def;
1227
+ const target = resolveTarget(spec.field, def.ref, spec.kind, false);
1228
+ out.push({
1229
+ field: spec.field,
1230
+ onTable: table,
1231
+ column: spec.column,
1232
+ name: fkName(spec.column),
1233
+ target: def.ref,
1234
+ targetTable: target.table,
1235
+ action: _nullishCoalesce(def.onDelete, () => ( "restrict"))
1236
+ });
1237
+ }
1238
+ for (const join of joins.values()) {
1239
+ const target = resolveTarget(join.field, join.target, join.item, true);
1240
+ const base = { field: join.field, onTable: join.table, action: "cascade" };
1241
+ out.push(
1242
+ {
1243
+ ...base,
1244
+ column: "owner_id",
1245
+ name: `${join.table}_owner_id_fkey`,
1246
+ target: name,
1247
+ targetTable: table
1248
+ },
1249
+ {
1250
+ ...base,
1251
+ column: "ref_id",
1252
+ name: `${join.table}_ref_id_fkey`,
1253
+ target: join.target,
1254
+ targetTable: target.table
1255
+ }
1256
+ );
1257
+ }
1258
+ return out;
1259
+ }
1260
+ const joinByTable = new Map([...joins.values()].map((j) => [j.table, j.field]));
1261
+ const managedIndexName = /_(key|idx)$/;
1262
+ function desiredIndexes() {
1263
+ const out = /* @__PURE__ */ new Map();
1264
+ for (const spec of columns.values()) {
1265
+ const def = _optionalChain([spec, 'access', _46 => _46.node, 'optionalAccess', _47 => _47.def]);
1266
+ if (!def) continue;
1267
+ const col = spec.column;
1268
+ if (def.unique) {
1269
+ out.set(
1270
+ `${table}_${col}_key`,
1271
+ `CREATE UNIQUE INDEX ${q(`${table}_${col}_key`)} ON ${q(table)} (${q(col)})`
1272
+ );
1273
+ } else if (def.index || isForeignKey(spec) && def.index !== false) {
1274
+ out.set(
1275
+ `${table}_${col}_idx`,
1276
+ `CREATE INDEX ${q(`${table}_${col}_idx`)} ON ${q(table)} (${q(col)})`
1277
+ );
1278
+ }
1279
+ }
1280
+ for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
1281
+ const fields = Object.entries(idx.fields).map(
1282
+ ([f, d]) => [_nullishCoalesce(_optionalChain([columns, 'access', _48 => _48.get, 'call', _49 => _49(f), 'optionalAccess', _50 => _50.column]), () => ( f)), d]
1283
+ );
1284
+ if (idx.expireAfterSeconds !== void 0) {
1285
+ throw new Error(`[EFC] ${name}: TTL indexes (expireAfterSeconds) are MongoDB-only`);
1286
+ }
1287
+ const idxName = _nullishCoalesce(idx.name, () => ( `${table}_${fields.map(([f]) => f).join("_")}_${idx.unique ? "key" : "idx"}`));
1288
+ if (fields.some(([, d]) => d === "text")) {
1289
+ const doc = fields.map(([f]) => `coalesce(${q(f)}::text, '')`).join(` || ' ' || `);
1290
+ out.set(
1291
+ idxName,
1292
+ `CREATE INDEX ${q(idxName)} ON ${q(table)} USING gin (to_tsvector('simple', ${doc}))`
1293
+ );
1294
+ } else {
1295
+ const cols = fields.map(([f, d]) => `${q(f)} ${d === -1 ? "DESC" : "ASC"}`).join(", ");
1296
+ out.set(
1297
+ idxName,
1298
+ `CREATE ${idx.unique ? "UNIQUE " : ""}INDEX ${q(idxName)} ON ${q(table)} (${cols})`
1299
+ );
1300
+ }
1301
+ }
1302
+ return out;
1303
+ }
1304
+ const tableExists = async (t) => (await _chunkMGH4VDV3cjs.getPool.call(void 0, ).query(
1305
+ `SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1306
+ WHERE c.relname = $1 AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
1307
+ [t]
1308
+ )).rowCount > 0;
1309
+ async function reconcile(dryRun) {
1310
+ const fks = foreignKeys();
1311
+ if (dryRun) return reconcileTable(true, fks, /* @__PURE__ */ new Set());
1312
+ let release;
1313
+ const mine = new Promise((resolve) => release = resolve);
1314
+ const prev = syncing.get(table);
1315
+ syncing.set(table, mine);
1316
+ try {
1317
+ const deferred = /* @__PURE__ */ new Set();
1318
+ const tx = currentTx();
1319
+ if (_optionalChain([tx, 'optionalAccess', _51 => _51.engine]) === "postgresql" && fks.length) {
1320
+ for (const fk of fks) deferred.add(fk.name);
1321
+ tx.afterCommit.push(() => {
1322
+ reconcile(false).catch(
1323
+ (err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
1324
+ );
1325
+ });
1326
+ }
1327
+ for (const fk of fks) {
1328
+ if (deferred.has(fk.name)) continue;
1329
+ if (fk.targetTable === table || await tableExists(fk.targetTable)) continue;
1330
+ const running = syncing.get(fk.targetTable);
1331
+ if (running) {
1332
+ deferred.add(fk.name);
1333
+ void running.then(() => reconcile(false)).catch(
1334
+ (err) => _chunkYL37D6KMcjs.getLogger.call(void 0, ).error({ err }, `${name}: adding foreign keys to "${table}" failed`)
1335
+ );
1336
+ } else {
1337
+ await getRegisteredModel(fk.target).sync();
1338
+ }
1339
+ }
1340
+ return await reconcileTable(false, fks, deferred);
1341
+ } finally {
1342
+ release();
1343
+ if (syncing.get(table) === mine) {
1344
+ if (prev) syncing.set(table, prev);
1345
+ else syncing.delete(table);
1346
+ }
1347
+ }
1348
+ }
1349
+ async function reconcileTable(dryRun, fks, deferred) {
1350
+ const pool = _chunkMGH4VDV3cjs.getPool.call(void 0, );
1351
+ const conn = await pool.connect();
1352
+ try {
1353
+ await conn.query("BEGIN");
1354
+ await conn.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`efc_sync:${table}`]);
1355
+ const existing = new Map(
1356
+ (await conn.query(
1357
+ `SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable
1358
+ FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1359
+ WHERE c.relname = $1 AND n.nspname = current_schema() AND a.attnum > 0 AND NOT a.attisdropped`,
1360
+ [table]
1361
+ )).rows.map((r) => [r.name, { type: r.type, nullable: r.nullable }])
1362
+ );
1363
+ const checks = new Map(
1364
+ (await conn.query(
1365
+ `SELECT con.conname AS name, pg_get_constraintdef(con.oid) AS def
1366
+ FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1367
+ WHERE c.relname = $1 AND n.nspname = current_schema() AND con.contype = 'c'`,
1368
+ [table]
1369
+ )).rows.map((r) => [r.name, r.def])
1370
+ );
1371
+ const indexes = new Set(
1372
+ (await conn.query(
1373
+ `SELECT indexname AS name FROM pg_indexes WHERE tablename = $1 AND schemaname = current_schema()`,
1374
+ [table]
1375
+ )).rows.map((r) => r.name)
1376
+ );
1377
+ const liveFks = new Map(
1378
+ (await conn.query(
1379
+ `SELECT con.conname AS name, ft.relname AS target, con.confdeltype AS action, con.convalidated AS valid
1380
+ FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
1381
+ JOIN pg_class ft ON ft.oid = con.confrelid
1382
+ WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND con.contype = 'f'`,
1383
+ [[table, ...joinByTable.keys()]]
1384
+ )).rows.map((r) => [r.name, r])
1385
+ );
1386
+ const liveJoinTables = new Set(
1387
+ (await conn.query(
1388
+ `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1389
+ WHERE c.relname = ANY($1) AND n.nspname = current_schema() AND c.relkind IN ('r', 'p')`,
1390
+ [[...joinByTable.keys()]]
1391
+ )).rows.map((r) => r.name)
1392
+ );
1393
+ const plan = [];
1394
+ const wantedFks = new Map(fks.map((fk) => [fk.name, fk]));
1395
+ for (const [con, live] of liveFks) {
1396
+ const want = wantedFks.get(con);
1397
+ const ours = [...joinByTable.keys()].some((jt) => con.startsWith(`${jt}_`)) || [...columns.values()].some((c) => c.field !== "id" && fkName(c.column) === con);
1398
+ if (ours && (!want || live.target !== want.targetTable || live.action !== ACTION_CODE[want.action])) {
1399
+ const on = _nullishCoalesce([...joinByTable.keys()].find((jt) => con.startsWith(`${jt}_`)), () => ( table));
1400
+ plan.push(`ALTER TABLE ${q(on)} DROP CONSTRAINT ${q(con)}`);
1401
+ liveFks.delete(con);
1402
+ }
1403
+ }
1404
+ for (const { key } of sequences) {
1405
+ const seq = sequenceName(key);
1406
+ const found = await conn.query(
1407
+ "SELECT 1 FROM pg_class WHERE relkind = $1 AND relname = $2",
1408
+ ["S", seq]
1409
+ );
1410
+ if (found.rowCount === 0) plan.push(`CREATE SEQUENCE IF NOT EXISTS ${q(seq)}`);
1411
+ }
1412
+ const enumSpecs = [...columns.values()].filter((c) => c.kind === "enum");
1413
+ if (enumSpecs.length) {
1414
+ const live = /* @__PURE__ */ new Map();
1415
+ for (const r of (await conn.query(
1416
+ `SELECT t.typname AS type, e.enumlabel AS label FROM pg_type t
1417
+ JOIN pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_enum e ON e.enumtypid = t.oid
1418
+ WHERE n.nspname = current_schema() AND t.typname = ANY($1)`,
1419
+ [enumSpecs.map((c) => c.enumType)]
1420
+ )).rows) {
1421
+ const set = _nullishCoalesce(live.get(r.type), () => ( /* @__PURE__ */ new Set()));
1422
+ if (r.label !== null) set.add(r.label);
1423
+ live.set(r.type, set);
1424
+ }
1425
+ for (const spec of enumSpecs) {
1426
+ const have = live.get(spec.enumType);
1427
+ if (!have) {
1428
+ plan.push(
1429
+ `CREATE TYPE ${spec.ddl} AS ENUM (${spec.enumValues.map(literal).join(", ")})`
1430
+ );
1431
+ } else {
1432
+ for (const v of spec.enumValues) {
1433
+ if (!have.has(v))
1434
+ plan.push(`ALTER TYPE ${spec.ddl} ADD VALUE IF NOT EXISTS ${literal(v)}`);
1435
+ }
1436
+ }
1437
+ }
1438
+ }
1439
+ const columnSql = (spec) => {
1440
+ const seq = sequenceKeys.get(spec.field);
1441
+ return `${q(spec.column)} ${spec.ddl}${seq ? ` DEFAULT nextval('${sequenceName(seq)}')` : ""}`;
1442
+ };
1443
+ const idSql = idKind === "uuid" ? `${q("id")} uuid PRIMARY KEY DEFAULT gen_random_uuid()` : `${q("id")} ${idSpec.ddl} GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`;
1444
+ if (existing.size === 0) {
1445
+ const defs = [...columns.values()].map(
1446
+ (spec) => spec.field === "id" ? idSql : columnSql(spec)
1447
+ );
1448
+ plan.push(`CREATE TABLE IF NOT EXISTS ${q(table)} (
1449
+ ${defs.join(",\n ")}
1450
+ )`);
1451
+ } else {
1452
+ const alters = [];
1453
+ for (const spec of columns.values()) {
1454
+ const col = existing.get(spec.column);
1455
+ if (!col) {
1456
+ alters.push(`ALTER TABLE ${q(table)} ADD COLUMN ${columnSql(spec)}`);
1457
+ } else if (spec.field !== "id" && needsTypeChange(spec, col.type)) {
1458
+ if (spec.kind === "array" && col.type === "jsonb" && !plan.includes(jsonbToArrayFn))
1459
+ plan.push(jsonbToArrayFn);
1460
+ alters.push(
1461
+ `ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${spec.ddl} USING ${castExpr(spec, col.type)}`
1462
+ );
1463
+ }
1464
+ }
1465
+ plan.push(...new Set(alters));
1466
+ for (const [column, col] of existing) {
1467
+ if (column !== "id" && !col.nullable) {
1468
+ plan.push(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} DROP NOT NULL`);
1469
+ }
1470
+ }
1471
+ }
1472
+ const wantedChecks = /* @__PURE__ */ new Map();
1473
+ for (const spec of columns.values()) {
1474
+ const def = _optionalChain([spec, 'access', _52 => _52.node, 'optionalAccess', _53 => _53.def]);
1475
+ if (_optionalChain([spec, 'access', _54 => _54.node, 'optionalAccess', _55 => _55.kind]) === "scalar" && _optionalChain([def, 'optionalAccess', _56 => _56.enum]) && spec.kind !== "enum") {
1476
+ wantedChecks.set(
1477
+ enumCheck(spec.column),
1478
+ `CHECK (${q(spec.column)} IN (${def.enum.map(literal).join(", ")}))`
1479
+ );
1480
+ }
1481
+ }
1482
+ for (const [con, def] of checks) {
1483
+ const legacy = con.endsWith("_check") && con.startsWith(`${table}_`);
1484
+ if (con.endsWith("_enum") && con.startsWith(`${table}_`) && !wantedChecks.has(con) || legacy) {
1485
+ plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
1486
+ checks.delete(con);
1487
+ } else if (wantedChecks.has(con)) {
1488
+ const want = wantedChecks.get(con);
1489
+ const values = (d) => [...d.matchAll(/'((?:[^']|'')*)'|(-?\d+(?:\.\d+)?)/g)].map((m) => _nullishCoalesce(m[1], () => ( m[2]))).sort().join("|");
1490
+ if (values(def) !== values(want)) {
1491
+ plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
1492
+ checks.delete(con);
1493
+ }
1494
+ }
1495
+ }
1496
+ for (const [con, def] of wantedChecks) {
1497
+ if (!checks.has(con))
1498
+ plan.push(`ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def} NOT VALID`);
1499
+ }
1500
+ const wantedIndexes = desiredIndexes();
1501
+ for (const idx of indexes) {
1502
+ if (idx !== `${table}_pkey` && idx.startsWith(`${table}_`) && managedIndexName.test(idx) && !wantedIndexes.has(idx)) {
1503
+ plan.push(`DROP INDEX ${q(idx)}`);
1504
+ }
1505
+ }
1506
+ for (const [idx, create] of wantedIndexes) if (!indexes.has(idx)) plan.push(create);
1507
+ const ownerDdl = idSpec.ddl;
1508
+ for (const join of joins.values()) {
1509
+ if (liveJoinTables.has(join.table)) continue;
1510
+ const refDdl = join.item;
1511
+ plan.push(
1512
+ `CREATE TABLE IF NOT EXISTS ${q(join.table)} (
1513
+ ${q("owner_id")} ${ownerDdl} NOT NULL,
1514
+ ${q("ref_id")} ${refDdl} NOT NULL,
1515
+ ${q("position")} integer NOT NULL DEFAULT 0,
1516
+ PRIMARY KEY (${q("owner_id")}, ${q("ref_id")})
1517
+ )`,
1518
+ `CREATE INDEX IF NOT EXISTS ${q(`${join.table}_ref_id_idx`)} ON ${q(join.table)} (${q("ref_id")})`
1519
+ );
1520
+ const legacy = _optionalChain([existing, 'access', _57 => _57.get, 'call', _58 => _58(join.legacyColumn), 'optionalAccess', _59 => _59.type]);
1521
+ if (legacy === "jsonb" || _optionalChain([legacy, 'optionalAccess', _60 => _60.endsWith, 'call', _61 => _61("[]")])) {
1522
+ const c = `o.${q(join.legacyColumn)}`;
1523
+ const items = legacy === "jsonb" ? `jsonb_array_elements_text(CASE WHEN jsonb_typeof(${c}) = 'array' THEN ${c} ELSE '[]'::jsonb END)` : `unnest(${c}::text[])`;
1524
+ 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}$'`;
1525
+ plan.push(
1526
+ `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`
1527
+ );
1528
+ }
1529
+ }
1530
+ const toValidate = [];
1531
+ for (const fk of fks) {
1532
+ if (deferred.has(fk.name)) continue;
1533
+ const live = liveFks.get(fk.name);
1534
+ if (!live) {
1535
+ plan.push(
1536
+ `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`
1537
+ );
1538
+ }
1539
+ if (!_optionalChain([live, 'optionalAccess', _62 => _62.valid])) toValidate.push(fk);
1540
+ }
1541
+ const validations = toValidate.map(
1542
+ (fk) => `ALTER TABLE ${q(fk.onTable)} VALIDATE CONSTRAINT ${q(fk.name)}`
1543
+ );
1544
+ if (!dryRun) {
1545
+ for (const stmt of plan) {
1546
+ try {
1547
+ await conn.query(stmt);
1548
+ } catch (err) {
1549
+ throw new Error(
1550
+ `[EFC] ${name}: syncing table "${table}" failed on: ${stmt}
1551
+ ${err.message}`
1552
+ );
1553
+ }
1554
+ }
1555
+ }
1556
+ await conn.query(dryRun ? "ROLLBACK" : "COMMIT");
1557
+ if (!dryRun) {
1558
+ for (const [i, fk] of toValidate.entries()) {
1559
+ try {
1560
+ await conn.query(validations[i]);
1561
+ } catch (e3) {
1562
+ const orphans = await conn.query(
1563
+ `SELECT count(*) AS n FROM ${q(fk.onTable)} r WHERE ${q(fk.column)} IS NOT NULL
1564
+ AND NOT EXISTS (SELECT 1 FROM ${q(fk.targetTable)} t WHERE t.${q("id")} = r.${q(fk.column)})`
1565
+ ).then((r) => _nullishCoalesce(_optionalChain([r, 'access', _63 => _63.rows, 'access', _64 => _64[0], 'optionalAccess', _65 => _65.n]), () => ( "?"))).catch(() => "?");
1566
+ _chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
1567
+ { table, constraint: fk.name, orphans: Number(orphans) },
1568
+ `${name}.${fk.field}: ${orphans} 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`
1569
+ );
1570
+ }
1571
+ }
1572
+ }
1573
+ return [...plan, ...validations];
1574
+ } catch (err) {
1575
+ await conn.query("ROLLBACK").catch(() => {
1576
+ });
1577
+ throw err;
1578
+ } finally {
1579
+ conn.release();
1580
+ }
1581
+ }
1582
+ async function drop() {
1583
+ const { sql } = await compile();
1584
+ await client().execute(sql.raw(`DROP TABLE IF EXISTS ${q(table)}`));
1585
+ }
1586
+ return {
1587
+ name,
1588
+ table,
1589
+ tree,
1590
+ idKind,
1591
+ columns,
1592
+ joins,
1593
+ ts,
1594
+ sequenceKeys,
1595
+ refs,
1596
+ compile,
1597
+ ready,
1598
+ client,
1599
+ columnFor,
1600
+ toDb,
1601
+ fromRow,
1602
+ fromRawRow,
1603
+ validate,
1604
+ known,
1605
+ prepareInsert,
1606
+ guard,
1607
+ reconcile,
1608
+ drop
1609
+ };
1610
+ }
1611
+
1612
+ // src/db/pg-model.ts
1613
+ function pgModel(name, tree, options) {
1614
+ const tbl = pgTable(name, tree, options, { native: false, api: "defineModel" });
1615
+ const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
1616
+ const kindOf = (field) => _optionalChain([columns, 'access', _66 => _66.get, 'call', _67 => _67(field), 'optionalAccess', _68 => _68.kind]);
1617
+ function missingField(sql, cond) {
1618
+ const ops = cond !== null && typeof cond === "object" && !Array.isArray(cond) && !(cond instanceof Date) && !(cond instanceof RegExp) ? cond : { $eq: cond };
1619
+ const matches = Object.entries(ops).every(([op, v]) => {
1620
+ switch (op) {
1621
+ case "$eq":
1622
+ return v === null;
1623
+ case "$ne":
1624
+ return v !== null;
1625
+ case "$exists":
1626
+ return v === false;
1627
+ case "$in":
1628
+ return v.includes(null);
1629
+ case "$nin":
1630
+ return !v.includes(null);
1631
+ default:
1632
+ return false;
1633
+ }
1634
+ });
1635
+ return matches ? sql`true` : sql`false`;
1636
+ }
1637
+ function condition(sql, t, path, cond) {
1638
+ const [field, ...rest] = path.split(".");
1639
+ if (!columns.has(field)) return missingField(sql, cond);
1640
+ const col = columnFor(t, field);
1641
+ const kind = kindOf(field);
1642
+ const isOps = cond != null && typeof cond === "object" && !Array.isArray(cond) && !(cond instanceof Date) && !(cond instanceof RegExp) && Object.keys(cond).some((k) => k.startsWith("$"));
1643
+ const jsonPath = rest.length > 0 ? `{${rest.join(",")}}` : void 0;
1644
+ const exprFor = (sample) => jsonPath === void 0 ? col : typeof sample === "number" ? sql`((${col} #>> ${jsonPath})::double precision)` : typeof sample === "boolean" ? sql`((${col} #>> ${jsonPath})::boolean)` : sql`(${col} #>> ${jsonPath})`;
1645
+ const eqCond = (v) => {
1646
+ if (v === null) return jsonPath ? sql`(${col} #> ${jsonPath}) is null` : sql`${col} is null`;
1647
+ if (kind === "jsonb" && jsonPath === void 0) {
1648
+ return Array.isArray(v) || typeof v === "object" && !(v instanceof Date) ? sql`${col} = ${JSON.stringify(v)}::jsonb` : sql`${col} @> ${JSON.stringify([v])}::jsonb`;
1649
+ }
1650
+ return sql`${exprFor(v)} = ${jsonPath ? v : toDb(field, v)}`;
1651
+ };
1652
+ if (!isOps) return eqCond(cond);
1653
+ const parts = [];
1654
+ for (const [op, v] of Object.entries(cond)) {
1655
+ const e = exprFor(Array.isArray(v) ? v[0] : v);
1656
+ const val = jsonPath ? v : toDb(field, v);
1657
+ switch (op) {
1658
+ case "$eq":
1659
+ parts.push(eqCond(v));
1660
+ break;
1661
+ case "$ne":
1662
+ if (v === null) parts.push(sql`${e} is not null`);
1663
+ else if (kind === "jsonb" && !jsonPath) {
1664
+ parts.push(
1665
+ Array.isArray(v) || typeof v === "object" && !(v instanceof Date) ? sql`(${col} is null or ${col} <> ${JSON.stringify(v)}::jsonb)` : sql`(${col} is null or not (${col} @> ${JSON.stringify([v])}::jsonb))`
1666
+ );
1667
+ } else parts.push(sql`(${e} is null or ${e} <> ${val})`);
1668
+ break;
1669
+ case "$gt":
1670
+ parts.push(sql`${e} > ${val}`);
1671
+ break;
1672
+ case "$gte":
1673
+ parts.push(sql`${e} >= ${val}`);
1674
+ break;
1675
+ case "$lt":
1676
+ parts.push(sql`${e} < ${val}`);
1677
+ break;
1678
+ case "$lte":
1679
+ parts.push(sql`${e} <= ${val}`);
1680
+ break;
1681
+ case "$in":
1682
+ case "$nin": {
1683
+ const list = v.map((x) => jsonPath ? x : toDb(field, x));
1684
+ if (list.length === 0) {
1685
+ parts.push(op === "$in" ? sql`false` : sql`true`);
1686
+ break;
1687
+ }
1688
+ const inList = kind === "jsonb" && !jsonPath ? sql.join(
1689
+ list.map((x) => sql`${col} @> ${JSON.stringify([x])}::jsonb`),
1690
+ sql` or `
1691
+ ) : sql`${e} in (${sql.join(
1692
+ list.map((x) => sql`${x}`),
1693
+ sql`, `
1694
+ )})`;
1695
+ parts.push(
1696
+ op === "$in" ? sql`(${inList})` : sql`(${kind === "jsonb" && !jsonPath ? sql`${col} is null or ` : sql``}not (${inList}))`
1697
+ );
1698
+ break;
1699
+ }
1700
+ case "$exists":
1701
+ parts.push(
1702
+ v ? sql`${exprFor(void 0)} is not null` : sql`${exprFor(void 0)} is null`
1703
+ );
1704
+ break;
1705
+ case "$regex": {
1706
+ const re = v instanceof RegExp ? v : new RegExp(String(v));
1707
+ const textExpr = jsonPath ? sql`(${col} #>> ${jsonPath})` : col;
1708
+ parts.push(
1709
+ re.flags.includes("i") ? sql`${textExpr} ~* ${re.source}` : sql`${textExpr} ~ ${re.source}`
1710
+ );
1711
+ break;
1712
+ }
1713
+ default:
1714
+ throw new ModelValidationError(name, [
1715
+ { path, message: `operator ${op} is not supported on PostgreSQL` }
1716
+ ]);
1717
+ }
1718
+ }
1719
+ return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
1720
+ }
1721
+ function where(sql, t, filter) {
1722
+ if (!filter) return void 0;
1723
+ const parts = [];
1724
+ for (const [k, v] of Object.entries(filter)) {
1725
+ if (v === void 0) continue;
1726
+ if (k === "$and" || k === "$or") {
1727
+ const sub = v.map((f) => _nullishCoalesce(where(sql, t, f), () => ( sql`true`)));
1728
+ if (sub.length) parts.push(sql`(${sql.join(sub, k === "$and" ? sql` and ` : sql` or `)})`);
1729
+ } else {
1730
+ parts.push(condition(sql, t, k, v));
1731
+ }
1732
+ }
1733
+ return parts.length === 0 ? void 0 : parts.length === 1 ? parts[0] : sql.join(parts, sql` and `);
1734
+ }
1735
+ function firstMatch(sql, t, filter) {
1736
+ const w = _nullishCoalesce(where(sql, t, filter), () => ( sql`true`));
1737
+ return sql`${t.id} = (select ${t.id} from ${t} where ${w} limit 1 for update)`;
1738
+ }
1739
+ const prepareInsert = tbl.prepareInsert;
1740
+ async function populate(records, paths) {
1741
+ if (!paths) return records;
1742
+ for (const path of Array.isArray(paths) ? paths : [paths]) {
1743
+ const ref = refs.get(path);
1744
+ if (!ref)
1745
+ throw new ModelValidationError(name, [{ path, message: "is not a populatable ref field" }]);
1746
+ const target = getRegisteredModel(ref.model);
1747
+ if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
1748
+ const ids = [
1749
+ ...new Set(
1750
+ records.flatMap(
1751
+ (r) => ref.many ? _nullishCoalesce(r[path], () => ( [])) : r[path] ? [r[path]] : []
1752
+ )
1753
+ )
1754
+ ];
1755
+ if (ids.length === 0) continue;
1756
+ const byId = new Map((await target.findByIds(ids)).map((d) => [d["id"], d]));
1757
+ for (const r of records) {
1758
+ if (ref.many) r[path] = (_nullishCoalesce(r[path], () => ( []))).map((id) => _nullishCoalesce(byId.get(id), () => ( id)));
1759
+ else if (r[path]) r[path] = _nullishCoalesce(byId.get(r[path]), () => ( r[path]));
1760
+ }
1761
+ }
1762
+ return records;
1763
+ }
1764
+ const selection = (t, select) => {
1765
+ if (!select) return void 0;
1766
+ const out = { id: t.id };
1767
+ for (const f of select) if (columns.has(f)) out[f] = columnFor(t, f);
1768
+ return out;
1769
+ };
1770
+ async function runFind(filter, opts) {
1771
+ const { t, sql } = await ready();
1772
+ const sel = selection(t, _optionalChain([opts, 'optionalAccess', _69 => _69.select]));
1773
+ let query = (sel ? client().select(sel) : client().select()).from(t);
1774
+ const w = where(sql, t, filter);
1775
+ if (w) query = query.where(w);
1776
+ if (_optionalChain([opts, 'optionalAccess', _70 => _70.sort])) {
1777
+ const order = Object.entries(opts.sort).filter(([f]) => columns.has(f)).map(([f, dir]) => {
1778
+ const col = columnFor(t, f);
1779
+ return dir === -1 || dir === "desc" ? sql`${col} desc nulls last` : sql`${col} asc nulls first`;
1780
+ });
1781
+ if (order.length) query = query.orderBy(...order);
1782
+ }
1783
+ if (_optionalChain([opts, 'optionalAccess', _71 => _71.limit]) !== void 0) query = query.limit(opts.limit);
1784
+ if (_optionalChain([opts, 'optionalAccess', _72 => _72.skip]) !== void 0) query = query.offset(opts.skip);
1785
+ const rows = (await query).map(fromRow);
1786
+ return populate(rows, _optionalChain([opts, 'optionalAccess', _73 => _73.populate]));
1787
+ }
1788
+ const strictUpdate = (update) => {
1789
+ const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || nodeAt(tree, path.split(".")) !== void 0);
1790
+ const out = {};
1791
+ for (const [k, v] of Object.entries(update)) {
1792
+ if (k.startsWith("$") && v !== null && typeof v === "object") {
1793
+ out[k] = Object.fromEntries(Object.entries(v).filter(([p]) => declared(p)));
1794
+ } else if (k.startsWith("$") || declared(k)) out[k] = v;
1795
+ }
1796
+ return out;
1797
+ };
1798
+ async function buildSet(input) {
1799
+ const { t, sql } = await compile();
1800
+ const update = strictUpdate(input);
1801
+ const ops = update;
1802
+ for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
1803
+ if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
1804
+ throw new ModelValidationError(name, [
1805
+ { path: op, message: "update operator is not supported on PostgreSQL" }
1806
+ ]);
1807
+ }
1808
+ }
1809
+ const plain = {};
1810
+ for (const [k, v] of Object.entries(update)) if (!k.startsWith("$")) plain[k] = v;
1811
+ const $set = { ..._nullishCoalesce(ops["$set"], () => ( {})), ...plain };
1812
+ const issues = [];
1813
+ const topLevel = {};
1814
+ for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
1815
+ for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
1816
+ for (const [k, v] of Object.entries($set))
1817
+ if (k.includes(".")) await validateAtPath(tree, k, v, issues);
1818
+ for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
1819
+ if (k.includes(".")) await validateAtPath(tree, k, null, issues);
1820
+ }
1821
+ for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
1822
+ if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
1823
+ const node = k.includes(".") ? nodeAt(tree, k.split(".")) : tree[k];
1824
+ if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
1825
+ issues.push({ path: k, message: "$inc only applies to number fields" });
1826
+ }
1827
+ }
1828
+ if (issues.length) throw new ModelValidationError(name, issues);
1829
+ await validate(topLevel, true);
1830
+ const set = {};
1831
+ const nested = /* @__PURE__ */ new Map();
1832
+ const touchedTop = /* @__PURE__ */ new Set();
1833
+ const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
1834
+ const conflict = (path) => {
1835
+ throw new ModelValidationError(name, [{ path, message: "conflicting update paths" }]);
1836
+ };
1837
+ const top = (field, value) => {
1838
+ if (touchedTop.has(field) || nested.has(field)) conflict(field);
1839
+ touchedTop.add(field);
1840
+ set[field] = value;
1841
+ };
1842
+ const withParents = (base, parts) => {
1843
+ let expr = sql`coalesce(${base}, '{}'::jsonb)`;
1844
+ for (let i = 1; i < parts.length; i++) {
1845
+ const prefix = `{${parts.slice(0, i).join(",")}}`;
1846
+ expr = sql`jsonb_set(${expr}, ${prefix}, coalesce(${expr} #> ${prefix}, '{}'::jsonb), true)`;
1847
+ }
1848
+ return expr;
1849
+ };
1850
+ const dotted = (path, apply) => {
1851
+ const [field, ...rest] = path.split(".");
1852
+ if (touchedTop.has(field)) conflict(path);
1853
+ columnFor(t, field);
1854
+ const base = withParents(acc(field), rest);
1855
+ nested.set(field, apply(base, `{${rest.join(",")}}`));
1856
+ };
1857
+ const items = (v) => JSON.stringify(
1858
+ v != null && typeof v === "object" && "$each" in v ? v.$each : [v]
1859
+ );
1860
+ for (const [k, v] of Object.entries($set)) {
1861
+ if (k.includes("."))
1862
+ dotted(k, (b, p) => sql`jsonb_set(${b}, ${p}, ${JSON.stringify(v)}::jsonb, true)`);
1863
+ else top(k, toDb(k, v));
1864
+ }
1865
+ for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
1866
+ if (k.includes(".")) dotted(k, (b, p) => sql`(${b} #- ${p})`);
1867
+ else top(k, null);
1868
+ }
1869
+ for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
1870
+ if (k.includes(".")) {
1871
+ dotted(
1872
+ k,
1873
+ (b, p) => sql`jsonb_set(${b}, ${p}, to_jsonb(coalesce((${b} #>> ${p})::double precision, 0) + ${by}), true)`
1874
+ );
1875
+ } else top(k, sql`coalesce(${columnFor(t, k)}, 0) + ${by}`);
1876
+ }
1877
+ for (const [k, v] of Object.entries(_nullishCoalesce(ops["$push"], () => ( {})))) {
1878
+ if (k.includes(".")) {
1879
+ dotted(
1880
+ k,
1881
+ (b, p) => sql`jsonb_set(${b}, ${p}, coalesce(${b} #> ${p}, '[]'::jsonb) || ${items(v)}::jsonb, true)`
1882
+ );
1883
+ } else top(k, sql`coalesce(${columnFor(t, k)}, '[]'::jsonb) || ${items(v)}::jsonb`);
1884
+ }
1885
+ for (const [k, v] of Object.entries(_nullishCoalesce(ops["$pull"], () => ( {})))) {
1886
+ const without = (arr) => sql`coalesce((select jsonb_agg(e) from jsonb_array_elements(${arr}) e where e <> ${JSON.stringify(v)}::jsonb), '[]'::jsonb)`;
1887
+ if (k.includes("."))
1888
+ dotted(k, (b, p) => sql`jsonb_set(${b}, ${p}, ${without(sql`(${b} #> ${p})`)}, true)`);
1889
+ else top(k, without(columnFor(t, k)));
1890
+ }
1891
+ for (const [field, expr] of nested) set[field] = expr;
1892
+ if (ts.updatedAt) set[ts.updatedAt] = /* @__PURE__ */ new Date();
1893
+ return set;
1894
+ }
1895
+ const UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1896
+ return {
1897
+ find: (filter, opts) => guard(async () => await runFind(filter, opts)),
1898
+ findById: (id, opts) => guard(async () => {
1899
+ if (!UUID_RE2.test(id)) return null;
1900
+ return await _asyncNullishCoalesce((await runFind({ id }, { ...opts, limit: 1 }))[0], async () => ( null));
1901
+ }),
1902
+ findOne: (filter, opts) => guard(
1903
+ async () => await _asyncNullishCoalesce((await runFind(filter, { ...opts, limit: 1 }))[0], async () => ( null))
1904
+ ),
1905
+ exists: (filter) => guard(async () => {
1906
+ const { t, sql } = await ready();
1907
+ let query = client().select({ one: sql`1` }).from(t);
1908
+ const w = where(sql, t, filter);
1909
+ if (w) query = query.where(w);
1910
+ return (await query.limit(1)).length > 0;
1911
+ }),
1912
+ distinct: (field, filter) => guard(async () => {
1913
+ const { t, sql } = await ready();
1914
+ if (!columns.has(field)) return [];
1915
+ let query = client().selectDistinct({ v: columnFor(t, field) }).from(t);
1916
+ const w = where(sql, t, filter);
1917
+ if (w) query = query.where(w);
1918
+ return (await query).map((r) => r.v);
1919
+ }),
1920
+ create: (data) => guard(async () => {
1921
+ const { t } = await ready();
1922
+ const row = await prepareInsert(data);
1923
+ const [inserted] = await client().insert(t).values(row).returning();
1924
+ return fromRow(inserted);
1925
+ }),
1926
+ createMany: (data) => guard(async () => {
1927
+ if (data.length === 0) return [];
1928
+ const { t } = await ready();
1929
+ const rows = await Promise.all(data.map((d) => prepareInsert(d)));
1930
+ return (await client().insert(t).values(rows).returning()).map(
1931
+ fromRow
1932
+ );
1933
+ }),
1934
+ update: (id, data) => guard(async () => {
1935
+ if (!UUID_RE2.test(id)) return null;
1936
+ const { t, sql } = await ready();
1937
+ const set = await buildSet(data);
1938
+ const [row] = await client().update(t).set(set).where(sql`${t.id} = ${id}`).returning();
1939
+ return row ? fromRow(row) : null;
1940
+ }),
1941
+ updateOne: (filter, data) => guard(async () => {
1942
+ const { t, sql } = await ready();
1943
+ const set = await buildSet(data);
1944
+ if (Object.keys(set).length === 0) {
1945
+ return await _asyncNullishCoalesce((await runFind(filter, { limit: 1 }))[0], async () => ( null));
1946
+ }
1947
+ const [row] = await client().update(t).set(set).where(firstMatch(sql, t, filter)).returning();
1948
+ return row ? fromRow(row) : null;
1949
+ }),
1950
+ updateMany: (filter, data) => guard(async () => {
1951
+ const { t, sql } = await ready();
1952
+ const set = await buildSet(data);
1953
+ let query = client().update(t).set(set);
1954
+ const w = where(sql, t, filter);
1955
+ if (w) query = query.where(w);
1956
+ return (await query.returning({ id: t.id })).length;
1957
+ }),
1958
+ delete: (id) => guard(async () => {
1959
+ if (!UUID_RE2.test(id)) return;
1960
+ const { t, sql } = await ready();
1961
+ await client().delete(t).where(sql`${t.id} = ${id}`);
1962
+ }),
1963
+ deleteOne: (filter) => guard(async () => {
1964
+ const { t, sql } = await ready();
1965
+ const [row] = await client().delete(t).where(firstMatch(sql, t, filter)).returning();
1966
+ return row ? fromRow(row) : null;
1967
+ }),
1968
+ deleteMany: (filter) => guard(async () => {
1969
+ const { t, sql } = await ready();
1970
+ let query = client().delete(t);
1971
+ const w = where(sql, t, filter);
1972
+ if (w) query = query.where(w);
1973
+ return (await query.returning({ id: t.id })).length;
1974
+ }),
1975
+ count: (filter) => guard(async () => {
1976
+ const { t, sql } = await ready();
1977
+ let query = client().select({ n: sql`count(*)::int` }).from(t);
1978
+ const w = where(sql, t, filter);
1979
+ if (w) query = query.where(w);
1980
+ const [row] = await query;
1981
+ return _nullishCoalesce(_optionalChain([row, 'optionalAccess', _74 => _74.n]), () => ( 0));
1982
+ }),
1983
+ aggregate() {
1984
+ return Promise.reject(
1985
+ new Error(
1986
+ "[EFC] aggregate() is MongoDB-only \u2014 on PostgreSQL use db.query() or Drizzle via Model.raw()"
1987
+ )
1988
+ );
1989
+ },
1990
+ raw: async () => (await compile()).t,
1991
+ sync: (opts) => tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _75 => _75.dryRun]), () => ( false))),
1992
+ drop: () => tbl.drop()
1993
+ };
1994
+ }
1995
+
1996
+ // src/db/model.ts
1997
+ var ENGINE_LABEL = {
1998
+ mongodb: "MongoDB",
1999
+ postgresql: "PostgreSQL"
2000
+ };
2001
+ function defineModel(name, schema, options) {
2002
+ return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
2003
+ }
2004
+ function distinctFields(tree, options) {
2005
+ const ts = timestampFields(options);
2006
+ const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
2007
+ for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
2008
+ return fields;
2009
+ }
2010
+ var MODEL_OPS = [
2011
+ "find",
2012
+ "findById",
2013
+ "findOne",
2014
+ "exists",
2015
+ "distinct",
2016
+ "create",
2017
+ "createMany",
2018
+ "update",
2019
+ "updateOne",
2020
+ "updateMany",
2021
+ "upsert",
2022
+ "delete",
2023
+ "deleteOne",
2024
+ "deleteMany",
2025
+ "count",
2026
+ "aggregate"
2027
+ ];
2028
+ var sortKey = (v) => v instanceof Date ? v.getTime() : v;
2029
+ function createModel(name, schema, options, native) {
2030
+ const tree = normalizeSchema(schema, "model", name);
2031
+ let engineModel;
2032
+ const impl = () => {
2033
+ if (engineModel) return engineModel;
2034
+ const engine2 = getDbEngine();
2035
+ if (native && native.engine !== engine2) {
2036
+ throw new Error(
2037
+ `[EFC] ${name} is a ${ENGINE_LABEL[native.engine]} ${native.kind} (${native.api}) but the app is connected to ${ENGINE_LABEL[engine2]} \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
2038
+ );
2039
+ }
2040
+ engineModel = engine2 === "postgresql" ? pgModel(name, tree, options) : mongoModel(name, tree, options);
2041
+ return engineModel;
2042
+ };
2043
+ const call = (fn) => Promise.resolve().then(() => fn(impl()));
2044
+ const scalarFields = distinctFields(tree, options);
2045
+ const model = {
2046
+ name,
2047
+ find: (filter, opts) => call((m) => m.find(filter, opts)),
2048
+ findById: (id, opts) => call((m) => m.findById(id, opts)),
2049
+ findOne: (filter, opts) => call((m) => m.findOne(filter, opts)),
2050
+ exists: (filter) => call((m) => m.exists(filter)),
2051
+ distinct: (field, filter) => call(async (m) => {
2052
+ if (!scalarFields.has(field)) {
2053
+ if (!(field in tree)) return [];
2054
+ throw new Error(
2055
+ `[EFC] ${name}.distinct('${field}'): only scalar fields are supported, not arrays or objects`
2056
+ );
2057
+ }
2058
+ const values = (await m.distinct(field, filter)).filter((v) => v != null);
2059
+ return values.sort((a, b) => {
2060
+ const x = sortKey(a);
2061
+ const y = sortKey(b);
2062
+ return x < y ? -1 : x > y ? 1 : 0;
2063
+ });
2064
+ }),
2065
+ create: (data) => call((m) => m.create(data)),
2066
+ createMany: (data) => call((m) => m.createMany(data)),
2067
+ update: (id, data) => call((m) => m.update(id, data)),
2068
+ updateOne: (filter, data) => call((m) => m.updateOne(filter, data)),
2069
+ updateMany: (filter, data) => call((m) => m.updateMany(filter, data)),
2070
+ upsert: (filter, create, update) => call(async (m) => {
2071
+ const updated = await m.updateOne(filter, update);
2072
+ if (updated) return updated;
2073
+ try {
2074
+ return await m.create(create);
2075
+ } catch (err) {
2076
+ if (isHttpError(err) && err.statusCode === 409 && !currentTx()) {
2077
+ const retried = await m.updateOne(filter, update);
2078
+ if (retried) return retried;
2079
+ }
2080
+ throw err;
2081
+ }
2082
+ }),
2083
+ delete: (id) => call((m) => m.delete(id)),
2084
+ deleteOne: (filter) => call((m) => m.deleteOne(filter)),
2085
+ deleteMany: (filter) => call((m) => m.deleteMany(filter)),
2086
+ count: (filter) => call((m) => m.count(filter)),
2087
+ aggregate: (pipeline) => call((m) => m.aggregate(pipeline)),
2088
+ raw: () => call((m) => m.raw()),
2089
+ sync: (opts) => call((m) => m.sync(opts)),
2090
+ drop: () => call((m) => m.drop())
2091
+ };
2092
+ _chunkMGH4VDV3cjs.traceOps.call(void 0, name, model, MODEL_OPS);
2093
+ registerModel({
2094
+ name,
2095
+ sync: model.sync,
2096
+ drop: model.drop,
2097
+ findByIds: (ids) => model.find({ id: { $in: ids } }),
2098
+ pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( tableNameFor(name))), idKind: "uuid" })
2099
+ });
2100
+ return model;
2101
+ }
2102
+
2103
+ // src/db/transaction.ts
2104
+ async function transaction(fn) {
2105
+ if (currentTx()) return fn();
2106
+ if (getDbEngine() === "postgresql") {
2107
+ let result;
2108
+ const afterCommit = [];
2109
+ await _chunkMGH4VDV3cjs.getOrm.call(void 0, ).transaction(async (tx) => {
2110
+ result = await runInTx({ engine: "postgresql", tx, afterCommit }, fn);
2111
+ });
2112
+ for (const run of afterCommit) run();
2113
+ return result;
2114
+ }
2115
+ const mg = await loadMongoose();
2116
+ const session = await mg.connection.startSession();
2117
+ try {
2118
+ let result;
2119
+ await session.withTransaction(async () => {
2120
+ result = await runInTx({ engine: "mongodb", session }, fn);
2121
+ });
2122
+ return result;
2123
+ } finally {
2124
+ await session.endSession();
2125
+ }
2126
+ }
2127
+
2128
+ // src/db/table-model.ts
2129
+
2130
+ var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
2131
+ var NUMERIC_KINDS = /* @__PURE__ */ new Set(["double", "integer", "bigint", "numeric"]);
2132
+ var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof RegExp) && typeof v !== "bigint";
2133
+ var likeEscape = (s) => s.replace(/[\\%_]/g, (c) => `\\${c}`);
2134
+ var relAlias = (field) => `efc_rel_${field}`;
2135
+ var incAlias = (name) => `efc_inc_${name}`;
2136
+ var ONE_OPS = /* @__PURE__ */ new Set(["connect", "create", "connectOrCreate", "disconnect"]);
2137
+ var JOIN_OPS = /* @__PURE__ */ new Set([
2138
+ "connect",
2139
+ "create",
2140
+ "connectOrCreate",
2141
+ "disconnect",
2142
+ "set",
2143
+ "push",
2144
+ "pull"
2145
+ ]);
2146
+ var BACK_ONE_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "delete"]);
2147
+ var BACK_MANY_OPS = /* @__PURE__ */ new Set(["connect", "create", "disconnect", "set", "delete", "deleteMany"]);
2148
+ var idJson = (_k, v) => typeof v === "bigint" ? String(v) : v;
2149
+ var aliasSeq = 0;
2150
+ var literal2 = (s) => `'${s.replace(/'/g, "''")}'`;
2151
+ var JSON_PAIRS_PER_CALL = 50;
2152
+ var idText = (v) => v == null ? v : String(v);
2153
+ var dedupe = (items) => {
2154
+ const seen = /* @__PURE__ */ new Set();
2155
+ return items.filter((v) => {
2156
+ const k = String(v);
2157
+ if (seen.has(k)) return false;
2158
+ seen.add(k);
2159
+ return true;
2160
+ });
2161
+ };
2162
+ var TableRuntime = (_class = class {
2163
+ constructor(name, schema, options) {;_class.prototype.__init.call(this);
2164
+ this.name = name;
2165
+ this.options = options;
2166
+ const tree = normalizeSchema(schema, "table", name);
2167
+ this.tbl = pgTable(name, tree, options, { native: true, api: "defineTable" });
2168
+ this.uniqueSets = [["id"]];
2169
+ for (const spec of this.tbl.columns.values()) {
2170
+ if (_optionalChain([spec, 'access', _76 => _76.node, 'optionalAccess', _77 => _77.def, 'access', _78 => _78.unique])) this.uniqueSets.push([spec.field]);
2171
+ }
2172
+ for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
2173
+ if (idx.unique) this.uniqueSets.push(Object.keys(idx.fields));
2174
+ }
2175
+ for (const j of this.tbl.joins.values()) {
2176
+ this.joinSpecs.set(j.field, {
2177
+ field: j.field,
2178
+ column: j.field,
2179
+ kind: "array",
2180
+ item: j.item,
2181
+ ddl: j.ddl,
2182
+ formatted: j.ddl,
2183
+ node: j.node
2184
+ });
2185
+ }
2186
+ }
2187
+
2188
+
2189
+
2190
+
2191
+ /** Many-to-many fields as list columns, so filters and projections treat them alike. */
2192
+ __init() {this.joinSpecs = /* @__PURE__ */ new Map()}
2193
+ fail(path, message) {
2194
+ throw new ModelValidationError(this.name, [{ path, message }]);
2195
+ }
2196
+ spec(field) {
2197
+ return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
2198
+ }
2199
+ join(field) {
2200
+ return this.tbl.joins.get(field);
2201
+ }
2202
+ /** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
2203
+ joinExpr(sql, join, owner) {
2204
+ return sql.raw(
2205
+ `coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${q(join.table)} efc_j where efc_j.owner_id = ${owner}.${q("id")}), '{}'::${join.ddl})`
2206
+ );
2207
+ }
2208
+ col(sql, field, alias) {
2209
+ const join = this.join(field);
2210
+ if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( q(this.tbl.table))));
2211
+ const spec = this.spec(field);
2212
+ return sql.raw(alias ? `${alias}.${q(spec.column)}` : q(spec.column));
2213
+ }
2214
+ /** SELECT items for the many-to-many fields among `fields`, as text arrays. */
2215
+ joinColumns(sql, fields, owner) {
2216
+ return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(q(relAlias(f)))}`);
2217
+ }
2218
+ /** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
2219
+ selectCols(sql, fields, owner) {
2220
+ return sql.join(
2221
+ [
2222
+ ...fields.filter((f) => !this.join(f)).map((f) => this.col(sql, f, owner)),
2223
+ ...this.joinColumns(sql, fields, owner)
2224
+ ],
2225
+ sql`, `
2226
+ );
2227
+ }
2228
+ /** Ids as stored text → the record's type (string uuids, numbers, bigints). */
2229
+ joinValues(join, items) {
2230
+ return items.map(
2231
+ (v) => v == null ? v : join.item === "bigint" ? BigInt(String(v)) : join.item === "integer" ? Number(v) : String(v)
2232
+ );
2233
+ }
2234
+ /** A value for `field`, encoded the way its Drizzle column does it. */
2235
+ val(sql, t, field, value) {
2236
+ const join = this.join(field);
2237
+ if (join) {
2238
+ const items = Array.isArray(value) ? value.map(idText) : value;
2239
+ return sql`${sql.param(items)}::${sql.raw(join.ddl)}`;
2240
+ }
2241
+ return sql`${sql.param(this.tbl.toDb(field, value), t[field])}`;
2242
+ }
2243
+ /** One array element / scalar compared against an array column's items. */
2244
+ itemVal(sql, field, value) {
2245
+ const spec = this.spec(field);
2246
+ const [v] = _nullishCoalesce(this.tbl.toDb(field, [value]), () => ( [value]));
2247
+ return sql`${sql.param(spec.item === "bigint" ? String(v) : v)}`;
2248
+ }
2249
+ fromRaw(t, row) {
2250
+ const keyed = {};
2251
+ for (const join of this.tbl.joins.values()) {
2252
+ const v = row[relAlias(join.field)];
2253
+ if (Array.isArray(v)) keyed[join.field] = this.joinValues(join, v);
2254
+ }
2255
+ for (const spec of this.tbl.columns.values()) {
2256
+ if (!(spec.column in row)) continue;
2257
+ const v = row[spec.column];
2258
+ keyed[spec.field] = v == null ? v : t[spec.field].mapFromDriverValue(v);
2259
+ }
2260
+ return this.tbl.fromRow(keyed);
2261
+ }
2262
+ // ── where ──────────────────────────────────────────────────────────────────
2263
+ /** WHERE for `where`; `alias` qualifies the columns (subqueries, e.g. inside `include`). */
2264
+ where(sql, t, where, alias) {
2265
+ if (!where) return void 0;
2266
+ const parts = [];
2267
+ for (const [key, value] of Object.entries(where)) {
2268
+ if (value === void 0) continue;
2269
+ if (key === "AND" || key === "OR" || key === "NOT") {
2270
+ const list = Array.isArray(value) ? value : [value];
2271
+ const subs = list.map((w) => _nullishCoalesce(this.where(sql, t, w, alias), () => ( sql`true`)));
2272
+ if (key === "AND")
2273
+ parts.push(subs.length ? sql`(${sql.join(subs, sql` and `)})` : sql`true`);
2274
+ else if (key === "OR")
2275
+ parts.push(subs.length ? sql`(${sql.join(subs, sql` or `)})` : sql`false`);
2276
+ else parts.push(subs.length ? sql`not (${sql.join(subs, sql` or `)})` : sql`true`);
2277
+ continue;
2278
+ }
2279
+ const rel = this.relationFilterOf(key, value);
2280
+ if (rel) {
2281
+ parts.push(this.relationFilter(sql, rel, value, alias));
2282
+ continue;
2283
+ }
2284
+ const spec = this.spec(key);
2285
+ if (!spec) {
2286
+ const isNull = value === null || isPlainObject(value) && value["equals"] === null;
2287
+ parts.push(isNull ? sql`true` : sql`false`);
2288
+ continue;
2289
+ }
2290
+ parts.push(this.fieldFilter(sql, t, spec, value, alias));
2291
+ }
2292
+ if (parts.length === 0) return void 0;
2293
+ return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
2294
+ }
2295
+ fieldFilter(sql, t, spec, filter, alias) {
2296
+ const c = this.col(sql, spec.field, alias);
2297
+ if (filter === null) return sql`${c} is null`;
2298
+ if (spec.kind === "jsonb") return this.jsonFilter(sql, t, spec, filter, alias);
2299
+ if (spec.kind === "array") return this.listFilter(sql, t, spec, filter, alias);
2300
+ if (!isPlainObject(filter)) return sql`${c} = ${this.val(sql, t, spec.field, filter)}`;
2301
+ const insensitive = filter["mode"] === "insensitive";
2302
+ const text = spec.kind === "enum" || insensitive ? sql`${c}::text` : c;
2303
+ const parts = [];
2304
+ for (const [op, v] of Object.entries(filter)) {
2305
+ if (v === void 0 || op === "mode") continue;
2306
+ const val = () => this.val(sql, t, spec.field, v);
2307
+ const eq = (x) => insensitive && typeof x === "string" ? sql`lower(${text}) = lower(${sql.param(x)})` : sql`${c} = ${this.val(sql, t, spec.field, x)}`;
2308
+ switch (op) {
2309
+ case "equals":
2310
+ parts.push(v === null ? sql`${c} is null` : eq(v));
2311
+ break;
2312
+ case "not":
2313
+ parts.push(
2314
+ v === null ? sql`${c} is not null` : isPlainObject(v) ? sql`not (${this.fieldFilter(sql, t, spec, { ...v, ...insensitive && { mode: "insensitive" } }, alias)})` : sql`not (${eq(v)})`
2315
+ );
2316
+ break;
2317
+ case "in":
2318
+ case "notIn": {
2319
+ const list = v;
2320
+ if (list.length === 0) {
2321
+ parts.push(op === "in" ? sql`false` : sql`true`);
2322
+ break;
2323
+ }
2324
+ const items = sql.join(
2325
+ list.map((x) => this.val(sql, t, spec.field, x)),
2326
+ sql`, `
2327
+ );
2328
+ parts.push(op === "in" ? sql`${c} in (${items})` : sql`${c} not in (${items})`);
2329
+ break;
2330
+ }
2331
+ case "lt":
2332
+ parts.push(sql`${c} < ${val()}`);
2333
+ break;
2334
+ case "lte":
2335
+ parts.push(sql`${c} <= ${val()}`);
2336
+ break;
2337
+ case "gt":
2338
+ parts.push(sql`${c} > ${val()}`);
2339
+ break;
2340
+ case "gte":
2341
+ parts.push(sql`${c} >= ${val()}`);
2342
+ break;
2343
+ case "contains":
2344
+ case "startsWith":
2345
+ case "endsWith": {
2346
+ const s = likeEscape(String(v));
2347
+ const pattern = op === "contains" ? `%${s}%` : op === "startsWith" ? `${s}%` : `%${s}`;
2348
+ parts.push(
2349
+ insensitive ? sql`${text} ilike ${sql.param(pattern)}` : sql`${text} like ${sql.param(pattern)}`
2350
+ );
2351
+ break;
2352
+ }
2353
+ default:
2354
+ this.fail(spec.field, `unknown filter "${op}"`);
2355
+ }
2356
+ }
2357
+ return parts.length === 0 ? sql`true` : parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
2358
+ }
2359
+ /** Scalar lists (native arrays): has, hasEvery, hasSome, isEmpty, equals. */
2360
+ listFilter(sql, t, spec, filter, alias) {
2361
+ const c = this.col(sql, spec.field, alias);
2362
+ if (!isPlainObject(filter)) return sql`${c} = ${this.val(sql, t, spec.field, filter)}`;
2363
+ const parts = [];
2364
+ for (const [op, v] of Object.entries(filter)) {
2365
+ if (v === void 0) continue;
2366
+ switch (op) {
2367
+ case "equals":
2368
+ parts.push(
2369
+ v === null ? sql`${c} is null` : sql`${c} = ${this.val(sql, t, spec.field, v)}`
2370
+ );
2371
+ break;
2372
+ case "has":
2373
+ parts.push(
2374
+ v === null ? sql`false` : sql`${this.itemVal(sql, spec.field, v)} = any(${c})`
2375
+ );
2376
+ break;
2377
+ case "hasEvery":
2378
+ parts.push(sql`${c} @> ${this.val(sql, t, spec.field, v)}`);
2379
+ break;
2380
+ case "hasSome":
2381
+ parts.push(sql`${c} && ${this.val(sql, t, spec.field, v)}`);
2382
+ break;
2383
+ case "isEmpty":
2384
+ parts.push(v ? sql`cardinality(${c}) = 0` : sql`cardinality(${c}) > 0`);
2385
+ break;
2386
+ default:
2387
+ this.fail(spec.field, `unknown list filter "${op}"`);
2388
+ }
2389
+ }
2390
+ return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
2391
+ }
2392
+ /** jsonb fields (embedded objects / arrays of objects / json): Prisma's JSON filters. */
2393
+ jsonFilter(sql, t, spec, filter, alias) {
2394
+ const c = this.col(sql, spec.field, alias);
2395
+ const json = (v) => sql`${sql.param(JSON.stringify(v))}::jsonb`;
2396
+ if (!isPlainObject(filter) || !Object.keys(filter).some((k) => JSON_OPS.has(k))) {
2397
+ return sql`${c} = ${json(filter)}`;
2398
+ }
2399
+ const path = filter["path"];
2400
+ const segs = path === void 0 ? [] : Array.isArray(path) ? path : String(path).split(".");
2401
+ const target = segs.length ? sql`(${c} #> ${sql.param(`{${segs.join(",")}}`)})` : c;
2402
+ const textTarget = segs.length ? sql`(${c} #>> ${sql.param(`{${segs.join(",")}}`)})` : sql`(${c} #>> '{}')`;
2403
+ const parts = [];
2404
+ for (const [op, v] of Object.entries(filter)) {
2405
+ if (v === void 0 || op === "path" || op === "mode") continue;
2406
+ switch (op) {
2407
+ case "equals":
2408
+ parts.push(v === null ? sql`${target} is null` : sql`${target} = ${json(v)}`);
2409
+ break;
2410
+ case "not":
2411
+ parts.push(
2412
+ v === null ? sql`${target} is not null` : sql`${target} is distinct from ${json(v)}`
2413
+ );
2414
+ break;
2415
+ case "string_contains":
2416
+ case "string_starts_with":
2417
+ case "string_ends_with": {
2418
+ const s = likeEscape(String(v));
2419
+ const p = op === "string_contains" ? `%${s}%` : op === "string_starts_with" ? `${s}%` : `%${s}`;
2420
+ parts.push(
2421
+ filter["mode"] === "insensitive" ? sql`${textTarget} ilike ${sql.param(p)}` : sql`${textTarget} like ${sql.param(p)}`
2422
+ );
2423
+ break;
2424
+ }
2425
+ case "array_contains":
2426
+ parts.push(sql`${target} @> ${json(Array.isArray(v) ? v : [v])}`);
2427
+ break;
2428
+ case "gt":
2429
+ case "gte":
2430
+ case "lt":
2431
+ case "lte": {
2432
+ const opSql = { gt: ">", gte: ">=", lt: "<", lte: "<=" }[op];
2433
+ parts.push(
2434
+ typeof v === "number" ? sql`(${textTarget})::double precision ${sql.raw(opSql)} ${sql.param(v)}` : sql`${textTarget} ${sql.raw(opSql)} ${sql.param(v instanceof Date ? v.toISOString() : String(v))}`
2435
+ );
2436
+ break;
2437
+ }
2438
+ default:
2439
+ this.fail(spec.field, `unknown JSON filter "${op}"`);
2440
+ }
2441
+ }
2442
+ return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
2443
+ }
2444
+ // ── ordering, projection, pagination ───────────────────────────────────────
2445
+ orderList(orderBy) {
2446
+ const list = orderBy === void 0 ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];
2447
+ const out = [];
2448
+ for (const entry of list) {
2449
+ for (const [field, dir] of Object.entries(entry)) {
2450
+ if (dir === void 0 || !this.spec(field)) continue;
2451
+ if (this.join(field)) this.fail(`orderBy.${field}`, "can't order by a many-to-many field");
2452
+ if (isPlainObject(dir))
2453
+ out.push({ field, desc: dir["sort"] === "desc", nulls: dir["nulls"] });
2454
+ else out.push({ field, desc: dir === "desc" });
2455
+ }
2456
+ }
2457
+ return out;
2458
+ }
2459
+ orderSql(sql, list, alias) {
2460
+ return sql.join(
2461
+ list.map(
2462
+ (o) => sql`${this.col(sql, o.field, alias)} ${sql.raw(o.desc ? "desc" : "asc")}${o.nulls ? sql.raw(` nulls ${o.nulls}`) : sql``}`
2463
+ ),
2464
+ sql`, `
2465
+ );
2466
+ }
2467
+ /** The fields a result keeps, from `select` / `omit`. */
2468
+ projection(args) {
2469
+ const all = [...this.tbl.columns.keys(), ...this.tbl.joins.keys()];
2470
+ if (args["select"] && args["omit"]) this.fail("select", "use either select or omit, not both");
2471
+ if (args["select"]) {
2472
+ const keep = Object.entries(args["select"]).filter(([f, on]) => on && this.spec(f)).map(([f]) => f);
2473
+ return keep;
2474
+ }
2475
+ if (args["omit"]) {
2476
+ const drop = new Set(
2477
+ Object.entries(args["omit"]).filter(([, on]) => on).map(([f]) => f)
2478
+ );
2479
+ return all.filter((f) => !drop.has(f));
2480
+ }
2481
+ return all;
2482
+ }
2483
+ project(record, fields) {
2484
+ const out = {};
2485
+ for (const f of fields) if (record[f] !== void 0) out[f] = record[f];
2486
+ return out;
2487
+ }
2488
+ /** Checks `where` names a unique key (id, a unique field, or a compound unique index). */
2489
+ uniqueKey(where, op) {
2490
+ const plain = (f) => _optionalChain([where, 'optionalAccess', _79 => _79[f]]) !== void 0 && where[f] !== null && !isPlainObject(where[f]);
2491
+ const key = this.uniqueSets.find((set) => set.every(plain));
2492
+ if (!key) {
2493
+ this.fail(
2494
+ "where",
2495
+ `${op} needs a unique field in where: ${this.uniqueSets.map((s) => s.join(" + ")).join(", ")}`
2496
+ );
2497
+ }
2498
+ return key;
2499
+ }
2500
+ /** WHERE for findMany-style reads: filter, plus the cursor's keyset condition. */
2501
+ readWhere(sql, t, args, order) {
2502
+ const parts = [];
2503
+ const w = this.where(sql, t, args["where"]);
2504
+ if (w) parts.push(w);
2505
+ if (args["cursor"]) {
2506
+ this.uniqueKey(args["cursor"], "cursor");
2507
+ const cw = this.where(sql, t, args["cursor"]);
2508
+ const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(q(this.tbl.table))} where ${cw})`;
2509
+ const ors = [];
2510
+ const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
2511
+ for (let i = 0; i < order.length; i++) {
2512
+ const o = order[i];
2513
+ const c = this.col(sql, o.field);
2514
+ const v = at(o.field);
2515
+ const nullsFirst = o.nulls ? o.nulls === "first" : o.desc;
2516
+ const after = sql`((${v} is null and ${nullsFirst ? sql`${c} is not null` : sql`false`}) or (${v} is not null and (${c} ${sql.raw(o.desc ? "<" : ">")} ${v}${nullsFirst ? sql`` : sql` or ${c} is null`})))`;
2517
+ const eqs = order.slice(0, i).map(same);
2518
+ ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
2519
+ }
2520
+ ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
2521
+ parts.push(sql`exists (select 1 from ${sql.raw(q(this.tbl.table))} where ${cw})`);
2522
+ parts.push(sql`(${sql.join(ors, sql` or `)})`);
2523
+ }
2524
+ return parts.length ? sql.join(parts, sql` and `) : sql`true`;
2525
+ }
2526
+ /** SELECT for a findMany-style read, and whether the rows come back reversed. */
2527
+ readQuery(sql, t, args, columnsSql) {
2528
+ const take = args["take"];
2529
+ const reversed = take !== void 0 && take < 0;
2530
+ let order = this.orderList(args["orderBy"]);
2531
+ const paged = args["cursor"] || take !== void 0 || args["skip"];
2532
+ if (paged && !order.some((o) => o.field === "id")) {
2533
+ order = [...order, { field: "id", desc: false }];
2534
+ }
2535
+ if (reversed) {
2536
+ order = order.map((o) => ({
2537
+ ...o,
2538
+ desc: !o.desc,
2539
+ ...o.nulls && { nulls: o.nulls === "first" ? "last" : "first" }
2540
+ }));
2541
+ }
2542
+ const limit = take === void 0 ? sql`` : sql` limit ${sql.param(Math.abs(take))}`;
2543
+ const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
2544
+ const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
2545
+ const where = this.readWhere(sql, t, args, order);
2546
+ const from = sql.raw(q(this.tbl.table));
2547
+ const distinct = _optionalChain([args, 'access', _80 => _80["distinct"], 'optionalAccess', _81 => _81.filter, 'call', _82 => _82((f) => this.spec(f))]);
2548
+ if (_optionalChain([distinct, 'optionalAccess', _83 => _83.length])) {
2549
+ const dcols = sql.join(
2550
+ distinct.map((f) => this.col(sql, f)),
2551
+ sql`, `
2552
+ );
2553
+ const inner = sql`select distinct on (${dcols}) * from ${from} where ${where} order by ${dcols}${order.length ? sql`, ${this.orderSql(sql, order)}` : sql``}`;
2554
+ return {
2555
+ query: sql`select ${columnsSql} from (${inner}) as efc_distinct${orderBy}${limit}${offset}`,
2556
+ reversed
2557
+ };
2558
+ }
2559
+ return {
2560
+ query: sql`select ${columnsSql} from ${from} where ${where}${orderBy}${limit}${offset}`,
2561
+ reversed
2562
+ };
2563
+ }
2564
+ // ── reads ──────────────────────────────────────────────────────────────────
2565
+ async findMany(args = {}) {
2566
+ const { t, sql } = await this.ready(args["where"], args["cursor"]);
2567
+ return this.tbl.guard(async () => {
2568
+ const fields = this.projection(args);
2569
+ const distinct = _optionalChain([args, 'access', _84 => _84["distinct"], 'optionalAccess', _85 => _85.some, 'call', _86 => _86((f) => this.spec(f))]);
2570
+ const cols = this.selectCols(
2571
+ sql,
2572
+ [.../* @__PURE__ */ new Set(["id", ...fields])],
2573
+ distinct ? "efc_distinct" : void 0
2574
+ );
2575
+ const include = this.includeArg(args);
2576
+ const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : q(this.tbl.table), 1) : [];
2577
+ const { query, reversed } = this.readQuery(
2578
+ sql,
2579
+ t,
2580
+ args,
2581
+ included.length ? sql`${cols}, ${sql.join(included, sql`, `)}` : cols
2582
+ );
2583
+ const rows = (await this.tbl.client().execute(query)).rows.map((r) => {
2584
+ const record = this.project(this.fromRaw(t, r), fields);
2585
+ if (include) this.attachIncludes(record, r, include);
2586
+ return record;
2587
+ });
2588
+ return reversed ? rows.reverse() : rows;
2589
+ });
2590
+ }
2591
+ // ── include ────────────────────────────────────────────────────────────────
2592
+
2593
+ /** What `include` can name on this model. */
2594
+ relations() {
2595
+ if (this.relationCache) return this.relationCache;
2596
+ const out = /* @__PURE__ */ new Map();
2597
+ for (const spec of this.tbl.columns.values()) {
2598
+ const ref = _optionalChain([spec, 'access', _87 => _87.node, 'optionalAccess', _88 => _88.kind]) === "scalar" ? spec.node.def.ref : void 0;
2599
+ if (ref)
2600
+ out.set(spec.field, {
2601
+ name: spec.field,
2602
+ kind: "one",
2603
+ via: "fk",
2604
+ target: ref,
2605
+ column: spec.column
2606
+ });
2607
+ }
2608
+ for (const join of this.tbl.joins.values()) {
2609
+ out.set(join.field, {
2610
+ name: join.field,
2611
+ kind: "many",
2612
+ via: "join",
2613
+ target: join.target,
2614
+ join
2615
+ });
2616
+ }
2617
+ for (const [name, def] of Object.entries(_nullishCoalesce(this.options.relations, () => ( {})))) {
2618
+ out.set(name, {
2619
+ name,
2620
+ kind: def.hasOne ? "one" : "many",
2621
+ via: "back",
2622
+ target: _nullishCoalesce(def.hasOne, () => ( def.hasMany)),
2623
+ foreignKey: def.foreignKey
2624
+ });
2625
+ }
2626
+ return this.relationCache = out;
2627
+ }
2628
+ relation(name) {
2629
+ const rel = this.relations().get(name);
2630
+ if (!rel) {
2631
+ const known = [...this.relations().keys()];
2632
+ this.fail(
2633
+ `include.${name}`,
2634
+ known.length ? `not a relation of ${this.name} (relations: ${known.join(", ")})` : `${this.name} has no relations \u2014 add a ref field or options.relations`
2635
+ );
2636
+ }
2637
+ return rel;
2638
+ }
2639
+ includeArg(args) {
2640
+ const include = args["include"];
2641
+ if (include === void 0) return void 0;
2642
+ if (!isPlainObject(include)) this.fail("include", "must be an object");
2643
+ return Object.values(include).some(Boolean) ? include : void 0;
2644
+ }
2645
+ /** SELECT items loading `include` for rows of this table aliased `owner`. */
2646
+ async includeColumns(sql, include, owner, depth) {
2647
+ const out = [];
2648
+ for (const [name, arg] of Object.entries(include)) {
2649
+ if (!arg) continue;
2650
+ const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
2651
+ out.push(sql`${expr} as ${sql.raw(q(incAlias(name)))}`);
2652
+ }
2653
+ return out;
2654
+ }
2655
+ /**
2656
+ * One relation as a correlated subquery yielding jsonb: a record (or null) for one, an
2657
+ * array of records for many. Nested includes nest inside it, so a read is one statement.
2658
+ */
2659
+ async relationExpr(sql, rel, args, owner, depth) {
2660
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2661
+ const { t } = await T.ready(args["where"]);
2662
+ const a = `efc_r${depth}`;
2663
+ const obj = await T.jsonRecord(sql, t, args, a, depth + 1);
2664
+ const { from, cond, defaultOrder } = this.relationSource(rel, owner, a, `efc_j${depth}`);
2665
+ if (rel.via === "fk") return sql`(select ${obj} from ${sql.raw(from)} where ${sql.raw(cond)})`;
2666
+ if (rel.kind === "one") {
2667
+ return sql`(select ${obj} from ${sql.raw(from)} where ${sql.raw(cond)} limit 1)`;
2668
+ }
2669
+ const where = T.where(sql, t, args["where"], a);
2670
+ const order = args["orderBy"] ? T.orderSql(sql, T.orderList(args["orderBy"]), a) : sql.raw(defaultOrder);
2671
+ const take = args["take"];
2672
+ if (take !== void 0 && (!Number.isInteger(take) || take < 0)) {
2673
+ this.fail(`include.${rel.name}.take`, "must be a whole number \u2265 0 inside include");
2674
+ }
2675
+ const s = `efc_s${depth}`;
2676
+ return sql`coalesce((select jsonb_agg(${sql.raw(`${s}.o order by ${s}.n`)}) from (select ${obj} as o, row_number() over (order by ${order}) as n from ${sql.raw(from)} where ${sql.raw(cond)}${where ? sql` and ${where}` : sql``} order by ${order}${take !== void 0 ? sql` limit ${sql.param(take)}` : sql``}${args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``}) ${sql.raw(s)}), '[]'::jsonb)`;
2677
+ }
2678
+ /**
2679
+ * Where a relation's records come from, for rows of this table aliased `owner`: the FROM
2680
+ * (target aliased `a`, plus its join table aliased `j` when there is one) and the
2681
+ * condition tying them to the owner row.
2682
+ */
2683
+ relationSource(rel, owner, a, j) {
2684
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2685
+ const target = `${q(T.tbl.table)} ${a}`;
2686
+ const ownerId = `${owner}.${q("id")}`;
2687
+ if (rel.via === "fk") {
2688
+ return {
2689
+ T,
2690
+ from: target,
2691
+ cond: `${a}.${q("id")} = ${owner}.${q(rel.column)}`,
2692
+ defaultOrder: `${a}.${q("id")}`
2693
+ };
2694
+ }
2695
+ let from;
2696
+ let cond;
2697
+ let defaultOrder;
2698
+ if (rel.via === "join") {
2699
+ from = `${q(rel.join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.ref_id`;
2700
+ cond = `${j}.owner_id = ${ownerId}`;
2701
+ defaultOrder = `${j}.position`;
2702
+ } else {
2703
+ const join = T.tbl.joins.get(rel.foreignKey);
2704
+ const column = T.tbl.columns.get(rel.foreignKey);
2705
+ const refs = join ? join.target : _optionalChain([column, 'optionalAccess', _89 => _89.node, 'optionalAccess', _90 => _90.kind]) === "scalar" && column.node.def.ref;
2706
+ if (refs !== this.name) {
2707
+ throw new Error(
2708
+ `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} must be a ref to ${this.name}`
2709
+ );
2710
+ }
2711
+ if (join) {
2712
+ if (rel.kind === "one") {
2713
+ throw new Error(
2714
+ `[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
2715
+ );
2716
+ }
2717
+ from = `${q(join.table)} ${j} join ${target} on ${a}.${q("id")} = ${j}.owner_id`;
2718
+ cond = `${j}.ref_id = ${ownerId}`;
2719
+ } else {
2720
+ if (rel.kind === "one" && !column.node.def.unique) {
2721
+ throw new Error(
2722
+ `[EFC] ${this.name}.${rel.name}: hasOne needs ${rel.target}.${rel.foreignKey} to be unique (one ${rel.target} per ${this.name}) \u2014 or use hasMany`
2723
+ );
2724
+ }
2725
+ from = target;
2726
+ cond = `${a}.${q(column.column)} = ${ownerId}`;
2727
+ }
2728
+ defaultOrder = `${a}.${q("id")}`;
2729
+ }
2730
+ return { T, from, cond, defaultOrder };
2731
+ }
2732
+ // ── nested writes ──────────────────────────────────────────────────────────
2733
+ /** Whether `data` writes related records (connect / create / … on a relation). */
2734
+ hasNested(data) {
2735
+ if (!isPlainObject(data)) return false;
2736
+ return Object.entries(data).some(([key, v]) => {
2737
+ const rel = this.relations().get(key);
2738
+ if (!rel || v === void 0) return false;
2739
+ if (rel.via === "back") return true;
2740
+ if (!isPlainObject(v)) return false;
2741
+ if (rel.via === "fk") return true;
2742
+ const keys = Object.keys(v);
2743
+ if (keys.some((k) => !["set", "push", "pull"].includes(k))) return true;
2744
+ return rel.via === "join" && Array.isArray(v["set"]) && v["set"].some(isPlainObject);
2745
+ });
2746
+ }
2747
+ /** The id of the `rel` record a unique where (or a bare id) names; 400 when none does. */
2748
+ async connectId(rel, w, path) {
2749
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2750
+ const where = isPlainObject(w) ? w : { id: w };
2751
+ const found = await T.findUnique({ where, select: { id: true } });
2752
+ if (!found) {
2753
+ throw new ModelValidationError(this.name, [
2754
+ { path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
2755
+ ]);
2756
+ }
2757
+ return found["id"];
2758
+ }
2759
+ async connectOrCreateId(rel, arg, path) {
2760
+ if (!isPlainObject(arg) || !isPlainObject(arg["where"]) || !isPlainObject(arg["create"])) {
2761
+ this.fail(path, "connectOrCreate needs { where, create }");
2762
+ }
2763
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2764
+ const found = await T.findUnique({ where: arg["where"], select: { id: true } });
2765
+ return found ? found["id"] : (await T.createNested({ data: arg["create"] }))["id"];
2766
+ }
2767
+ /**
2768
+ * Splits nested relation writes out of `data`: own refs and many-to-many fields are
2769
+ * resolved to ids before the row is written; back-relations become steps to run with
2770
+ * the owner's id afterwards. Runs inside the caller's transaction.
2771
+ */
2772
+ async resolveNested(data, mode) {
2773
+ const out = { ...data };
2774
+ const after = [];
2775
+ const list = (v) => v === void 0 ? [] : Array.isArray(v) ? v : [v];
2776
+ for (const [key, v] of Object.entries(data)) {
2777
+ const rel = this.relations().get(key);
2778
+ if (!rel || v === void 0) continue;
2779
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2780
+ const ops = isPlainObject(v) ? v : void 0;
2781
+ for (const op of Object.keys(_nullishCoalesce(ops, () => ( {})))) {
2782
+ const allowed = rel.via === "fk" ? ONE_OPS : rel.via === "join" ? JOIN_OPS : rel.kind === "one" ? BACK_ONE_OPS : BACK_MANY_OPS;
2783
+ if (!allowed.has(op)) {
2784
+ this.fail(key, `"${op}" isn't a nested write here (use ${[...allowed].join(", ")})`);
2785
+ }
2786
+ }
2787
+ if (rel.via === "fk") {
2788
+ if (!ops) continue;
2789
+ if (ops["disconnect"]) {
2790
+ if (mode === "create") this.fail(key, "disconnect only applies to updates");
2791
+ out[key] = null;
2792
+ } else if (ops["connect"] !== void 0) {
2793
+ out[key] = await this.connectId(rel, ops["connect"], key);
2794
+ } else if (ops["connectOrCreate"] !== void 0) {
2795
+ out[key] = await this.connectOrCreateId(rel, ops["connectOrCreate"], key);
2796
+ } else if (ops["create"] !== void 0) {
2797
+ out[key] = (await T.createNested({ data: ops["create"] }))["id"];
2798
+ }
2799
+ continue;
2800
+ }
2801
+ if (rel.via === "join") {
2802
+ if (!ops || !this.hasNested({ [key]: v })) continue;
2803
+ const ids = async (items) => {
2804
+ const got = [];
2805
+ for (const w of items) got.push(await this.connectId(rel, w, key));
2806
+ return got;
2807
+ };
2808
+ const added = await ids(list(ops["connect"]));
2809
+ for (const a of list(ops["connectOrCreate"])) {
2810
+ added.push(await this.connectOrCreateId(rel, a, key));
2811
+ }
2812
+ for (const c of list(ops["create"])) added.push((await T.createNested({ data: c }))["id"]);
2813
+ const removed = [];
2814
+ for (const w of list(ops["disconnect"])) {
2815
+ const where = isPlainObject(w) ? w : { id: w };
2816
+ const found = await T.findUnique({ where, select: { id: true } });
2817
+ if (found) removed.push(found["id"]);
2818
+ }
2819
+ const gone = new Set(removed.map(String));
2820
+ if (ops["set"] !== void 0 || mode === "create") {
2821
+ const base = ops["set"] === void 0 ? [] : await ids(list(ops["set"]));
2822
+ const all = dedupe([...base, ...added]).filter((x) => !gone.has(String(x)));
2823
+ out[key] = mode === "create" ? all : { set: all };
2824
+ } else {
2825
+ out[key] = {
2826
+ ...added.length && { push: added },
2827
+ ...removed.length && { pull: removed }
2828
+ };
2829
+ }
2830
+ continue;
2831
+ }
2832
+ delete out[key];
2833
+ const fk = rel.foreignKey;
2834
+ const many = T.tbl.joins.has(fk);
2835
+ const mine = (owner) => many ? { [fk]: { has: owner } } : { [fk]: owner };
2836
+ const whereOf = (w) => isPlainObject(w) ? w : { id: w };
2837
+ const link = async (owner, w) => {
2838
+ if (many) {
2839
+ const id = await this.connectId(rel, w, key);
2840
+ await T.updateNested({ where: { id }, data: { [fk]: { push: owner } } });
2841
+ } else {
2842
+ try {
2843
+ await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
2844
+ } catch (err) {
2845
+ if (isHttpError(err) && err.statusCode === 404) {
2846
+ throw new ModelValidationError(this.name, [
2847
+ {
2848
+ path: key,
2849
+ message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
2850
+ }
2851
+ ]);
2852
+ }
2853
+ throw err;
2854
+ }
2855
+ }
2856
+ };
2857
+ const unlink = (owner, where) => many ? T.updateManyLinks(fk, owner, where) : T.updateMany(
2858
+ { where: { AND: [mine(owner), ...where ? [where] : []] }, data: { [fk]: null } },
2859
+ false
2860
+ );
2861
+ const createChild = (owner, c) => {
2862
+ if (!isPlainObject(c)) this.fail(key, "create needs record data");
2863
+ return T.createNested({ data: { ...c, [fk]: many ? [owner] : owner } });
2864
+ };
2865
+ after.push(async (owner) => {
2866
+ if (rel.kind === "one") {
2867
+ if (mode === "update" && (_optionalChain([ops, 'optionalAccess', _91 => _91["create"]]) || _optionalChain([ops, 'optionalAccess', _92 => _92["connect"]]) || _optionalChain([ops, 'optionalAccess', _93 => _93["disconnect"]]))) {
2868
+ await unlink(owner);
2869
+ }
2870
+ if (_optionalChain([ops, 'optionalAccess', _94 => _94["delete"]])) await T.deleteMany({ where: mine(owner) });
2871
+ if (_optionalChain([ops, 'optionalAccess', _95 => _95["connect"]]) !== void 0) await link(owner, ops["connect"]);
2872
+ if (_optionalChain([ops, 'optionalAccess', _96 => _96["create"]]) !== void 0) await createChild(owner, ops["create"]);
2873
+ return;
2874
+ }
2875
+ if (_optionalChain([ops, 'optionalAccess', _97 => _97["set"]]) !== void 0) {
2876
+ const keep = list(ops["set"]).map(whereOf);
2877
+ await unlink(owner, keep.length ? { NOT: { OR: keep } } : void 0);
2878
+ for (const w of keep) await link(owner, w);
2879
+ }
2880
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _98 => _98["disconnect"]]))) await unlink(owner, whereOf(w));
2881
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _99 => _99["delete"]])))
2882
+ await T.deleteMany({ where: { AND: [mine(owner), whereOf(w)] } });
2883
+ if (_optionalChain([ops, 'optionalAccess', _100 => _100["deleteMany"]]) !== void 0) {
2884
+ for (const w of list(ops["deleteMany"])) {
2885
+ await T.deleteMany({ where: { AND: [mine(owner), ...isPlainObject(w) ? [w] : []] } });
2886
+ }
2887
+ }
2888
+ for (const w of list(_optionalChain([ops, 'optionalAccess', _101 => _101["connect"]]))) await link(owner, w);
2889
+ for (const c of list(_optionalChain([ops, 'optionalAccess', _102 => _102["create"]]))) await createChild(owner, c);
2890
+ });
2891
+ }
2892
+ return { data: out, after };
2893
+ }
2894
+ /** Removes `owner` from the many-to-many field `fk` of the records `where` matches. */
2895
+ async updateManyLinks(fk, owner, where) {
2896
+ const matches = await this.findMany({
2897
+ where: { AND: [{ [fk]: { has: owner } }, ...where ? [where] : []] },
2898
+ select: { id: true }
2899
+ });
2900
+ const { sql } = await this.ready();
2901
+ await this.applyJoins(
2902
+ sql,
2903
+ matches.map((m) => ({ id: m["id"], ops: [{ field: fk, mode: "pull", items: [owner] }] }))
2904
+ );
2905
+ }
2906
+ /** Runs a write whose data may hold nested writes, all in one transaction. */
2907
+ withNested(data, mode, write) {
2908
+ if (!this.hasNested(data)) return write(data);
2909
+ return transaction(async () => {
2910
+ const { data: plain, after } = await this.resolveNested(data, mode);
2911
+ const record = await write(plain);
2912
+ for (const step of after) await step(record["id"]);
2913
+ return record;
2914
+ });
2915
+ }
2916
+ createNested(args) {
2917
+ return this.withNested(args["data"], "create", (data) => this.create({ ...args, data }));
2918
+ }
2919
+ updateNested(args) {
2920
+ return this.withNested(args["data"], "update", (data) => this.update({ ...args, data }));
2921
+ }
2922
+ /** upsert with nested writes: find, then update or create — in one transaction. */
2923
+ async upsertNested(args) {
2924
+ if (!this.hasNested(args["create"]) && !this.hasNested(args["update"]))
2925
+ return this.upsert(args);
2926
+ this.uniqueKey(args["where"], "upsert");
2927
+ return transaction(async () => {
2928
+ const found = await this.findUnique({ where: args["where"], select: { id: true } });
2929
+ const { create, update, where, ...rest } = args;
2930
+ if (found)
2931
+ return this.updateNested({ ...rest, where: { id: found["id"] }, data: _nullishCoalesce(update, () => ( {})) });
2932
+ const key = this.uniqueKey(where, "upsert");
2933
+ const data = { ...create };
2934
+ for (const f of key) if (data[f] === void 0) data[f] = where[f];
2935
+ return this.createNested({ ...rest, data });
2936
+ });
2937
+ }
2938
+ /** createMany / updateMany write rows only, as in Prisma. */
2939
+ noNested(data, op) {
2940
+ for (const d of Array.isArray(data) ? data : [data]) {
2941
+ if (this.hasNested(d))
2942
+ this.fail(
2943
+ "data",
2944
+ `${op} doesn't take nested writes \u2014 use ${op === "updateMany" ? "update" : "create"}`
2945
+ );
2946
+ }
2947
+ }
2948
+ // ── relation filters ───────────────────────────────────────────────────────
2949
+ /** The compiled Drizzle table, once `ready()` has run (relation filters need it sync). */
2950
+
2951
+ /**
2952
+ * Compiles (and auto-syncs) this table, and every table a relation filter in `wheres`
2953
+ * reaches, so `where()` can build those filters synchronously.
2954
+ */
2955
+ async ready(...wheres) {
2956
+ const out = await this.tbl.ready();
2957
+ this.t = out.t;
2958
+ for (const w of wheres) await this.prepareWhere(w);
2959
+ return out;
2960
+ }
2961
+ async prepareWhere(where) {
2962
+ if (!isPlainObject(where)) return;
2963
+ for (const [key, value] of Object.entries(where)) {
2964
+ if (key === "AND" || key === "OR" || key === "NOT") {
2965
+ for (const w of Array.isArray(value) ? value : [value]) await this.prepareWhere(w);
2966
+ continue;
2967
+ }
2968
+ const rel = this.relationFilterOf(key, value);
2969
+ if (!rel) continue;
2970
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
2971
+ for (const sub of Object.values(value)) await T.ready(sub);
2972
+ }
2973
+ }
2974
+ /** The relation `where.key` filters on, when `value` is a relation filter. */
2975
+ relationFilterOf(key, value) {
2976
+ const rel = this.relations().get(key);
2977
+ if (!rel) return void 0;
2978
+ const ops = rel.kind === "many" ? ["some", "every", "none"] : ["is", "isNot"];
2979
+ const keys = isPlainObject(value) ? Object.keys(value) : [];
2980
+ const isFilter = keys.length > 0 && keys.every((k) => ops.includes(k));
2981
+ if (!isFilter && rel.via === "back") {
2982
+ this.fail(`where.${key}`, `filter a relation with ${ops.join(" / ")}`);
2983
+ }
2984
+ return isFilter ? rel : void 0;
2985
+ }
2986
+ /** some / every / none, is / isNot → EXISTS subqueries on the related table. */
2987
+ relationFilter(sql, rel, filter, owner) {
2988
+ const a = `efc_f${++aliasSeq}`;
2989
+ const { T, from, cond } = this.relationSource(
2990
+ rel,
2991
+ _nullishCoalesce(owner, () => ( q(this.tbl.table))),
2992
+ a,
2993
+ `efc_fj${aliasSeq}`
2994
+ );
2995
+ if (T.t === void 0) {
2996
+ throw new Error(
2997
+ `[EFC] ${this.name}: relation filter on ${rel.name} before its table was ready`
2998
+ );
2999
+ }
3000
+ const exists = (w, negate = false) => {
3001
+ const inner = isPlainObject(w) ? T.where(sql, T.t, w, a) : void 0;
3002
+ const extra = inner ? negate ? sql` and not (${inner})` : sql` and ${inner}` : negate ? sql` and false` : sql``;
3003
+ return sql`exists (select 1 from ${sql.raw(from)} where ${sql.raw(cond)}${extra})`;
3004
+ };
3005
+ const parts = [];
3006
+ for (const [op, w] of Object.entries(filter)) {
3007
+ if (w === void 0) continue;
3008
+ switch (op) {
3009
+ case "some":
3010
+ parts.push(exists(w));
3011
+ break;
3012
+ case "none":
3013
+ parts.push(sql`not ${exists(w)}`);
3014
+ break;
3015
+ case "every":
3016
+ parts.push(sql`not ${exists(w, true)}`);
3017
+ break;
3018
+ case "is":
3019
+ parts.push(w === null ? sql`not ${exists(void 0)}` : exists(w));
3020
+ break;
3021
+ case "isNot":
3022
+ parts.push(w === null ? exists(void 0) : sql`not ${exists(w)}`);
3023
+ break;
3024
+ }
3025
+ }
3026
+ return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
3027
+ }
3028
+ /** A record of this table (aliased `alias`) as jsonb, with its own includes. */
3029
+ async jsonRecord(sql, t, args, alias, depth) {
3030
+ const include = this.includeArg(args);
3031
+ const pairs = [];
3032
+ for (const f of this.projection(args)) {
3033
+ if (_optionalChain([include, 'optionalAccess', _103 => _103[f]])) continue;
3034
+ pairs.push(sql`${sql.raw(literal2(f))}, ${this.jsonValue(sql, f, alias)}`);
3035
+ }
3036
+ for (const [name, arg] of Object.entries(_nullishCoalesce(include, () => ( {})))) {
3037
+ if (!arg) continue;
3038
+ const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), alias, depth);
3039
+ pairs.push(sql`${sql.raw(literal2(name))}, ${expr}`);
3040
+ }
3041
+ if (pairs.length === 0) return sql`'{}'::jsonb`;
3042
+ const chunks = [];
3043
+ for (let i = 0; i < pairs.length; i += JSON_PAIRS_PER_CALL) {
3044
+ chunks.push(
3045
+ sql`jsonb_build_object(${sql.join(pairs.slice(i, i + JSON_PAIRS_PER_CALL), sql`, `)})`
3046
+ );
3047
+ }
3048
+ return sql.join(chunks, sql` || `);
3049
+ }
3050
+ // JSON can't hold bigints exactly, NaN/Infinity or decimals verbatim: send those as text.
3051
+ jsonValue(sql, field, alias) {
3052
+ const c = this.col(sql, field, alias);
3053
+ const spec = this.spec(field);
3054
+ if (this.join(field)) return sql`${c}::text[]`;
3055
+ const textual = (k) => k === "bigint" || k === "double" || k === "numeric";
3056
+ if (spec.kind === "array") return textual(spec.item) ? sql`${c}::text[]` : c;
3057
+ return textual(spec.kind) ? sql`${c}::text` : c;
3058
+ }
3059
+ /** A record from `jsonRecord` → the same record a direct read returns. */
3060
+ fromJson(json, args) {
3061
+ const include = this.includeArg(args);
3062
+ const keyed = {};
3063
+ for (const f of this.projection(args)) {
3064
+ if (_optionalChain([include, 'optionalAccess', _104 => _104[f]])) continue;
3065
+ const v = json[f];
3066
+ const join = this.join(f);
3067
+ if (v == null || join) {
3068
+ keyed[f] = join && Array.isArray(v) ? this.joinValues(join, v) : v;
3069
+ continue;
3070
+ }
3071
+ const spec = this.spec(f);
3072
+ const one = (kind, x) => x == null ? x : kind === "timestamptz" ? new Date(x) : kind === "double" ? Number(x) : kind === "bigint" && spec.bigintAs === "number" ? Number(x) : x;
3073
+ keyed[f] = spec.kind === "array" && Array.isArray(v) ? v.map((x) => one(spec.item, x)) : spec.kind === "array" ? v : one(spec.kind, v);
3074
+ }
3075
+ const record = this.tbl.fromRow(keyed);
3076
+ for (const [name, arg] of Object.entries(_nullishCoalesce(include, () => ( {})))) {
3077
+ if (arg) record[name] = this.decodeRelation(this.relation(name), json[name], relArgs(arg));
3078
+ }
3079
+ return record;
3080
+ }
3081
+ decodeRelation(rel, value, args) {
3082
+ const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
3083
+ if (rel.kind === "one") return value == null ? null : T.fromJson(value, args);
3084
+ return (_nullishCoalesce(value, () => ( []))).map((v) => T.fromJson(v, args));
3085
+ }
3086
+ attachIncludes(record, row, include) {
3087
+ for (const [name, arg] of Object.entries(include)) {
3088
+ if (!arg) continue;
3089
+ record[name] = this.decodeRelation(this.relation(name), row[incAlias(name)], relArgs(arg));
3090
+ }
3091
+ }
3092
+ /** A write with `include`: write, then read the record back with its relations. */
3093
+ async withInclude(args, write) {
3094
+ if (!this.includeArg(_nullishCoalesce(args, () => ( {})))) return write(args);
3095
+ const { include, select, omit, ...rest } = args;
3096
+ const record = await write(rest);
3097
+ const [full] = await this.findMany({ where: { id: record["id"] }, select, omit, include });
3098
+ return _nullishCoalesce(full, () => ( record));
3099
+ }
3100
+ /** `delete` with `include`: read the record and its relations, then delete it. */
3101
+ async deleteWithInclude(args) {
3102
+ if (!this.includeArg(args)) return this.delete(args);
3103
+ this.uniqueKey(args["where"], "delete");
3104
+ return transaction(async () => {
3105
+ const [found] = await this.findMany({
3106
+ where: args["where"],
3107
+ select: args["select"],
3108
+ omit: args["omit"],
3109
+ include: args["include"],
3110
+ take: 1
3111
+ });
3112
+ await this.delete({ where: args["where"] });
3113
+ return found;
3114
+ });
3115
+ }
3116
+ async findFirst(args = {}) {
3117
+ const take = args["take"];
3118
+ const rows = await this.findMany({ ...args, take: take !== void 0 && take < 0 ? -1 : 1 });
3119
+ return _nullishCoalesce(rows[0], () => ( null));
3120
+ }
3121
+ async findUnique(args) {
3122
+ this.uniqueKey(args["where"], "findUnique");
3123
+ return this.findFirst({
3124
+ where: args["where"],
3125
+ select: args["select"],
3126
+ omit: args["omit"],
3127
+ include: args["include"]
3128
+ });
3129
+ }
3130
+ async orThrow(p) {
3131
+ const r = await p;
3132
+ if (r === null) throw new HttpError(404, `${this.name} not found`);
3133
+ return r;
3134
+ }
3135
+ async count(args = {}) {
3136
+ const { t, sql } = await this.ready(args["where"]);
3137
+ return this.tbl.guard(async () => {
3138
+ const select = args["select"];
3139
+ const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
3140
+ const exprs = sql.join(
3141
+ counted.map(
3142
+ ([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(q("_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(q(f))}`
3143
+ ),
3144
+ sql`, `
3145
+ );
3146
+ const { query } = this.readQuery(
3147
+ sql,
3148
+ t,
3149
+ { ...args, select: void 0, distinct: args["distinct"] },
3150
+ sql`*`
3151
+ );
3152
+ const [row] = (await this.tbl.client().execute(sql`select ${exprs} from (${query}) as efc_rows`)).rows;
3153
+ return select ? row : row["_all"];
3154
+ });
3155
+ }
3156
+ // ── aggregates ─────────────────────────────────────────────────────────────
3157
+ aggregateSpec(args) {
3158
+ const out = [];
3159
+ for (const agg of AGGREGATES) {
3160
+ const v = args[agg];
3161
+ if (!v) continue;
3162
+ if (v === true) {
3163
+ if (agg !== "_count") this.fail(agg, `${agg} needs fields, e.g. { total: true }`);
3164
+ out.push({ agg, field: "_all", alias: `${agg}._all` });
3165
+ continue;
3166
+ }
3167
+ for (const [field, on] of Object.entries(v)) {
3168
+ if (!on) continue;
3169
+ if (field === "_all" && agg === "_count") {
3170
+ out.push({ agg, field, alias: `${agg}._all` });
3171
+ continue;
3172
+ }
3173
+ const spec = this.spec(field);
3174
+ if (!spec) this.fail(`${agg}.${field}`, "unknown field");
3175
+ if (agg !== "_count" && this.join(field)) {
3176
+ this.fail(`${agg}.${field}`, `${agg} doesn't apply to a many-to-many field`);
3177
+ }
3178
+ if ((agg === "_sum" || agg === "_avg") && !NUMERIC_KINDS.has(spec.kind)) {
3179
+ this.fail(`${agg}.${field}`, `${agg} needs a numeric field`);
3180
+ }
3181
+ out.push({ agg, field, alias: `${agg}.${field}` });
3182
+ }
3183
+ }
3184
+ return out;
3185
+ }
3186
+ aggregateExpr(sql, agg, field) {
3187
+ if (agg === "_count")
3188
+ return field === "_all" ? sql`count(*)` : sql`count(${this.col(sql, field)})`;
3189
+ const fn = { _sum: "sum", _avg: "avg", _min: "min", _max: "max" }[agg];
3190
+ return sql`${sql.raw(fn)}(${this.col(sql, field)})`;
3191
+ }
3192
+ /** Raw aggregate value → the type Prisma returns for it. */
3193
+ aggregateValue(t, agg, field, v) {
3194
+ if (agg === "_count") return Number(v);
3195
+ if (v == null) return null;
3196
+ const spec = this.spec(field);
3197
+ if (agg === "_min" || agg === "_max") return t[field].mapFromDriverValue(v);
3198
+ if (spec.kind === "numeric") return String(v);
3199
+ if (agg === "_sum" && spec.kind === "bigint") return BigInt(String(v).split(".")[0]);
3200
+ return Number(v);
3201
+ }
3202
+ aggregateRow(t, specs, row, args) {
3203
+ const out = {};
3204
+ for (const { agg, field, alias } of specs) {
3205
+ const value = this.aggregateValue(t, agg, field, row[alias]);
3206
+ if (agg === "_count" && args["_count"] === true) out[agg] = value;
3207
+ else (out[agg] ??= {})[field] = value;
3208
+ }
3209
+ return out;
3210
+ }
3211
+ async aggregate(args = {}) {
3212
+ const { t, sql } = await this.ready(args["where"]);
3213
+ return this.tbl.guard(async () => {
3214
+ const specs = this.aggregateSpec(args);
3215
+ if (specs.length === 0) return {};
3216
+ const exprs = sql.join(
3217
+ specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`),
3218
+ sql`, `
3219
+ );
3220
+ const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
3221
+ const [row] = (await this.tbl.client().execute(sql`select ${exprs} from (${query}) as efc_rows`)).rows;
3222
+ return this.aggregateRow(t, specs, row, args);
3223
+ });
3224
+ }
3225
+ havingSql(sql, t, having) {
3226
+ if (!having) return void 0;
3227
+ const parts = [];
3228
+ for (const [key, value] of Object.entries(having)) {
3229
+ if (value === void 0) continue;
3230
+ if (key === "AND" || key === "OR" || key === "NOT") {
3231
+ const list = Array.isArray(value) ? value : [value];
3232
+ const subs = list.map((h) => _nullishCoalesce(this.havingSql(sql, t, h), () => ( sql`true`)));
3233
+ const joined = sql.join(
3234
+ subs,
3235
+ key === "OR" ? sql` or ` : key === "NOT" ? sql` or ` : sql` and `
3236
+ );
3237
+ parts.push(key === "NOT" ? sql`not (${joined})` : sql`(${joined})`);
3238
+ continue;
3239
+ }
3240
+ const spec = this.spec(key);
3241
+ if (!spec) this.fail(`having.${key}`, "unknown field");
3242
+ const filter = value;
3243
+ const aggKeys = isPlainObject(filter) ? Object.keys(filter).filter((k) => AGGREGATES.includes(k)) : [];
3244
+ if (aggKeys.length === 0) {
3245
+ parts.push(this.fieldFilter(sql, t, spec, filter));
3246
+ continue;
3247
+ }
3248
+ for (const agg of aggKeys) {
3249
+ const expr = this.aggregateExpr(sql, agg, key);
3250
+ for (const [op, v] of Object.entries(filter[agg])) {
3251
+ const opSql = { equals: "=", not: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=" }[op];
3252
+ if (!opSql) this.fail(`having.${key}.${agg}`, `unknown filter "${op}"`);
3253
+ parts.push(
3254
+ sql`${expr} ${sql.raw(opSql)} ${sql.param(typeof v === "bigint" ? String(v) : v instanceof Date ? v : v)}`
3255
+ );
3256
+ }
3257
+ }
3258
+ }
3259
+ return parts.length ? sql.join(parts, sql` and `) : void 0;
3260
+ }
3261
+ async groupBy(args) {
3262
+ const { t, sql } = await this.ready(args["where"]);
3263
+ return this.tbl.guard(async () => {
3264
+ const by = Array.isArray(args["by"]) ? args["by"] : [args["by"]];
3265
+ if (by.length === 0) this.fail("by", "groupBy needs at least one field");
3266
+ for (const f of by) {
3267
+ if (!this.spec(f)) this.fail(`by.${f}`, "unknown field");
3268
+ if (this.join(f)) this.fail(`by.${f}`, "can't group by a many-to-many field");
3269
+ }
3270
+ const specs = this.aggregateSpec(args);
3271
+ const select = sql.join(
3272
+ [
3273
+ ...by.map((f) => this.col(sql, f)),
3274
+ ...specs.map(
3275
+ (s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`
3276
+ )
3277
+ ],
3278
+ sql`, `
3279
+ );
3280
+ const where = this.where(sql, t, args["where"]);
3281
+ const having = this.havingSql(sql, t, args["having"]);
3282
+ const orders = [];
3283
+ for (const entry of Array.isArray(args["orderBy"]) ? args["orderBy"] : args["orderBy"] ? [args["orderBy"]] : []) {
3284
+ for (const [key, dir] of Object.entries(entry)) {
3285
+ if (AGGREGATES.includes(key)) {
3286
+ for (const [field, d] of Object.entries(dir)) {
3287
+ orders.push(
3288
+ sql`${this.aggregateExpr(sql, key, field)} ${sql.raw(d === "desc" ? "desc" : "asc")}`
3289
+ );
3290
+ }
3291
+ } else if (this.spec(key)) {
3292
+ if (!by.includes(key))
3293
+ this.fail(`orderBy.${key}`, "groupBy can only order by grouped fields or aggregates");
3294
+ const d = isPlainObject(dir) ? dir["sort"] : dir;
3295
+ orders.push(sql`${this.col(sql, key)} ${sql.raw(d === "desc" ? "desc" : "asc")}`);
3296
+ }
3297
+ }
3298
+ }
3299
+ const query = sql`select ${select} from ${sql.raw(q(this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
3300
+ by.map((f) => this.col(sql, f)),
3301
+ sql`, `
3302
+ )}${having ? sql` having ${having}` : sql``}${orders.length ? sql` order by ${sql.join(orders, sql`, `)}` : sql``}${args["take"] !== void 0 ? sql` limit ${sql.param(args["take"])}` : sql``}${args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``}`;
3303
+ const rows = (await this.tbl.client().execute(query)).rows;
3304
+ return rows.map((row) => {
3305
+ const keyed = {};
3306
+ for (const f of by) keyed[f] = row[this.spec(f).column];
3307
+ const out = this.project(
3308
+ this.fromRaw(t, Object.fromEntries(by.map((f) => [this.spec(f).column, keyed[f]]))),
3309
+ by
3310
+ );
3311
+ for (const f of by) if (!(f in out)) out[f] = null;
3312
+ return { ...out, ...this.aggregateRow(t, specs, row, args) };
3313
+ });
3314
+ });
3315
+ }
3316
+ // ── writes ─────────────────────────────────────────────────────────────────
3317
+ /** Prisma update data → SET expressions and many-to-many changes, validated. */
3318
+ async setList(sql, t, data, alias) {
3319
+ const sets = [];
3320
+ const joinOps = [];
3321
+ const plain = {};
3322
+ const issues = [];
3323
+ const ref = (f) => this.col(sql, f, alias);
3324
+ for (const [field, value] of Object.entries(data)) {
3325
+ if (value === void 0) continue;
3326
+ const spec = this.spec(field);
3327
+ if (!spec || field === "id" || field === this.tbl.ts.createdAt || field === this.tbl.ts.updatedAt) {
3328
+ continue;
3329
+ }
3330
+ if (this.join(field)) {
3331
+ const entries = isPlainObject(value) ? Object.entries(value) : [["set", value]];
3332
+ for (const [op, v] of entries) {
3333
+ if (v === void 0) continue;
3334
+ if (op !== "set" && op !== "push" && op !== "pull") {
3335
+ issues.push({ path: field, message: `unknown update operation "${op}"` });
3336
+ continue;
3337
+ }
3338
+ const items = v === null ? [] : Array.isArray(v) ? v : op !== "set" ? [v] : v;
3339
+ await this.tbl.validate({ [field]: items }, true);
3340
+ joinOps.push({ field, mode: op, items });
3341
+ }
3342
+ continue;
3343
+ }
3344
+ const ops = isPlainObject(value) && spec.kind !== "jsonb" ? value : void 0;
3345
+ if (!ops) {
3346
+ plain[field] = value;
3347
+ continue;
3348
+ }
3349
+ for (const [op, v] of Object.entries(ops)) {
3350
+ if (v === void 0) continue;
3351
+ if (op === "set") {
3352
+ plain[field] = v;
3353
+ } else if (op === "increment" || op === "decrement" || op === "multiply" || op === "divide") {
3354
+ if (!NUMERIC_KINDS.has(spec.kind)) {
3355
+ issues.push({ path: field, message: `${op} only applies to number fields` });
3356
+ continue;
3357
+ }
3358
+ const okOperand = typeof v === "number" && Number.isFinite(v) || typeof v === "bigint" || spec.kind === "numeric" && typeof v === "string";
3359
+ if (!okOperand) {
3360
+ issues.push({ path: field, message: `${op} needs a number` });
3361
+ continue;
3362
+ }
3363
+ const sym = { increment: "+", decrement: "-", multiply: "*", divide: "/" }[op];
3364
+ sets.push(
3365
+ sql`${this.col(sql, field)} = ${ref(field)} ${sql.raw(sym)} ${this.val(sql, t, field, v)}`
3366
+ );
3367
+ } else if (op === "push" && spec.kind === "array") {
3368
+ const items = Array.isArray(v) ? v : [v];
3369
+ sets.push(
3370
+ sql`${this.col(sql, field)} = coalesce(${ref(field)}, ${sql.raw(`'{}'::${spec.ddl}`)}) || ${this.val(sql, t, field, items)}::${sql.raw(spec.ddl)}`
3371
+ );
3372
+ } else {
3373
+ issues.push({ path: field, message: `unknown update operation "${op}"` });
3374
+ }
3375
+ }
3376
+ }
3377
+ if (issues.length) throw new ModelValidationError(this.name, issues);
3378
+ await this.tbl.validate(plain, true);
3379
+ for (const [field, v] of Object.entries(plain)) {
3380
+ sets.push(
3381
+ sql`${this.col(sql, field)} = ${v === null ? sql`null` : this.val(sql, t, field, v)}`
3382
+ );
3383
+ }
3384
+ if (this.tbl.ts.updatedAt && (sets.length || joinOps.length)) {
3385
+ sets.push(
3386
+ sql`${this.col(sql, this.tbl.ts.updatedAt)} = ${this.val(sql, t, this.tbl.ts.updatedAt, /* @__PURE__ */ new Date())}`
3387
+ );
3388
+ }
3389
+ return { sets, joinOps };
3390
+ }
3391
+ // ── many-to-many links ─────────────────────────────────────────────────────
3392
+ /** Splits an insert row into its columns and the `set` ops for its many-to-many fields. */
3393
+ splitJoins(row) {
3394
+ if (this.tbl.joins.size === 0) return { row, ops: [] };
3395
+ const out = {};
3396
+ const ops = [];
3397
+ for (const [k, v] of Object.entries(row)) {
3398
+ if (this.join(k)) ops.push({ field: k, mode: "set", items: _nullishCoalesce(v, () => ( [])) });
3399
+ else out[k] = v;
3400
+ }
3401
+ return { row: out, ops };
3402
+ }
3403
+ exec(query) {
3404
+ return this.tbl.client().execute(query);
3405
+ }
3406
+ /** Applies many-to-many changes for each owner id, in the current transaction. */
3407
+ async applyJoins(sql, ops) {
3408
+ const idDdl = this.tbl.columns.get("id").ddl;
3409
+ const byField = /* @__PURE__ */ new Map();
3410
+ for (const { id, ops: list } of ops) {
3411
+ for (const op of list) {
3412
+ const entry = _nullishCoalesce(byField.get(op.field), () => ( []));
3413
+ entry.push({ id, op });
3414
+ byField.set(op.field, entry);
3415
+ }
3416
+ }
3417
+ for (const [field, entries] of byField) {
3418
+ const join = this.join(field);
3419
+ const jt = sql.raw(q(join.table));
3420
+ const sets = entries.filter((e) => e.op.mode === "set");
3421
+ if (sets.length) {
3422
+ const owners2 = sets.map((e) => idText(e.id));
3423
+ const lists = sets.map((e) => `{${dedupe(e.op.items).map(idText).join(",")}}`);
3424
+ await this.exec(
3425
+ sql`delete from ${jt} as efc_j using unnest(${sql.param(owners2)}::${sql.raw(idDdl)}[], ${sql.param(lists)}::text[]) as w(owner, ids) where efc_j.owner_id = w.owner and not (efc_j.ref_id = any(w.ids::${sql.raw(join.ddl)}))`
3426
+ );
3427
+ }
3428
+ const pulls = entries.filter((e) => e.op.mode === "pull");
3429
+ if (pulls.length) {
3430
+ const pairs = pulls.flatMap((e) => dedupe(e.op.items).map((ref) => [e.id, ref]));
3431
+ if (pairs.length) {
3432
+ await this.exec(
3433
+ sql`delete from ${jt} as efc_j using unnest(${sql.param(pairs.map((p) => idText(p[0])))}::${sql.raw(idDdl)}[], ${sql.param(pairs.map((p) => idText(p[1])))}::${sql.raw(join.ddl)}) as d(o, r) where efc_j.owner_id = d.o and efc_j.ref_id = d.r`
3434
+ );
3435
+ }
3436
+ }
3437
+ const adds = entries.filter((e) => e.op.mode !== "pull");
3438
+ const links = [];
3439
+ for (const { id, op } of adds) {
3440
+ dedupe(op.items).forEach((ref, i) => links.push([id, ref, i + 1]));
3441
+ }
3442
+ if (links.length === 0) continue;
3443
+ const pushes = new Set(adds.filter((e) => e.op.mode === "push").map((e) => idText(e.id)));
3444
+ const owners = sql`${sql.param(links.map((l) => idText(l[0])))}::${sql.raw(idDdl)}[]`;
3445
+ const refs = sql`${sql.param(links.map((l) => idText(l[1])))}::${sql.raw(join.ddl)}`;
3446
+ const pos = sql`${sql.param(links.map((l) => l[2]))}::integer[]`;
3447
+ if (pushes.size === 0) {
3448
+ await this.exec(
3449
+ sql`insert into ${jt} (owner_id, ref_id, position) select * from unnest(${owners}, ${refs}, ${pos}) on conflict (owner_id, ref_id) do update set position = excluded.position`
3450
+ );
3451
+ } else {
3452
+ await this.exec(
3453
+ sql`insert into ${jt} (owner_id, ref_id, position) select l.o, l.r, coalesce((select max(efc_j.position) from ${jt} efc_j where efc_j.owner_id = l.o), 0) + l.p from unnest(${owners}, ${refs}, ${pos}) as l(o, r, p) on conflict (owner_id, ref_id) do nothing`
3454
+ );
3455
+ }
3456
+ }
3457
+ }
3458
+ /** The current links of `fields` for these owners, read in one statement. */
3459
+ async loadJoins(sql, ids, fields) {
3460
+ const out = /* @__PURE__ */ new Map();
3461
+ const joins = fields.map((f) => this.join(f)).filter(Boolean);
3462
+ if (joins.length === 0 || ids.length === 0) return out;
3463
+ const idDdl = this.tbl.columns.get("id").ddl;
3464
+ const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
3465
+ const parts = joins.map(
3466
+ (j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(q(j.table))} where owner_id = any(${owners}) group by owner_id`
3467
+ );
3468
+ const { rows } = await this.exec(sql.join(parts, sql` union all `));
3469
+ for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
3470
+ for (const r of rows) {
3471
+ const join = this.join(r["f"]);
3472
+ out.get(join.field).set(r["o"], this.joinValues(join, r["ids"]));
3473
+ }
3474
+ return out;
3475
+ }
3476
+ /** Writes the loaded links into records (owners without any get an empty list). */
3477
+ attachJoins(records, loaded) {
3478
+ for (const [field, byOwner] of loaded) {
3479
+ for (const r of records) r[field] = _nullishCoalesce(byOwner.get(String(r["id"])), () => ( []));
3480
+ }
3481
+ }
3482
+ /** Runs `fn` in a transaction when it changes links (main statement + link statements). */
3483
+ withLinks(changesLinks, fn) {
3484
+ return changesLinks ? transaction(fn) : fn();
3485
+ }
3486
+ insertSql(sql, t, rows) {
3487
+ const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
3488
+ const head = sql`insert into ${sql.raw(q(this.tbl.table))} (${sql.join(
3489
+ fields.map((f) => this.col(sql, f)),
3490
+ sql`, `
3491
+ )})`;
3492
+ const values = sql.join(
3493
+ rows.map(
3494
+ (r) => sql`(${sql.join(
3495
+ fields.map((f) => r[f] === void 0 ? sql`default` : sql`${sql.param(r[f], t[f])}`),
3496
+ sql`, `
3497
+ )})`
3498
+ ),
3499
+ sql`, `
3500
+ );
3501
+ return { head, values };
3502
+ }
3503
+ async prepare(data) {
3504
+ if (!isPlainObject(data)) this.fail("data", "must be an object");
3505
+ return this.tbl.prepareInsert(data);
3506
+ }
3507
+ async create(args) {
3508
+ const { t, sql } = await this.ready();
3509
+ return this.tbl.guard(async () => {
3510
+ const { row, ops } = this.splitJoins(await this.prepare(args["data"]));
3511
+ return this.withLinks(
3512
+ ops.some((o) => o.items.length),
3513
+ async () => {
3514
+ const { head, values } = this.insertSql(sql, t, [row]);
3515
+ const [inserted] = (await this.exec(sql`${head} values ${values} returning *`)).rows;
3516
+ const record = this.fromRaw(t, inserted);
3517
+ await this.applyJoins(sql, [
3518
+ { id: record["id"], ops: ops.filter((o) => o.items.length) }
3519
+ ]);
3520
+ for (const join of this.tbl.joins.values()) {
3521
+ const op = ops.find((o) => o.field === join.field);
3522
+ record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
3523
+ }
3524
+ return this.project(record, this.projection(args));
3525
+ }
3526
+ );
3527
+ });
3528
+ }
3529
+ async createMany(args, returning) {
3530
+ const { t, sql } = await this.ready();
3531
+ return this.tbl.guard(async () => {
3532
+ const data = Array.isArray(args["data"]) ? args["data"] : [args["data"]];
3533
+ if (data.length === 0) return returning ? [] : { count: 0 };
3534
+ const split = (await Promise.all(data.map((d) => this.prepare(d)))).map(
3535
+ (r) => this.splitJoins(r)
3536
+ );
3537
+ const linked = split.some((x) => x.ops.some((o) => o.items.length));
3538
+ return this.withLinks(linked, async () => {
3539
+ if (linked)
3540
+ await this.assignIds(
3541
+ sql,
3542
+ split.map((x) => x.row)
3543
+ );
3544
+ const { head, values } = this.insertSql(
3545
+ sql,
3546
+ t,
3547
+ split.map((x) => x.row)
3548
+ );
3549
+ const conflict = args["skipDuplicates"] ? sql` on conflict do nothing` : sql``;
3550
+ const result = await this.exec(
3551
+ sql`${head} values ${values}${conflict}${returning ? sql` returning *` : linked ? sql` returning ${this.col(sql, "id")}` : sql``}`
3552
+ );
3553
+ if (linked) {
3554
+ const inserted = new Set(result.rows.map((r) => String(r["id"])));
3555
+ await this.applyJoins(
3556
+ sql,
3557
+ split.filter((x) => inserted.has(String(x.row["id"]))).map((x) => ({ id: x.row["id"], ops: x.ops.filter((o) => o.items.length) }))
3558
+ );
3559
+ }
3560
+ if (!returning) return { count: linked ? result.rows.length : _nullishCoalesce(result.rowCount, () => ( 0)) };
3561
+ const fields = this.projection(args);
3562
+ const records = result.rows.map((r) => this.fromRaw(t, r));
3563
+ if (this.tbl.joins.size) {
3564
+ const ops = new Map(split.map((x) => [String(x.row["id"]), x.ops]));
3565
+ for (const record of records) {
3566
+ for (const join of this.tbl.joins.values()) {
3567
+ const op = _optionalChain([ops, 'access', _105 => _105.get, 'call', _106 => _106(String(record["id"])), 'optionalAccess', _107 => _107.find, 'call', _108 => _108((o) => o.field === join.field)]);
3568
+ record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
3569
+ }
3570
+ }
3571
+ }
3572
+ return records.map((r) => this.project(r, fields));
3573
+ });
3574
+ });
3575
+ }
3576
+ /** Gives rows without an id one up front, so their links can name their owner. */
3577
+ async assignIds(sql, rows) {
3578
+ const missing = rows.filter((r) => r["id"] === void 0);
3579
+ if (missing.length === 0) return;
3580
+ if (this.tbl.idKind === "uuid") {
3581
+ for (const r of missing) r["id"] = _crypto.randomUUID.call(void 0, );
3582
+ return;
3583
+ }
3584
+ const { rows: ids } = await this.exec(
3585
+ sql`select nextval(pg_get_serial_sequence(${sql.param(q(this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
3586
+ );
3587
+ missing.forEach((r, i) => {
3588
+ const id = ids[i]["id"];
3589
+ r["id"] = this.tbl.idKind === "bigserial" ? BigInt(id) : Number(id);
3590
+ });
3591
+ }
3592
+ /** Reloads the links of the fields `ops` changed into `records`. */
3593
+ async refreshJoins(sql, records, ops) {
3594
+ const fields = [...new Set(ops.map((o) => o.field))];
3595
+ if (fields.length === 0 || records.length === 0) return;
3596
+ this.attachJoins(
3597
+ records,
3598
+ await this.loadJoins(
3599
+ sql,
3600
+ records.map((r) => r["id"]),
3601
+ fields
3602
+ )
3603
+ );
3604
+ }
3605
+ async update(args) {
3606
+ this.uniqueKey(args["where"], "update");
3607
+ const { t, sql } = await this.ready(args["where"]);
3608
+ return this.tbl.guard(async () => {
3609
+ const { sets, joinOps } = await this.setList(sql, t, _nullishCoalesce(args["data"], () => ( {})));
3610
+ return this.withLinks(joinOps.length > 0, async () => {
3611
+ const where = this.where(sql, t, args["where"]);
3612
+ const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
3613
+ const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
3614
+ const query = sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(q(this.tbl.table))} where ${where} limit 1`;
3615
+ const [row] = (await this.exec(query)).rows;
3616
+ if (!row) throw new HttpError(404, `${this.name} not found`);
3617
+ const record = this.fromRaw(t, row);
3618
+ await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
3619
+ await this.refreshJoins(sql, [record], joinOps);
3620
+ return this.project(record, this.projection(args));
3621
+ });
3622
+ });
3623
+ }
3624
+ async updateMany(args, returning) {
3625
+ const { t, sql } = await this.ready(args["where"]);
3626
+ return this.tbl.guard(async () => {
3627
+ const { sets, joinOps } = await this.setList(sql, t, _nullishCoalesce(args["data"], () => ( {})));
3628
+ if (sets.length === 0 && joinOps.length === 0) {
3629
+ if (!returning) return { count: 0 };
3630
+ return this.findMany({ where: args["where"], select: args["select"], omit: args["omit"] });
3631
+ }
3632
+ return this.withLinks(joinOps.length > 0, async () => {
3633
+ const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
3634
+ const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
3635
+ const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
3636
+ const result = await this.exec(
3637
+ sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(q(this.tbl.table))} where ${where}`
3638
+ );
3639
+ const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
3640
+ await this.applyJoins(
3641
+ sql,
3642
+ records.map((r) => ({ id: r["id"], ops: joinOps }))
3643
+ );
3644
+ if (!returning)
3645
+ return { count: joinOps.length ? result.rows.length : _nullishCoalesce(result.rowCount, () => ( 0)) };
3646
+ await this.refreshJoins(sql, records, joinOps);
3647
+ const fields = this.projection(args);
3648
+ return records.map((r) => this.project(r, fields));
3649
+ });
3650
+ });
3651
+ }
3652
+ async upsert(args) {
3653
+ const key = this.uniqueKey(args["where"], "upsert");
3654
+ const { t, sql } = await this.ready(args["where"]);
3655
+ return this.tbl.guard(async () => {
3656
+ const { row, ops: createOps } = this.splitJoins(await this.prepare(args["create"]));
3657
+ for (const f of key) {
3658
+ if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
3659
+ }
3660
+ const { head, values } = this.insertSql(sql, t, [row]);
3661
+ const table = q(this.tbl.table);
3662
+ const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
3663
+ const { joinOps } = update;
3664
+ let { sets } = update;
3665
+ if (sets.length === 0)
3666
+ sets = [sql`${this.col(sql, key[0])} = excluded.${this.col(sql, key[0])}`];
3667
+ const target = sql.join(
3668
+ key.map((f) => this.col(sql, f)),
3669
+ sql`, `
3670
+ );
3671
+ const extra = Object.keys(args["where"]).filter((f) => !key.includes(f));
3672
+ const cond = extra.length ? sql` where ${this.where(sql, t, Object.fromEntries(extra.map((f) => [f, args["where"][f]])))}` : sql``;
3673
+ const linked = this.tbl.joins.size > 0;
3674
+ const links = this.joinColumns(sql, [...this.tbl.joins.keys()], table);
3675
+ const returning = linked ? sql` returning *, (${sql.raw(table)}.xmax = 0) as efc_inserted, ${sql.join(links, sql`, `)}` : sql` returning *`;
3676
+ return this.withLinks(
3677
+ createOps.some((o) => o.items.length) || joinOps.length > 0,
3678
+ async () => {
3679
+ const [out] = (await this.exec(
3680
+ sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
3681
+ )).rows;
3682
+ if (!out) throw new HttpError(404, `${this.name} not found`);
3683
+ const record = this.fromRaw(t, out);
3684
+ if (linked) {
3685
+ const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
3686
+ await this.applyJoins(sql, [{ id: record["id"], ops }]);
3687
+ await this.refreshJoins(sql, [record], ops);
3688
+ }
3689
+ return this.project(record, this.projection(args));
3690
+ }
3691
+ );
3692
+ });
3693
+ }
3694
+ async delete(args) {
3695
+ this.uniqueKey(args["where"], "delete");
3696
+ const { t, sql } = await this.ready(args["where"]);
3697
+ return this.tbl.guard(async () => {
3698
+ const where = this.where(sql, t, args["where"]);
3699
+ const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
3700
+ const [row] = (await this.exec(
3701
+ sql`delete from ${sql.raw(q(this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
3702
+ )).rows;
3703
+ if (!row) throw new HttpError(404, `${this.name} not found`);
3704
+ return this.project(this.fromRaw(t, row), this.projection(args));
3705
+ });
3706
+ }
3707
+ async deleteMany(args = {}) {
3708
+ const { t, sql } = await this.ready(args["where"]);
3709
+ return this.tbl.guard(async () => {
3710
+ const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
3711
+ const result = await this.tbl.client().execute(sql`delete from ${sql.raw(q(this.tbl.table))} where ${where}`);
3712
+ return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
3713
+ });
3714
+ }
3715
+ }, _class);
3716
+ function relArgs(arg) {
3717
+ return isPlainObject(arg) ? arg : {};
3718
+ }
3719
+ function runtimeOf(name, from) {
3720
+ const runtime = _optionalChain([getRegisteredModel, 'call', _109 => _109(name), 'optionalAccess', _110 => _110.tableRuntime, 'optionalCall', _111 => _111()]);
3721
+ if (!runtime) {
3722
+ throw new Error(
3723
+ getRegisteredModel(name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
3724
+ );
3725
+ }
3726
+ return runtime;
3727
+ }
3728
+ var JSON_OPS = /* @__PURE__ */ new Set([
3729
+ "path",
3730
+ "equals",
3731
+ "not",
3732
+ "string_contains",
3733
+ "string_starts_with",
3734
+ "string_ends_with",
3735
+ "array_contains",
3736
+ "gt",
3737
+ "gte",
3738
+ "lt",
3739
+ "lte",
3740
+ "mode"
3741
+ ]);
3742
+ function createTable(name, schema, options = {}) {
3743
+ normalizeSchema(schema, "table", name);
3744
+ for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
3745
+ const where = `[EFC] ${name}.relations.${rel}`;
3746
+ if (rel in schema) throw new Error(`${where}: a field already has this name`);
3747
+ if (!def || def.hasMany === void 0 === (def.hasOne === void 0)) {
3748
+ throw new Error(`${where}: give either hasMany or hasOne (a model name)`);
3749
+ }
3750
+ if (typeof def.foreignKey !== "string") {
3751
+ throw new Error(
3752
+ `${where}: foreignKey must name the ${_nullishCoalesce(def.hasMany, () => ( def.hasOne))} field that references ${name}`
3753
+ );
3754
+ }
3755
+ }
3756
+ let runtime;
3757
+ const rt = () => {
3758
+ const engine2 = getDbEngine();
3759
+ if (engine2 !== "postgresql") {
3760
+ throw new Error(
3761
+ `[EFC] ${name} is a PostgreSQL table (defineTable) but the app is connected to MongoDB \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
3762
+ );
3763
+ }
3764
+ return runtime ??= new TableRuntime(name, schema, options);
3765
+ };
3766
+ const call = (fn) => Promise.resolve().then(() => fn(rt()));
3767
+ const model = {
3768
+ name,
3769
+ findMany: (args) => call((r) => r.findMany(args)),
3770
+ findFirst: (args) => call((r) => r.findFirst(args)),
3771
+ findFirstOrThrow: (args) => call((r) => r.orThrow(r.findFirst(args))),
3772
+ findUnique: (args) => call((r) => r.findUnique(args)),
3773
+ findUniqueOrThrow: (args) => call((r) => r.orThrow(r.findUnique(args))),
3774
+ count: (args) => call((r) => r.count(args)),
3775
+ aggregate: (args) => call((r) => r.aggregate(args)),
3776
+ groupBy: (args) => call((r) => r.groupBy(args)),
3777
+ create: (args) => call((r) => r.withInclude(args, (a) => r.createNested(a))),
3778
+ createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _112 => _112["data"]]), "createMany"), r.createMany(args, false))),
3779
+ createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _113 => _113["data"]]), "createMany"), r.createMany(args, true))),
3780
+ update: (args) => call((r) => r.withInclude(args, (a) => r.updateNested(a))),
3781
+ updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _114 => _114["data"]]), "updateMany"), r.updateMany(args, false))),
3782
+ updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _115 => _115["data"]]), "updateMany"), r.updateMany(args, true))),
3783
+ upsert: (args) => call((r) => r.withInclude(args, (a) => r.upsertNested(a))),
3784
+ delete: (args) => call((r) => r.deleteWithInclude(args)),
3785
+ deleteMany: (args) => call((r) => r.deleteMany(args)),
3786
+ raw: () => call(async (r) => (await r.tbl.compile()).t),
3787
+ sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _116 => _116.dryRun]), () => ( false)))),
3788
+ drop: () => call((r) => r.tbl.drop())
3789
+ };
3790
+ _chunkMGH4VDV3cjs.traceOps.call(void 0,
3791
+ name,
3792
+ model,
3793
+ Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
3794
+ );
3795
+ registerModel({
3796
+ name,
3797
+ sync: model.sync,
3798
+ drop: model.drop,
3799
+ findByIds: (ids) => model.findMany({ where: { id: { in: ids } } }),
3800
+ pgTarget: () => ({ table: rt().tbl.table, idKind: rt().tbl.idKind }),
3801
+ tableRuntime: () => rt()
3802
+ });
3803
+ return model;
3804
+ }
3805
+ function defineTable(name, schema, options) {
3806
+ return createTable(name, schema, _nullishCoalesce(options, () => ( {})));
3807
+ }
3808
+
3809
+ // src/db/index.ts
3810
+ var _client = null;
3811
+ function setDbClient(client) {
3812
+ _client = client;
3813
+ }
3814
+ function getDbClient() {
3815
+ if (!_client) {
3816
+ throw new Error("[EFC] db not ready \u2014 accessed before Pre-Flight completed");
3817
+ }
3818
+ return _client;
3819
+ }
3820
+ var db = new Proxy({}, {
3821
+ get(_target, prop) {
3822
+ const client = getDbClient();
3823
+ const value = client[prop];
3824
+ return typeof value === "function" ? value.bind(client) : value;
3825
+ },
3826
+ set(_target, prop, value) {
3827
+ getDbClient()[prop] = value;
3828
+ return true;
3829
+ }
3830
+ });
3831
+
3832
+
3833
+
3834
+
3835
+
3836
+
3837
+
3838
+
3839
+
3840
+
3841
+
3842
+
3843
+
3844
+
3845
+
3846
+ exports.HttpError = HttpError; exports.isHttpError = isHttpError; exports.ModelValidationError = ModelValidationError; exports.setDbEngine = setDbEngine; exports.setAutoSync = setAutoSync; exports.registeredModels = registeredModels; exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
3847
+ //# sourceMappingURL=chunk-AZYXQU3Z.cjs.map