express-file-cluster 0.3.15 → 0.5.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.
- package/README.md +71 -33
- package/dist/auth/index.cjs +12 -2
- package/dist/auth/index.cjs.map +1 -1
- package/dist/auth/index.d.cts +13 -2
- package/dist/auth/index.d.ts +13 -2
- package/dist/auth/index.js +12 -2
- package/dist/chunk-3VWD2ZED.js +60 -0
- package/dist/chunk-3VWD2ZED.js.map +1 -0
- package/dist/chunk-47K2532L.cjs +196 -0
- package/dist/chunk-47K2532L.cjs.map +1 -0
- package/dist/chunk-5PDAWMGF.js +438 -0
- package/dist/chunk-5PDAWMGF.js.map +1 -0
- package/dist/chunk-7YEX4MQV.cjs +38 -0
- package/dist/chunk-7YEX4MQV.cjs.map +1 -0
- package/dist/chunk-ALBDM5R3.cjs +60 -0
- package/dist/chunk-ALBDM5R3.cjs.map +1 -0
- package/dist/chunk-JJJJTACK.js +196 -0
- package/dist/chunk-JJJJTACK.js.map +1 -0
- package/dist/chunk-LJNSJFOL.js +38 -0
- package/dist/chunk-LJNSJFOL.js.map +1 -0
- package/dist/chunk-M7MUPWCE.js +116 -0
- package/dist/chunk-M7MUPWCE.js.map +1 -0
- package/dist/chunk-PMF4GMHD.js +154 -0
- package/dist/chunk-PMF4GMHD.js.map +1 -0
- package/dist/chunk-QTRGJ2EN.cjs +2635 -0
- package/dist/chunk-QTRGJ2EN.cjs.map +1 -0
- package/dist/chunk-RSBW2B3D.cjs +126 -0
- package/dist/chunk-RSBW2B3D.cjs.map +1 -0
- package/dist/chunk-RTFJ32T5.js +2635 -0
- package/dist/chunk-RTFJ32T5.js.map +1 -0
- package/dist/chunk-SFVEQ2T5.cjs +438 -0
- package/dist/chunk-SFVEQ2T5.cjs.map +1 -0
- package/dist/chunk-SZT36SGB.cjs +154 -0
- package/dist/chunk-SZT36SGB.cjs.map +1 -0
- package/dist/chunk-TI24L4XE.cjs.map +1 -1
- package/dist/chunk-ULQXD4YZ.cjs +116 -0
- package/dist/chunk-ULQXD4YZ.cjs.map +1 -0
- package/dist/chunk-VYHJX54R.js +126 -0
- package/dist/chunk-VYHJX54R.js.map +1 -0
- package/dist/cli/db-runner.cjs +497 -0
- package/dist/cli/db-runner.cjs.map +1 -0
- package/dist/cli/db-runner.d.cts +2 -0
- package/dist/cli/db-runner.d.ts +2 -0
- package/dist/cli/db-runner.js +497 -0
- package/dist/cli/db-runner.js.map +1 -0
- package/dist/cli/index.cjs +447 -69
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +473 -95
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/auth.md +232 -0
- package/dist/docs/api-reference/compose.md +78 -0
- package/dist/docs/api-reference/db.md +351 -0
- package/dist/docs/api-reference/http-error.md +109 -0
- package/dist/docs/api-reference/ignite.md +323 -0
- package/dist/docs/api-reference/table.md +250 -0
- package/dist/docs/api-reference/tasks.md +140 -0
- package/dist/docs/cli/db.md +38 -0
- package/dist/docs/cli/diagnostics.md +145 -0
- package/dist/docs/cli/generate.md +120 -0
- package/dist/docs/cli/index.md +48 -0
- package/dist/docs/cli/start.md +112 -0
- package/dist/docs/contributing/index.md +139 -0
- package/dist/docs/core-concepts/background-tasks.md +228 -0
- package/dist/docs/core-concepts/clustering.md +114 -0
- package/dist/docs/core-concepts/file-based-routing.md +235 -0
- package/dist/docs/core-concepts/index.md +79 -0
- package/dist/docs/core-concepts/middleware.md +144 -0
- package/dist/docs/getting-started/index.md +91 -0
- package/dist/docs/getting-started/project-structure.md +154 -0
- package/dist/docs/guides/ai-agents.md +48 -0
- package/dist/docs/guides/authentication.md +196 -0
- package/dist/docs/guides/caching.md +124 -0
- package/dist/docs/guides/database.md +217 -0
- package/dist/docs/guides/deployment.md +171 -0
- package/dist/docs/guides/environment-variables.md +106 -0
- package/dist/docs/guides/error-handling.md +172 -0
- package/dist/docs/guides/generated-portals.md +115 -0
- package/dist/docs/guides/logging.md +70 -0
- package/dist/docs/guides/mailer.md +166 -0
- package/dist/docs/guides/migrations.md +106 -0
- package/dist/docs/guides/rbac.md +89 -0
- package/dist/docs/guides/validation.md +95 -0
- package/dist/docs/index.md +93 -0
- package/dist/docs/skills/SKILL.md +44 -0
- package/dist/docs/skills/api-surface.md +308 -0
- package/dist/docs/skills/auth-internals.md +141 -0
- package/dist/docs/skills/pre-flight.md +142 -0
- package/dist/docs/skills/routing-rules.md +114 -0
- package/dist/docs/skills/tasks-internals.md +172 -0
- package/dist/docs/skills/what-not-to-invent.md +251 -0
- package/dist/index.cjs +289 -391
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +472 -7
- package/dist/index.d.ts +472 -7
- package/dist/index.js +283 -385
- package/dist/index.js.map +1 -1
- package/dist/pgboss-backend-3E6ATY42.cjs +14 -0
- package/dist/pgboss-backend-3E6ATY42.cjs.map +1 -0
- package/dist/pgboss-backend-UUJOVEYK.js +14 -0
- package/dist/pgboss-backend-UUJOVEYK.js.map +1 -0
- package/dist/tasks/index.cjs.map +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/types-DJCPAsM4.d.cts +541 -0
- package/dist/types-DJCPAsM4.d.ts +541 -0
- package/package.json +28 -5
- package/dist/chunk-6522HS2J.cjs +0 -99
- package/dist/chunk-6522HS2J.cjs.map +0 -1
- package/dist/chunk-DGVOJNR6.cjs +0 -55
- package/dist/chunk-DGVOJNR6.cjs.map +0 -1
- package/dist/chunk-KOHLLUN7.js +0 -55
- package/dist/chunk-KOHLLUN7.js.map +0 -1
- package/dist/chunk-VIP3PFWZ.js +0 -99
- package/dist/chunk-VIP3PFWZ.js.map +0 -1
- package/dist/types-BusbSenn.d.cts +0 -162
- package/dist/types-BusbSenn.d.ts +0 -162
|
@@ -0,0 +1,2635 @@
|
|
|
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; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
var _chunkALBDM5R3cjs = require('./chunk-ALBDM5R3.cjs');
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
var _chunkRSBW2B3Dcjs = require('./chunk-RSBW2B3D.cjs');
|
|
10
|
+
|
|
11
|
+
// src/errors.ts
|
|
12
|
+
var HttpError = class _HttpError extends Error {
|
|
13
|
+
|
|
14
|
+
constructor(statusCode, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "HttpError";
|
|
17
|
+
this.statusCode = statusCode;
|
|
18
|
+
Error.captureStackTrace(this, _HttpError);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Wraps an unknown caught value into an `HttpError`.
|
|
22
|
+
* If the value is already an `HttpError`, it is returned as-is.
|
|
23
|
+
* Otherwise the `message` from the caught `Error` (or a fallback) is used.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* } catch (err) {
|
|
27
|
+
* throw HttpError.from(err, 500, 'Something went wrong');
|
|
28
|
+
* }
|
|
29
|
+
*/
|
|
30
|
+
static from(err, statusCode = 500, fallback = "Internal Server Error") {
|
|
31
|
+
if (err instanceof _HttpError) return err;
|
|
32
|
+
const message = err instanceof Error ? err.message : fallback;
|
|
33
|
+
return new _HttpError(statusCode, message);
|
|
34
|
+
}
|
|
35
|
+
/** Returns a plain object representation suitable for JSON serialization. */
|
|
36
|
+
toJSON() {
|
|
37
|
+
return {
|
|
38
|
+
statusCode: this.statusCode,
|
|
39
|
+
error: this.name,
|
|
40
|
+
message: this.message
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
function isHttpError(value) {
|
|
45
|
+
return value instanceof HttpError;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// src/db/schema.ts
|
|
49
|
+
var _crypto = require('crypto');
|
|
50
|
+
var MODEL_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "date", "object", "objectId", "array"]);
|
|
51
|
+
var TABLE_ONLY_TYPES = /* @__PURE__ */ new Set(["integer", "bigint", "decimal", "uuid", "json"]);
|
|
52
|
+
var TABLE_ONLY_OPTIONS = ["precision", "scale", "nativeEnum", "column"];
|
|
53
|
+
function isFieldDefinition(value) {
|
|
54
|
+
if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
55
|
+
const type = value.type;
|
|
56
|
+
return typeof type === "string" && (MODEL_TYPES.has(type) || TABLE_ONLY_TYPES.has(type));
|
|
57
|
+
}
|
|
58
|
+
var untyped = () => ({ kind: "json", def: { type: "object" } });
|
|
59
|
+
var SchemaBuilder = class {
|
|
60
|
+
constructor(model, mode) {
|
|
61
|
+
this.model = model;
|
|
62
|
+
this.mode = mode;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
fail(path, message) {
|
|
67
|
+
throw new Error(`[EFC] ${this.model}.${path}: ${message}`);
|
|
68
|
+
}
|
|
69
|
+
checkType(type, path) {
|
|
70
|
+
if (this.mode === "model" && TABLE_ONLY_TYPES.has(type)) {
|
|
71
|
+
this.fail(path, `type '${type}' is PostgreSQL-only \u2014 use defineTable, or a portable type`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
checkDefinition(def, path, topLevel) {
|
|
75
|
+
this.checkType(def.type, path);
|
|
76
|
+
if (this.mode === "model") {
|
|
77
|
+
for (const opt of TABLE_ONLY_OPTIONS) {
|
|
78
|
+
if (def[opt] !== void 0) this.fail(path, `'${opt}' is a defineTable option`);
|
|
79
|
+
}
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if ((def.precision !== void 0 || def.scale !== void 0) && def.type !== "decimal") {
|
|
83
|
+
this.fail(path, `'precision' / 'scale' only apply to decimal fields`);
|
|
84
|
+
}
|
|
85
|
+
if (def.scale !== void 0 && def.precision === void 0) {
|
|
86
|
+
this.fail(path, `'scale' needs 'precision'`);
|
|
87
|
+
}
|
|
88
|
+
if (def.nativeEnum && !(def.enum && def.enum.every((v) => typeof v === "string"))) {
|
|
89
|
+
this.fail(path, `'nativeEnum' needs a string 'enum'`);
|
|
90
|
+
}
|
|
91
|
+
if (def.column !== void 0 && !topLevel) {
|
|
92
|
+
this.fail(path, `'column' only applies to top-level fields`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
item(of, parent, path) {
|
|
96
|
+
if (of === void 0) return untyped();
|
|
97
|
+
if (typeof of === "string") {
|
|
98
|
+
this.checkType(of, path);
|
|
99
|
+
if (of === "object" || of === "json") return untyped();
|
|
100
|
+
const def = {
|
|
101
|
+
type: of,
|
|
102
|
+
...parent.ref !== void 0 && { ref: parent.ref }
|
|
103
|
+
};
|
|
104
|
+
return { kind: "scalar", type: of, def };
|
|
105
|
+
}
|
|
106
|
+
return { kind: "object", fields: this.tree(of, `${path}.$`), def: { type: "object" } };
|
|
107
|
+
}
|
|
108
|
+
field(field, path, topLevel) {
|
|
109
|
+
if (Array.isArray(field)) {
|
|
110
|
+
const inner = field[0];
|
|
111
|
+
return {
|
|
112
|
+
kind: "array",
|
|
113
|
+
item: inner ? { kind: "object", fields: this.tree(inner, `${path}.$`), def: { type: "object" } } : untyped(),
|
|
114
|
+
def: { type: "array" }
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
if (!isFieldDefinition(field)) {
|
|
118
|
+
const type = field.type;
|
|
119
|
+
if (typeof type === "string") this.fail(path, `unknown field type '${type}'`);
|
|
120
|
+
return {
|
|
121
|
+
kind: "object",
|
|
122
|
+
fields: this.tree(field, path),
|
|
123
|
+
def: { type: "object" }
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const def = field;
|
|
127
|
+
this.checkDefinition(def, path, topLevel);
|
|
128
|
+
if (def.type === "array") return { kind: "array", item: this.item(def.of, def, path), def };
|
|
129
|
+
if (def.type === "object") {
|
|
130
|
+
return def.fields ? { kind: "object", fields: this.tree(def.fields, path), def } : { kind: "json", def };
|
|
131
|
+
}
|
|
132
|
+
if (def.type === "json") return { kind: "json", def };
|
|
133
|
+
return { kind: "scalar", type: def.type, def };
|
|
134
|
+
}
|
|
135
|
+
tree(schema, prefix = "") {
|
|
136
|
+
const out = {};
|
|
137
|
+
for (const [key, field] of Object.entries(schema)) {
|
|
138
|
+
out[key] = this.field(field, prefix ? `${prefix}.${key}` : key, prefix === "");
|
|
139
|
+
}
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
function normalizeSchema(schema, mode = "model", model = "Model") {
|
|
144
|
+
return new SchemaBuilder(model, mode).tree(schema);
|
|
145
|
+
}
|
|
146
|
+
function timestampFields(options) {
|
|
147
|
+
const ts = _nullishCoalesce(options.timestamps, () => ( true));
|
|
148
|
+
if (ts === false) return {};
|
|
149
|
+
if (ts === true) return { createdAt: "createdAt", updatedAt: "updatedAt" };
|
|
150
|
+
const out = {};
|
|
151
|
+
if (ts.createdAt !== false) out.createdAt = _nullishCoalesce(ts.createdAt, () => ( "createdAt"));
|
|
152
|
+
if (ts.updatedAt !== false) out.updatedAt = _nullishCoalesce(ts.updatedAt, () => ( "updatedAt"));
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
var STATIC_DEFAULT_OPERATORS = {
|
|
156
|
+
$now: () => /* @__PURE__ */ new Date(),
|
|
157
|
+
$uuid: () => _crypto.randomUUID.call(void 0, ),
|
|
158
|
+
$timestamp: () => Date.now(),
|
|
159
|
+
$shortId: () => _crypto.randomBytes.call(void 0, 12).toString("base64url")
|
|
160
|
+
};
|
|
161
|
+
var FIXED_DEFAULT_OPERATORS = /* @__PURE__ */ new Set(["$now", "$uuid", "$objectId", "$timestamp", "$shortId"]);
|
|
162
|
+
function isCurrentUserOperator(value) {
|
|
163
|
+
return typeof value === "string" && (value === "$currentUser" || value.startsWith("$currentUser."));
|
|
164
|
+
}
|
|
165
|
+
function isDefaultOperator(value) {
|
|
166
|
+
return typeof value === "string" && FIXED_DEFAULT_OPERATORS.has(value) || isCurrentUserOperator(value);
|
|
167
|
+
}
|
|
168
|
+
function resolveDefault(value, objectId) {
|
|
169
|
+
if (!isDefaultOperator(value)) return value;
|
|
170
|
+
if (value === "$objectId") return objectId;
|
|
171
|
+
if (value === "$currentUser") return () => _chunkRSBW2B3Dcjs.getCurrentUser.call(void 0, );
|
|
172
|
+
if (isCurrentUserOperator(value)) {
|
|
173
|
+
const key = value.slice("$currentUser.".length);
|
|
174
|
+
return () => _optionalChain([_chunkRSBW2B3Dcjs.getCurrentUser.call(void 0, ), 'optionalAccess', _ => _[key]]);
|
|
175
|
+
}
|
|
176
|
+
return STATIC_DEFAULT_OPERATORS[value];
|
|
177
|
+
}
|
|
178
|
+
function applyDefaults(tree, data, objectId) {
|
|
179
|
+
const out = { ...data };
|
|
180
|
+
for (const [key, node] of Object.entries(tree)) {
|
|
181
|
+
if (out[key] === void 0 && node.def.default !== void 0) {
|
|
182
|
+
const d = resolveDefault(node.def.default, objectId);
|
|
183
|
+
const value = typeof d === "function" ? d() : structuredClone(d);
|
|
184
|
+
if (value !== void 0) out[key] = value;
|
|
185
|
+
}
|
|
186
|
+
if (node.kind === "object" && out[key] != null && typeof out[key] === "object") {
|
|
187
|
+
out[key] = applyDefaults(node.fields, out[key], objectId);
|
|
188
|
+
}
|
|
189
|
+
if (node.kind === "array" && node.item.kind === "object" && Array.isArray(out[key])) {
|
|
190
|
+
const fields = node.item.fields;
|
|
191
|
+
out[key] = out[key].map(
|
|
192
|
+
(v) => v != null && typeof v === "object" ? applyDefaults(fields, v, objectId) : v
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
var ModelValidationError = class extends HttpError {
|
|
199
|
+
|
|
200
|
+
constructor(model, issues) {
|
|
201
|
+
super(
|
|
202
|
+
400,
|
|
203
|
+
`${model} validation failed: ${issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`
|
|
204
|
+
);
|
|
205
|
+
this.name = "ModelValidationError";
|
|
206
|
+
this.issues = issues;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
210
|
+
var INT4 = 2 ** 31;
|
|
211
|
+
var INT8_MIN = -(2n ** 63n);
|
|
212
|
+
var INT8_MAX = 2n ** 63n - 1n;
|
|
213
|
+
var DECIMAL_RE = /^[+-]?(\d+(\.\d*)?|\.\d+)$/;
|
|
214
|
+
function decimalDigits(value) {
|
|
215
|
+
const str = typeof value === "number" ? String(value) : value;
|
|
216
|
+
const [i = "", f = ""] = str.replace(/^[+-]/, "").split(".");
|
|
217
|
+
return { int: i.replace(/^0+/, "").length, frac: f.replace(/0+$/, "").length };
|
|
218
|
+
}
|
|
219
|
+
function typeError(type, def, value) {
|
|
220
|
+
switch (type) {
|
|
221
|
+
case "string":
|
|
222
|
+
return typeof value === "string" ? null : "must be a string";
|
|
223
|
+
case "number":
|
|
224
|
+
return typeof value === "number" && Number.isFinite(value) ? null : "must be a number";
|
|
225
|
+
case "integer":
|
|
226
|
+
return typeof value === "number" && Number.isInteger(value) && value >= -INT4 && value < INT4 ? null : "must be a 32-bit integer";
|
|
227
|
+
case "bigint": {
|
|
228
|
+
const big = typeof value === "bigint" ? value : typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : void 0;
|
|
229
|
+
return big !== void 0 && big >= INT8_MIN && big <= INT8_MAX ? null : "must be a 64-bit integer (bigint)";
|
|
230
|
+
}
|
|
231
|
+
case "decimal": {
|
|
232
|
+
const ok = typeof value === "number" && Number.isFinite(value) || typeof value === "string" && DECIMAL_RE.test(value);
|
|
233
|
+
if (!ok) return "must be a decimal number or numeric string";
|
|
234
|
+
if (def.precision !== void 0) {
|
|
235
|
+
const scale = _nullishCoalesce(def.scale, () => ( 0));
|
|
236
|
+
const { int, frac } = decimalDigits(value);
|
|
237
|
+
if (frac > scale) return `must have at most ${scale} decimal places`;
|
|
238
|
+
if (int > def.precision - scale)
|
|
239
|
+
return `must have at most ${def.precision - scale} digits before the decimal point`;
|
|
240
|
+
}
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
case "boolean":
|
|
244
|
+
return typeof value === "boolean" ? null : "must be a boolean";
|
|
245
|
+
case "date":
|
|
246
|
+
return !Number.isNaN(new Date(value).getTime()) ? null : "must be a date";
|
|
247
|
+
case "objectId":
|
|
248
|
+
return typeof value === "string" && UUID_RE.test(value) ? null : "must be a valid id";
|
|
249
|
+
case "uuid":
|
|
250
|
+
return typeof value === "string" && UUID_RE.test(value) ? null : "must be a UUID";
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
function compareBound(def, value, bound) {
|
|
254
|
+
if (def.type === "bigint") {
|
|
255
|
+
const a = BigInt(value);
|
|
256
|
+
const b = BigInt(bound instanceof Date ? bound.getTime() : bound);
|
|
257
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
258
|
+
}
|
|
259
|
+
const num = (v) => v instanceof Date ? v.getTime() : def.type === "date" ? new Date(v).getTime() : Number(v);
|
|
260
|
+
return num(value) - num(bound);
|
|
261
|
+
}
|
|
262
|
+
async function checkRules(def, value, path, issues) {
|
|
263
|
+
if (def.enum && !def.enum.includes(value)) {
|
|
264
|
+
issues.push({ path, message: `must be one of: ${def.enum.join(", ")}` });
|
|
265
|
+
}
|
|
266
|
+
const ordered = typeof value === "number" || typeof value === "bigint" || value instanceof Date || def.type === "date" || def.type === "decimal" && typeof value === "string";
|
|
267
|
+
if (ordered) {
|
|
268
|
+
if (def.min !== void 0 && compareBound(def, value, def.min) < 0)
|
|
269
|
+
issues.push({ path, message: `must be >= ${String(def.min)}` });
|
|
270
|
+
if (def.max !== void 0 && compareBound(def, value, def.max) > 0)
|
|
271
|
+
issues.push({ path, message: `must be <= ${String(def.max)}` });
|
|
272
|
+
}
|
|
273
|
+
if (typeof value === "string" && def.type !== "decimal") {
|
|
274
|
+
if (def.minLength !== void 0 && value.length < def.minLength)
|
|
275
|
+
issues.push({ path, message: `must be at least ${def.minLength} characters` });
|
|
276
|
+
if (def.maxLength !== void 0 && value.length > def.maxLength)
|
|
277
|
+
issues.push({ path, message: `must be at most ${def.maxLength} characters` });
|
|
278
|
+
if (def.match && !def.match.test(value))
|
|
279
|
+
issues.push({ path, message: `must match ${String(def.match)}` });
|
|
280
|
+
}
|
|
281
|
+
if (def.validate) {
|
|
282
|
+
const result = await def.validate(value);
|
|
283
|
+
if (result !== true)
|
|
284
|
+
issues.push({ path, message: typeof result === "string" ? result : "is invalid" });
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async function validateNode(node, value, path, issues, partial) {
|
|
288
|
+
if (value === void 0 || value === null) {
|
|
289
|
+
if (node.def.required && !partial) issues.push({ path, message: "is required" });
|
|
290
|
+
if (node.def.required && partial && value === null)
|
|
291
|
+
issues.push({ path, message: "is required" });
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
switch (node.kind) {
|
|
295
|
+
case "scalar": {
|
|
296
|
+
const err = typeError(node.type, node.def, value);
|
|
297
|
+
if (err) {
|
|
298
|
+
issues.push({ path, message: err });
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
await checkRules(node.def, value, path, issues);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
case "json":
|
|
305
|
+
await checkRules(node.def, value, path, issues);
|
|
306
|
+
return;
|
|
307
|
+
case "object":
|
|
308
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
309
|
+
issues.push({ path, message: "must be an object" });
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
await validateTree(node.fields, value, issues, false, path);
|
|
313
|
+
await checkRules(node.def, value, path, issues);
|
|
314
|
+
return;
|
|
315
|
+
case "array":
|
|
316
|
+
if (!Array.isArray(value)) {
|
|
317
|
+
issues.push({ path, message: "must be an array" });
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
for (let i = 0; i < value.length; i++) {
|
|
321
|
+
await validateNode(
|
|
322
|
+
{ ...node.item, def: { ...node.item.def, required: true } },
|
|
323
|
+
value[i],
|
|
324
|
+
`${path}.${i}`,
|
|
325
|
+
issues,
|
|
326
|
+
false
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
await checkRules(node.def, value, path, issues);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
async function validateTree(tree, data, issues, partial, prefix = "") {
|
|
333
|
+
for (const [key, node] of Object.entries(tree)) {
|
|
334
|
+
if (partial && !(key in data)) continue;
|
|
335
|
+
await validateNode(node, data[key], prefix ? `${prefix}.${key}` : key, issues, partial);
|
|
336
|
+
}
|
|
337
|
+
return issues;
|
|
338
|
+
}
|
|
339
|
+
function refFields(tree) {
|
|
340
|
+
const refs = /* @__PURE__ */ new Map();
|
|
341
|
+
for (const [key, node] of Object.entries(tree)) {
|
|
342
|
+
if (node.kind === "scalar" && node.type === "objectId" && node.def.ref) {
|
|
343
|
+
refs.set(key, { model: node.def.ref, many: false });
|
|
344
|
+
} else if (node.kind === "array" && node.item.kind === "scalar" && node.item.type === "objectId" && node.def.ref) {
|
|
345
|
+
refs.set(key, { model: node.def.ref, many: true });
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return refs;
|
|
349
|
+
}
|
|
350
|
+
function sequenceFields(name, tree) {
|
|
351
|
+
const out = [];
|
|
352
|
+
for (const [path, node] of Object.entries(tree)) {
|
|
353
|
+
if (node.def.sequence) {
|
|
354
|
+
out.push({
|
|
355
|
+
path,
|
|
356
|
+
key: typeof node.def.sequence === "string" ? node.def.sequence : `${name}.${path}`
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return out;
|
|
361
|
+
}
|
|
362
|
+
function nodeAt(tree, path) {
|
|
363
|
+
let node = tree[path[0]];
|
|
364
|
+
for (const part of path.slice(1)) {
|
|
365
|
+
if (!node) return void 0;
|
|
366
|
+
if (node.kind === "object") node = node.fields[part];
|
|
367
|
+
else if (node.kind === "array" && /^\d+$/.test(part)) node = node.item;
|
|
368
|
+
else if (node.kind === "json")
|
|
369
|
+
return node;
|
|
370
|
+
else return void 0;
|
|
371
|
+
}
|
|
372
|
+
return node;
|
|
373
|
+
}
|
|
374
|
+
async function validateAtPath(tree, dotted, value, issues) {
|
|
375
|
+
const node = nodeAt(tree, dotted.split("."));
|
|
376
|
+
if (!node) {
|
|
377
|
+
issues.push({ path: dotted, message: "unknown field" });
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
await validateNode(node, value, dotted, issues, true);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// src/db/engine.ts
|
|
384
|
+
var _async_hooks = require('async_hooks');
|
|
385
|
+
var engine;
|
|
386
|
+
function setDbEngine(value) {
|
|
387
|
+
engine = value;
|
|
388
|
+
}
|
|
389
|
+
function getDbEngine() {
|
|
390
|
+
return _nullishCoalesce(engine, () => ( "mongodb"));
|
|
391
|
+
}
|
|
392
|
+
var autoSync = true;
|
|
393
|
+
function setAutoSync(value) {
|
|
394
|
+
autoSync = value;
|
|
395
|
+
}
|
|
396
|
+
function isAutoSync() {
|
|
397
|
+
return autoSync;
|
|
398
|
+
}
|
|
399
|
+
var registry = /* @__PURE__ */ new Map();
|
|
400
|
+
function registerModel(model) {
|
|
401
|
+
registry.set(model.name, model);
|
|
402
|
+
}
|
|
403
|
+
function getRegisteredModel(name) {
|
|
404
|
+
return registry.get(name);
|
|
405
|
+
}
|
|
406
|
+
function registeredModels() {
|
|
407
|
+
return [...registry.values()];
|
|
408
|
+
}
|
|
409
|
+
var txStorage = new (0, _async_hooks.AsyncLocalStorage)();
|
|
410
|
+
function currentTx() {
|
|
411
|
+
return txStorage.getStore();
|
|
412
|
+
}
|
|
413
|
+
function runInTx(handle, fn) {
|
|
414
|
+
return txStorage.run(handle, fn);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// src/db/mongo-model.ts
|
|
418
|
+
var mongoosePromise;
|
|
419
|
+
function loadMongoose() {
|
|
420
|
+
mongoosePromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("mongoose"))).then((mod) => _nullishCoalesce(mod.default, () => ( mod))).catch((err) => {
|
|
421
|
+
mongoosePromise = void 0;
|
|
422
|
+
throw _chunkALBDM5R3cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
|
|
423
|
+
});
|
|
424
|
+
return mongoosePromise;
|
|
425
|
+
}
|
|
426
|
+
function ctor(type, mg) {
|
|
427
|
+
switch (type) {
|
|
428
|
+
case "string":
|
|
429
|
+
return String;
|
|
430
|
+
case "number":
|
|
431
|
+
return Number;
|
|
432
|
+
case "boolean":
|
|
433
|
+
return Boolean;
|
|
434
|
+
case "date":
|
|
435
|
+
return Date;
|
|
436
|
+
case "objectId":
|
|
437
|
+
return mg.Schema.Types.ObjectId;
|
|
438
|
+
}
|
|
439
|
+
return mg.Schema.Types.Mixed;
|
|
440
|
+
}
|
|
441
|
+
function rules(node, mg) {
|
|
442
|
+
const d = node.def;
|
|
443
|
+
const entry = {};
|
|
444
|
+
if (d.required !== void 0) entry["required"] = d.required;
|
|
445
|
+
if (d.unique !== void 0) entry["unique"] = d.unique;
|
|
446
|
+
if (d.index !== void 0) entry["index"] = d.index;
|
|
447
|
+
if (d.default !== void 0)
|
|
448
|
+
entry["default"] = resolveDefault(d.default, () => new mg.Types.ObjectId());
|
|
449
|
+
if (d.enum !== void 0) entry["enum"] = d.enum;
|
|
450
|
+
if (d.min !== void 0) entry["min"] = d.min;
|
|
451
|
+
if (d.max !== void 0) entry["max"] = d.max;
|
|
452
|
+
if (d.minLength !== void 0) entry["minlength"] = d.minLength;
|
|
453
|
+
if (d.maxLength !== void 0) entry["maxlength"] = d.maxLength;
|
|
454
|
+
if (d.match !== void 0) entry["match"] = d.match;
|
|
455
|
+
if (d.validate !== void 0) {
|
|
456
|
+
const check = d.validate;
|
|
457
|
+
entry["validate"] = {
|
|
458
|
+
validator: async (v) => {
|
|
459
|
+
const result = await check(v);
|
|
460
|
+
if (result === true) return true;
|
|
461
|
+
throw new Error(typeof result === "string" ? result : "is invalid");
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
return entry;
|
|
466
|
+
}
|
|
467
|
+
function buildNode(node, mg) {
|
|
468
|
+
switch (node.kind) {
|
|
469
|
+
case "scalar": {
|
|
470
|
+
const entry = { type: ctor(node.type, mg), ...rules(node, mg) };
|
|
471
|
+
if (node.type === "objectId" && node.def.ref !== void 0) entry["ref"] = node.def.ref;
|
|
472
|
+
return entry;
|
|
473
|
+
}
|
|
474
|
+
case "json":
|
|
475
|
+
return { type: mg.Schema.Types.Mixed, ...rules(node, mg) };
|
|
476
|
+
case "object":
|
|
477
|
+
return {
|
|
478
|
+
type: new mg.Schema(buildTree(node.fields, mg), { _id: false }),
|
|
479
|
+
...rules(node, mg)
|
|
480
|
+
};
|
|
481
|
+
case "array": {
|
|
482
|
+
let item;
|
|
483
|
+
if (node.item.kind === "object") item = new mg.Schema(buildTree(node.item.fields, mg));
|
|
484
|
+
else if (node.item.kind === "json") item = mg.Schema.Types.Mixed;
|
|
485
|
+
else item = buildNode(node.item, mg);
|
|
486
|
+
return { type: [item], ...rules(node, mg) };
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function buildTree(tree, mg) {
|
|
491
|
+
const out = {};
|
|
492
|
+
for (const [key, node] of Object.entries(tree)) out[key] = buildNode(node, mg);
|
|
493
|
+
return out;
|
|
494
|
+
}
|
|
495
|
+
var COUNTER_MODEL_NAME = "__EFCCounter__";
|
|
496
|
+
function getCounterModel(mg) {
|
|
497
|
+
if (mg.models[COUNTER_MODEL_NAME])
|
|
498
|
+
return mg.models[COUNTER_MODEL_NAME];
|
|
499
|
+
const counterSchema = new mg.Schema(
|
|
500
|
+
{ _id: { type: String, required: true }, seq: { type: Number, default: 0 } },
|
|
501
|
+
{ collection: "efc_counters", versionKey: false }
|
|
502
|
+
);
|
|
503
|
+
return mg.model(COUNTER_MODEL_NAME, counterSchema);
|
|
504
|
+
}
|
|
505
|
+
async function nextSequence(mg, key) {
|
|
506
|
+
const doc = await getCounterModel(mg).findByIdAndUpdate(key, { $inc: { seq: 1 } }, { returnDocument: "after", upsert: true }).lean();
|
|
507
|
+
return doc.seq;
|
|
508
|
+
}
|
|
509
|
+
function normalise(value) {
|
|
510
|
+
if (Array.isArray(value)) return value.map(normalise);
|
|
511
|
+
if (value == null || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
|
|
512
|
+
return value;
|
|
513
|
+
}
|
|
514
|
+
const out = {};
|
|
515
|
+
for (const [k, v] of Object.entries(value)) out[k] = normalise(v);
|
|
516
|
+
if ("_id" in out) out["id"] = String(out["_id"]);
|
|
517
|
+
return out;
|
|
518
|
+
}
|
|
519
|
+
function translateError(model, err) {
|
|
520
|
+
const e = err;
|
|
521
|
+
if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "ValidationError" && e.errors) {
|
|
522
|
+
throw new ModelValidationError(
|
|
523
|
+
model,
|
|
524
|
+
Object.entries(e.errors).map(([path, v]) => ({
|
|
525
|
+
path,
|
|
526
|
+
message: v.message.replace(
|
|
527
|
+
/^Validator failed for path `[^`]+` with value `[^`]*`$/,
|
|
528
|
+
"is invalid"
|
|
529
|
+
)
|
|
530
|
+
}))
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
if (_optionalChain([e, 'optionalAccess', _3 => _3.name]) === "CastError") {
|
|
534
|
+
throw new ModelValidationError(model, [
|
|
535
|
+
{ path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
|
|
536
|
+
]);
|
|
537
|
+
}
|
|
538
|
+
if (_optionalChain([e, 'optionalAccess', _4 => _4.code]) === 11e3) {
|
|
539
|
+
const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
|
|
540
|
+
throw new HttpError(409, `${model} with this ${field} already exists`);
|
|
541
|
+
}
|
|
542
|
+
throw err;
|
|
543
|
+
}
|
|
544
|
+
function isCastErrorOnId(err) {
|
|
545
|
+
const e = err;
|
|
546
|
+
return _optionalChain([e, 'optionalAccess', _5 => _5.name]) === "CastError" && e.path === "_id";
|
|
547
|
+
}
|
|
548
|
+
function mapFilter(filter) {
|
|
549
|
+
if (!filter) return {};
|
|
550
|
+
const out = {};
|
|
551
|
+
for (const [k, v] of Object.entries(filter)) {
|
|
552
|
+
if (k === "$and" || k === "$or") out[k] = v.map(mapFilter);
|
|
553
|
+
else out[k === "id" ? "_id" : k] = v;
|
|
554
|
+
}
|
|
555
|
+
return out;
|
|
556
|
+
}
|
|
557
|
+
function mapSort(sort) {
|
|
558
|
+
if (!sort) return void 0;
|
|
559
|
+
const out = {};
|
|
560
|
+
for (const [k, v] of Object.entries(sort))
|
|
561
|
+
out[k === "id" ? "_id" : k] = v === -1 || v === "desc" ? -1 : 1;
|
|
562
|
+
return out;
|
|
563
|
+
}
|
|
564
|
+
function mongoModel(name, tree, options) {
|
|
565
|
+
let compiled;
|
|
566
|
+
const model = () => compiled ??= loadMongoose().then(async (mg) => {
|
|
567
|
+
if (mg.models[name]) return mg.models[name];
|
|
568
|
+
const schema = new mg.Schema(buildTree(tree, mg), {
|
|
569
|
+
timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
|
|
570
|
+
// autoSync: false hands collection and index creation to migrations, on MongoDB too.
|
|
571
|
+
autoIndex: isAutoSync(),
|
|
572
|
+
autoCreate: isAutoSync(),
|
|
573
|
+
...options.collection !== void 0 && { collection: options.collection }
|
|
574
|
+
});
|
|
575
|
+
for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
|
|
576
|
+
schema.index(idx.fields, {
|
|
577
|
+
...idx.unique !== void 0 && { unique: idx.unique },
|
|
578
|
+
...idx.expireAfterSeconds !== void 0 && {
|
|
579
|
+
expireAfterSeconds: idx.expireAfterSeconds
|
|
580
|
+
},
|
|
581
|
+
...idx.name !== void 0 && { name: idx.name }
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
const sequences = sequenceFields(name, tree);
|
|
585
|
+
if (sequences.length > 0) {
|
|
586
|
+
schema.pre("validate", async function() {
|
|
587
|
+
if (!this.isNew) return;
|
|
588
|
+
for (const { path, key } of sequences) {
|
|
589
|
+
if (this.get(path) == null) this.set(path, await nextSequence(mg, key));
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
const M = mg.model(name, schema);
|
|
594
|
+
if (isAutoSync()) {
|
|
595
|
+
await M.init().catch((err) => {
|
|
596
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).warn(
|
|
597
|
+
{ model: name, err: err.message },
|
|
598
|
+
`${name}: could not build its indexes \u2014 fix the data, then run efc db sync`
|
|
599
|
+
);
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
return M;
|
|
603
|
+
});
|
|
604
|
+
const session = () => {
|
|
605
|
+
const tx = currentTx();
|
|
606
|
+
return _optionalChain([tx, 'optionalAccess', _6 => _6.engine]) === "mongodb" ? { session: tx.session } : {};
|
|
607
|
+
};
|
|
608
|
+
const applyQueryOptions = (q2, opts) => {
|
|
609
|
+
if (_optionalChain([opts, 'optionalAccess', _7 => _7.populate])) q2.populate(opts.populate);
|
|
610
|
+
if (_optionalChain([opts, 'optionalAccess', _8 => _8.select])) q2.select(opts.select.join(" "));
|
|
611
|
+
const f = opts;
|
|
612
|
+
const sort = mapSort(_optionalChain([f, 'optionalAccess', _9 => _9.sort]));
|
|
613
|
+
if (sort) q2.sort(sort);
|
|
614
|
+
if (_optionalChain([f, 'optionalAccess', _10 => _10.skip]) !== void 0) q2.skip(f.skip);
|
|
615
|
+
if (_optionalChain([f, 'optionalAccess', _11 => _11.limit]) !== void 0) q2.limit(f.limit);
|
|
616
|
+
return q2;
|
|
617
|
+
};
|
|
618
|
+
const guard = async (fn) => {
|
|
619
|
+
try {
|
|
620
|
+
return await fn();
|
|
621
|
+
} catch (err) {
|
|
622
|
+
return translateError(name, err);
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
return {
|
|
626
|
+
find: (filter, opts) => guard(async () => {
|
|
627
|
+
const M = await model();
|
|
628
|
+
const docs = await applyQueryOptions(
|
|
629
|
+
M.find(mapFilter(filter), null, session()),
|
|
630
|
+
opts
|
|
631
|
+
).lean();
|
|
632
|
+
return normalise(docs);
|
|
633
|
+
}),
|
|
634
|
+
async findById(id, opts) {
|
|
635
|
+
try {
|
|
636
|
+
const M = await model();
|
|
637
|
+
const doc = await applyQueryOptions(M.findById(id, null, session()), opts).lean();
|
|
638
|
+
return doc ? normalise(doc) : null;
|
|
639
|
+
} catch (err) {
|
|
640
|
+
if (isCastErrorOnId(err)) return null;
|
|
641
|
+
return translateError(name, err);
|
|
642
|
+
}
|
|
643
|
+
},
|
|
644
|
+
findOne: (filter, opts) => guard(async () => {
|
|
645
|
+
const M = await model();
|
|
646
|
+
const doc = await applyQueryOptions(
|
|
647
|
+
M.findOne(mapFilter(filter), null, session()),
|
|
648
|
+
opts
|
|
649
|
+
).lean();
|
|
650
|
+
return doc ? normalise(doc) : null;
|
|
651
|
+
}),
|
|
652
|
+
create: (data) => guard(async () => {
|
|
653
|
+
const M = await model();
|
|
654
|
+
const [doc] = await M.create([data], session());
|
|
655
|
+
return normalise(doc.toObject());
|
|
656
|
+
}),
|
|
657
|
+
exists: (filter) => guard(async () => {
|
|
658
|
+
const M = await model();
|
|
659
|
+
return await M.exists(mapFilter(filter)).session(_nullishCoalesce(session().session, () => ( null))) !== null;
|
|
660
|
+
}),
|
|
661
|
+
distinct: (field, filter) => guard(async () => {
|
|
662
|
+
const mg = await loadMongoose();
|
|
663
|
+
const M = await model();
|
|
664
|
+
const values = await M.distinct(
|
|
665
|
+
field === "id" ? "_id" : field,
|
|
666
|
+
mapFilter(filter)
|
|
667
|
+
).session(_nullishCoalesce(session().session, () => ( null)));
|
|
668
|
+
return values.map((v) => v instanceof mg.Types.ObjectId ? String(v) : v);
|
|
669
|
+
}),
|
|
670
|
+
createMany: (data) => guard(async () => {
|
|
671
|
+
const M = await model();
|
|
672
|
+
if (data.length === 0) return [];
|
|
673
|
+
const docs = await M.create(data, { ...session(), ordered: true });
|
|
674
|
+
return docs.map((d) => normalise(d.toObject()));
|
|
675
|
+
}),
|
|
676
|
+
async update(id, data) {
|
|
677
|
+
try {
|
|
678
|
+
const M = await model();
|
|
679
|
+
const doc = await M.findByIdAndUpdate(id, data, {
|
|
680
|
+
returnDocument: "after",
|
|
681
|
+
runValidators: true,
|
|
682
|
+
...session()
|
|
683
|
+
}).lean();
|
|
684
|
+
return doc ? normalise(doc) : null;
|
|
685
|
+
} catch (err) {
|
|
686
|
+
if (isCastErrorOnId(err)) return null;
|
|
687
|
+
return translateError(name, err);
|
|
688
|
+
}
|
|
689
|
+
},
|
|
690
|
+
updateOne: (filter, data) => guard(async () => {
|
|
691
|
+
const M = await model();
|
|
692
|
+
const doc = await M.findOneAndUpdate(mapFilter(filter), data, {
|
|
693
|
+
returnDocument: "after",
|
|
694
|
+
runValidators: true,
|
|
695
|
+
...session()
|
|
696
|
+
}).lean();
|
|
697
|
+
return doc ? normalise(doc) : null;
|
|
698
|
+
}),
|
|
699
|
+
updateMany: (filter, data) => guard(async () => {
|
|
700
|
+
const M = await model();
|
|
701
|
+
const r = await M.updateMany(mapFilter(filter), data, {
|
|
702
|
+
runValidators: true,
|
|
703
|
+
...session()
|
|
704
|
+
});
|
|
705
|
+
return r.modifiedCount;
|
|
706
|
+
}),
|
|
707
|
+
async delete(id) {
|
|
708
|
+
try {
|
|
709
|
+
const M = await model();
|
|
710
|
+
await M.findByIdAndDelete(id, session());
|
|
711
|
+
} catch (err) {
|
|
712
|
+
if (isCastErrorOnId(err)) return;
|
|
713
|
+
translateError(name, err);
|
|
714
|
+
}
|
|
715
|
+
},
|
|
716
|
+
deleteOne: (filter) => guard(async () => {
|
|
717
|
+
const M = await model();
|
|
718
|
+
const doc = await M.findOneAndDelete(mapFilter(filter), session()).lean();
|
|
719
|
+
return doc ? normalise(doc) : null;
|
|
720
|
+
}),
|
|
721
|
+
deleteMany: (filter) => guard(async () => {
|
|
722
|
+
const M = await model();
|
|
723
|
+
const r = await M.deleteMany(mapFilter(filter), session());
|
|
724
|
+
return r.deletedCount;
|
|
725
|
+
}),
|
|
726
|
+
count: (filter) => guard(async () => {
|
|
727
|
+
const M = await model();
|
|
728
|
+
return M.countDocuments(mapFilter(filter), session());
|
|
729
|
+
}),
|
|
730
|
+
aggregate: (pipeline) => guard(async () => {
|
|
731
|
+
const M = await model();
|
|
732
|
+
const agg = M.aggregate(pipeline);
|
|
733
|
+
const s = session().session;
|
|
734
|
+
if (s) agg.session(s);
|
|
735
|
+
return await agg;
|
|
736
|
+
}),
|
|
737
|
+
raw: () => model(),
|
|
738
|
+
async sync(opts) {
|
|
739
|
+
const M = await model();
|
|
740
|
+
const changes = [];
|
|
741
|
+
const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
|
|
742
|
+
if (!exists) changes.push(`createCollection ${M.collection.collectionName}`);
|
|
743
|
+
const diff = await M.diffIndexes().catch(() => ({ toDrop: [], toCreate: [] }));
|
|
744
|
+
for (const idx of diff.toDrop) changes.push(`dropIndex ${String(idx)}`);
|
|
745
|
+
for (const idx of diff.toCreate) changes.push(`createIndex ${JSON.stringify(idx)}`);
|
|
746
|
+
if (_optionalChain([opts, 'optionalAccess', _12 => _12.dryRun])) return changes;
|
|
747
|
+
if (!exists) {
|
|
748
|
+
await M.createCollection().catch((err) => {
|
|
749
|
+
if (_optionalChain([err, 'optionalAccess', _13 => _13.code]) !== 48) throw err;
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
await M.syncIndexes();
|
|
753
|
+
return changes;
|
|
754
|
+
},
|
|
755
|
+
async drop() {
|
|
756
|
+
const M = await model();
|
|
757
|
+
await M.collection.drop().catch((err) => {
|
|
758
|
+
if (_optionalChain([err, 'optionalAccess', _14 => _14.code]) !== 26) throw err;
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/db/mongo.ts
|
|
765
|
+
async function connectMongo(url) {
|
|
766
|
+
const mg = await loadMongoose();
|
|
767
|
+
await mg.connect(url);
|
|
768
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info("MongoDB connected");
|
|
769
|
+
return mg.connection;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
// src/db/pg-table.ts
|
|
773
|
+
|
|
774
|
+
var drizzlePromise;
|
|
775
|
+
function loadDrizzle() {
|
|
776
|
+
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(() => {
|
|
777
|
+
drizzlePromise = void 0;
|
|
778
|
+
throw new Error("[EFC] drizzle-orm is not installed. Run: npm install pg drizzle-orm");
|
|
779
|
+
});
|
|
780
|
+
return drizzlePromise;
|
|
781
|
+
}
|
|
782
|
+
function tableNameFor(model) {
|
|
783
|
+
const lower = model.toLowerCase();
|
|
784
|
+
if (/[^aeiou]y$/.test(lower)) return lower.slice(0, -1) + "ies";
|
|
785
|
+
if (/(s|x|z|ch|sh)$/.test(lower)) return lower + "es";
|
|
786
|
+
return lower + "s";
|
|
787
|
+
}
|
|
788
|
+
var snakeCase = (s) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z])([A-Z][a-z])/g, "$1_$2").toLowerCase();
|
|
789
|
+
var q = (ident) => `"${ident.replace(/"/g, '""')}"`;
|
|
790
|
+
var sequenceName = (key) => `efc_seq_${key.replace(/[^A-Za-z0-9_]/g, "_").toLowerCase()}`;
|
|
791
|
+
var literal = (v) => typeof v === "number" ? String(v) : `'${v.replace(/'/g, "''")}'`;
|
|
792
|
+
function scalarSpec(type, def, native) {
|
|
793
|
+
switch (type) {
|
|
794
|
+
case "string":
|
|
795
|
+
if (native && def.maxLength !== void 0) {
|
|
796
|
+
return {
|
|
797
|
+
kind: "varchar",
|
|
798
|
+
ddl: `varchar(${def.maxLength})`,
|
|
799
|
+
formatted: `character varying(${def.maxLength})`,
|
|
800
|
+
length: def.maxLength
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
return { kind: "text", ddl: "text", formatted: "text" };
|
|
804
|
+
case "number":
|
|
805
|
+
return { kind: "double", ddl: "double precision", formatted: "double precision" };
|
|
806
|
+
case "integer":
|
|
807
|
+
return { kind: "integer", ddl: "integer", formatted: "integer" };
|
|
808
|
+
case "bigint":
|
|
809
|
+
return { kind: "bigint", ddl: "bigint", formatted: "bigint", bigintAs: "bigint" };
|
|
810
|
+
case "decimal": {
|
|
811
|
+
if (def.precision === void 0)
|
|
812
|
+
return { kind: "numeric", ddl: "numeric", formatted: "numeric" };
|
|
813
|
+
const t = `numeric(${def.precision},${_nullishCoalesce(def.scale, () => ( 0))})`;
|
|
814
|
+
return {
|
|
815
|
+
kind: "numeric",
|
|
816
|
+
ddl: t,
|
|
817
|
+
formatted: t,
|
|
818
|
+
precision: def.precision,
|
|
819
|
+
scale: _nullishCoalesce(def.scale, () => ( 0))
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
case "boolean":
|
|
823
|
+
return { kind: "boolean", ddl: "boolean", formatted: "boolean" };
|
|
824
|
+
case "date":
|
|
825
|
+
return { kind: "timestamptz", ddl: "timestamptz", formatted: "timestamp with time zone" };
|
|
826
|
+
case "objectId":
|
|
827
|
+
case "uuid":
|
|
828
|
+
return { kind: "uuid", ddl: "uuid", formatted: "uuid" };
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
function pgTable(name, tree, options, config) {
|
|
832
|
+
const snake = config.native && options.naming === "snake_case";
|
|
833
|
+
const table = _nullishCoalesce(options.collection, () => ( tableNameFor(snake ? snakeCase(name) : name)));
|
|
834
|
+
const columnName = (field, def) => _nullishCoalesce(_optionalChain([def, 'optionalAccess', _15 => _15.column]), () => ( (snake ? snakeCase(field) : field)));
|
|
835
|
+
const idKind = config.native && options.id || "uuid";
|
|
836
|
+
if (tree["id"]) throw new Error(`[EFC] ${name}: "id" is the primary key \u2014 don't declare it`);
|
|
837
|
+
const ts = timestampFields(options);
|
|
838
|
+
const sequences = sequenceFields(name, tree);
|
|
839
|
+
const sequenceKeys = new Map(sequences.map((s) => [s.path, s.key]));
|
|
840
|
+
const refs = refFields(tree);
|
|
841
|
+
const columns = /* @__PURE__ */ new Map();
|
|
842
|
+
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" } : {
|
|
843
|
+
field: "id",
|
|
844
|
+
column: "id",
|
|
845
|
+
kind: "bigint",
|
|
846
|
+
ddl: "bigint",
|
|
847
|
+
formatted: "bigint",
|
|
848
|
+
bigintAs: "bigint"
|
|
849
|
+
};
|
|
850
|
+
columns.set("id", idSpec);
|
|
851
|
+
for (const [field, node] of Object.entries(tree)) {
|
|
852
|
+
const column = columnName(field, node.def);
|
|
853
|
+
const base = { field, column, node };
|
|
854
|
+
if (sequenceKeys.has(field)) {
|
|
855
|
+
columns.set(field, {
|
|
856
|
+
...base,
|
|
857
|
+
kind: "bigint",
|
|
858
|
+
ddl: "bigint",
|
|
859
|
+
formatted: "bigint",
|
|
860
|
+
bigintAs: "number"
|
|
861
|
+
});
|
|
862
|
+
} else if (node.kind === "scalar") {
|
|
863
|
+
if (config.native && node.def.nativeEnum && node.def.enum) {
|
|
864
|
+
const enumType = `${table}_${column}_enum`;
|
|
865
|
+
columns.set(field, {
|
|
866
|
+
...base,
|
|
867
|
+
kind: "enum",
|
|
868
|
+
ddl: q(enumType),
|
|
869
|
+
formatted: /^[a-z_][a-z0-9_]*$/.test(enumType) ? enumType : q(enumType),
|
|
870
|
+
enumType,
|
|
871
|
+
enumValues: node.def.enum.map(String)
|
|
872
|
+
});
|
|
873
|
+
} else {
|
|
874
|
+
columns.set(field, { ...base, ...scalarSpec(node.type, node.def, config.native) });
|
|
875
|
+
}
|
|
876
|
+
} else if (config.native && node.kind === "array" && node.item.kind === "scalar") {
|
|
877
|
+
const item = scalarSpec(node.item.type, node.item.def, false);
|
|
878
|
+
columns.set(field, {
|
|
879
|
+
...base,
|
|
880
|
+
...item,
|
|
881
|
+
kind: "array",
|
|
882
|
+
item: item.kind,
|
|
883
|
+
ddl: `${item.ddl}[]`,
|
|
884
|
+
formatted: `${item.formatted}[]`
|
|
885
|
+
});
|
|
886
|
+
} else {
|
|
887
|
+
columns.set(field, { ...base, kind: "jsonb", ddl: "jsonb", formatted: "jsonb" });
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
for (const field of [ts.createdAt, ts.updatedAt]) {
|
|
891
|
+
if (field) {
|
|
892
|
+
columns.set(field, {
|
|
893
|
+
field,
|
|
894
|
+
column: columnName(field),
|
|
895
|
+
kind: "timestamptz",
|
|
896
|
+
ddl: "timestamptz",
|
|
897
|
+
formatted: "timestamp with time zone"
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
const byColumn = new Map([...columns.values()].map((c) => [c.column, c]));
|
|
902
|
+
const builder = (pgCore, kind, spec) => {
|
|
903
|
+
const c = spec.column;
|
|
904
|
+
switch (kind) {
|
|
905
|
+
case "varchar":
|
|
906
|
+
return pgCore.varchar(c, { length: spec.length });
|
|
907
|
+
case "double":
|
|
908
|
+
return pgCore.doublePrecision(c);
|
|
909
|
+
case "integer":
|
|
910
|
+
return pgCore.integer(c);
|
|
911
|
+
case "bigint":
|
|
912
|
+
return pgCore.bigint(c, { mode: _nullishCoalesce(spec.bigintAs, () => ( "bigint")) });
|
|
913
|
+
case "numeric":
|
|
914
|
+
return pgCore.numeric(
|
|
915
|
+
c,
|
|
916
|
+
spec.precision !== void 0 ? { precision: spec.precision, scale: spec.scale } : {}
|
|
917
|
+
);
|
|
918
|
+
case "boolean":
|
|
919
|
+
return pgCore.boolean(c);
|
|
920
|
+
case "timestamptz":
|
|
921
|
+
return pgCore.timestamp(c, { withTimezone: true, mode: "date" });
|
|
922
|
+
case "uuid":
|
|
923
|
+
return pgCore.uuid(c);
|
|
924
|
+
default:
|
|
925
|
+
return pgCore.text(c);
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
let compiled;
|
|
929
|
+
const compile = () => compiled ??= loadDrizzle().then(({ sql, pgCore }) => {
|
|
930
|
+
const cols = {};
|
|
931
|
+
for (const [field, spec] of columns) {
|
|
932
|
+
let c;
|
|
933
|
+
if (spec.kind === "jsonb") c = pgCore.jsonb(spec.column);
|
|
934
|
+
else if (spec.kind === "array") c = builder(pgCore, spec.item, spec).array();
|
|
935
|
+
else c = builder(pgCore, spec.kind, spec);
|
|
936
|
+
if (field === "id") {
|
|
937
|
+
c = idKind === "uuid" ? c.primaryKey().defaultRandom() : c.primaryKey().generatedByDefaultAsIdentity();
|
|
938
|
+
}
|
|
939
|
+
cols[field] = c;
|
|
940
|
+
}
|
|
941
|
+
return { t: pgCore.pgTable(table, cols), sql };
|
|
942
|
+
});
|
|
943
|
+
let synced;
|
|
944
|
+
const ready = async () => {
|
|
945
|
+
const result = await compile();
|
|
946
|
+
if (isAutoSync()) {
|
|
947
|
+
synced ??= reconcile(false).then(
|
|
948
|
+
(changes) => {
|
|
949
|
+
if (changes.length)
|
|
950
|
+
_chunkRSBW2B3Dcjs.getLogger.call(void 0, ).info({ table, changes: changes.length }, `Synced table ${table}`);
|
|
951
|
+
},
|
|
952
|
+
(err) => {
|
|
953
|
+
synced = void 0;
|
|
954
|
+
throw err;
|
|
955
|
+
}
|
|
956
|
+
);
|
|
957
|
+
await synced;
|
|
958
|
+
}
|
|
959
|
+
return result;
|
|
960
|
+
};
|
|
961
|
+
const client = () => {
|
|
962
|
+
const tx = currentTx();
|
|
963
|
+
return _optionalChain([tx, 'optionalAccess', _16 => _16.engine]) === "postgresql" ? tx.tx : _chunkALBDM5R3cjs.getOrm.call(void 0, );
|
|
964
|
+
};
|
|
965
|
+
const columnFor = (t, field) => {
|
|
966
|
+
if (!columns.has(field))
|
|
967
|
+
throw new ModelValidationError(name, [{ path: field, message: "unknown field" }]);
|
|
968
|
+
return t[field];
|
|
969
|
+
};
|
|
970
|
+
const scalarToDb = (kind, spec, v) => {
|
|
971
|
+
if (v == null) return v;
|
|
972
|
+
if (kind === "timestamptz") return v instanceof Date ? v : new Date(v);
|
|
973
|
+
if (kind === "bigint")
|
|
974
|
+
return spec.bigintAs === "number" ? Number(v) : BigInt(v);
|
|
975
|
+
if (kind === "numeric") return String(v);
|
|
976
|
+
return v;
|
|
977
|
+
};
|
|
978
|
+
const toDb = (field, value) => {
|
|
979
|
+
const spec = columns.get(field);
|
|
980
|
+
if (!spec || value == null) return value;
|
|
981
|
+
if (spec.kind === "array") {
|
|
982
|
+
return Array.isArray(value) ? value.map((v) => scalarToDb(spec.item, spec, v)) : value;
|
|
983
|
+
}
|
|
984
|
+
if (spec.kind === "jsonb") return value;
|
|
985
|
+
return scalarToDb(spec.kind, spec, value);
|
|
986
|
+
};
|
|
987
|
+
const revive = (node, value) => {
|
|
988
|
+
if (value == null) return value;
|
|
989
|
+
if (node.kind === "scalar") {
|
|
990
|
+
if (node.type === "date" && typeof value === "string") return new Date(value);
|
|
991
|
+
return value;
|
|
992
|
+
}
|
|
993
|
+
if (node.kind === "array" && Array.isArray(value))
|
|
994
|
+
return value.map((v) => revive(node.item, v));
|
|
995
|
+
if (node.kind === "object" && typeof value === "object" && !Array.isArray(value)) {
|
|
996
|
+
const out = { ...value };
|
|
997
|
+
for (const [k, child] of Object.entries(node.fields)) {
|
|
998
|
+
if (out[k] !== void 0) out[k] = revive(child, out[k]);
|
|
999
|
+
}
|
|
1000
|
+
return out;
|
|
1001
|
+
}
|
|
1002
|
+
return value;
|
|
1003
|
+
};
|
|
1004
|
+
const hasNestedDate = (node) => node.kind === "scalar" ? node.type === "date" : node.kind === "array" ? hasNestedDate(node.item) : node.kind === "object" && Object.values(node.fields).some(hasNestedDate);
|
|
1005
|
+
const datedJson = [...columns.values()].filter(
|
|
1006
|
+
(c) => c.kind === "jsonb" && c.node && hasNestedDate(c.node)
|
|
1007
|
+
);
|
|
1008
|
+
const bigintCols = [...columns.values()].filter(
|
|
1009
|
+
(c) => c.kind === "bigint" && c.bigintAs === "bigint" || c.kind === "array" && c.item === "bigint"
|
|
1010
|
+
);
|
|
1011
|
+
const fromRow = (row) => {
|
|
1012
|
+
const out = {};
|
|
1013
|
+
for (const [k, v] of Object.entries(row)) if (v !== null) out[k] = v;
|
|
1014
|
+
for (const c of datedJson)
|
|
1015
|
+
if (out[c.field] !== void 0) out[c.field] = revive(c.node, out[c.field]);
|
|
1016
|
+
for (const c of bigintCols) {
|
|
1017
|
+
const v = out[c.field];
|
|
1018
|
+
if (typeof v === "string" || typeof v === "number") out[c.field] = BigInt(v);
|
|
1019
|
+
else if (Array.isArray(v)) out[c.field] = v.map((x) => x == null ? x : BigInt(x));
|
|
1020
|
+
}
|
|
1021
|
+
return out;
|
|
1022
|
+
};
|
|
1023
|
+
const fromRawRow = (row) => {
|
|
1024
|
+
const keyed = {};
|
|
1025
|
+
for (const [col, v] of Object.entries(row)) {
|
|
1026
|
+
const spec = byColumn.get(col);
|
|
1027
|
+
if (!spec) continue;
|
|
1028
|
+
keyed[spec.field] = v != null && spec.kind === "timestamptz" && !(v instanceof Date) ? new Date(v) : v;
|
|
1029
|
+
}
|
|
1030
|
+
return fromRow(keyed);
|
|
1031
|
+
};
|
|
1032
|
+
const validate = async (data, partial) => {
|
|
1033
|
+
const issues = [];
|
|
1034
|
+
const checkTree = {};
|
|
1035
|
+
for (const [k, node] of Object.entries(tree)) {
|
|
1036
|
+
checkTree[k] = sequenceKeys.has(k) ? { ...node, def: { ...node.def, required: false } } : node;
|
|
1037
|
+
}
|
|
1038
|
+
await validateTree(checkTree, data, issues, partial);
|
|
1039
|
+
if (issues.length) throw new ModelValidationError(name, issues);
|
|
1040
|
+
};
|
|
1041
|
+
const known = (data) => Object.fromEntries(Object.entries(data).filter(([k]) => columns.has(k.split(".")[0])));
|
|
1042
|
+
const prepareInsert = async (input) => {
|
|
1043
|
+
const { id, ...rest } = known(input);
|
|
1044
|
+
for (const f of [ts.createdAt, ts.updatedAt]) if (f) delete rest[f];
|
|
1045
|
+
const data = applyDefaults(tree, rest, _crypto.randomUUID);
|
|
1046
|
+
await validate(data, false);
|
|
1047
|
+
const now = /* @__PURE__ */ new Date();
|
|
1048
|
+
if (ts.createdAt) data[ts.createdAt] = now;
|
|
1049
|
+
if (ts.updatedAt) data[ts.updatedAt] = now;
|
|
1050
|
+
if (id !== void 0) data["id"] = id;
|
|
1051
|
+
for (const [k, v] of Object.entries(data)) data[k] = toDb(k, v);
|
|
1052
|
+
return data;
|
|
1053
|
+
};
|
|
1054
|
+
const fieldOfColumn = (column) => _nullishCoalesce(_optionalChain([byColumn, 'access', _17 => _17.get, 'call', _18 => _18(column), 'optionalAccess', _19 => _19.field]), () => ( column));
|
|
1055
|
+
const guard = async (fn) => {
|
|
1056
|
+
try {
|
|
1057
|
+
return await fn();
|
|
1058
|
+
} catch (err) {
|
|
1059
|
+
const e = _nullishCoalesce(err.cause, () => ( err));
|
|
1060
|
+
if (_optionalChain([e, 'optionalAccess', _20 => _20.code]) === "42P01") {
|
|
1061
|
+
throw new Error(
|
|
1062
|
+
`[EFC] ${name}: table "${table}" does not exist \u2014 autoSync is off, so create it with a migration (Model.sync() / efc db sync)`
|
|
1063
|
+
);
|
|
1064
|
+
}
|
|
1065
|
+
if (_optionalChain([e, 'optionalAccess', _21 => _21.code]) === "23505") {
|
|
1066
|
+
const cols = _nullishCoalesce(_optionalChain([/\(([^)]+)\)=/, 'access', _22 => _22.exec, 'call', _23 => _23(_nullishCoalesce(e.detail, () => ( ""))), 'optionalAccess', _24 => _24[1]]), () => ( "field"));
|
|
1067
|
+
const fields = cols.split(",").map((c) => fieldOfColumn(c.trim().replace(/"/g, ""))).join(", ");
|
|
1068
|
+
throw new HttpError(409, `${name} with this ${fields} already exists`);
|
|
1069
|
+
}
|
|
1070
|
+
if (_optionalChain([e, 'optionalAccess', _25 => _25.code]) === "23502")
|
|
1071
|
+
throw new ModelValidationError(name, [
|
|
1072
|
+
{ path: fieldOfColumn(_nullishCoalesce(e.column, () => ( ""))), message: "is required" }
|
|
1073
|
+
]);
|
|
1074
|
+
if (_optionalChain([e, 'optionalAccess', _26 => _26.code]) === "22P02" || _optionalChain([e, 'optionalAccess', _27 => _27.code]) === "22003" || _optionalChain([e, 'optionalAccess', _28 => _28.code]) === "23514")
|
|
1075
|
+
throw new ModelValidationError(name, [{ path: "", message: "invalid value" }]);
|
|
1076
|
+
throw err;
|
|
1077
|
+
}
|
|
1078
|
+
};
|
|
1079
|
+
const JSONB_TO_ARRAY = "efc_jsonb_text_array";
|
|
1080
|
+
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 $$`;
|
|
1081
|
+
const castExpr = (spec, from) => {
|
|
1082
|
+
const c = q(spec.column);
|
|
1083
|
+
if (spec.kind === "jsonb") return `to_jsonb(${c})`;
|
|
1084
|
+
if (spec.kind === "array") {
|
|
1085
|
+
if (from === "jsonb") return `${JSONB_TO_ARRAY}(${c})::${spec.ddl}`;
|
|
1086
|
+
if (from.endsWith("[]")) return `${c}::${spec.ddl}`;
|
|
1087
|
+
return `CASE WHEN ${c} IS NULL THEN NULL ELSE ARRAY[${c}::text]::${spec.ddl} END`;
|
|
1088
|
+
}
|
|
1089
|
+
const scalar = from === "jsonb" ? `(${c} #>> '{}')` : c;
|
|
1090
|
+
if (spec.kind === "enum") return `${scalar}::text::${spec.ddl}`;
|
|
1091
|
+
if (spec.kind === "bigint" || spec.kind === "integer") {
|
|
1092
|
+
return `round(${scalar}::numeric)::${spec.ddl}`;
|
|
1093
|
+
}
|
|
1094
|
+
return `${scalar}::${spec.ddl}`;
|
|
1095
|
+
};
|
|
1096
|
+
const needsTypeChange = (spec, existing) => {
|
|
1097
|
+
if (existing === spec.formatted) return false;
|
|
1098
|
+
if (spec.kind === "varchar") {
|
|
1099
|
+
if (existing === "text") return false;
|
|
1100
|
+
const m = /^character varying\((\d+)\)$/.exec(existing);
|
|
1101
|
+
if (m && Number(m[1]) >= spec.length) return false;
|
|
1102
|
+
}
|
|
1103
|
+
return true;
|
|
1104
|
+
};
|
|
1105
|
+
const enumCheck = (column) => `${table}_${column}_enum`;
|
|
1106
|
+
const managedIndexName = /_(key|idx)$/;
|
|
1107
|
+
function desiredIndexes() {
|
|
1108
|
+
const out = /* @__PURE__ */ new Map();
|
|
1109
|
+
for (const spec of columns.values()) {
|
|
1110
|
+
const def = _optionalChain([spec, 'access', _29 => _29.node, 'optionalAccess', _30 => _30.def]);
|
|
1111
|
+
if (!def) continue;
|
|
1112
|
+
const col = spec.column;
|
|
1113
|
+
if (def.unique) {
|
|
1114
|
+
out.set(
|
|
1115
|
+
`${table}_${col}_key`,
|
|
1116
|
+
`CREATE UNIQUE INDEX ${q(`${table}_${col}_key`)} ON ${q(table)} (${q(col)})`
|
|
1117
|
+
);
|
|
1118
|
+
} else if (def.index) {
|
|
1119
|
+
out.set(
|
|
1120
|
+
`${table}_${col}_idx`,
|
|
1121
|
+
`CREATE INDEX ${q(`${table}_${col}_idx`)} ON ${q(table)} (${q(col)})`
|
|
1122
|
+
);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
|
|
1126
|
+
const fields = Object.entries(idx.fields).map(
|
|
1127
|
+
([f, d]) => [_nullishCoalesce(_optionalChain([columns, 'access', _31 => _31.get, 'call', _32 => _32(f), 'optionalAccess', _33 => _33.column]), () => ( f)), d]
|
|
1128
|
+
);
|
|
1129
|
+
if (idx.expireAfterSeconds !== void 0) {
|
|
1130
|
+
throw new Error(`[EFC] ${name}: TTL indexes (expireAfterSeconds) are MongoDB-only`);
|
|
1131
|
+
}
|
|
1132
|
+
const idxName = _nullishCoalesce(idx.name, () => ( `${table}_${fields.map(([f]) => f).join("_")}_${idx.unique ? "key" : "idx"}`));
|
|
1133
|
+
if (fields.some(([, d]) => d === "text")) {
|
|
1134
|
+
const doc = fields.map(([f]) => `coalesce(${q(f)}::text, '')`).join(` || ' ' || `);
|
|
1135
|
+
out.set(
|
|
1136
|
+
idxName,
|
|
1137
|
+
`CREATE INDEX ${q(idxName)} ON ${q(table)} USING gin (to_tsvector('simple', ${doc}))`
|
|
1138
|
+
);
|
|
1139
|
+
} else {
|
|
1140
|
+
const cols = fields.map(([f, d]) => `${q(f)} ${d === -1 ? "DESC" : "ASC"}`).join(", ");
|
|
1141
|
+
out.set(
|
|
1142
|
+
idxName,
|
|
1143
|
+
`CREATE ${idx.unique ? "UNIQUE " : ""}INDEX ${q(idxName)} ON ${q(table)} (${cols})`
|
|
1144
|
+
);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
return out;
|
|
1148
|
+
}
|
|
1149
|
+
async function reconcile(dryRun) {
|
|
1150
|
+
const pool = _chunkALBDM5R3cjs.getPool.call(void 0, );
|
|
1151
|
+
const conn = await pool.connect();
|
|
1152
|
+
try {
|
|
1153
|
+
await conn.query("BEGIN");
|
|
1154
|
+
await conn.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`efc_sync:${table}`]);
|
|
1155
|
+
const existing = new Map(
|
|
1156
|
+
(await conn.query(
|
|
1157
|
+
`SELECT a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, NOT a.attnotnull AS nullable
|
|
1158
|
+
FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1159
|
+
WHERE c.relname = $1 AND n.nspname = current_schema() AND a.attnum > 0 AND NOT a.attisdropped`,
|
|
1160
|
+
[table]
|
|
1161
|
+
)).rows.map((r) => [r.name, { type: r.type, nullable: r.nullable }])
|
|
1162
|
+
);
|
|
1163
|
+
const checks = new Map(
|
|
1164
|
+
(await conn.query(
|
|
1165
|
+
`SELECT con.conname AS name, pg_get_constraintdef(con.oid) AS def
|
|
1166
|
+
FROM pg_constraint con JOIN pg_class c ON c.oid = con.conrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1167
|
+
WHERE c.relname = $1 AND n.nspname = current_schema() AND con.contype = 'c'`,
|
|
1168
|
+
[table]
|
|
1169
|
+
)).rows.map((r) => [r.name, r.def])
|
|
1170
|
+
);
|
|
1171
|
+
const indexes = new Set(
|
|
1172
|
+
(await conn.query(
|
|
1173
|
+
`SELECT indexname AS name FROM pg_indexes WHERE tablename = $1 AND schemaname = current_schema()`,
|
|
1174
|
+
[table]
|
|
1175
|
+
)).rows.map((r) => r.name)
|
|
1176
|
+
);
|
|
1177
|
+
const plan = [];
|
|
1178
|
+
for (const { key } of sequences) {
|
|
1179
|
+
const seq = sequenceName(key);
|
|
1180
|
+
const found = await conn.query(
|
|
1181
|
+
"SELECT 1 FROM pg_class WHERE relkind = $1 AND relname = $2",
|
|
1182
|
+
["S", seq]
|
|
1183
|
+
);
|
|
1184
|
+
if (found.rowCount === 0) plan.push(`CREATE SEQUENCE IF NOT EXISTS ${q(seq)}`);
|
|
1185
|
+
}
|
|
1186
|
+
const enumSpecs = [...columns.values()].filter((c) => c.kind === "enum");
|
|
1187
|
+
if (enumSpecs.length) {
|
|
1188
|
+
const live = /* @__PURE__ */ new Map();
|
|
1189
|
+
for (const r of (await conn.query(
|
|
1190
|
+
`SELECT t.typname AS type, e.enumlabel AS label FROM pg_type t
|
|
1191
|
+
JOIN pg_namespace n ON n.oid = t.typnamespace LEFT JOIN pg_enum e ON e.enumtypid = t.oid
|
|
1192
|
+
WHERE n.nspname = current_schema() AND t.typname = ANY($1)`,
|
|
1193
|
+
[enumSpecs.map((c) => c.enumType)]
|
|
1194
|
+
)).rows) {
|
|
1195
|
+
const set = _nullishCoalesce(live.get(r.type), () => ( /* @__PURE__ */ new Set()));
|
|
1196
|
+
if (r.label !== null) set.add(r.label);
|
|
1197
|
+
live.set(r.type, set);
|
|
1198
|
+
}
|
|
1199
|
+
for (const spec of enumSpecs) {
|
|
1200
|
+
const have = live.get(spec.enumType);
|
|
1201
|
+
if (!have) {
|
|
1202
|
+
plan.push(
|
|
1203
|
+
`CREATE TYPE ${spec.ddl} AS ENUM (${spec.enumValues.map(literal).join(", ")})`
|
|
1204
|
+
);
|
|
1205
|
+
} else {
|
|
1206
|
+
for (const v of spec.enumValues) {
|
|
1207
|
+
if (!have.has(v))
|
|
1208
|
+
plan.push(`ALTER TYPE ${spec.ddl} ADD VALUE IF NOT EXISTS ${literal(v)}`);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
const columnSql = (spec) => {
|
|
1214
|
+
const seq = sequenceKeys.get(spec.field);
|
|
1215
|
+
return `${q(spec.column)} ${spec.ddl}${seq ? ` DEFAULT nextval('${sequenceName(seq)}')` : ""}`;
|
|
1216
|
+
};
|
|
1217
|
+
const idSql = idKind === "uuid" ? `${q("id")} uuid PRIMARY KEY DEFAULT gen_random_uuid()` : `${q("id")} ${idSpec.ddl} GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY`;
|
|
1218
|
+
if (existing.size === 0) {
|
|
1219
|
+
const defs = [...columns.values()].map(
|
|
1220
|
+
(spec) => spec.field === "id" ? idSql : columnSql(spec)
|
|
1221
|
+
);
|
|
1222
|
+
plan.push(`CREATE TABLE IF NOT EXISTS ${q(table)} (
|
|
1223
|
+
${defs.join(",\n ")}
|
|
1224
|
+
)`);
|
|
1225
|
+
} else {
|
|
1226
|
+
const alters = [];
|
|
1227
|
+
for (const spec of columns.values()) {
|
|
1228
|
+
const col = existing.get(spec.column);
|
|
1229
|
+
if (!col) {
|
|
1230
|
+
alters.push(`ALTER TABLE ${q(table)} ADD COLUMN ${columnSql(spec)}`);
|
|
1231
|
+
} else if (spec.field !== "id" && needsTypeChange(spec, col.type)) {
|
|
1232
|
+
if (spec.kind === "array" && col.type === "jsonb" && !plan.includes(jsonbToArrayFn))
|
|
1233
|
+
plan.push(jsonbToArrayFn);
|
|
1234
|
+
alters.push(
|
|
1235
|
+
`ALTER TABLE ${q(table)} ALTER COLUMN ${q(spec.column)} TYPE ${spec.ddl} USING ${castExpr(spec, col.type)}`
|
|
1236
|
+
);
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
plan.push(...new Set(alters));
|
|
1240
|
+
for (const [column, col] of existing) {
|
|
1241
|
+
if (column !== "id" && !col.nullable) {
|
|
1242
|
+
plan.push(`ALTER TABLE ${q(table)} ALTER COLUMN ${q(column)} DROP NOT NULL`);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
const wantedChecks = /* @__PURE__ */ new Map();
|
|
1247
|
+
for (const spec of columns.values()) {
|
|
1248
|
+
const def = _optionalChain([spec, 'access', _34 => _34.node, 'optionalAccess', _35 => _35.def]);
|
|
1249
|
+
if (_optionalChain([spec, 'access', _36 => _36.node, 'optionalAccess', _37 => _37.kind]) === "scalar" && _optionalChain([def, 'optionalAccess', _38 => _38.enum]) && spec.kind !== "enum") {
|
|
1250
|
+
wantedChecks.set(
|
|
1251
|
+
enumCheck(spec.column),
|
|
1252
|
+
`CHECK (${q(spec.column)} IN (${def.enum.map(literal).join(", ")}))`
|
|
1253
|
+
);
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
for (const [con, def] of checks) {
|
|
1257
|
+
const legacy = con.endsWith("_check") && con.startsWith(`${table}_`);
|
|
1258
|
+
if (con.endsWith("_enum") && con.startsWith(`${table}_`) && !wantedChecks.has(con) || legacy) {
|
|
1259
|
+
plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
|
|
1260
|
+
checks.delete(con);
|
|
1261
|
+
} else if (wantedChecks.has(con)) {
|
|
1262
|
+
const want = wantedChecks.get(con);
|
|
1263
|
+
const values = (d) => [...d.matchAll(/'((?:[^']|'')*)'|(-?\d+(?:\.\d+)?)/g)].map((m) => _nullishCoalesce(m[1], () => ( m[2]))).sort().join("|");
|
|
1264
|
+
if (values(def) !== values(want)) {
|
|
1265
|
+
plan.push(`ALTER TABLE ${q(table)} DROP CONSTRAINT ${q(con)}`);
|
|
1266
|
+
checks.delete(con);
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
for (const [con, def] of wantedChecks) {
|
|
1271
|
+
if (!checks.has(con))
|
|
1272
|
+
plan.push(`ALTER TABLE ${q(table)} ADD CONSTRAINT ${q(con)} ${def} NOT VALID`);
|
|
1273
|
+
}
|
|
1274
|
+
const wantedIndexes = desiredIndexes();
|
|
1275
|
+
for (const idx of indexes) {
|
|
1276
|
+
if (idx !== `${table}_pkey` && idx.startsWith(`${table}_`) && managedIndexName.test(idx) && !wantedIndexes.has(idx)) {
|
|
1277
|
+
plan.push(`DROP INDEX ${q(idx)}`);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
for (const [idx, create] of wantedIndexes) if (!indexes.has(idx)) plan.push(create);
|
|
1281
|
+
if (!dryRun) {
|
|
1282
|
+
for (const stmt of plan) {
|
|
1283
|
+
try {
|
|
1284
|
+
await conn.query(stmt);
|
|
1285
|
+
} catch (err) {
|
|
1286
|
+
throw new Error(
|
|
1287
|
+
`[EFC] ${name}: syncing table "${table}" failed on: ${stmt}
|
|
1288
|
+
${err.message}`
|
|
1289
|
+
);
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
await conn.query(dryRun ? "ROLLBACK" : "COMMIT");
|
|
1294
|
+
return plan;
|
|
1295
|
+
} catch (err) {
|
|
1296
|
+
await conn.query("ROLLBACK").catch(() => {
|
|
1297
|
+
});
|
|
1298
|
+
throw err;
|
|
1299
|
+
} finally {
|
|
1300
|
+
conn.release();
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
async function drop() {
|
|
1304
|
+
const { sql } = await compile();
|
|
1305
|
+
await client().execute(sql.raw(`DROP TABLE IF EXISTS ${q(table)}`));
|
|
1306
|
+
}
|
|
1307
|
+
return {
|
|
1308
|
+
name,
|
|
1309
|
+
table,
|
|
1310
|
+
tree,
|
|
1311
|
+
idKind,
|
|
1312
|
+
columns,
|
|
1313
|
+
ts,
|
|
1314
|
+
sequenceKeys,
|
|
1315
|
+
refs,
|
|
1316
|
+
compile,
|
|
1317
|
+
ready,
|
|
1318
|
+
client,
|
|
1319
|
+
columnFor,
|
|
1320
|
+
toDb,
|
|
1321
|
+
fromRow,
|
|
1322
|
+
fromRawRow,
|
|
1323
|
+
validate,
|
|
1324
|
+
known,
|
|
1325
|
+
prepareInsert,
|
|
1326
|
+
guard,
|
|
1327
|
+
reconcile,
|
|
1328
|
+
drop
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// src/db/pg-model.ts
|
|
1333
|
+
function pgModel(name, tree, options) {
|
|
1334
|
+
const tbl = pgTable(name, tree, options, { native: false, api: "defineModel" });
|
|
1335
|
+
const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
|
|
1336
|
+
const kindOf = (field) => _optionalChain([columns, 'access', _39 => _39.get, 'call', _40 => _40(field), 'optionalAccess', _41 => _41.kind]);
|
|
1337
|
+
function missingField(sql, cond) {
|
|
1338
|
+
const ops = cond !== null && typeof cond === "object" && !Array.isArray(cond) && !(cond instanceof Date) && !(cond instanceof RegExp) ? cond : { $eq: cond };
|
|
1339
|
+
const matches = Object.entries(ops).every(([op, v]) => {
|
|
1340
|
+
switch (op) {
|
|
1341
|
+
case "$eq":
|
|
1342
|
+
return v === null;
|
|
1343
|
+
case "$ne":
|
|
1344
|
+
return v !== null;
|
|
1345
|
+
case "$exists":
|
|
1346
|
+
return v === false;
|
|
1347
|
+
case "$in":
|
|
1348
|
+
return v.includes(null);
|
|
1349
|
+
case "$nin":
|
|
1350
|
+
return !v.includes(null);
|
|
1351
|
+
default:
|
|
1352
|
+
return false;
|
|
1353
|
+
}
|
|
1354
|
+
});
|
|
1355
|
+
return matches ? sql`true` : sql`false`;
|
|
1356
|
+
}
|
|
1357
|
+
function condition(sql, t, path, cond) {
|
|
1358
|
+
const [field, ...rest] = path.split(".");
|
|
1359
|
+
if (!columns.has(field)) return missingField(sql, cond);
|
|
1360
|
+
const col = columnFor(t, field);
|
|
1361
|
+
const kind = kindOf(field);
|
|
1362
|
+
const isOps = cond != null && typeof cond === "object" && !Array.isArray(cond) && !(cond instanceof Date) && !(cond instanceof RegExp) && Object.keys(cond).some((k) => k.startsWith("$"));
|
|
1363
|
+
const jsonPath = rest.length > 0 ? `{${rest.join(",")}}` : void 0;
|
|
1364
|
+
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})`;
|
|
1365
|
+
const eqCond = (v) => {
|
|
1366
|
+
if (v === null) return jsonPath ? sql`(${col} #> ${jsonPath}) is null` : sql`${col} is null`;
|
|
1367
|
+
if (kind === "jsonb" && jsonPath === void 0) {
|
|
1368
|
+
return Array.isArray(v) || typeof v === "object" && !(v instanceof Date) ? sql`${col} = ${JSON.stringify(v)}::jsonb` : sql`${col} @> ${JSON.stringify([v])}::jsonb`;
|
|
1369
|
+
}
|
|
1370
|
+
return sql`${exprFor(v)} = ${jsonPath ? v : toDb(field, v)}`;
|
|
1371
|
+
};
|
|
1372
|
+
if (!isOps) return eqCond(cond);
|
|
1373
|
+
const parts = [];
|
|
1374
|
+
for (const [op, v] of Object.entries(cond)) {
|
|
1375
|
+
const e = exprFor(Array.isArray(v) ? v[0] : v);
|
|
1376
|
+
const val = jsonPath ? v : toDb(field, v);
|
|
1377
|
+
switch (op) {
|
|
1378
|
+
case "$eq":
|
|
1379
|
+
parts.push(eqCond(v));
|
|
1380
|
+
break;
|
|
1381
|
+
case "$ne":
|
|
1382
|
+
if (v === null) parts.push(sql`${e} is not null`);
|
|
1383
|
+
else if (kind === "jsonb" && !jsonPath) {
|
|
1384
|
+
parts.push(
|
|
1385
|
+
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))`
|
|
1386
|
+
);
|
|
1387
|
+
} else parts.push(sql`(${e} is null or ${e} <> ${val})`);
|
|
1388
|
+
break;
|
|
1389
|
+
case "$gt":
|
|
1390
|
+
parts.push(sql`${e} > ${val}`);
|
|
1391
|
+
break;
|
|
1392
|
+
case "$gte":
|
|
1393
|
+
parts.push(sql`${e} >= ${val}`);
|
|
1394
|
+
break;
|
|
1395
|
+
case "$lt":
|
|
1396
|
+
parts.push(sql`${e} < ${val}`);
|
|
1397
|
+
break;
|
|
1398
|
+
case "$lte":
|
|
1399
|
+
parts.push(sql`${e} <= ${val}`);
|
|
1400
|
+
break;
|
|
1401
|
+
case "$in":
|
|
1402
|
+
case "$nin": {
|
|
1403
|
+
const list = v.map((x) => jsonPath ? x : toDb(field, x));
|
|
1404
|
+
if (list.length === 0) {
|
|
1405
|
+
parts.push(op === "$in" ? sql`false` : sql`true`);
|
|
1406
|
+
break;
|
|
1407
|
+
}
|
|
1408
|
+
const inList = kind === "jsonb" && !jsonPath ? sql.join(
|
|
1409
|
+
list.map((x) => sql`${col} @> ${JSON.stringify([x])}::jsonb`),
|
|
1410
|
+
sql` or `
|
|
1411
|
+
) : sql`${e} in (${sql.join(
|
|
1412
|
+
list.map((x) => sql`${x}`),
|
|
1413
|
+
sql`, `
|
|
1414
|
+
)})`;
|
|
1415
|
+
parts.push(
|
|
1416
|
+
op === "$in" ? sql`(${inList})` : sql`(${kind === "jsonb" && !jsonPath ? sql`${col} is null or ` : sql``}not (${inList}))`
|
|
1417
|
+
);
|
|
1418
|
+
break;
|
|
1419
|
+
}
|
|
1420
|
+
case "$exists":
|
|
1421
|
+
parts.push(
|
|
1422
|
+
v ? sql`${exprFor(void 0)} is not null` : sql`${exprFor(void 0)} is null`
|
|
1423
|
+
);
|
|
1424
|
+
break;
|
|
1425
|
+
case "$regex": {
|
|
1426
|
+
const re = v instanceof RegExp ? v : new RegExp(String(v));
|
|
1427
|
+
const textExpr = jsonPath ? sql`(${col} #>> ${jsonPath})` : col;
|
|
1428
|
+
parts.push(
|
|
1429
|
+
re.flags.includes("i") ? sql`${textExpr} ~* ${re.source}` : sql`${textExpr} ~ ${re.source}`
|
|
1430
|
+
);
|
|
1431
|
+
break;
|
|
1432
|
+
}
|
|
1433
|
+
default:
|
|
1434
|
+
throw new ModelValidationError(name, [
|
|
1435
|
+
{ path, message: `operator ${op} is not supported on PostgreSQL` }
|
|
1436
|
+
]);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
|
|
1440
|
+
}
|
|
1441
|
+
function where(sql, t, filter) {
|
|
1442
|
+
if (!filter) return void 0;
|
|
1443
|
+
const parts = [];
|
|
1444
|
+
for (const [k, v] of Object.entries(filter)) {
|
|
1445
|
+
if (v === void 0) continue;
|
|
1446
|
+
if (k === "$and" || k === "$or") {
|
|
1447
|
+
const sub = v.map((f) => _nullishCoalesce(where(sql, t, f), () => ( sql`true`)));
|
|
1448
|
+
if (sub.length) parts.push(sql`(${sql.join(sub, k === "$and" ? sql` and ` : sql` or `)})`);
|
|
1449
|
+
} else {
|
|
1450
|
+
parts.push(condition(sql, t, k, v));
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
return parts.length === 0 ? void 0 : parts.length === 1 ? parts[0] : sql.join(parts, sql` and `);
|
|
1454
|
+
}
|
|
1455
|
+
function firstMatch(sql, t, filter) {
|
|
1456
|
+
const w = _nullishCoalesce(where(sql, t, filter), () => ( sql`true`));
|
|
1457
|
+
return sql`${t.id} = (select ${t.id} from ${t} where ${w} limit 1 for update)`;
|
|
1458
|
+
}
|
|
1459
|
+
const prepareInsert = tbl.prepareInsert;
|
|
1460
|
+
async function populate(records, paths) {
|
|
1461
|
+
if (!paths) return records;
|
|
1462
|
+
for (const path of Array.isArray(paths) ? paths : [paths]) {
|
|
1463
|
+
const ref = refs.get(path);
|
|
1464
|
+
if (!ref)
|
|
1465
|
+
throw new ModelValidationError(name, [{ path, message: "is not a populatable ref field" }]);
|
|
1466
|
+
const target = getRegisteredModel(ref.model);
|
|
1467
|
+
if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
|
|
1468
|
+
const ids = [
|
|
1469
|
+
...new Set(
|
|
1470
|
+
records.flatMap(
|
|
1471
|
+
(r) => ref.many ? _nullishCoalesce(r[path], () => ( [])) : r[path] ? [r[path]] : []
|
|
1472
|
+
)
|
|
1473
|
+
)
|
|
1474
|
+
];
|
|
1475
|
+
if (ids.length === 0) continue;
|
|
1476
|
+
const byId = new Map((await target.findByIds(ids)).map((d) => [d["id"], d]));
|
|
1477
|
+
for (const r of records) {
|
|
1478
|
+
if (ref.many) r[path] = (_nullishCoalesce(r[path], () => ( []))).map((id) => _nullishCoalesce(byId.get(id), () => ( id)));
|
|
1479
|
+
else if (r[path]) r[path] = _nullishCoalesce(byId.get(r[path]), () => ( r[path]));
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
return records;
|
|
1483
|
+
}
|
|
1484
|
+
const selection = (t, select) => {
|
|
1485
|
+
if (!select) return void 0;
|
|
1486
|
+
const out = { id: t.id };
|
|
1487
|
+
for (const f of select) if (columns.has(f)) out[f] = columnFor(t, f);
|
|
1488
|
+
return out;
|
|
1489
|
+
};
|
|
1490
|
+
async function runFind(filter, opts) {
|
|
1491
|
+
const { t, sql } = await ready();
|
|
1492
|
+
const sel = selection(t, _optionalChain([opts, 'optionalAccess', _42 => _42.select]));
|
|
1493
|
+
let query = (sel ? client().select(sel) : client().select()).from(t);
|
|
1494
|
+
const w = where(sql, t, filter);
|
|
1495
|
+
if (w) query = query.where(w);
|
|
1496
|
+
if (_optionalChain([opts, 'optionalAccess', _43 => _43.sort])) {
|
|
1497
|
+
const order = Object.entries(opts.sort).filter(([f]) => columns.has(f)).map(([f, dir]) => {
|
|
1498
|
+
const col = columnFor(t, f);
|
|
1499
|
+
return dir === -1 || dir === "desc" ? sql`${col} desc nulls last` : sql`${col} asc nulls first`;
|
|
1500
|
+
});
|
|
1501
|
+
if (order.length) query = query.orderBy(...order);
|
|
1502
|
+
}
|
|
1503
|
+
if (_optionalChain([opts, 'optionalAccess', _44 => _44.limit]) !== void 0) query = query.limit(opts.limit);
|
|
1504
|
+
if (_optionalChain([opts, 'optionalAccess', _45 => _45.skip]) !== void 0) query = query.offset(opts.skip);
|
|
1505
|
+
const rows = (await query).map(fromRow);
|
|
1506
|
+
return populate(rows, _optionalChain([opts, 'optionalAccess', _46 => _46.populate]));
|
|
1507
|
+
}
|
|
1508
|
+
const strictUpdate = (update) => {
|
|
1509
|
+
const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || nodeAt(tree, path.split(".")) !== void 0);
|
|
1510
|
+
const out = {};
|
|
1511
|
+
for (const [k, v] of Object.entries(update)) {
|
|
1512
|
+
if (k.startsWith("$") && v !== null && typeof v === "object") {
|
|
1513
|
+
out[k] = Object.fromEntries(Object.entries(v).filter(([p]) => declared(p)));
|
|
1514
|
+
} else if (k.startsWith("$") || declared(k)) out[k] = v;
|
|
1515
|
+
}
|
|
1516
|
+
return out;
|
|
1517
|
+
};
|
|
1518
|
+
async function buildSet(input) {
|
|
1519
|
+
const { t, sql } = await compile();
|
|
1520
|
+
const update = strictUpdate(input);
|
|
1521
|
+
const ops = update;
|
|
1522
|
+
for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
|
|
1523
|
+
if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
|
|
1524
|
+
throw new ModelValidationError(name, [
|
|
1525
|
+
{ path: op, message: "update operator is not supported on PostgreSQL" }
|
|
1526
|
+
]);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
const plain = {};
|
|
1530
|
+
for (const [k, v] of Object.entries(update)) if (!k.startsWith("$")) plain[k] = v;
|
|
1531
|
+
const $set = { ..._nullishCoalesce(ops["$set"], () => ( {})), ...plain };
|
|
1532
|
+
const issues = [];
|
|
1533
|
+
const topLevel = {};
|
|
1534
|
+
for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
|
|
1535
|
+
for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
|
|
1536
|
+
for (const [k, v] of Object.entries($set))
|
|
1537
|
+
if (k.includes(".")) await validateAtPath(tree, k, v, issues);
|
|
1538
|
+
for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
|
|
1539
|
+
if (k.includes(".")) await validateAtPath(tree, k, null, issues);
|
|
1540
|
+
}
|
|
1541
|
+
for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
|
|
1542
|
+
if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
|
|
1543
|
+
const node = k.includes(".") ? nodeAt(tree, k.split(".")) : tree[k];
|
|
1544
|
+
if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
|
|
1545
|
+
issues.push({ path: k, message: "$inc only applies to number fields" });
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
if (issues.length) throw new ModelValidationError(name, issues);
|
|
1549
|
+
await validate(topLevel, true);
|
|
1550
|
+
const set = {};
|
|
1551
|
+
const nested = /* @__PURE__ */ new Map();
|
|
1552
|
+
const touchedTop = /* @__PURE__ */ new Set();
|
|
1553
|
+
const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
|
|
1554
|
+
const conflict = (path) => {
|
|
1555
|
+
throw new ModelValidationError(name, [{ path, message: "conflicting update paths" }]);
|
|
1556
|
+
};
|
|
1557
|
+
const top = (field, value) => {
|
|
1558
|
+
if (touchedTop.has(field) || nested.has(field)) conflict(field);
|
|
1559
|
+
touchedTop.add(field);
|
|
1560
|
+
set[field] = value;
|
|
1561
|
+
};
|
|
1562
|
+
const withParents = (base, parts) => {
|
|
1563
|
+
let expr = sql`coalesce(${base}, '{}'::jsonb)`;
|
|
1564
|
+
for (let i = 1; i < parts.length; i++) {
|
|
1565
|
+
const prefix = `{${parts.slice(0, i).join(",")}}`;
|
|
1566
|
+
expr = sql`jsonb_set(${expr}, ${prefix}, coalesce(${expr} #> ${prefix}, '{}'::jsonb), true)`;
|
|
1567
|
+
}
|
|
1568
|
+
return expr;
|
|
1569
|
+
};
|
|
1570
|
+
const dotted = (path, apply) => {
|
|
1571
|
+
const [field, ...rest] = path.split(".");
|
|
1572
|
+
if (touchedTop.has(field)) conflict(path);
|
|
1573
|
+
columnFor(t, field);
|
|
1574
|
+
const base = withParents(acc(field), rest);
|
|
1575
|
+
nested.set(field, apply(base, `{${rest.join(",")}}`));
|
|
1576
|
+
};
|
|
1577
|
+
const items = (v) => JSON.stringify(
|
|
1578
|
+
v != null && typeof v === "object" && "$each" in v ? v.$each : [v]
|
|
1579
|
+
);
|
|
1580
|
+
for (const [k, v] of Object.entries($set)) {
|
|
1581
|
+
if (k.includes("."))
|
|
1582
|
+
dotted(k, (b, p) => sql`jsonb_set(${b}, ${p}, ${JSON.stringify(v)}::jsonb, true)`);
|
|
1583
|
+
else top(k, toDb(k, v));
|
|
1584
|
+
}
|
|
1585
|
+
for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
|
|
1586
|
+
if (k.includes(".")) dotted(k, (b, p) => sql`(${b} #- ${p})`);
|
|
1587
|
+
else top(k, null);
|
|
1588
|
+
}
|
|
1589
|
+
for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
|
|
1590
|
+
if (k.includes(".")) {
|
|
1591
|
+
dotted(
|
|
1592
|
+
k,
|
|
1593
|
+
(b, p) => sql`jsonb_set(${b}, ${p}, to_jsonb(coalesce((${b} #>> ${p})::double precision, 0) + ${by}), true)`
|
|
1594
|
+
);
|
|
1595
|
+
} else top(k, sql`coalesce(${columnFor(t, k)}, 0) + ${by}`);
|
|
1596
|
+
}
|
|
1597
|
+
for (const [k, v] of Object.entries(_nullishCoalesce(ops["$push"], () => ( {})))) {
|
|
1598
|
+
if (k.includes(".")) {
|
|
1599
|
+
dotted(
|
|
1600
|
+
k,
|
|
1601
|
+
(b, p) => sql`jsonb_set(${b}, ${p}, coalesce(${b} #> ${p}, '[]'::jsonb) || ${items(v)}::jsonb, true)`
|
|
1602
|
+
);
|
|
1603
|
+
} else top(k, sql`coalesce(${columnFor(t, k)}, '[]'::jsonb) || ${items(v)}::jsonb`);
|
|
1604
|
+
}
|
|
1605
|
+
for (const [k, v] of Object.entries(_nullishCoalesce(ops["$pull"], () => ( {})))) {
|
|
1606
|
+
const without = (arr) => sql`coalesce((select jsonb_agg(e) from jsonb_array_elements(${arr}) e where e <> ${JSON.stringify(v)}::jsonb), '[]'::jsonb)`;
|
|
1607
|
+
if (k.includes("."))
|
|
1608
|
+
dotted(k, (b, p) => sql`jsonb_set(${b}, ${p}, ${without(sql`(${b} #> ${p})`)}, true)`);
|
|
1609
|
+
else top(k, without(columnFor(t, k)));
|
|
1610
|
+
}
|
|
1611
|
+
for (const [field, expr] of nested) set[field] = expr;
|
|
1612
|
+
if (ts.updatedAt) set[ts.updatedAt] = /* @__PURE__ */ new Date();
|
|
1613
|
+
return set;
|
|
1614
|
+
}
|
|
1615
|
+
const UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1616
|
+
return {
|
|
1617
|
+
find: (filter, opts) => guard(async () => await runFind(filter, opts)),
|
|
1618
|
+
findById: (id, opts) => guard(async () => {
|
|
1619
|
+
if (!UUID_RE2.test(id)) return null;
|
|
1620
|
+
return await _asyncNullishCoalesce((await runFind({ id }, { ...opts, limit: 1 }))[0], async () => ( null));
|
|
1621
|
+
}),
|
|
1622
|
+
findOne: (filter, opts) => guard(
|
|
1623
|
+
async () => await _asyncNullishCoalesce((await runFind(filter, { ...opts, limit: 1 }))[0], async () => ( null))
|
|
1624
|
+
),
|
|
1625
|
+
exists: (filter) => guard(async () => {
|
|
1626
|
+
const { t, sql } = await ready();
|
|
1627
|
+
let query = client().select({ one: sql`1` }).from(t);
|
|
1628
|
+
const w = where(sql, t, filter);
|
|
1629
|
+
if (w) query = query.where(w);
|
|
1630
|
+
return (await query.limit(1)).length > 0;
|
|
1631
|
+
}),
|
|
1632
|
+
distinct: (field, filter) => guard(async () => {
|
|
1633
|
+
const { t, sql } = await ready();
|
|
1634
|
+
if (!columns.has(field)) return [];
|
|
1635
|
+
let query = client().selectDistinct({ v: columnFor(t, field) }).from(t);
|
|
1636
|
+
const w = where(sql, t, filter);
|
|
1637
|
+
if (w) query = query.where(w);
|
|
1638
|
+
return (await query).map((r) => r.v);
|
|
1639
|
+
}),
|
|
1640
|
+
create: (data) => guard(async () => {
|
|
1641
|
+
const { t } = await ready();
|
|
1642
|
+
const row = await prepareInsert(data);
|
|
1643
|
+
const [inserted] = await client().insert(t).values(row).returning();
|
|
1644
|
+
return fromRow(inserted);
|
|
1645
|
+
}),
|
|
1646
|
+
createMany: (data) => guard(async () => {
|
|
1647
|
+
if (data.length === 0) return [];
|
|
1648
|
+
const { t } = await ready();
|
|
1649
|
+
const rows = await Promise.all(data.map((d) => prepareInsert(d)));
|
|
1650
|
+
return (await client().insert(t).values(rows).returning()).map(
|
|
1651
|
+
fromRow
|
|
1652
|
+
);
|
|
1653
|
+
}),
|
|
1654
|
+
update: (id, data) => guard(async () => {
|
|
1655
|
+
if (!UUID_RE2.test(id)) return null;
|
|
1656
|
+
const { t, sql } = await ready();
|
|
1657
|
+
const set = await buildSet(data);
|
|
1658
|
+
const [row] = await client().update(t).set(set).where(sql`${t.id} = ${id}`).returning();
|
|
1659
|
+
return row ? fromRow(row) : null;
|
|
1660
|
+
}),
|
|
1661
|
+
updateOne: (filter, data) => guard(async () => {
|
|
1662
|
+
const { t, sql } = await ready();
|
|
1663
|
+
const set = await buildSet(data);
|
|
1664
|
+
if (Object.keys(set).length === 0) {
|
|
1665
|
+
return await _asyncNullishCoalesce((await runFind(filter, { limit: 1 }))[0], async () => ( null));
|
|
1666
|
+
}
|
|
1667
|
+
const [row] = await client().update(t).set(set).where(firstMatch(sql, t, filter)).returning();
|
|
1668
|
+
return row ? fromRow(row) : null;
|
|
1669
|
+
}),
|
|
1670
|
+
updateMany: (filter, data) => guard(async () => {
|
|
1671
|
+
const { t, sql } = await ready();
|
|
1672
|
+
const set = await buildSet(data);
|
|
1673
|
+
let query = client().update(t).set(set);
|
|
1674
|
+
const w = where(sql, t, filter);
|
|
1675
|
+
if (w) query = query.where(w);
|
|
1676
|
+
return (await query.returning({ id: t.id })).length;
|
|
1677
|
+
}),
|
|
1678
|
+
delete: (id) => guard(async () => {
|
|
1679
|
+
if (!UUID_RE2.test(id)) return;
|
|
1680
|
+
const { t, sql } = await ready();
|
|
1681
|
+
await client().delete(t).where(sql`${t.id} = ${id}`);
|
|
1682
|
+
}),
|
|
1683
|
+
deleteOne: (filter) => guard(async () => {
|
|
1684
|
+
const { t, sql } = await ready();
|
|
1685
|
+
const [row] = await client().delete(t).where(firstMatch(sql, t, filter)).returning();
|
|
1686
|
+
return row ? fromRow(row) : null;
|
|
1687
|
+
}),
|
|
1688
|
+
deleteMany: (filter) => guard(async () => {
|
|
1689
|
+
const { t, sql } = await ready();
|
|
1690
|
+
let query = client().delete(t);
|
|
1691
|
+
const w = where(sql, t, filter);
|
|
1692
|
+
if (w) query = query.where(w);
|
|
1693
|
+
return (await query.returning({ id: t.id })).length;
|
|
1694
|
+
}),
|
|
1695
|
+
count: (filter) => guard(async () => {
|
|
1696
|
+
const { t, sql } = await ready();
|
|
1697
|
+
let query = client().select({ n: sql`count(*)::int` }).from(t);
|
|
1698
|
+
const w = where(sql, t, filter);
|
|
1699
|
+
if (w) query = query.where(w);
|
|
1700
|
+
const [row] = await query;
|
|
1701
|
+
return _nullishCoalesce(_optionalChain([row, 'optionalAccess', _47 => _47.n]), () => ( 0));
|
|
1702
|
+
}),
|
|
1703
|
+
aggregate() {
|
|
1704
|
+
return Promise.reject(
|
|
1705
|
+
new Error(
|
|
1706
|
+
"[EFC] aggregate() is MongoDB-only \u2014 on PostgreSQL use db.query() or Drizzle via Model.raw()"
|
|
1707
|
+
)
|
|
1708
|
+
);
|
|
1709
|
+
},
|
|
1710
|
+
raw: async () => (await compile()).t,
|
|
1711
|
+
sync: (opts) => tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _48 => _48.dryRun]), () => ( false))),
|
|
1712
|
+
drop: () => tbl.drop()
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
// src/db/model.ts
|
|
1717
|
+
var ENGINE_LABEL = {
|
|
1718
|
+
mongodb: "MongoDB",
|
|
1719
|
+
postgresql: "PostgreSQL"
|
|
1720
|
+
};
|
|
1721
|
+
function defineModel(name, schema, options) {
|
|
1722
|
+
return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
|
|
1723
|
+
}
|
|
1724
|
+
function distinctFields(tree, options) {
|
|
1725
|
+
const ts = timestampFields(options);
|
|
1726
|
+
const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
|
|
1727
|
+
for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
|
|
1728
|
+
return fields;
|
|
1729
|
+
}
|
|
1730
|
+
var sortKey = (v) => v instanceof Date ? v.getTime() : v;
|
|
1731
|
+
function createModel(name, schema, options, native) {
|
|
1732
|
+
const tree = normalizeSchema(schema, "model", name);
|
|
1733
|
+
let engineModel;
|
|
1734
|
+
const impl = () => {
|
|
1735
|
+
if (engineModel) return engineModel;
|
|
1736
|
+
const engine2 = getDbEngine();
|
|
1737
|
+
if (native && native.engine !== engine2) {
|
|
1738
|
+
throw new Error(
|
|
1739
|
+
`[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`
|
|
1740
|
+
);
|
|
1741
|
+
}
|
|
1742
|
+
engineModel = engine2 === "postgresql" ? pgModel(name, tree, options) : mongoModel(name, tree, options);
|
|
1743
|
+
return engineModel;
|
|
1744
|
+
};
|
|
1745
|
+
const call = (fn) => Promise.resolve().then(() => fn(impl()));
|
|
1746
|
+
const scalarFields = distinctFields(tree, options);
|
|
1747
|
+
const model = {
|
|
1748
|
+
name,
|
|
1749
|
+
find: (filter, opts) => call((m) => m.find(filter, opts)),
|
|
1750
|
+
findById: (id, opts) => call((m) => m.findById(id, opts)),
|
|
1751
|
+
findOne: (filter, opts) => call((m) => m.findOne(filter, opts)),
|
|
1752
|
+
exists: (filter) => call((m) => m.exists(filter)),
|
|
1753
|
+
distinct: (field, filter) => call(async (m) => {
|
|
1754
|
+
if (!scalarFields.has(field)) {
|
|
1755
|
+
if (!(field in tree)) return [];
|
|
1756
|
+
throw new Error(
|
|
1757
|
+
`[EFC] ${name}.distinct('${field}'): only scalar fields are supported, not arrays or objects`
|
|
1758
|
+
);
|
|
1759
|
+
}
|
|
1760
|
+
const values = (await m.distinct(field, filter)).filter((v) => v != null);
|
|
1761
|
+
return values.sort((a, b) => {
|
|
1762
|
+
const x = sortKey(a);
|
|
1763
|
+
const y = sortKey(b);
|
|
1764
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
1765
|
+
});
|
|
1766
|
+
}),
|
|
1767
|
+
create: (data) => call((m) => m.create(data)),
|
|
1768
|
+
createMany: (data) => call((m) => m.createMany(data)),
|
|
1769
|
+
update: (id, data) => call((m) => m.update(id, data)),
|
|
1770
|
+
updateOne: (filter, data) => call((m) => m.updateOne(filter, data)),
|
|
1771
|
+
updateMany: (filter, data) => call((m) => m.updateMany(filter, data)),
|
|
1772
|
+
upsert: (filter, create, update) => call(async (m) => {
|
|
1773
|
+
const updated = await m.updateOne(filter, update);
|
|
1774
|
+
if (updated) return updated;
|
|
1775
|
+
try {
|
|
1776
|
+
return await m.create(create);
|
|
1777
|
+
} catch (err) {
|
|
1778
|
+
if (isHttpError(err) && err.statusCode === 409 && !currentTx()) {
|
|
1779
|
+
const retried = await m.updateOne(filter, update);
|
|
1780
|
+
if (retried) return retried;
|
|
1781
|
+
}
|
|
1782
|
+
throw err;
|
|
1783
|
+
}
|
|
1784
|
+
}),
|
|
1785
|
+
delete: (id) => call((m) => m.delete(id)),
|
|
1786
|
+
deleteOne: (filter) => call((m) => m.deleteOne(filter)),
|
|
1787
|
+
deleteMany: (filter) => call((m) => m.deleteMany(filter)),
|
|
1788
|
+
count: (filter) => call((m) => m.count(filter)),
|
|
1789
|
+
aggregate: (pipeline) => call((m) => m.aggregate(pipeline)),
|
|
1790
|
+
raw: () => call((m) => m.raw()),
|
|
1791
|
+
sync: (opts) => call((m) => m.sync(opts)),
|
|
1792
|
+
drop: () => call((m) => m.drop())
|
|
1793
|
+
};
|
|
1794
|
+
registerModel({
|
|
1795
|
+
name,
|
|
1796
|
+
sync: model.sync,
|
|
1797
|
+
drop: model.drop,
|
|
1798
|
+
findByIds: (ids) => model.find({ id: { $in: ids } })
|
|
1799
|
+
});
|
|
1800
|
+
return model;
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
// src/db/table-model.ts
|
|
1804
|
+
var AGGREGATES = ["_count", "_sum", "_avg", "_min", "_max"];
|
|
1805
|
+
var NUMERIC_KINDS = /* @__PURE__ */ new Set(["double", "integer", "bigint", "numeric"]);
|
|
1806
|
+
var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof RegExp) && typeof v !== "bigint";
|
|
1807
|
+
var likeEscape = (s) => s.replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
1808
|
+
var TableRuntime = class {
|
|
1809
|
+
constructor(name, schema, options) {
|
|
1810
|
+
this.name = name;
|
|
1811
|
+
this.options = options;
|
|
1812
|
+
const tree = normalizeSchema(schema, "table", name);
|
|
1813
|
+
this.tbl = pgTable(name, tree, options, { native: true, api: "defineTable" });
|
|
1814
|
+
this.uniqueSets = [["id"]];
|
|
1815
|
+
for (const spec of this.tbl.columns.values()) {
|
|
1816
|
+
if (_optionalChain([spec, 'access', _49 => _49.node, 'optionalAccess', _50 => _50.def, 'access', _51 => _51.unique])) this.uniqueSets.push([spec.field]);
|
|
1817
|
+
}
|
|
1818
|
+
for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
|
|
1819
|
+
if (idx.unique) this.uniqueSets.push(Object.keys(idx.fields));
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
|
|
1824
|
+
|
|
1825
|
+
|
|
1826
|
+
fail(path, message) {
|
|
1827
|
+
throw new ModelValidationError(this.name, [{ path, message }]);
|
|
1828
|
+
}
|
|
1829
|
+
spec(field) {
|
|
1830
|
+
return this.tbl.columns.get(field);
|
|
1831
|
+
}
|
|
1832
|
+
col(sql, field, alias) {
|
|
1833
|
+
const spec = this.spec(field);
|
|
1834
|
+
return sql.raw(alias ? `${alias}.${q(spec.column)}` : q(spec.column));
|
|
1835
|
+
}
|
|
1836
|
+
/** A value for `field`, encoded the way its Drizzle column does it. */
|
|
1837
|
+
val(sql, t, field, value) {
|
|
1838
|
+
return sql`${sql.param(this.tbl.toDb(field, value), t[field])}`;
|
|
1839
|
+
}
|
|
1840
|
+
/** One array element / scalar compared against an array column's items. */
|
|
1841
|
+
itemVal(sql, field, value) {
|
|
1842
|
+
const spec = this.spec(field);
|
|
1843
|
+
const [v] = _nullishCoalesce(this.tbl.toDb(field, [value]), () => ( [value]));
|
|
1844
|
+
return sql`${sql.param(spec.item === "bigint" ? String(v) : v)}`;
|
|
1845
|
+
}
|
|
1846
|
+
fromRaw(t, row) {
|
|
1847
|
+
const keyed = {};
|
|
1848
|
+
for (const spec of this.tbl.columns.values()) {
|
|
1849
|
+
if (!(spec.column in row)) continue;
|
|
1850
|
+
const v = row[spec.column];
|
|
1851
|
+
keyed[spec.field] = v == null ? v : t[spec.field].mapFromDriverValue(v);
|
|
1852
|
+
}
|
|
1853
|
+
return this.tbl.fromRow(keyed);
|
|
1854
|
+
}
|
|
1855
|
+
// ── where ──────────────────────────────────────────────────────────────────
|
|
1856
|
+
where(sql, t, where) {
|
|
1857
|
+
if (!where) return void 0;
|
|
1858
|
+
const parts = [];
|
|
1859
|
+
for (const [key, value] of Object.entries(where)) {
|
|
1860
|
+
if (value === void 0) continue;
|
|
1861
|
+
if (key === "AND" || key === "OR" || key === "NOT") {
|
|
1862
|
+
const list = Array.isArray(value) ? value : [value];
|
|
1863
|
+
const subs = list.map((w) => _nullishCoalesce(this.where(sql, t, w), () => ( sql`true`)));
|
|
1864
|
+
if (key === "AND")
|
|
1865
|
+
parts.push(subs.length ? sql`(${sql.join(subs, sql` and `)})` : sql`true`);
|
|
1866
|
+
else if (key === "OR")
|
|
1867
|
+
parts.push(subs.length ? sql`(${sql.join(subs, sql` or `)})` : sql`false`);
|
|
1868
|
+
else parts.push(subs.length ? sql`not (${sql.join(subs, sql` or `)})` : sql`true`);
|
|
1869
|
+
continue;
|
|
1870
|
+
}
|
|
1871
|
+
const spec = this.spec(key);
|
|
1872
|
+
if (!spec) {
|
|
1873
|
+
const isNull = value === null || isPlainObject(value) && value["equals"] === null;
|
|
1874
|
+
parts.push(isNull ? sql`true` : sql`false`);
|
|
1875
|
+
continue;
|
|
1876
|
+
}
|
|
1877
|
+
parts.push(this.fieldFilter(sql, t, spec, value));
|
|
1878
|
+
}
|
|
1879
|
+
if (parts.length === 0) return void 0;
|
|
1880
|
+
return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
|
|
1881
|
+
}
|
|
1882
|
+
fieldFilter(sql, t, spec, filter) {
|
|
1883
|
+
const c = this.col(sql, spec.field);
|
|
1884
|
+
if (filter === null) return sql`${c} is null`;
|
|
1885
|
+
if (spec.kind === "jsonb") return this.jsonFilter(sql, t, spec, filter);
|
|
1886
|
+
if (spec.kind === "array") return this.listFilter(sql, t, spec, filter);
|
|
1887
|
+
if (!isPlainObject(filter)) return sql`${c} = ${this.val(sql, t, spec.field, filter)}`;
|
|
1888
|
+
const insensitive = filter["mode"] === "insensitive";
|
|
1889
|
+
const text = spec.kind === "enum" || insensitive ? sql`${c}::text` : c;
|
|
1890
|
+
const parts = [];
|
|
1891
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
1892
|
+
if (v === void 0 || op === "mode") continue;
|
|
1893
|
+
const val = () => this.val(sql, t, spec.field, v);
|
|
1894
|
+
const eq = (x) => insensitive && typeof x === "string" ? sql`lower(${text}) = lower(${sql.param(x)})` : sql`${c} = ${this.val(sql, t, spec.field, x)}`;
|
|
1895
|
+
switch (op) {
|
|
1896
|
+
case "equals":
|
|
1897
|
+
parts.push(v === null ? sql`${c} is null` : eq(v));
|
|
1898
|
+
break;
|
|
1899
|
+
case "not":
|
|
1900
|
+
parts.push(
|
|
1901
|
+
v === null ? sql`${c} is not null` : isPlainObject(v) ? sql`not (${this.fieldFilter(sql, t, spec, { ...v, ...insensitive && { mode: "insensitive" } })})` : sql`not (${eq(v)})`
|
|
1902
|
+
);
|
|
1903
|
+
break;
|
|
1904
|
+
case "in":
|
|
1905
|
+
case "notIn": {
|
|
1906
|
+
const list = v;
|
|
1907
|
+
if (list.length === 0) {
|
|
1908
|
+
parts.push(op === "in" ? sql`false` : sql`true`);
|
|
1909
|
+
break;
|
|
1910
|
+
}
|
|
1911
|
+
const items = sql.join(
|
|
1912
|
+
list.map((x) => this.val(sql, t, spec.field, x)),
|
|
1913
|
+
sql`, `
|
|
1914
|
+
);
|
|
1915
|
+
parts.push(op === "in" ? sql`${c} in (${items})` : sql`${c} not in (${items})`);
|
|
1916
|
+
break;
|
|
1917
|
+
}
|
|
1918
|
+
case "lt":
|
|
1919
|
+
parts.push(sql`${c} < ${val()}`);
|
|
1920
|
+
break;
|
|
1921
|
+
case "lte":
|
|
1922
|
+
parts.push(sql`${c} <= ${val()}`);
|
|
1923
|
+
break;
|
|
1924
|
+
case "gt":
|
|
1925
|
+
parts.push(sql`${c} > ${val()}`);
|
|
1926
|
+
break;
|
|
1927
|
+
case "gte":
|
|
1928
|
+
parts.push(sql`${c} >= ${val()}`);
|
|
1929
|
+
break;
|
|
1930
|
+
case "contains":
|
|
1931
|
+
case "startsWith":
|
|
1932
|
+
case "endsWith": {
|
|
1933
|
+
const s = likeEscape(String(v));
|
|
1934
|
+
const pattern = op === "contains" ? `%${s}%` : op === "startsWith" ? `${s}%` : `%${s}`;
|
|
1935
|
+
parts.push(
|
|
1936
|
+
insensitive ? sql`${text} ilike ${sql.param(pattern)}` : sql`${text} like ${sql.param(pattern)}`
|
|
1937
|
+
);
|
|
1938
|
+
break;
|
|
1939
|
+
}
|
|
1940
|
+
default:
|
|
1941
|
+
this.fail(spec.field, `unknown filter "${op}"`);
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
return parts.length === 0 ? sql`true` : parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
|
|
1945
|
+
}
|
|
1946
|
+
/** Scalar lists (native arrays): has, hasEvery, hasSome, isEmpty, equals. */
|
|
1947
|
+
listFilter(sql, t, spec, filter) {
|
|
1948
|
+
const c = this.col(sql, spec.field);
|
|
1949
|
+
if (!isPlainObject(filter)) return sql`${c} = ${this.val(sql, t, spec.field, filter)}`;
|
|
1950
|
+
const parts = [];
|
|
1951
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
1952
|
+
if (v === void 0) continue;
|
|
1953
|
+
switch (op) {
|
|
1954
|
+
case "equals":
|
|
1955
|
+
parts.push(
|
|
1956
|
+
v === null ? sql`${c} is null` : sql`${c} = ${this.val(sql, t, spec.field, v)}`
|
|
1957
|
+
);
|
|
1958
|
+
break;
|
|
1959
|
+
case "has":
|
|
1960
|
+
parts.push(
|
|
1961
|
+
v === null ? sql`false` : sql`${this.itemVal(sql, spec.field, v)} = any(${c})`
|
|
1962
|
+
);
|
|
1963
|
+
break;
|
|
1964
|
+
case "hasEvery":
|
|
1965
|
+
parts.push(sql`${c} @> ${this.val(sql, t, spec.field, v)}`);
|
|
1966
|
+
break;
|
|
1967
|
+
case "hasSome":
|
|
1968
|
+
parts.push(sql`${c} && ${this.val(sql, t, spec.field, v)}`);
|
|
1969
|
+
break;
|
|
1970
|
+
case "isEmpty":
|
|
1971
|
+
parts.push(v ? sql`cardinality(${c}) = 0` : sql`cardinality(${c}) > 0`);
|
|
1972
|
+
break;
|
|
1973
|
+
default:
|
|
1974
|
+
this.fail(spec.field, `unknown list filter "${op}"`);
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
|
|
1978
|
+
}
|
|
1979
|
+
/** jsonb fields (embedded objects / arrays of objects / json): Prisma's JSON filters. */
|
|
1980
|
+
jsonFilter(sql, t, spec, filter) {
|
|
1981
|
+
const c = this.col(sql, spec.field);
|
|
1982
|
+
const json = (v) => sql`${sql.param(JSON.stringify(v))}::jsonb`;
|
|
1983
|
+
if (!isPlainObject(filter) || !Object.keys(filter).some((k) => JSON_OPS.has(k))) {
|
|
1984
|
+
return sql`${c} = ${json(filter)}`;
|
|
1985
|
+
}
|
|
1986
|
+
const path = filter["path"];
|
|
1987
|
+
const segs = path === void 0 ? [] : Array.isArray(path) ? path : String(path).split(".");
|
|
1988
|
+
const target = segs.length ? sql`(${c} #> ${sql.param(`{${segs.join(",")}}`)})` : c;
|
|
1989
|
+
const textTarget = segs.length ? sql`(${c} #>> ${sql.param(`{${segs.join(",")}}`)})` : sql`(${c} #>> '{}')`;
|
|
1990
|
+
const parts = [];
|
|
1991
|
+
for (const [op, v] of Object.entries(filter)) {
|
|
1992
|
+
if (v === void 0 || op === "path" || op === "mode") continue;
|
|
1993
|
+
switch (op) {
|
|
1994
|
+
case "equals":
|
|
1995
|
+
parts.push(v === null ? sql`${target} is null` : sql`${target} = ${json(v)}`);
|
|
1996
|
+
break;
|
|
1997
|
+
case "not":
|
|
1998
|
+
parts.push(
|
|
1999
|
+
v === null ? sql`${target} is not null` : sql`${target} is distinct from ${json(v)}`
|
|
2000
|
+
);
|
|
2001
|
+
break;
|
|
2002
|
+
case "string_contains":
|
|
2003
|
+
case "string_starts_with":
|
|
2004
|
+
case "string_ends_with": {
|
|
2005
|
+
const s = likeEscape(String(v));
|
|
2006
|
+
const p = op === "string_contains" ? `%${s}%` : op === "string_starts_with" ? `${s}%` : `%${s}`;
|
|
2007
|
+
parts.push(
|
|
2008
|
+
filter["mode"] === "insensitive" ? sql`${textTarget} ilike ${sql.param(p)}` : sql`${textTarget} like ${sql.param(p)}`
|
|
2009
|
+
);
|
|
2010
|
+
break;
|
|
2011
|
+
}
|
|
2012
|
+
case "array_contains":
|
|
2013
|
+
parts.push(sql`${target} @> ${json(Array.isArray(v) ? v : [v])}`);
|
|
2014
|
+
break;
|
|
2015
|
+
case "gt":
|
|
2016
|
+
case "gte":
|
|
2017
|
+
case "lt":
|
|
2018
|
+
case "lte": {
|
|
2019
|
+
const opSql = { gt: ">", gte: ">=", lt: "<", lte: "<=" }[op];
|
|
2020
|
+
parts.push(
|
|
2021
|
+
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))}`
|
|
2022
|
+
);
|
|
2023
|
+
break;
|
|
2024
|
+
}
|
|
2025
|
+
default:
|
|
2026
|
+
this.fail(spec.field, `unknown JSON filter "${op}"`);
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
return parts.length === 1 ? parts[0] : sql`(${sql.join(parts, sql` and `)})`;
|
|
2030
|
+
}
|
|
2031
|
+
// ── ordering, projection, pagination ───────────────────────────────────────
|
|
2032
|
+
orderList(orderBy) {
|
|
2033
|
+
const list = orderBy === void 0 ? [] : Array.isArray(orderBy) ? orderBy : [orderBy];
|
|
2034
|
+
const out = [];
|
|
2035
|
+
for (const entry of list) {
|
|
2036
|
+
for (const [field, dir] of Object.entries(entry)) {
|
|
2037
|
+
if (dir === void 0 || !this.spec(field)) continue;
|
|
2038
|
+
if (isPlainObject(dir))
|
|
2039
|
+
out.push({ field, desc: dir["sort"] === "desc", nulls: dir["nulls"] });
|
|
2040
|
+
else out.push({ field, desc: dir === "desc" });
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
return out;
|
|
2044
|
+
}
|
|
2045
|
+
orderSql(sql, list) {
|
|
2046
|
+
return sql.join(
|
|
2047
|
+
list.map(
|
|
2048
|
+
(o) => sql`${this.col(sql, o.field)} ${sql.raw(o.desc ? "desc" : "asc")}${o.nulls ? sql.raw(` nulls ${o.nulls}`) : sql``}`
|
|
2049
|
+
),
|
|
2050
|
+
sql`, `
|
|
2051
|
+
);
|
|
2052
|
+
}
|
|
2053
|
+
/** The fields a result keeps, from `select` / `omit`. */
|
|
2054
|
+
projection(args) {
|
|
2055
|
+
const all = [...this.tbl.columns.keys()];
|
|
2056
|
+
if (args["select"] && args["omit"]) this.fail("select", "use either select or omit, not both");
|
|
2057
|
+
if (args["select"]) {
|
|
2058
|
+
const keep = Object.entries(args["select"]).filter(([f, on]) => on && this.spec(f)).map(([f]) => f);
|
|
2059
|
+
return keep;
|
|
2060
|
+
}
|
|
2061
|
+
if (args["omit"]) {
|
|
2062
|
+
const drop = new Set(
|
|
2063
|
+
Object.entries(args["omit"]).filter(([, on]) => on).map(([f]) => f)
|
|
2064
|
+
);
|
|
2065
|
+
return all.filter((f) => !drop.has(f));
|
|
2066
|
+
}
|
|
2067
|
+
return all;
|
|
2068
|
+
}
|
|
2069
|
+
project(record, fields) {
|
|
2070
|
+
const out = {};
|
|
2071
|
+
for (const f of fields) if (record[f] !== void 0) out[f] = record[f];
|
|
2072
|
+
return out;
|
|
2073
|
+
}
|
|
2074
|
+
/** Checks `where` names a unique key (id, a unique field, or a compound unique index). */
|
|
2075
|
+
uniqueKey(where, op) {
|
|
2076
|
+
const plain = (f) => _optionalChain([where, 'optionalAccess', _52 => _52[f]]) !== void 0 && where[f] !== null && !isPlainObject(where[f]);
|
|
2077
|
+
const key = this.uniqueSets.find((set) => set.every(plain));
|
|
2078
|
+
if (!key) {
|
|
2079
|
+
this.fail(
|
|
2080
|
+
"where",
|
|
2081
|
+
`${op} needs a unique field in where: ${this.uniqueSets.map((s) => s.join(" + ")).join(", ")}`
|
|
2082
|
+
);
|
|
2083
|
+
}
|
|
2084
|
+
return key;
|
|
2085
|
+
}
|
|
2086
|
+
/** WHERE for findMany-style reads: filter, plus the cursor's keyset condition. */
|
|
2087
|
+
readWhere(sql, t, args, order) {
|
|
2088
|
+
const parts = [];
|
|
2089
|
+
const w = this.where(sql, t, args["where"]);
|
|
2090
|
+
if (w) parts.push(w);
|
|
2091
|
+
if (args["cursor"]) {
|
|
2092
|
+
this.uniqueKey(args["cursor"], "cursor");
|
|
2093
|
+
const cw = this.where(sql, t, args["cursor"]);
|
|
2094
|
+
const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(q(this.tbl.table))} where ${cw})`;
|
|
2095
|
+
const ors = [];
|
|
2096
|
+
const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
|
|
2097
|
+
for (let i = 0; i < order.length; i++) {
|
|
2098
|
+
const o = order[i];
|
|
2099
|
+
const c = this.col(sql, o.field);
|
|
2100
|
+
const v = at(o.field);
|
|
2101
|
+
const nullsFirst = o.nulls ? o.nulls === "first" : o.desc;
|
|
2102
|
+
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`})))`;
|
|
2103
|
+
const eqs = order.slice(0, i).map(same);
|
|
2104
|
+
ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
|
|
2105
|
+
}
|
|
2106
|
+
ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
|
|
2107
|
+
parts.push(sql`exists (select 1 from ${sql.raw(q(this.tbl.table))} where ${cw})`);
|
|
2108
|
+
parts.push(sql`(${sql.join(ors, sql` or `)})`);
|
|
2109
|
+
}
|
|
2110
|
+
return parts.length ? sql.join(parts, sql` and `) : sql`true`;
|
|
2111
|
+
}
|
|
2112
|
+
/** SELECT for a findMany-style read, and whether the rows come back reversed. */
|
|
2113
|
+
readQuery(sql, t, args, columnsSql) {
|
|
2114
|
+
const take = args["take"];
|
|
2115
|
+
const reversed = take !== void 0 && take < 0;
|
|
2116
|
+
let order = this.orderList(args["orderBy"]);
|
|
2117
|
+
const paged = args["cursor"] || take !== void 0 || args["skip"];
|
|
2118
|
+
if (paged && !order.some((o) => o.field === "id")) {
|
|
2119
|
+
order = [...order, { field: "id", desc: false }];
|
|
2120
|
+
}
|
|
2121
|
+
if (reversed) {
|
|
2122
|
+
order = order.map((o) => ({
|
|
2123
|
+
...o,
|
|
2124
|
+
desc: !o.desc,
|
|
2125
|
+
...o.nulls && { nulls: o.nulls === "first" ? "last" : "first" }
|
|
2126
|
+
}));
|
|
2127
|
+
}
|
|
2128
|
+
const limit = take === void 0 ? sql`` : sql` limit ${sql.param(Math.abs(take))}`;
|
|
2129
|
+
const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
|
|
2130
|
+
const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
|
|
2131
|
+
const where = this.readWhere(sql, t, args, order);
|
|
2132
|
+
const from = sql.raw(q(this.tbl.table));
|
|
2133
|
+
const distinct = _optionalChain([args, 'access', _53 => _53["distinct"], 'optionalAccess', _54 => _54.filter, 'call', _55 => _55((f) => this.spec(f))]);
|
|
2134
|
+
if (_optionalChain([distinct, 'optionalAccess', _56 => _56.length])) {
|
|
2135
|
+
const dcols = sql.join(
|
|
2136
|
+
distinct.map((f) => this.col(sql, f)),
|
|
2137
|
+
sql`, `
|
|
2138
|
+
);
|
|
2139
|
+
const inner = sql`select distinct on (${dcols}) * from ${from} where ${where} order by ${dcols}${order.length ? sql`, ${this.orderSql(sql, order)}` : sql``}`;
|
|
2140
|
+
return {
|
|
2141
|
+
query: sql`select ${columnsSql} from (${inner}) as efc_distinct${orderBy}${limit}${offset}`,
|
|
2142
|
+
reversed
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
return {
|
|
2146
|
+
query: sql`select ${columnsSql} from ${from} where ${where}${orderBy}${limit}${offset}`,
|
|
2147
|
+
reversed
|
|
2148
|
+
};
|
|
2149
|
+
}
|
|
2150
|
+
// ── reads ──────────────────────────────────────────────────────────────────
|
|
2151
|
+
async findMany(args = {}) {
|
|
2152
|
+
const { t, sql } = await this.tbl.ready();
|
|
2153
|
+
return this.tbl.guard(async () => {
|
|
2154
|
+
const fields = this.projection(args);
|
|
2155
|
+
const cols = sql.join(
|
|
2156
|
+
[.../* @__PURE__ */ new Set(["id", ...fields])].map((f) => this.col(sql, f)),
|
|
2157
|
+
sql`, `
|
|
2158
|
+
);
|
|
2159
|
+
const { query, reversed } = this.readQuery(sql, t, args, cols);
|
|
2160
|
+
const rows = (await this.tbl.client().execute(query)).rows.map(
|
|
2161
|
+
(r) => this.project(this.fromRaw(t, r), fields)
|
|
2162
|
+
);
|
|
2163
|
+
return reversed ? rows.reverse() : rows;
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
async findFirst(args = {}) {
|
|
2167
|
+
const take = args["take"];
|
|
2168
|
+
const rows = await this.findMany({ ...args, take: take !== void 0 && take < 0 ? -1 : 1 });
|
|
2169
|
+
return _nullishCoalesce(rows[0], () => ( null));
|
|
2170
|
+
}
|
|
2171
|
+
async findUnique(args) {
|
|
2172
|
+
this.uniqueKey(args["where"], "findUnique");
|
|
2173
|
+
return this.findFirst({ where: args["where"], select: args["select"], omit: args["omit"] });
|
|
2174
|
+
}
|
|
2175
|
+
async orThrow(p) {
|
|
2176
|
+
const r = await p;
|
|
2177
|
+
if (r === null) throw new HttpError(404, `${this.name} not found`);
|
|
2178
|
+
return r;
|
|
2179
|
+
}
|
|
2180
|
+
async count(args = {}) {
|
|
2181
|
+
const { t, sql } = await this.tbl.ready();
|
|
2182
|
+
return this.tbl.guard(async () => {
|
|
2183
|
+
const select = args["select"];
|
|
2184
|
+
const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
|
|
2185
|
+
const exprs = sql.join(
|
|
2186
|
+
counted.map(
|
|
2187
|
+
([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))}`
|
|
2188
|
+
),
|
|
2189
|
+
sql`, `
|
|
2190
|
+
);
|
|
2191
|
+
const { query } = this.readQuery(
|
|
2192
|
+
sql,
|
|
2193
|
+
t,
|
|
2194
|
+
{ ...args, select: void 0, distinct: args["distinct"] },
|
|
2195
|
+
sql`*`
|
|
2196
|
+
);
|
|
2197
|
+
const [row] = (await this.tbl.client().execute(sql`select ${exprs} from (${query}) as efc_rows`)).rows;
|
|
2198
|
+
return select ? row : row["_all"];
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
// ── aggregates ─────────────────────────────────────────────────────────────
|
|
2202
|
+
aggregateSpec(args) {
|
|
2203
|
+
const out = [];
|
|
2204
|
+
for (const agg of AGGREGATES) {
|
|
2205
|
+
const v = args[agg];
|
|
2206
|
+
if (!v) continue;
|
|
2207
|
+
if (v === true) {
|
|
2208
|
+
if (agg !== "_count") this.fail(agg, `${agg} needs fields, e.g. { total: true }`);
|
|
2209
|
+
out.push({ agg, field: "_all", alias: `${agg}._all` });
|
|
2210
|
+
continue;
|
|
2211
|
+
}
|
|
2212
|
+
for (const [field, on] of Object.entries(v)) {
|
|
2213
|
+
if (!on) continue;
|
|
2214
|
+
if (field === "_all" && agg === "_count") {
|
|
2215
|
+
out.push({ agg, field, alias: `${agg}._all` });
|
|
2216
|
+
continue;
|
|
2217
|
+
}
|
|
2218
|
+
const spec = this.spec(field);
|
|
2219
|
+
if (!spec) this.fail(`${agg}.${field}`, "unknown field");
|
|
2220
|
+
if ((agg === "_sum" || agg === "_avg") && !NUMERIC_KINDS.has(spec.kind)) {
|
|
2221
|
+
this.fail(`${agg}.${field}`, `${agg} needs a numeric field`);
|
|
2222
|
+
}
|
|
2223
|
+
out.push({ agg, field, alias: `${agg}.${field}` });
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
return out;
|
|
2227
|
+
}
|
|
2228
|
+
aggregateExpr(sql, agg, field) {
|
|
2229
|
+
if (agg === "_count")
|
|
2230
|
+
return field === "_all" ? sql`count(*)` : sql`count(${this.col(sql, field)})`;
|
|
2231
|
+
const fn = { _sum: "sum", _avg: "avg", _min: "min", _max: "max" }[agg];
|
|
2232
|
+
return sql`${sql.raw(fn)}(${this.col(sql, field)})`;
|
|
2233
|
+
}
|
|
2234
|
+
/** Raw aggregate value → the type Prisma returns for it. */
|
|
2235
|
+
aggregateValue(t, agg, field, v) {
|
|
2236
|
+
if (agg === "_count") return Number(v);
|
|
2237
|
+
if (v == null) return null;
|
|
2238
|
+
const spec = this.spec(field);
|
|
2239
|
+
if (agg === "_min" || agg === "_max") return t[field].mapFromDriverValue(v);
|
|
2240
|
+
if (spec.kind === "numeric") return String(v);
|
|
2241
|
+
if (agg === "_sum" && spec.kind === "bigint") return BigInt(String(v).split(".")[0]);
|
|
2242
|
+
return Number(v);
|
|
2243
|
+
}
|
|
2244
|
+
aggregateRow(t, specs, row, args) {
|
|
2245
|
+
const out = {};
|
|
2246
|
+
for (const { agg, field, alias } of specs) {
|
|
2247
|
+
const value = this.aggregateValue(t, agg, field, row[alias]);
|
|
2248
|
+
if (agg === "_count" && args["_count"] === true) out[agg] = value;
|
|
2249
|
+
else (out[agg] ??= {})[field] = value;
|
|
2250
|
+
}
|
|
2251
|
+
return out;
|
|
2252
|
+
}
|
|
2253
|
+
async aggregate(args = {}) {
|
|
2254
|
+
const { t, sql } = await this.tbl.ready();
|
|
2255
|
+
return this.tbl.guard(async () => {
|
|
2256
|
+
const specs = this.aggregateSpec(args);
|
|
2257
|
+
if (specs.length === 0) return {};
|
|
2258
|
+
const exprs = sql.join(
|
|
2259
|
+
specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`),
|
|
2260
|
+
sql`, `
|
|
2261
|
+
);
|
|
2262
|
+
const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
|
|
2263
|
+
const [row] = (await this.tbl.client().execute(sql`select ${exprs} from (${query}) as efc_rows`)).rows;
|
|
2264
|
+
return this.aggregateRow(t, specs, row, args);
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
havingSql(sql, t, having) {
|
|
2268
|
+
if (!having) return void 0;
|
|
2269
|
+
const parts = [];
|
|
2270
|
+
for (const [key, value] of Object.entries(having)) {
|
|
2271
|
+
if (value === void 0) continue;
|
|
2272
|
+
if (key === "AND" || key === "OR" || key === "NOT") {
|
|
2273
|
+
const list = Array.isArray(value) ? value : [value];
|
|
2274
|
+
const subs = list.map((h) => _nullishCoalesce(this.havingSql(sql, t, h), () => ( sql`true`)));
|
|
2275
|
+
const joined = sql.join(
|
|
2276
|
+
subs,
|
|
2277
|
+
key === "OR" ? sql` or ` : key === "NOT" ? sql` or ` : sql` and `
|
|
2278
|
+
);
|
|
2279
|
+
parts.push(key === "NOT" ? sql`not (${joined})` : sql`(${joined})`);
|
|
2280
|
+
continue;
|
|
2281
|
+
}
|
|
2282
|
+
const spec = this.spec(key);
|
|
2283
|
+
if (!spec) this.fail(`having.${key}`, "unknown field");
|
|
2284
|
+
const filter = value;
|
|
2285
|
+
const aggKeys = isPlainObject(filter) ? Object.keys(filter).filter((k) => AGGREGATES.includes(k)) : [];
|
|
2286
|
+
if (aggKeys.length === 0) {
|
|
2287
|
+
parts.push(this.fieldFilter(sql, t, spec, filter));
|
|
2288
|
+
continue;
|
|
2289
|
+
}
|
|
2290
|
+
for (const agg of aggKeys) {
|
|
2291
|
+
const expr = this.aggregateExpr(sql, agg, key);
|
|
2292
|
+
for (const [op, v] of Object.entries(filter[agg])) {
|
|
2293
|
+
const opSql = { equals: "=", not: "<>", gt: ">", gte: ">=", lt: "<", lte: "<=" }[op];
|
|
2294
|
+
if (!opSql) this.fail(`having.${key}.${agg}`, `unknown filter "${op}"`);
|
|
2295
|
+
parts.push(
|
|
2296
|
+
sql`${expr} ${sql.raw(opSql)} ${sql.param(typeof v === "bigint" ? String(v) : v instanceof Date ? v : v)}`
|
|
2297
|
+
);
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
return parts.length ? sql.join(parts, sql` and `) : void 0;
|
|
2302
|
+
}
|
|
2303
|
+
async groupBy(args) {
|
|
2304
|
+
const { t, sql } = await this.tbl.ready();
|
|
2305
|
+
return this.tbl.guard(async () => {
|
|
2306
|
+
const by = Array.isArray(args["by"]) ? args["by"] : [args["by"]];
|
|
2307
|
+
if (by.length === 0) this.fail("by", "groupBy needs at least one field");
|
|
2308
|
+
for (const f of by) if (!this.spec(f)) this.fail(`by.${f}`, "unknown field");
|
|
2309
|
+
const specs = this.aggregateSpec(args);
|
|
2310
|
+
const select = sql.join(
|
|
2311
|
+
[
|
|
2312
|
+
...by.map((f) => this.col(sql, f)),
|
|
2313
|
+
...specs.map(
|
|
2314
|
+
(s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(q(s.alias))}`
|
|
2315
|
+
)
|
|
2316
|
+
],
|
|
2317
|
+
sql`, `
|
|
2318
|
+
);
|
|
2319
|
+
const where = this.where(sql, t, args["where"]);
|
|
2320
|
+
const having = this.havingSql(sql, t, args["having"]);
|
|
2321
|
+
const orders = [];
|
|
2322
|
+
for (const entry of Array.isArray(args["orderBy"]) ? args["orderBy"] : args["orderBy"] ? [args["orderBy"]] : []) {
|
|
2323
|
+
for (const [key, dir] of Object.entries(entry)) {
|
|
2324
|
+
if (AGGREGATES.includes(key)) {
|
|
2325
|
+
for (const [field, d] of Object.entries(dir)) {
|
|
2326
|
+
orders.push(
|
|
2327
|
+
sql`${this.aggregateExpr(sql, key, field)} ${sql.raw(d === "desc" ? "desc" : "asc")}`
|
|
2328
|
+
);
|
|
2329
|
+
}
|
|
2330
|
+
} else if (this.spec(key)) {
|
|
2331
|
+
if (!by.includes(key))
|
|
2332
|
+
this.fail(`orderBy.${key}`, "groupBy can only order by grouped fields or aggregates");
|
|
2333
|
+
const d = isPlainObject(dir) ? dir["sort"] : dir;
|
|
2334
|
+
orders.push(sql`${this.col(sql, key)} ${sql.raw(d === "desc" ? "desc" : "asc")}`);
|
|
2335
|
+
}
|
|
2336
|
+
}
|
|
2337
|
+
}
|
|
2338
|
+
const query = sql`select ${select} from ${sql.raw(q(this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
|
|
2339
|
+
by.map((f) => this.col(sql, f)),
|
|
2340
|
+
sql`, `
|
|
2341
|
+
)}${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``}`;
|
|
2342
|
+
const rows = (await this.tbl.client().execute(query)).rows;
|
|
2343
|
+
return rows.map((row) => {
|
|
2344
|
+
const keyed = {};
|
|
2345
|
+
for (const f of by) keyed[f] = row[this.spec(f).column];
|
|
2346
|
+
const out = this.project(
|
|
2347
|
+
this.fromRaw(t, Object.fromEntries(by.map((f) => [this.spec(f).column, keyed[f]]))),
|
|
2348
|
+
by
|
|
2349
|
+
);
|
|
2350
|
+
for (const f of by) if (!(f in out)) out[f] = null;
|
|
2351
|
+
return { ...out, ...this.aggregateRow(t, specs, row, args) };
|
|
2352
|
+
});
|
|
2353
|
+
});
|
|
2354
|
+
}
|
|
2355
|
+
// ── writes ─────────────────────────────────────────────────────────────────
|
|
2356
|
+
/** Prisma update data → SET expressions, validated. */
|
|
2357
|
+
async setList(sql, t, data, alias) {
|
|
2358
|
+
const sets = [];
|
|
2359
|
+
const plain = {};
|
|
2360
|
+
const issues = [];
|
|
2361
|
+
const ref = (f) => this.col(sql, f, alias);
|
|
2362
|
+
for (const [field, value] of Object.entries(data)) {
|
|
2363
|
+
if (value === void 0) continue;
|
|
2364
|
+
const spec = this.spec(field);
|
|
2365
|
+
if (!spec || field === "id" || field === this.tbl.ts.createdAt || field === this.tbl.ts.updatedAt) {
|
|
2366
|
+
continue;
|
|
2367
|
+
}
|
|
2368
|
+
const ops = isPlainObject(value) && spec.kind !== "jsonb" ? value : void 0;
|
|
2369
|
+
if (!ops) {
|
|
2370
|
+
plain[field] = value;
|
|
2371
|
+
continue;
|
|
2372
|
+
}
|
|
2373
|
+
for (const [op, v] of Object.entries(ops)) {
|
|
2374
|
+
if (v === void 0) continue;
|
|
2375
|
+
if (op === "set") {
|
|
2376
|
+
plain[field] = v;
|
|
2377
|
+
} else if (op === "increment" || op === "decrement" || op === "multiply" || op === "divide") {
|
|
2378
|
+
if (!NUMERIC_KINDS.has(spec.kind)) {
|
|
2379
|
+
issues.push({ path: field, message: `${op} only applies to number fields` });
|
|
2380
|
+
continue;
|
|
2381
|
+
}
|
|
2382
|
+
const okOperand = typeof v === "number" && Number.isFinite(v) || typeof v === "bigint" || spec.kind === "numeric" && typeof v === "string";
|
|
2383
|
+
if (!okOperand) {
|
|
2384
|
+
issues.push({ path: field, message: `${op} needs a number` });
|
|
2385
|
+
continue;
|
|
2386
|
+
}
|
|
2387
|
+
const sym = { increment: "+", decrement: "-", multiply: "*", divide: "/" }[op];
|
|
2388
|
+
sets.push(
|
|
2389
|
+
sql`${this.col(sql, field)} = ${ref(field)} ${sql.raw(sym)} ${this.val(sql, t, field, v)}`
|
|
2390
|
+
);
|
|
2391
|
+
} else if (op === "push" && spec.kind === "array") {
|
|
2392
|
+
const items = Array.isArray(v) ? v : [v];
|
|
2393
|
+
sets.push(
|
|
2394
|
+
sql`${this.col(sql, field)} = coalesce(${ref(field)}, ${sql.raw(`'{}'::${spec.ddl}`)}) || ${this.val(sql, t, field, items)}::${sql.raw(spec.ddl)}`
|
|
2395
|
+
);
|
|
2396
|
+
} else {
|
|
2397
|
+
issues.push({ path: field, message: `unknown update operation "${op}"` });
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
if (issues.length) throw new ModelValidationError(this.name, issues);
|
|
2402
|
+
await this.tbl.validate(plain, true);
|
|
2403
|
+
for (const [field, v] of Object.entries(plain)) {
|
|
2404
|
+
sets.push(
|
|
2405
|
+
sql`${this.col(sql, field)} = ${v === null ? sql`null` : this.val(sql, t, field, v)}`
|
|
2406
|
+
);
|
|
2407
|
+
}
|
|
2408
|
+
if (this.tbl.ts.updatedAt && sets.length) {
|
|
2409
|
+
sets.push(
|
|
2410
|
+
sql`${this.col(sql, this.tbl.ts.updatedAt)} = ${this.val(sql, t, this.tbl.ts.updatedAt, /* @__PURE__ */ new Date())}`
|
|
2411
|
+
);
|
|
2412
|
+
}
|
|
2413
|
+
return sets;
|
|
2414
|
+
}
|
|
2415
|
+
insertSql(sql, t, rows) {
|
|
2416
|
+
const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
|
|
2417
|
+
const head = sql`insert into ${sql.raw(q(this.tbl.table))} (${sql.join(
|
|
2418
|
+
fields.map((f) => this.col(sql, f)),
|
|
2419
|
+
sql`, `
|
|
2420
|
+
)})`;
|
|
2421
|
+
const values = sql.join(
|
|
2422
|
+
rows.map(
|
|
2423
|
+
(r) => sql`(${sql.join(
|
|
2424
|
+
fields.map((f) => r[f] === void 0 ? sql`default` : sql`${sql.param(r[f], t[f])}`),
|
|
2425
|
+
sql`, `
|
|
2426
|
+
)})`
|
|
2427
|
+
),
|
|
2428
|
+
sql`, `
|
|
2429
|
+
);
|
|
2430
|
+
return { head, values };
|
|
2431
|
+
}
|
|
2432
|
+
async prepare(data) {
|
|
2433
|
+
if (!isPlainObject(data)) this.fail("data", "must be an object");
|
|
2434
|
+
return this.tbl.prepareInsert(data);
|
|
2435
|
+
}
|
|
2436
|
+
async create(args) {
|
|
2437
|
+
const { t, sql } = await this.tbl.ready();
|
|
2438
|
+
return this.tbl.guard(async () => {
|
|
2439
|
+
const row = await this.prepare(args["data"]);
|
|
2440
|
+
const { head, values } = this.insertSql(sql, t, [row]);
|
|
2441
|
+
const [inserted] = (await this.tbl.client().execute(sql`${head} values ${values} returning *`)).rows;
|
|
2442
|
+
return this.project(this.fromRaw(t, inserted), this.projection(args));
|
|
2443
|
+
});
|
|
2444
|
+
}
|
|
2445
|
+
async createMany(args, returning) {
|
|
2446
|
+
const { t, sql } = await this.tbl.ready();
|
|
2447
|
+
return this.tbl.guard(async () => {
|
|
2448
|
+
const data = Array.isArray(args["data"]) ? args["data"] : [args["data"]];
|
|
2449
|
+
if (data.length === 0) return returning ? [] : { count: 0 };
|
|
2450
|
+
const rows = await Promise.all(data.map((d) => this.prepare(d)));
|
|
2451
|
+
const { head, values } = this.insertSql(sql, t, rows);
|
|
2452
|
+
const conflict = args["skipDuplicates"] ? sql` on conflict do nothing` : sql``;
|
|
2453
|
+
const result = await this.tbl.client().execute(sql`${head} values ${values}${conflict}${returning ? sql` returning *` : sql``}`);
|
|
2454
|
+
if (!returning) return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
|
|
2455
|
+
const fields = this.projection(args);
|
|
2456
|
+
return result.rows.map((r) => this.project(this.fromRaw(t, r), fields));
|
|
2457
|
+
});
|
|
2458
|
+
}
|
|
2459
|
+
async update(args) {
|
|
2460
|
+
this.uniqueKey(args["where"], "update");
|
|
2461
|
+
const { t, sql } = await this.tbl.ready();
|
|
2462
|
+
return this.tbl.guard(async () => {
|
|
2463
|
+
const sets = await this.setList(sql, t, _nullishCoalesce(args["data"], () => ( {})));
|
|
2464
|
+
const where = this.where(sql, t, args["where"]);
|
|
2465
|
+
const query = sets.length ? sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *` : sql`select * from ${sql.raw(q(this.tbl.table))} where ${where} limit 1`;
|
|
2466
|
+
const [row] = (await this.tbl.client().execute(query)).rows;
|
|
2467
|
+
if (!row) throw new HttpError(404, `${this.name} not found`);
|
|
2468
|
+
return this.project(this.fromRaw(t, row), this.projection(args));
|
|
2469
|
+
});
|
|
2470
|
+
}
|
|
2471
|
+
async updateMany(args, returning) {
|
|
2472
|
+
const { t, sql } = await this.tbl.ready();
|
|
2473
|
+
return this.tbl.guard(async () => {
|
|
2474
|
+
const sets = await this.setList(sql, t, _nullishCoalesce(args["data"], () => ( {})));
|
|
2475
|
+
if (sets.length === 0) {
|
|
2476
|
+
if (!returning) return { count: 0 };
|
|
2477
|
+
return this.findMany({ where: args["where"], select: args["select"], omit: args["omit"] });
|
|
2478
|
+
}
|
|
2479
|
+
const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
|
|
2480
|
+
const result = await this.tbl.client().execute(
|
|
2481
|
+
sql`update ${sql.raw(q(this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${returning ? sql` returning *` : sql``}`
|
|
2482
|
+
);
|
|
2483
|
+
if (!returning) return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
|
|
2484
|
+
const fields = this.projection(args);
|
|
2485
|
+
return result.rows.map((r) => this.project(this.fromRaw(t, r), fields));
|
|
2486
|
+
});
|
|
2487
|
+
}
|
|
2488
|
+
async upsert(args) {
|
|
2489
|
+
const key = this.uniqueKey(args["where"], "upsert");
|
|
2490
|
+
const { t, sql } = await this.tbl.ready();
|
|
2491
|
+
return this.tbl.guard(async () => {
|
|
2492
|
+
const row = await this.prepare(args["create"]);
|
|
2493
|
+
for (const f of key) {
|
|
2494
|
+
if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
|
|
2495
|
+
}
|
|
2496
|
+
const { head, values } = this.insertSql(sql, t, [row]);
|
|
2497
|
+
let sets = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), q(this.tbl.table));
|
|
2498
|
+
if (sets.length === 0)
|
|
2499
|
+
sets = [sql`${this.col(sql, key[0])} = excluded.${this.col(sql, key[0])}`];
|
|
2500
|
+
const target = sql.join(
|
|
2501
|
+
key.map((f) => this.col(sql, f)),
|
|
2502
|
+
sql`, `
|
|
2503
|
+
);
|
|
2504
|
+
const extra = Object.keys(args["where"]).filter((f) => !key.includes(f));
|
|
2505
|
+
const cond = extra.length ? sql` where ${this.where(sql, t, Object.fromEntries(extra.map((f) => [f, args["where"][f]])))}` : sql``;
|
|
2506
|
+
const [out] = (await this.tbl.client().execute(
|
|
2507
|
+
sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond} returning *`
|
|
2508
|
+
)).rows;
|
|
2509
|
+
if (!out) throw new HttpError(404, `${this.name} not found`);
|
|
2510
|
+
return this.project(this.fromRaw(t, out), this.projection(args));
|
|
2511
|
+
});
|
|
2512
|
+
}
|
|
2513
|
+
async delete(args) {
|
|
2514
|
+
this.uniqueKey(args["where"], "delete");
|
|
2515
|
+
const { t, sql } = await this.tbl.ready();
|
|
2516
|
+
return this.tbl.guard(async () => {
|
|
2517
|
+
const where = this.where(sql, t, args["where"]);
|
|
2518
|
+
const [row] = (await this.tbl.client().execute(sql`delete from ${sql.raw(q(this.tbl.table))} where ${where} returning *`)).rows;
|
|
2519
|
+
if (!row) throw new HttpError(404, `${this.name} not found`);
|
|
2520
|
+
return this.project(this.fromRaw(t, row), this.projection(args));
|
|
2521
|
+
});
|
|
2522
|
+
}
|
|
2523
|
+
async deleteMany(args = {}) {
|
|
2524
|
+
const { t, sql } = await this.tbl.ready();
|
|
2525
|
+
return this.tbl.guard(async () => {
|
|
2526
|
+
const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
|
|
2527
|
+
const result = await this.tbl.client().execute(sql`delete from ${sql.raw(q(this.tbl.table))} where ${where}`);
|
|
2528
|
+
return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
|
|
2529
|
+
});
|
|
2530
|
+
}
|
|
2531
|
+
};
|
|
2532
|
+
var JSON_OPS = /* @__PURE__ */ new Set([
|
|
2533
|
+
"path",
|
|
2534
|
+
"equals",
|
|
2535
|
+
"not",
|
|
2536
|
+
"string_contains",
|
|
2537
|
+
"string_starts_with",
|
|
2538
|
+
"string_ends_with",
|
|
2539
|
+
"array_contains",
|
|
2540
|
+
"gt",
|
|
2541
|
+
"gte",
|
|
2542
|
+
"lt",
|
|
2543
|
+
"lte",
|
|
2544
|
+
"mode"
|
|
2545
|
+
]);
|
|
2546
|
+
function createTable(name, schema, options = {}) {
|
|
2547
|
+
normalizeSchema(schema, "table", name);
|
|
2548
|
+
let runtime;
|
|
2549
|
+
const rt = () => {
|
|
2550
|
+
const engine2 = getDbEngine();
|
|
2551
|
+
if (engine2 !== "postgresql") {
|
|
2552
|
+
throw new Error(
|
|
2553
|
+
`[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`
|
|
2554
|
+
);
|
|
2555
|
+
}
|
|
2556
|
+
return runtime ??= new TableRuntime(name, schema, options);
|
|
2557
|
+
};
|
|
2558
|
+
const call = (fn) => Promise.resolve().then(() => fn(rt()));
|
|
2559
|
+
const model = {
|
|
2560
|
+
name,
|
|
2561
|
+
findMany: (args) => call((r) => r.findMany(args)),
|
|
2562
|
+
findFirst: (args) => call((r) => r.findFirst(args)),
|
|
2563
|
+
findFirstOrThrow: (args) => call((r) => r.orThrow(r.findFirst(args))),
|
|
2564
|
+
findUnique: (args) => call((r) => r.findUnique(args)),
|
|
2565
|
+
findUniqueOrThrow: (args) => call((r) => r.orThrow(r.findUnique(args))),
|
|
2566
|
+
count: (args) => call((r) => r.count(args)),
|
|
2567
|
+
aggregate: (args) => call((r) => r.aggregate(args)),
|
|
2568
|
+
groupBy: (args) => call((r) => r.groupBy(args)),
|
|
2569
|
+
create: (args) => call((r) => r.create(args)),
|
|
2570
|
+
createMany: (args) => call((r) => r.createMany(args, false)),
|
|
2571
|
+
createManyAndReturn: (args) => call((r) => r.createMany(args, true)),
|
|
2572
|
+
update: (args) => call((r) => r.update(args)),
|
|
2573
|
+
updateMany: (args) => call((r) => r.updateMany(args, false)),
|
|
2574
|
+
updateManyAndReturn: (args) => call((r) => r.updateMany(args, true)),
|
|
2575
|
+
upsert: (args) => call((r) => r.upsert(args)),
|
|
2576
|
+
delete: (args) => call((r) => r.delete(args)),
|
|
2577
|
+
deleteMany: (args) => call((r) => r.deleteMany(args)),
|
|
2578
|
+
raw: () => call(async (r) => (await r.tbl.compile()).t),
|
|
2579
|
+
sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _57 => _57.dryRun]), () => ( false)))),
|
|
2580
|
+
drop: () => call((r) => r.tbl.drop())
|
|
2581
|
+
};
|
|
2582
|
+
registerModel({
|
|
2583
|
+
name,
|
|
2584
|
+
sync: model.sync,
|
|
2585
|
+
drop: model.drop,
|
|
2586
|
+
findByIds: (ids) => model.findMany({ where: { id: { in: ids } } })
|
|
2587
|
+
});
|
|
2588
|
+
return model;
|
|
2589
|
+
}
|
|
2590
|
+
function defineTable(name, schema, options) {
|
|
2591
|
+
return createTable(name, schema, _nullishCoalesce(options, () => ( {})));
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
// src/db/index.ts
|
|
2595
|
+
var _client = null;
|
|
2596
|
+
function setDbClient(client) {
|
|
2597
|
+
_client = client;
|
|
2598
|
+
}
|
|
2599
|
+
function getDbClient() {
|
|
2600
|
+
if (!_client) {
|
|
2601
|
+
throw new Error("[EFC] db not ready \u2014 accessed before Pre-Flight completed");
|
|
2602
|
+
}
|
|
2603
|
+
return _client;
|
|
2604
|
+
}
|
|
2605
|
+
var db = new Proxy({}, {
|
|
2606
|
+
get(_target, prop) {
|
|
2607
|
+
const client = getDbClient();
|
|
2608
|
+
const value = client[prop];
|
|
2609
|
+
return typeof value === "function" ? value.bind(client) : value;
|
|
2610
|
+
},
|
|
2611
|
+
set(_target, prop, value) {
|
|
2612
|
+
getDbClient()[prop] = value;
|
|
2613
|
+
return true;
|
|
2614
|
+
}
|
|
2615
|
+
});
|
|
2616
|
+
|
|
2617
|
+
|
|
2618
|
+
|
|
2619
|
+
|
|
2620
|
+
|
|
2621
|
+
|
|
2622
|
+
|
|
2623
|
+
|
|
2624
|
+
|
|
2625
|
+
|
|
2626
|
+
|
|
2627
|
+
|
|
2628
|
+
|
|
2629
|
+
|
|
2630
|
+
|
|
2631
|
+
|
|
2632
|
+
|
|
2633
|
+
|
|
2634
|
+
exports.HttpError = HttpError; exports.isHttpError = isHttpError; exports.ModelValidationError = ModelValidationError; exports.setDbEngine = setDbEngine; exports.getDbEngine = getDbEngine; exports.setAutoSync = setAutoSync; exports.registeredModels = registeredModels; exports.currentTx = currentTx; exports.runInTx = runInTx; exports.loadMongoose = loadMongoose; exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.defineTable = defineTable; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
|
|
2635
|
+
//# sourceMappingURL=chunk-QTRGJ2EN.cjs.map
|