express-file-cluster 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/auth/index.cjs +3 -3
- package/dist/auth/index.d.cts +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +2 -2
- package/dist/{chunk-ZDM5JHVK.cjs → chunk-2J3HHQKP.cjs} +3 -3
- package/dist/{chunk-ZDM5JHVK.cjs.map → chunk-2J3HHQKP.cjs.map} +1 -1
- package/dist/{chunk-BUBXO7WU.js → chunk-HXV543HZ.js} +10 -3
- package/dist/chunk-HXV543HZ.js.map +1 -0
- package/dist/{chunk-OSES7ZQ5.js → chunk-QKQZF573.js} +27 -5
- package/dist/chunk-QKQZF573.js.map +1 -0
- package/dist/{chunk-B2I7SYQ3.js → chunk-RRQ2RK5M.js} +371 -8
- package/dist/chunk-RRQ2RK5M.js.map +1 -0
- package/dist/{chunk-TRC4DUZB.js → chunk-RSZB7VAO.js} +2 -2
- package/dist/{chunk-FQFKHPLR.cjs → chunk-RTF7PHS2.cjs} +473 -110
- package/dist/chunk-RTF7PHS2.cjs.map +1 -0
- package/dist/{chunk-MGH4VDV3.cjs → chunk-VQSWSYK6.cjs} +10 -3
- package/dist/chunk-VQSWSYK6.cjs.map +1 -0
- package/dist/{chunk-75O3WQKR.cjs → chunk-X2US4RAM.cjs} +30 -8
- package/dist/chunk-X2US4RAM.cjs.map +1 -0
- package/dist/cli/db-runner.cjs +19 -19
- package/dist/cli/db-runner.js +3 -3
- package/dist/cli/index.cjs +364 -27
- package/dist/cli/index.cjs.map +1 -1
- package/dist/cli/index.js +344 -7
- package/dist/cli/index.js.map +1 -1
- package/dist/docs/api-reference/collection.md +155 -0
- package/dist/docs/api-reference/ignite.md +19 -0
- package/dist/docs/api-reference/table.md +3 -0
- package/dist/docs/cli/add.md +36 -7
- package/dist/docs/guides/authentication.md +50 -0
- package/dist/docs/guides/coming-from-mongoose.md +60 -0
- package/dist/docs/guides/database.md +2 -0
- package/dist/docs/guides/relations.md +147 -0
- package/dist/docs/guides/which-api.md +59 -0
- package/dist/docs/index.md +5 -1
- package/dist/docs/skills/SKILL.md +3 -3
- package/dist/docs/skills/api-surface.md +9 -0
- package/dist/docs/skills/what-not-to-invent.md +3 -2
- package/dist/index.cjs +21 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +193 -3
- package/dist/index.d.ts +193 -3
- package/dist/index.js +8 -6
- package/dist/index.js.map +1 -1
- package/dist/registry/index.json +1 -1
- package/dist/tasks/index.d.cts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/{types-B1tJoI4g.d.cts → types-BY-ObnZH.d.cts} +47 -7
- package/dist/{types-B1tJoI4g.d.ts → types-BY-ObnZH.d.ts} +47 -7
- package/package.json +1 -1
- package/dist/chunk-75O3WQKR.cjs.map +0 -1
- package/dist/chunk-B2I7SYQ3.js.map +0 -1
- package/dist/chunk-BUBXO7WU.js.map +0 -1
- package/dist/chunk-FQFKHPLR.cjs.map +0 -1
- package/dist/chunk-MGH4VDV3.cjs.map +0 -1
- package/dist/chunk-OSES7ZQ5.js.map +0 -1
- /package/dist/{chunk-TRC4DUZB.js.map → chunk-RSZB7VAO.js.map} +0 -0
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
|
|
19
19
|
|
|
20
20
|
|
|
21
|
-
var
|
|
21
|
+
var _chunkX2US4RAMcjs = require('./chunk-X2US4RAM.cjs');
|
|
22
22
|
|
|
23
23
|
|
|
24
24
|
|
|
@@ -26,7 +26,7 @@ var _chunk75O3WQKRcjs = require('./chunk-75O3WQKR.cjs');
|
|
|
26
26
|
|
|
27
27
|
|
|
28
28
|
|
|
29
|
-
var
|
|
29
|
+
var _chunkVQSWSYK6cjs = require('./chunk-VQSWSYK6.cjs');
|
|
30
30
|
|
|
31
31
|
|
|
32
32
|
var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
|
|
@@ -35,11 +35,11 @@ var _chunkYL37D6KMcjs = require('./chunk-YL37D6KM.cjs');
|
|
|
35
35
|
var mongoosePromise;
|
|
36
36
|
function loadMongoose() {
|
|
37
37
|
mongoosePromise ??= Promise.resolve().then(() => _interopRequireWildcard(require("mongoose"))).then((mod) => _nullishCoalesce(mod.default, () => ( mod))).then((mg) => {
|
|
38
|
-
|
|
38
|
+
_chunkVQSWSYK6cjs.whenQueryTracking.call(void 0, () => mg.set("debug", _chunkVQSWSYK6cjs.countStatement));
|
|
39
39
|
return mg;
|
|
40
40
|
}).catch((err) => {
|
|
41
41
|
mongoosePromise = void 0;
|
|
42
|
-
throw
|
|
42
|
+
throw _chunkVQSWSYK6cjs.notInstalled.call(void 0, err, "mongoose", "npm install mongoose");
|
|
43
43
|
});
|
|
44
44
|
return mongoosePromise;
|
|
45
45
|
}
|
|
@@ -55,6 +55,29 @@ function ctor(type, mg) {
|
|
|
55
55
|
return Date;
|
|
56
56
|
case "objectId":
|
|
57
57
|
return mg.Schema.Types.ObjectId;
|
|
58
|
+
// defineCollection only:
|
|
59
|
+
case "decimal128":
|
|
60
|
+
return mg.Schema.Types.Decimal128;
|
|
61
|
+
case "long":
|
|
62
|
+
return BigInt;
|
|
63
|
+
// stored as a BSON Long (int64)
|
|
64
|
+
case "binary":
|
|
65
|
+
return Buffer;
|
|
66
|
+
case "geoPoint":
|
|
67
|
+
return new mg.Schema(
|
|
68
|
+
{
|
|
69
|
+
type: { type: String, enum: ["Point"], required: true },
|
|
70
|
+
coordinates: {
|
|
71
|
+
type: [Number],
|
|
72
|
+
required: true,
|
|
73
|
+
validate: {
|
|
74
|
+
validator: (c) => c.length === 2 && Math.abs(c[0]) <= 180 && Math.abs(c[1]) <= 90,
|
|
75
|
+
message: "must be [longitude, latitude]"
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
{ _id: false }
|
|
80
|
+
);
|
|
58
81
|
}
|
|
59
82
|
return mg.Schema.Types.Mixed;
|
|
60
83
|
}
|
|
@@ -65,7 +88,7 @@ function rules(node, mg) {
|
|
|
65
88
|
if (d.unique !== void 0) entry["unique"] = d.unique;
|
|
66
89
|
if (d.index !== void 0) entry["index"] = d.index;
|
|
67
90
|
if (d.default !== void 0)
|
|
68
|
-
entry["default"] =
|
|
91
|
+
entry["default"] = _chunkX2US4RAMcjs.resolveDefault.call(void 0, d.default, () => new mg.Types.ObjectId());
|
|
69
92
|
if (d.enum !== void 0) entry["enum"] = d.enum;
|
|
70
93
|
if (d.min !== void 0) entry["min"] = d.min;
|
|
71
94
|
if (d.max !== void 0) entry["max"] = d.max;
|
|
@@ -139,7 +162,7 @@ function normalise(value) {
|
|
|
139
162
|
function translateError(model, err) {
|
|
140
163
|
const e = err;
|
|
141
164
|
if (_optionalChain([e, 'optionalAccess', _ => _.name]) === "ValidationError" && e.errors) {
|
|
142
|
-
throw new (0,
|
|
165
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(
|
|
143
166
|
model,
|
|
144
167
|
Object.entries(e.errors).map(([path, v]) => ({
|
|
145
168
|
path,
|
|
@@ -151,13 +174,13 @@ function translateError(model, err) {
|
|
|
151
174
|
);
|
|
152
175
|
}
|
|
153
176
|
if (_optionalChain([e, 'optionalAccess', _2 => _2.name]) === "CastError") {
|
|
154
|
-
throw new (0,
|
|
177
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(model, [
|
|
155
178
|
{ path: _nullishCoalesce(e.path, () => ( "")), message: _nullishCoalesce(e.message, () => ( "invalid value")) }
|
|
156
179
|
]);
|
|
157
180
|
}
|
|
158
181
|
if (_optionalChain([e, 'optionalAccess', _3 => _3.code]) === 11e3) {
|
|
159
182
|
const field = _nullishCoalesce(Object.keys(_nullishCoalesce(e.keyValue, () => ( {})))[0], () => ( "field"));
|
|
160
|
-
throw new (0,
|
|
183
|
+
throw new (0, _chunkX2US4RAMcjs.HttpError)(409, `${model} with this ${field} already exists`);
|
|
161
184
|
}
|
|
162
185
|
throw err;
|
|
163
186
|
}
|
|
@@ -183,14 +206,14 @@ function mapSort(sort) {
|
|
|
183
206
|
}
|
|
184
207
|
function mongoModel(name, tree, options) {
|
|
185
208
|
let compiled;
|
|
186
|
-
const model = () => compiled ??=
|
|
209
|
+
const model = () => compiled ??= _chunkVQSWSYK6cjs.untracked.call(void 0,
|
|
187
210
|
() => loadMongoose().then(async (mg) => {
|
|
188
211
|
if (mg.models[name]) return mg.models[name];
|
|
189
212
|
const schema = new mg.Schema(buildTree(tree, mg), {
|
|
190
213
|
timestamps: _nullishCoalesce(options.timestamps, () => ( true)),
|
|
191
214
|
// autoSync: false hands collection and index creation to migrations, on MongoDB too.
|
|
192
|
-
autoIndex:
|
|
193
|
-
autoCreate:
|
|
215
|
+
autoIndex: _chunkX2US4RAMcjs.isAutoSync.call(void 0, ),
|
|
216
|
+
autoCreate: _chunkX2US4RAMcjs.isAutoSync.call(void 0, ),
|
|
194
217
|
...options.collection !== void 0 && { collection: options.collection }
|
|
195
218
|
});
|
|
196
219
|
for (const idx of _nullishCoalesce(options.indexes, () => ( []))) {
|
|
@@ -199,10 +222,13 @@ function mongoModel(name, tree, options) {
|
|
|
199
222
|
...idx.expireAfterSeconds !== void 0 && {
|
|
200
223
|
expireAfterSeconds: idx.expireAfterSeconds
|
|
201
224
|
},
|
|
202
|
-
...idx.name !== void 0 && { name: idx.name }
|
|
225
|
+
...idx.name !== void 0 && { name: idx.name },
|
|
226
|
+
...idx.partialFilterExpression !== void 0 && {
|
|
227
|
+
partialFilterExpression: idx.partialFilterExpression
|
|
228
|
+
}
|
|
203
229
|
});
|
|
204
230
|
}
|
|
205
|
-
const sequences =
|
|
231
|
+
const sequences = _chunkX2US4RAMcjs.sequenceFields.call(void 0, name, tree);
|
|
206
232
|
if (sequences.length > 0) {
|
|
207
233
|
schema.pre("validate", async function() {
|
|
208
234
|
if (!this.isNew) return;
|
|
@@ -212,7 +238,7 @@ function mongoModel(name, tree, options) {
|
|
|
212
238
|
});
|
|
213
239
|
}
|
|
214
240
|
const M = mg.model(name, schema);
|
|
215
|
-
if (
|
|
241
|
+
if (_chunkX2US4RAMcjs.isAutoSync.call(void 0, )) {
|
|
216
242
|
await M.init().catch((err) => {
|
|
217
243
|
_chunkYL37D6KMcjs.getLogger.call(void 0, ).warn(
|
|
218
244
|
{ model: name, err: err.message },
|
|
@@ -224,7 +250,7 @@ function mongoModel(name, tree, options) {
|
|
|
224
250
|
})
|
|
225
251
|
);
|
|
226
252
|
const session = () => {
|
|
227
|
-
const tx =
|
|
253
|
+
const tx = _chunkX2US4RAMcjs.currentTx.call(void 0, );
|
|
228
254
|
return _optionalChain([tx, 'optionalAccess', _5 => _5.engine]) === "mongodb" ? { session: tx.session } : {};
|
|
229
255
|
};
|
|
230
256
|
const applyQueryOptions = (q2, opts) => {
|
|
@@ -358,7 +384,7 @@ function mongoModel(name, tree, options) {
|
|
|
358
384
|
}),
|
|
359
385
|
raw: () => model(),
|
|
360
386
|
async sync(opts) {
|
|
361
|
-
if (
|
|
387
|
+
if (_chunkX2US4RAMcjs.isSyncSuppressed.call(void 0, )) return [];
|
|
362
388
|
const M = await model();
|
|
363
389
|
const changes = [];
|
|
364
390
|
const exists = (await M.db.db.listCollections({ name: M.collection.collectionName }).toArray()).length > 0;
|
|
@@ -444,16 +470,23 @@ function mongoModel(name, tree, options) {
|
|
|
444
470
|
}
|
|
445
471
|
|
|
446
472
|
// src/db/mongo.ts
|
|
447
|
-
async function connectMongo(url) {
|
|
473
|
+
async function connectMongo(url, pool = {}) {
|
|
448
474
|
const mg = await loadMongoose();
|
|
449
|
-
await mg.connect(url
|
|
475
|
+
await mg.connect(url, {
|
|
476
|
+
...pool.max !== void 0 && { maxPoolSize: pool.max },
|
|
477
|
+
...pool.idleTimeoutMs !== void 0 && { maxIdleTimeMS: pool.idleTimeoutMs },
|
|
478
|
+
...pool.connectionTimeoutMs !== void 0 && {
|
|
479
|
+
serverSelectionTimeoutMS: pool.connectionTimeoutMs,
|
|
480
|
+
waitQueueTimeoutMS: pool.connectionTimeoutMs
|
|
481
|
+
}
|
|
482
|
+
});
|
|
450
483
|
_chunkYL37D6KMcjs.getLogger.call(void 0, ).info("MongoDB connected");
|
|
451
484
|
return mg.connection;
|
|
452
485
|
}
|
|
453
486
|
|
|
454
487
|
// src/db/pg-model.ts
|
|
455
488
|
function pgModel(name, tree, options) {
|
|
456
|
-
const tbl =
|
|
489
|
+
const tbl = _chunkX2US4RAMcjs.pgTable.call(void 0, name, tree, options, { native: false, api: "defineModel" });
|
|
457
490
|
const { columns, ts, refs, ready, compile, client, columnFor, toDb, fromRow, validate, guard } = tbl;
|
|
458
491
|
const kindOf = (field) => _optionalChain([columns, 'access', _15 => _15.get, 'call', _16 => _16(field), 'optionalAccess', _17 => _17.kind]);
|
|
459
492
|
function missingField(sql, cond) {
|
|
@@ -553,7 +586,7 @@ function pgModel(name, tree, options) {
|
|
|
553
586
|
break;
|
|
554
587
|
}
|
|
555
588
|
default:
|
|
556
|
-
throw new (0,
|
|
589
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [
|
|
557
590
|
{ path, message: `operator ${op} is not supported on PostgreSQL` }
|
|
558
591
|
]);
|
|
559
592
|
}
|
|
@@ -584,8 +617,8 @@ function pgModel(name, tree, options) {
|
|
|
584
617
|
for (const path of Array.isArray(paths) ? paths : [paths]) {
|
|
585
618
|
const ref = refs.get(path);
|
|
586
619
|
if (!ref)
|
|
587
|
-
throw new (0,
|
|
588
|
-
const target =
|
|
620
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [{ path, message: "is not a populatable ref field" }]);
|
|
621
|
+
const target = _chunkX2US4RAMcjs.getRegisteredModel.call(void 0, ref.model);
|
|
589
622
|
if (!target) throw new Error(`[EFC] populate: model "${ref.model}" is not defined`);
|
|
590
623
|
const ids = [
|
|
591
624
|
...new Set(
|
|
@@ -628,7 +661,7 @@ function pgModel(name, tree, options) {
|
|
|
628
661
|
return populate(rows, _optionalChain([opts, 'optionalAccess', _22 => _22.populate]));
|
|
629
662
|
}
|
|
630
663
|
const strictUpdate = (update) => {
|
|
631
|
-
const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") ||
|
|
664
|
+
const declared = (path) => columns.has(path.split(".")[0]) && (!path.includes(".") || _chunkX2US4RAMcjs.nodeAt.call(void 0, tree, path.split(".")) !== void 0);
|
|
632
665
|
const out = {};
|
|
633
666
|
for (const [k, v] of Object.entries(update)) {
|
|
634
667
|
if (k.startsWith("$") && v !== null && typeof v === "object") {
|
|
@@ -643,7 +676,7 @@ function pgModel(name, tree, options) {
|
|
|
643
676
|
const ops = update;
|
|
644
677
|
for (const op of Object.keys(update).filter((k) => k.startsWith("$"))) {
|
|
645
678
|
if (!["$set", "$unset", "$inc", "$push", "$pull"].includes(op)) {
|
|
646
|
-
throw new (0,
|
|
679
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [
|
|
647
680
|
{ path: op, message: "update operator is not supported on PostgreSQL" }
|
|
648
681
|
]);
|
|
649
682
|
}
|
|
@@ -656,25 +689,25 @@ function pgModel(name, tree, options) {
|
|
|
656
689
|
for (const [k, v] of Object.entries($set)) if (!k.includes(".")) topLevel[k] = v;
|
|
657
690
|
for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) if (!k.includes(".")) topLevel[k] = null;
|
|
658
691
|
for (const [k, v] of Object.entries($set))
|
|
659
|
-
if (k.includes(".")) await
|
|
692
|
+
if (k.includes(".")) await _chunkX2US4RAMcjs.validateAtPath.call(void 0, tree, k, v, issues);
|
|
660
693
|
for (const k of Object.keys(_nullishCoalesce(ops["$unset"], () => ( {})))) {
|
|
661
|
-
if (k.includes(".")) await
|
|
694
|
+
if (k.includes(".")) await _chunkX2US4RAMcjs.validateAtPath.call(void 0, tree, k, null, issues);
|
|
662
695
|
}
|
|
663
696
|
for (const [k, by] of Object.entries(_nullishCoalesce(ops["$inc"], () => ( {})))) {
|
|
664
697
|
if (typeof by !== "number") issues.push({ path: k, message: "$inc needs a number" });
|
|
665
|
-
const node = k.includes(".") ?
|
|
698
|
+
const node = k.includes(".") ? _chunkX2US4RAMcjs.nodeAt.call(void 0, tree, k.split(".")) : tree[k];
|
|
666
699
|
if (node && !(node.kind === "scalar" && node.type === "number") && node.kind !== "json") {
|
|
667
700
|
issues.push({ path: k, message: "$inc only applies to number fields" });
|
|
668
701
|
}
|
|
669
702
|
}
|
|
670
|
-
if (issues.length) throw new (0,
|
|
703
|
+
if (issues.length) throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, issues);
|
|
671
704
|
await validate(topLevel, true);
|
|
672
705
|
const set = {};
|
|
673
706
|
const nested = /* @__PURE__ */ new Map();
|
|
674
707
|
const touchedTop = /* @__PURE__ */ new Set();
|
|
675
708
|
const acc = (field) => _nullishCoalesce(nested.get(field), () => ( columnFor(t, field)));
|
|
676
709
|
const conflict = (path) => {
|
|
677
|
-
throw new (0,
|
|
710
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(name, [{ path, message: "conflicting update paths" }]);
|
|
678
711
|
};
|
|
679
712
|
const top = (field, value) => {
|
|
680
713
|
if (touchedTop.has(field) || nested.has(field)) conflict(field);
|
|
@@ -845,7 +878,7 @@ function defineModel(name, schema, options) {
|
|
|
845
878
|
return createModel(name, schema, _nullishCoalesce(options, () => ( {})));
|
|
846
879
|
}
|
|
847
880
|
function distinctFields(tree, options) {
|
|
848
|
-
const ts =
|
|
881
|
+
const ts = _chunkX2US4RAMcjs.timestampFields.call(void 0, options);
|
|
849
882
|
const fields = /* @__PURE__ */ new Set(["id", ...Object.values(ts)]);
|
|
850
883
|
for (const [key, node] of Object.entries(tree)) if (node.kind === "scalar") fields.add(key);
|
|
851
884
|
return fields;
|
|
@@ -870,11 +903,11 @@ var MODEL_OPS = [
|
|
|
870
903
|
];
|
|
871
904
|
var sortKey = (v) => v instanceof Date ? v.getTime() : v;
|
|
872
905
|
function createModel(name, schema, options, native) {
|
|
873
|
-
const tree =
|
|
906
|
+
const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "model", name);
|
|
874
907
|
let engineModel;
|
|
875
908
|
const impl = () => {
|
|
876
909
|
if (engineModel) return engineModel;
|
|
877
|
-
const engine =
|
|
910
|
+
const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
|
|
878
911
|
if (native && native.engine !== engine) {
|
|
879
912
|
throw new Error(
|
|
880
913
|
`[EFC] ${name} is a ${ENGINE_LABEL[native.engine]} ${native.kind} (${native.api}) but the app is connected to ${ENGINE_LABEL[engine]} \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
|
|
@@ -916,7 +949,7 @@ function createModel(name, schema, options, native) {
|
|
|
916
949
|
try {
|
|
917
950
|
return await m.create(create);
|
|
918
951
|
} catch (err) {
|
|
919
|
-
if (
|
|
952
|
+
if (_chunkX2US4RAMcjs.isHttpError.call(void 0, err) && err.statusCode === 409 && !_chunkX2US4RAMcjs.currentTx.call(void 0, )) {
|
|
920
953
|
const retried = await m.updateOne(filter, update);
|
|
921
954
|
if (retried) return retried;
|
|
922
955
|
}
|
|
@@ -932,26 +965,26 @@ function createModel(name, schema, options, native) {
|
|
|
932
965
|
sync: (opts) => call((m) => m.sync(opts)),
|
|
933
966
|
drop: () => call((m) => m.drop())
|
|
934
967
|
};
|
|
935
|
-
|
|
936
|
-
|
|
968
|
+
_chunkVQSWSYK6cjs.traceOps.call(void 0, name, model, MODEL_OPS);
|
|
969
|
+
_chunkX2US4RAMcjs.registerModel.call(void 0, {
|
|
937
970
|
name,
|
|
938
971
|
sync: model.sync,
|
|
939
972
|
plan: (opts) => call((m) => m.plan(opts)),
|
|
940
973
|
drop: model.drop,
|
|
941
974
|
findByIds: (ids) => model.find({ id: { $in: ids } }),
|
|
942
|
-
pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => (
|
|
975
|
+
pgTarget: () => ({ table: _nullishCoalesce(options.collection, () => ( _chunkX2US4RAMcjs.tableNameFor.call(void 0, name))), idKind: "uuid" })
|
|
943
976
|
});
|
|
944
977
|
return model;
|
|
945
978
|
}
|
|
946
979
|
|
|
947
980
|
// src/db/transaction.ts
|
|
948
981
|
async function transaction(fn) {
|
|
949
|
-
if (
|
|
950
|
-
if (
|
|
982
|
+
if (_chunkX2US4RAMcjs.currentTx.call(void 0, )) return fn();
|
|
983
|
+
if (_chunkX2US4RAMcjs.getDbEngine.call(void 0, ) === "postgresql") {
|
|
951
984
|
let result;
|
|
952
985
|
const afterCommit = [];
|
|
953
|
-
await
|
|
954
|
-
result = await
|
|
986
|
+
await _chunkVQSWSYK6cjs.getOrm.call(void 0, ).transaction(async (tx) => {
|
|
987
|
+
result = await _chunkX2US4RAMcjs.runInTx.call(void 0, { engine: "postgresql", tx, afterCommit }, fn);
|
|
955
988
|
});
|
|
956
989
|
for (const run of afterCommit) run();
|
|
957
990
|
return result;
|
|
@@ -961,7 +994,7 @@ async function transaction(fn) {
|
|
|
961
994
|
try {
|
|
962
995
|
let result;
|
|
963
996
|
await session.withTransaction(async () => {
|
|
964
|
-
result = await
|
|
997
|
+
result = await _chunkX2US4RAMcjs.runInTx.call(void 0, { engine: "mongodb", session }, fn);
|
|
965
998
|
});
|
|
966
999
|
return result;
|
|
967
1000
|
} finally {
|
|
@@ -1007,8 +1040,8 @@ var TableRuntime = (_class = class {
|
|
|
1007
1040
|
constructor(name, schema, options) {;_class.prototype.__init.call(this);
|
|
1008
1041
|
this.name = name;
|
|
1009
1042
|
this.options = options;
|
|
1010
|
-
const tree =
|
|
1011
|
-
this.tbl =
|
|
1043
|
+
const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "table", name);
|
|
1044
|
+
this.tbl = _chunkX2US4RAMcjs.pgTable.call(void 0, name, tree, options, { native: true, api: "defineTable" });
|
|
1012
1045
|
this.uniqueSets = [["id"]];
|
|
1013
1046
|
for (const spec of this.tbl.columns.values()) {
|
|
1014
1047
|
if (_optionalChain([spec, 'access', _25 => _25.node, 'optionalAccess', _26 => _26.def, 'access', _27 => _27.unique])) this.uniqueSets.push([spec.field]);
|
|
@@ -1035,7 +1068,7 @@ var TableRuntime = (_class = class {
|
|
|
1035
1068
|
/** Many-to-many fields as list columns, so filters and projections treat them alike. */
|
|
1036
1069
|
__init() {this.joinSpecs = /* @__PURE__ */ new Map()}
|
|
1037
1070
|
fail(path, message) {
|
|
1038
|
-
throw new (0,
|
|
1071
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [{ path, message }]);
|
|
1039
1072
|
}
|
|
1040
1073
|
spec(field) {
|
|
1041
1074
|
return _nullishCoalesce(this.tbl.columns.get(field), () => ( this.joinSpecs.get(field)));
|
|
@@ -1046,18 +1079,18 @@ var TableRuntime = (_class = class {
|
|
|
1046
1079
|
/** A many-to-many field's ids, in order, for the row `owner` (a table name or alias). */
|
|
1047
1080
|
joinExpr(sql, join, owner) {
|
|
1048
1081
|
return sql.raw(
|
|
1049
|
-
`coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${
|
|
1082
|
+
`coalesce((select array_agg(efc_j.ref_id order by efc_j.position) from ${_chunkX2US4RAMcjs.q.call(void 0, join.table)} efc_j where efc_j.owner_id = ${owner}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}), '{}'::${join.ddl})`
|
|
1050
1083
|
);
|
|
1051
1084
|
}
|
|
1052
1085
|
col(sql, field, alias) {
|
|
1053
1086
|
const join = this.join(field);
|
|
1054
|
-
if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => (
|
|
1087
|
+
if (join) return this.joinExpr(sql, join, _nullishCoalesce(alias, () => ( _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))));
|
|
1055
1088
|
const spec = this.spec(field);
|
|
1056
|
-
return sql.raw(alias ? `${alias}.${
|
|
1089
|
+
return sql.raw(alias ? `${alias}.${_chunkX2US4RAMcjs.q.call(void 0, spec.column)}` : _chunkX2US4RAMcjs.q.call(void 0, spec.column));
|
|
1057
1090
|
}
|
|
1058
1091
|
/** SELECT items for the many-to-many fields among `fields`, as text arrays. */
|
|
1059
1092
|
joinColumns(sql, fields, owner) {
|
|
1060
|
-
return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(
|
|
1093
|
+
return fields.filter((f) => this.join(f)).map((f) => sql`${this.col(sql, f, owner)}::text[] as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, relAlias(f)))}`);
|
|
1061
1094
|
}
|
|
1062
1095
|
/** `col` for SELECT lists: many-to-many fields come back as text arrays under an alias. */
|
|
1063
1096
|
selectCols(sql, fields, owner) {
|
|
@@ -1349,7 +1382,7 @@ var TableRuntime = (_class = class {
|
|
|
1349
1382
|
if (args["cursor"]) {
|
|
1350
1383
|
this.uniqueKey(args["cursor"], "cursor");
|
|
1351
1384
|
const cw = this.where(sql, t, args["cursor"]);
|
|
1352
|
-
const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(
|
|
1385
|
+
const at = (field) => sql`(select ${this.col(sql, field)} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${cw})`;
|
|
1353
1386
|
const ors = [];
|
|
1354
1387
|
const same = (o) => sql`${this.col(sql, o.field)} is not distinct from ${at(o.field)}`;
|
|
1355
1388
|
for (let i = 0; i < order.length; i++) {
|
|
@@ -1362,7 +1395,7 @@ var TableRuntime = (_class = class {
|
|
|
1362
1395
|
ors.push(eqs.length ? sql`(${sql.join([...eqs, after], sql` and `)})` : after);
|
|
1363
1396
|
}
|
|
1364
1397
|
ors.push(sql`(${sql.join(order.map(same), sql` and `)})`);
|
|
1365
|
-
parts.push(sql`exists (select 1 from ${sql.raw(
|
|
1398
|
+
parts.push(sql`exists (select 1 from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${cw})`);
|
|
1366
1399
|
parts.push(sql`(${sql.join(ors, sql` or `)})`);
|
|
1367
1400
|
}
|
|
1368
1401
|
return parts.length ? sql.join(parts, sql` and `) : sql`true`;
|
|
@@ -1387,7 +1420,7 @@ var TableRuntime = (_class = class {
|
|
|
1387
1420
|
const offset = args["skip"] ? sql` offset ${sql.param(args["skip"])}` : sql``;
|
|
1388
1421
|
const orderBy = order.length ? sql` order by ${this.orderSql(sql, order)}` : sql``;
|
|
1389
1422
|
const where = this.readWhere(sql, t, args, order);
|
|
1390
|
-
const from = sql.raw(
|
|
1423
|
+
const from = sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table));
|
|
1391
1424
|
const distinct = _optionalChain([args, 'access', _29 => _29["distinct"], 'optionalAccess', _30 => _30.filter, 'call', _31 => _31((f) => this.spec(f))]);
|
|
1392
1425
|
if (_optionalChain([distinct, 'optionalAccess', _32 => _32.length])) {
|
|
1393
1426
|
const dcols = sql.join(
|
|
@@ -1417,7 +1450,7 @@ var TableRuntime = (_class = class {
|
|
|
1417
1450
|
distinct ? "efc_distinct" : void 0
|
|
1418
1451
|
);
|
|
1419
1452
|
const include = this.includeArg(args);
|
|
1420
|
-
const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" :
|
|
1453
|
+
const included = include ? await this.includeColumns(sql, include, distinct ? "efc_distinct" : _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table), 1) : [];
|
|
1421
1454
|
const { query, reversed } = this.readQuery(
|
|
1422
1455
|
sql,
|
|
1423
1456
|
t,
|
|
@@ -1492,7 +1525,7 @@ var TableRuntime = (_class = class {
|
|
|
1492
1525
|
for (const [name, arg] of Object.entries(include)) {
|
|
1493
1526
|
if (!arg) continue;
|
|
1494
1527
|
const expr = await this.relationExpr(sql, this.relation(name), relArgs(arg), owner, depth);
|
|
1495
|
-
out.push(sql`${expr} as ${sql.raw(
|
|
1528
|
+
out.push(sql`${expr} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, incAlias(name)))}`);
|
|
1496
1529
|
}
|
|
1497
1530
|
return out;
|
|
1498
1531
|
}
|
|
@@ -1526,21 +1559,21 @@ var TableRuntime = (_class = class {
|
|
|
1526
1559
|
*/
|
|
1527
1560
|
relationSource(rel, owner, a, j) {
|
|
1528
1561
|
const T = runtimeOf(rel.target, `${this.name}.${rel.name}`);
|
|
1529
|
-
const target = `${
|
|
1530
|
-
const ownerId = `${owner}.${
|
|
1562
|
+
const target = `${_chunkX2US4RAMcjs.q.call(void 0, T.tbl.table)} ${a}`;
|
|
1563
|
+
const ownerId = `${owner}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`;
|
|
1531
1564
|
if (rel.via === "fk") {
|
|
1532
1565
|
return {
|
|
1533
1566
|
T,
|
|
1534
1567
|
from: target,
|
|
1535
|
-
cond: `${a}.${
|
|
1536
|
-
defaultOrder: `${a}.${
|
|
1568
|
+
cond: `${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${owner}.${_chunkX2US4RAMcjs.q.call(void 0, rel.column)}`,
|
|
1569
|
+
defaultOrder: `${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`
|
|
1537
1570
|
};
|
|
1538
1571
|
}
|
|
1539
1572
|
let from;
|
|
1540
1573
|
let cond;
|
|
1541
1574
|
let defaultOrder;
|
|
1542
1575
|
if (rel.via === "join") {
|
|
1543
|
-
from = `${
|
|
1576
|
+
from = `${_chunkX2US4RAMcjs.q.call(void 0, rel.join.table)} ${j} join ${target} on ${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${j}.ref_id`;
|
|
1544
1577
|
cond = `${j}.owner_id = ${ownerId}`;
|
|
1545
1578
|
defaultOrder = `${j}.position`;
|
|
1546
1579
|
} else {
|
|
@@ -1558,7 +1591,7 @@ var TableRuntime = (_class = class {
|
|
|
1558
1591
|
`[EFC] ${this.name}.${rel.name}: ${rel.target}.${rel.foreignKey} is many-to-many \u2014 use hasMany`
|
|
1559
1592
|
);
|
|
1560
1593
|
}
|
|
1561
|
-
from = `${
|
|
1594
|
+
from = `${_chunkX2US4RAMcjs.q.call(void 0, join.table)} ${j} join ${target} on ${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")} = ${j}.owner_id`;
|
|
1562
1595
|
cond = `${j}.ref_id = ${ownerId}`;
|
|
1563
1596
|
} else {
|
|
1564
1597
|
if (rel.kind === "one" && !column.node.def.unique) {
|
|
@@ -1567,9 +1600,9 @@ var TableRuntime = (_class = class {
|
|
|
1567
1600
|
);
|
|
1568
1601
|
}
|
|
1569
1602
|
from = target;
|
|
1570
|
-
cond = `${a}.${
|
|
1603
|
+
cond = `${a}.${_chunkX2US4RAMcjs.q.call(void 0, column.column)} = ${ownerId}`;
|
|
1571
1604
|
}
|
|
1572
|
-
defaultOrder = `${a}.${
|
|
1605
|
+
defaultOrder = `${a}.${_chunkX2US4RAMcjs.q.call(void 0, "id")}`;
|
|
1573
1606
|
}
|
|
1574
1607
|
return { T, from, cond, defaultOrder };
|
|
1575
1608
|
}
|
|
@@ -1594,7 +1627,7 @@ var TableRuntime = (_class = class {
|
|
|
1594
1627
|
const where = isPlainObject(w) ? w : { id: w };
|
|
1595
1628
|
const found = await T.findUnique({ where, select: { id: true } });
|
|
1596
1629
|
if (!found) {
|
|
1597
|
-
throw new (0,
|
|
1630
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [
|
|
1598
1631
|
{ path, message: `no ${rel.target} matches ${JSON.stringify(where, idJson)}` }
|
|
1599
1632
|
]);
|
|
1600
1633
|
}
|
|
@@ -1686,8 +1719,8 @@ var TableRuntime = (_class = class {
|
|
|
1686
1719
|
try {
|
|
1687
1720
|
await T.updateNested({ where: whereOf(w), data: { [fk]: owner } });
|
|
1688
1721
|
} catch (err) {
|
|
1689
|
-
if (
|
|
1690
|
-
throw new (0,
|
|
1722
|
+
if (_chunkX2US4RAMcjs.isHttpError.call(void 0, err) && err.statusCode === 404) {
|
|
1723
|
+
throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, [
|
|
1691
1724
|
{
|
|
1692
1725
|
path: key,
|
|
1693
1726
|
message: `no ${rel.target} matches ${JSON.stringify(whereOf(w), idJson)}`
|
|
@@ -1708,29 +1741,35 @@ var TableRuntime = (_class = class {
|
|
|
1708
1741
|
};
|
|
1709
1742
|
after.push(async (owner) => {
|
|
1710
1743
|
if (rel.kind === "one") {
|
|
1711
|
-
if (
|
|
1712
|
-
|
|
1744
|
+
if (_optionalChain([ops, 'optionalAccess', _40 => _40["delete"]])) await T.deleteMany({ where: mine(owner) });
|
|
1745
|
+
if (mode === "update" && (_optionalChain([ops, 'optionalAccess', _41 => _41["create"]]) || _optionalChain([ops, 'optionalAccess', _42 => _42["connect"]]) || _optionalChain([ops, 'optionalAccess', _43 => _43["disconnect"]]))) {
|
|
1746
|
+
if (!_optionalChain([T, 'access', _44 => _44.tbl, 'access', _45 => _45.columns, 'access', _46 => _46.get, 'call', _47 => _47(fk), 'optionalAccess', _48 => _48.node, 'optionalAccess', _49 => _49.def, 'access', _50 => _50.required])) await unlink(owner);
|
|
1747
|
+
else if ((await T.findMany({ where: mine(owner), select: { id: true }, take: 1 })).length) {
|
|
1748
|
+
this.fail(
|
|
1749
|
+
key,
|
|
1750
|
+
`${rel.target}.${fk} is required, so the current ${rel.target} can't be unlinked \u2014 add delete: true to replace it`
|
|
1751
|
+
);
|
|
1752
|
+
}
|
|
1713
1753
|
}
|
|
1714
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
1715
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
1716
|
-
if (_optionalChain([ops, 'optionalAccess', _45 => _45["create"]]) !== void 0) await createChild(owner, ops["create"]);
|
|
1754
|
+
if (_optionalChain([ops, 'optionalAccess', _51 => _51["connect"]]) !== void 0) await link(owner, ops["connect"]);
|
|
1755
|
+
if (_optionalChain([ops, 'optionalAccess', _52 => _52["create"]]) !== void 0) await createChild(owner, ops["create"]);
|
|
1717
1756
|
return;
|
|
1718
1757
|
}
|
|
1719
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
1758
|
+
if (_optionalChain([ops, 'optionalAccess', _53 => _53["set"]]) !== void 0) {
|
|
1720
1759
|
const keep = list(ops["set"]).map(whereOf);
|
|
1721
1760
|
await unlink(owner, keep.length ? { NOT: { OR: keep } } : void 0);
|
|
1722
1761
|
for (const w of keep) await link(owner, w);
|
|
1723
1762
|
}
|
|
1724
|
-
for (const w of list(_optionalChain([ops, 'optionalAccess',
|
|
1725
|
-
for (const w of list(_optionalChain([ops, 'optionalAccess',
|
|
1763
|
+
for (const w of list(_optionalChain([ops, 'optionalAccess', _54 => _54["disconnect"]]))) await unlink(owner, whereOf(w));
|
|
1764
|
+
for (const w of list(_optionalChain([ops, 'optionalAccess', _55 => _55["delete"]])))
|
|
1726
1765
|
await T.deleteMany({ where: { AND: [mine(owner), whereOf(w)] } });
|
|
1727
|
-
if (_optionalChain([ops, 'optionalAccess',
|
|
1766
|
+
if (_optionalChain([ops, 'optionalAccess', _56 => _56["deleteMany"]]) !== void 0) {
|
|
1728
1767
|
for (const w of list(ops["deleteMany"])) {
|
|
1729
1768
|
await T.deleteMany({ where: { AND: [mine(owner), ...isPlainObject(w) ? [w] : []] } });
|
|
1730
1769
|
}
|
|
1731
1770
|
}
|
|
1732
|
-
for (const w of list(_optionalChain([ops, 'optionalAccess',
|
|
1733
|
-
for (const c of list(_optionalChain([ops, 'optionalAccess',
|
|
1771
|
+
for (const w of list(_optionalChain([ops, 'optionalAccess', _57 => _57["connect"]]))) await link(owner, w);
|
|
1772
|
+
for (const c of list(_optionalChain([ops, 'optionalAccess', _58 => _58["create"]]))) await createChild(owner, c);
|
|
1734
1773
|
});
|
|
1735
1774
|
}
|
|
1736
1775
|
return { data: out, after };
|
|
@@ -1832,7 +1871,7 @@ var TableRuntime = (_class = class {
|
|
|
1832
1871
|
const a = `efc_f${++aliasSeq}`;
|
|
1833
1872
|
const { T, from, cond } = this.relationSource(
|
|
1834
1873
|
rel,
|
|
1835
|
-
_nullishCoalesce(owner, () => (
|
|
1874
|
+
_nullishCoalesce(owner, () => ( _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))),
|
|
1836
1875
|
a,
|
|
1837
1876
|
`efc_fj${aliasSeq}`
|
|
1838
1877
|
);
|
|
@@ -1874,7 +1913,7 @@ var TableRuntime = (_class = class {
|
|
|
1874
1913
|
const include = this.includeArg(args);
|
|
1875
1914
|
const pairs = [];
|
|
1876
1915
|
for (const f of this.projection(args)) {
|
|
1877
|
-
if (_optionalChain([include, 'optionalAccess',
|
|
1916
|
+
if (_optionalChain([include, 'optionalAccess', _59 => _59[f]])) continue;
|
|
1878
1917
|
pairs.push(sql`${sql.raw(literal(f))}, ${this.jsonValue(sql, f, alias)}`);
|
|
1879
1918
|
}
|
|
1880
1919
|
for (const [name, arg] of Object.entries(_nullishCoalesce(include, () => ( {})))) {
|
|
@@ -1905,7 +1944,7 @@ var TableRuntime = (_class = class {
|
|
|
1905
1944
|
const include = this.includeArg(args);
|
|
1906
1945
|
const keyed = {};
|
|
1907
1946
|
for (const f of this.projection(args)) {
|
|
1908
|
-
if (_optionalChain([include, 'optionalAccess',
|
|
1947
|
+
if (_optionalChain([include, 'optionalAccess', _60 => _60[f]])) continue;
|
|
1909
1948
|
const v = json[f];
|
|
1910
1949
|
const join = this.join(f);
|
|
1911
1950
|
if (v == null || join) {
|
|
@@ -1973,7 +2012,7 @@ var TableRuntime = (_class = class {
|
|
|
1973
2012
|
}
|
|
1974
2013
|
async orThrow(p) {
|
|
1975
2014
|
const r = await p;
|
|
1976
|
-
if (r === null) throw new (0,
|
|
2015
|
+
if (r === null) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
|
|
1977
2016
|
return r;
|
|
1978
2017
|
}
|
|
1979
2018
|
async count(args = {}) {
|
|
@@ -1983,7 +2022,7 @@ var TableRuntime = (_class = class {
|
|
|
1983
2022
|
const counted = select ? Object.entries(select).filter(([f, on]) => on && (f === "_all" || this.spec(f))) : [["_all", true]];
|
|
1984
2023
|
const exprs = sql.join(
|
|
1985
2024
|
counted.map(
|
|
1986
|
-
([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(
|
|
2025
|
+
([f]) => f === "_all" ? sql`count(*)::int as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, "_all"))}` : sql`count(${this.col(sql, f, "efc_rows")})::int as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, f))}`
|
|
1987
2026
|
),
|
|
1988
2027
|
sql`, `
|
|
1989
2028
|
);
|
|
@@ -2058,7 +2097,7 @@ var TableRuntime = (_class = class {
|
|
|
2058
2097
|
const specs = this.aggregateSpec(args);
|
|
2059
2098
|
if (specs.length === 0) return {};
|
|
2060
2099
|
const exprs = sql.join(
|
|
2061
|
-
specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(
|
|
2100
|
+
specs.map((s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, s.alias))}`),
|
|
2062
2101
|
sql`, `
|
|
2063
2102
|
);
|
|
2064
2103
|
const { query } = this.readQuery(sql, t, { ...args, select: void 0 }, sql`*`);
|
|
@@ -2116,7 +2155,7 @@ var TableRuntime = (_class = class {
|
|
|
2116
2155
|
[
|
|
2117
2156
|
...by.map((f) => this.col(sql, f)),
|
|
2118
2157
|
...specs.map(
|
|
2119
|
-
(s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(
|
|
2158
|
+
(s) => sql`${this.aggregateExpr(sql, s.agg, s.field)} as ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, s.alias))}`
|
|
2120
2159
|
)
|
|
2121
2160
|
],
|
|
2122
2161
|
sql`, `
|
|
@@ -2140,7 +2179,7 @@ var TableRuntime = (_class = class {
|
|
|
2140
2179
|
}
|
|
2141
2180
|
}
|
|
2142
2181
|
}
|
|
2143
|
-
const query = sql`select ${select} from ${sql.raw(
|
|
2182
|
+
const query = sql`select ${select} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))}${where ? sql` where ${where}` : sql``} group by ${sql.join(
|
|
2144
2183
|
by.map((f) => this.col(sql, f)),
|
|
2145
2184
|
sql`, `
|
|
2146
2185
|
)}${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``}`;
|
|
@@ -2218,7 +2257,7 @@ var TableRuntime = (_class = class {
|
|
|
2218
2257
|
}
|
|
2219
2258
|
}
|
|
2220
2259
|
}
|
|
2221
|
-
if (issues.length) throw new (0,
|
|
2260
|
+
if (issues.length) throw new (0, _chunkX2US4RAMcjs.ModelValidationError)(this.name, issues);
|
|
2222
2261
|
await this.tbl.validate(plain, true);
|
|
2223
2262
|
for (const [field, v] of Object.entries(plain)) {
|
|
2224
2263
|
sets.push(
|
|
@@ -2260,7 +2299,7 @@ var TableRuntime = (_class = class {
|
|
|
2260
2299
|
}
|
|
2261
2300
|
for (const [field, entries] of byField) {
|
|
2262
2301
|
const join = this.join(field);
|
|
2263
|
-
const jt = sql.raw(
|
|
2302
|
+
const jt = sql.raw(_chunkX2US4RAMcjs.q.call(void 0, join.table));
|
|
2264
2303
|
const sets = entries.filter((e) => e.op.mode === "set");
|
|
2265
2304
|
if (sets.length) {
|
|
2266
2305
|
const owners2 = sets.map((e) => idText(e.id));
|
|
@@ -2307,7 +2346,7 @@ var TableRuntime = (_class = class {
|
|
|
2307
2346
|
const idDdl = this.tbl.columns.get("id").ddl;
|
|
2308
2347
|
const owners = sql`${sql.param(ids.map(idText))}::${sql.raw(idDdl)}[]`;
|
|
2309
2348
|
const parts = joins.map(
|
|
2310
|
-
(j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(
|
|
2349
|
+
(j) => sql`select ${sql.param(j.field)}::text as f, owner_id::text as o, array_agg(ref_id::text order by position) as ids from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, j.table))} where owner_id = any(${owners}) group by owner_id`
|
|
2311
2350
|
);
|
|
2312
2351
|
const { rows } = await this.exec(sql.join(parts, sql` union all `));
|
|
2313
2352
|
for (const j of joins) out.set(j.field, /* @__PURE__ */ new Map());
|
|
@@ -2329,7 +2368,7 @@ var TableRuntime = (_class = class {
|
|
|
2329
2368
|
}
|
|
2330
2369
|
insertSql(sql, t, rows) {
|
|
2331
2370
|
const fields = [...new Set(rows.flatMap((r) => Object.keys(r)))];
|
|
2332
|
-
const head = sql`insert into ${sql.raw(
|
|
2371
|
+
const head = sql`insert into ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} (${sql.join(
|
|
2333
2372
|
fields.map((f) => this.col(sql, f)),
|
|
2334
2373
|
sql`, `
|
|
2335
2374
|
)})`;
|
|
@@ -2408,7 +2447,7 @@ var TableRuntime = (_class = class {
|
|
|
2408
2447
|
const ops = new Map(split.map((x) => [String(x.row["id"]), x.ops]));
|
|
2409
2448
|
for (const record of records) {
|
|
2410
2449
|
for (const join of this.tbl.joins.values()) {
|
|
2411
|
-
const op = _optionalChain([ops, 'access',
|
|
2450
|
+
const op = _optionalChain([ops, 'access', _61 => _61.get, 'call', _62 => _62(String(record["id"])), 'optionalAccess', _63 => _63.find, 'call', _64 => _64((o) => o.field === join.field)]);
|
|
2412
2451
|
record[join.field] = this.joinValues(join, op ? dedupe(op.items).map(idText) : []);
|
|
2413
2452
|
}
|
|
2414
2453
|
}
|
|
@@ -2426,7 +2465,7 @@ var TableRuntime = (_class = class {
|
|
|
2426
2465
|
return;
|
|
2427
2466
|
}
|
|
2428
2467
|
const { rows: ids } = await this.exec(
|
|
2429
|
-
sql`select nextval(pg_get_serial_sequence(${sql.param(
|
|
2468
|
+
sql`select nextval(pg_get_serial_sequence(${sql.param(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))}, 'id'))::text as id from generate_series(1, ${sql.param(missing.length)})`
|
|
2430
2469
|
);
|
|
2431
2470
|
missing.forEach((r, i) => {
|
|
2432
2471
|
const id = ids[i]["id"];
|
|
@@ -2455,9 +2494,9 @@ var TableRuntime = (_class = class {
|
|
|
2455
2494
|
const where = this.where(sql, t, args["where"]);
|
|
2456
2495
|
const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
|
|
2457
2496
|
const extra = links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``;
|
|
2458
|
-
const query = sets.length ? sql`update ${sql.raw(
|
|
2497
|
+
const query = sets.length ? sql`update ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where} returning *${extra}` : sql`select *${extra} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where} limit 1`;
|
|
2459
2498
|
const [row] = (await this.exec(query)).rows;
|
|
2460
|
-
if (!row) throw new (0,
|
|
2499
|
+
if (!row) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
|
|
2461
2500
|
const record = this.fromRaw(t, row);
|
|
2462
2501
|
await this.applyJoins(sql, [{ id: record["id"], ops: joinOps }]);
|
|
2463
2502
|
await this.refreshJoins(sql, [record], joinOps);
|
|
@@ -2478,7 +2517,7 @@ var TableRuntime = (_class = class {
|
|
|
2478
2517
|
const links = returning ? this.joinColumns(sql, [...this.tbl.joins.keys()]) : [];
|
|
2479
2518
|
const list = returning ? sql` returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : joinOps.length ? sql` returning ${this.col(sql, "id")}` : sql``;
|
|
2480
2519
|
const result = await this.exec(
|
|
2481
|
-
sets.length ? sql`update ${sql.raw(
|
|
2520
|
+
sets.length ? sql`update ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} set ${sql.join(sets, sql`, `)} where ${where}${list}` : sql`select ${returning ? sql`*${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}` : this.col(sql, "id")} from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where}`
|
|
2482
2521
|
);
|
|
2483
2522
|
const records = result.rows.map((r) => returning ? this.fromRaw(t, r) : r);
|
|
2484
2523
|
await this.applyJoins(
|
|
@@ -2502,7 +2541,7 @@ var TableRuntime = (_class = class {
|
|
|
2502
2541
|
if (row[f] === void 0) row[f] = this.tbl.toDb(f, args["where"][f]);
|
|
2503
2542
|
}
|
|
2504
2543
|
const { head, values } = this.insertSql(sql, t, [row]);
|
|
2505
|
-
const table =
|
|
2544
|
+
const table = _chunkX2US4RAMcjs.q.call(void 0, this.tbl.table);
|
|
2506
2545
|
const update = await this.setList(sql, t, _nullishCoalesce(args["update"], () => ( {})), table);
|
|
2507
2546
|
const { joinOps } = update;
|
|
2508
2547
|
let { sets } = update;
|
|
@@ -2523,7 +2562,7 @@ var TableRuntime = (_class = class {
|
|
|
2523
2562
|
const [out] = (await this.exec(
|
|
2524
2563
|
sql`${head} values ${values} on conflict (${target}) do update set ${sql.join(sets, sql`, `)}${cond}${returning}`
|
|
2525
2564
|
)).rows;
|
|
2526
|
-
if (!out) throw new (0,
|
|
2565
|
+
if (!out) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
|
|
2527
2566
|
const record = this.fromRaw(t, out);
|
|
2528
2567
|
if (linked) {
|
|
2529
2568
|
const ops = out["efc_inserted"] ? createOps.filter((o) => o.items.length) : joinOps;
|
|
@@ -2542,9 +2581,9 @@ var TableRuntime = (_class = class {
|
|
|
2542
2581
|
const where = this.where(sql, t, args["where"]);
|
|
2543
2582
|
const links = this.joinColumns(sql, [...this.tbl.joins.keys()]);
|
|
2544
2583
|
const [row] = (await this.exec(
|
|
2545
|
-
sql`delete from ${sql.raw(
|
|
2584
|
+
sql`delete from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where} returning *${links.length ? sql`, ${sql.join(links, sql`, `)}` : sql``}`
|
|
2546
2585
|
)).rows;
|
|
2547
|
-
if (!row) throw new (0,
|
|
2586
|
+
if (!row) throw new (0, _chunkX2US4RAMcjs.HttpError)(404, `${this.name} not found`);
|
|
2548
2587
|
return this.project(this.fromRaw(t, row), this.projection(args));
|
|
2549
2588
|
});
|
|
2550
2589
|
}
|
|
@@ -2552,7 +2591,7 @@ var TableRuntime = (_class = class {
|
|
|
2552
2591
|
const { t, sql } = await this.ready(args["where"]);
|
|
2553
2592
|
return this.tbl.guard(async () => {
|
|
2554
2593
|
const where = _nullishCoalesce(this.where(sql, t, args["where"]), () => ( sql`true`));
|
|
2555
|
-
const result = await this.tbl.client().execute(sql`delete from ${sql.raw(
|
|
2594
|
+
const result = await this.tbl.client().execute(sql`delete from ${sql.raw(_chunkX2US4RAMcjs.q.call(void 0, this.tbl.table))} where ${where}`);
|
|
2556
2595
|
return { count: _nullishCoalesce(result.rowCount, () => ( 0)) };
|
|
2557
2596
|
});
|
|
2558
2597
|
}
|
|
@@ -2561,10 +2600,10 @@ function relArgs(arg) {
|
|
|
2561
2600
|
return isPlainObject(arg) ? arg : {};
|
|
2562
2601
|
}
|
|
2563
2602
|
function runtimeOf(name, from) {
|
|
2564
|
-
const runtime = _optionalChain([
|
|
2603
|
+
const runtime = _optionalChain([_chunkX2US4RAMcjs.getRegisteredModel.call(void 0, name), 'optionalAccess', _65 => _65.tableRuntime, 'optionalCall', _66 => _66()]);
|
|
2565
2604
|
if (!runtime) {
|
|
2566
2605
|
throw new Error(
|
|
2567
|
-
|
|
2606
|
+
_chunkX2US4RAMcjs.getRegisteredModel.call(void 0, name) ? `[EFC] ${from}: include needs ${name} to be a defineTable model` : `[EFC] ${from}: "${name}" is not defined \u2014 import that model before including it`
|
|
2568
2607
|
);
|
|
2569
2608
|
}
|
|
2570
2609
|
return runtime;
|
|
@@ -2584,7 +2623,7 @@ var JSON_OPS = /* @__PURE__ */ new Set([
|
|
|
2584
2623
|
"mode"
|
|
2585
2624
|
]);
|
|
2586
2625
|
function createTable(name, schema, options = {}) {
|
|
2587
|
-
|
|
2626
|
+
_chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "table", name);
|
|
2588
2627
|
for (const [rel, def] of Object.entries(_nullishCoalesce(options.relations, () => ( {})))) {
|
|
2589
2628
|
const where = `[EFC] ${name}.relations.${rel}`;
|
|
2590
2629
|
if (rel in schema) throw new Error(`${where}: a field already has this name`);
|
|
@@ -2599,7 +2638,7 @@ function createTable(name, schema, options = {}) {
|
|
|
2599
2638
|
}
|
|
2600
2639
|
let runtime;
|
|
2601
2640
|
const rt = () => {
|
|
2602
|
-
const engine =
|
|
2641
|
+
const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
|
|
2603
2642
|
if (engine !== "postgresql") {
|
|
2604
2643
|
throw new Error(
|
|
2605
2644
|
`[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`
|
|
@@ -2619,24 +2658,24 @@ function createTable(name, schema, options = {}) {
|
|
|
2619
2658
|
aggregate: (args) => call((r) => r.aggregate(args)),
|
|
2620
2659
|
groupBy: (args) => call((r) => r.groupBy(args)),
|
|
2621
2660
|
create: (args) => call((r) => r.withInclude(args, (a) => r.createNested(a))),
|
|
2622
|
-
createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
2623
|
-
createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
2661
|
+
createMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _67 => _67["data"]]), "createMany"), r.createMany(args, false))),
|
|
2662
|
+
createManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _68 => _68["data"]]), "createMany"), r.createMany(args, true))),
|
|
2624
2663
|
update: (args) => call((r) => r.withInclude(args, (a) => r.updateNested(a))),
|
|
2625
|
-
updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
2626
|
-
updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess',
|
|
2664
|
+
updateMany: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _69 => _69["data"]]), "updateMany"), r.updateMany(args, false))),
|
|
2665
|
+
updateManyAndReturn: (args) => call((r) => (r.noNested(_optionalChain([args, 'optionalAccess', _70 => _70["data"]]), "updateMany"), r.updateMany(args, true))),
|
|
2627
2666
|
upsert: (args) => call((r) => r.withInclude(args, (a) => r.upsertNested(a))),
|
|
2628
2667
|
delete: (args) => call((r) => r.deleteWithInclude(args)),
|
|
2629
2668
|
deleteMany: (args) => call((r) => r.deleteMany(args)),
|
|
2630
2669
|
raw: () => call(async (r) => (await r.tbl.compile()).t),
|
|
2631
|
-
sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess',
|
|
2670
|
+
sync: (opts) => call((r) => r.tbl.reconcile(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _71 => _71.dryRun]), () => ( false)))),
|
|
2632
2671
|
drop: () => call((r) => r.tbl.drop())
|
|
2633
2672
|
};
|
|
2634
|
-
|
|
2673
|
+
_chunkVQSWSYK6cjs.traceOps.call(void 0,
|
|
2635
2674
|
name,
|
|
2636
2675
|
model,
|
|
2637
2676
|
Object.keys(model).filter((op) => !["name", "raw", "sync", "drop"].includes(op))
|
|
2638
2677
|
);
|
|
2639
|
-
|
|
2678
|
+
_chunkX2US4RAMcjs.registerModel.call(void 0, {
|
|
2640
2679
|
name,
|
|
2641
2680
|
sync: model.sync,
|
|
2642
2681
|
plan: (opts) => call((r) => r.tbl.plan(opts)),
|
|
@@ -2651,6 +2690,329 @@ function defineTable(name, schema, options) {
|
|
|
2651
2690
|
return createTable(name, schema, _nullishCoalesce(options, () => ( {})));
|
|
2652
2691
|
}
|
|
2653
2692
|
|
|
2693
|
+
// src/db/collection-model.ts
|
|
2694
|
+
function fromBson(value) {
|
|
2695
|
+
if (Array.isArray(value)) return value.map(fromBson);
|
|
2696
|
+
if (value == null || typeof value !== "object") return value;
|
|
2697
|
+
switch (value._bsontype) {
|
|
2698
|
+
case "Decimal128":
|
|
2699
|
+
return String(value);
|
|
2700
|
+
case "Long":
|
|
2701
|
+
return BigInt(String(value));
|
|
2702
|
+
case "Binary":
|
|
2703
|
+
return Buffer.from(value.buffer);
|
|
2704
|
+
case void 0:
|
|
2705
|
+
break;
|
|
2706
|
+
default:
|
|
2707
|
+
return value;
|
|
2708
|
+
}
|
|
2709
|
+
if (Object.getPrototypeOf(value) !== Object.prototype) return value;
|
|
2710
|
+
const out = {};
|
|
2711
|
+
for (const [k, v] of Object.entries(value)) out[k] = fromBson(v);
|
|
2712
|
+
return out;
|
|
2713
|
+
}
|
|
2714
|
+
function castLongs(value, node) {
|
|
2715
|
+
if (value == null) return value;
|
|
2716
|
+
if (node.kind === "scalar") {
|
|
2717
|
+
return node.type === "long" && typeof value === "number" ? BigInt(value) : value;
|
|
2718
|
+
}
|
|
2719
|
+
if (node.kind === "array" && Array.isArray(value))
|
|
2720
|
+
return value.map((v) => castLongs(v, node.item));
|
|
2721
|
+
if (node.kind === "object" && typeof value === "object") {
|
|
2722
|
+
castTree(value, node.fields);
|
|
2723
|
+
}
|
|
2724
|
+
return value;
|
|
2725
|
+
}
|
|
2726
|
+
function castTree(doc, tree) {
|
|
2727
|
+
for (const [key, node] of Object.entries(tree)) {
|
|
2728
|
+
if (key in doc) doc[key] = castLongs(doc[key], node);
|
|
2729
|
+
}
|
|
2730
|
+
return doc;
|
|
2731
|
+
}
|
|
2732
|
+
function hasLong(tree) {
|
|
2733
|
+
const walk = (n) => n.kind === "scalar" ? n.type === "long" : n.kind === "array" ? walk(n.item) : n.kind === "object" ? hasLong(n.fields) : false;
|
|
2734
|
+
return Object.values(tree).some(walk);
|
|
2735
|
+
}
|
|
2736
|
+
function writeResult(r) {
|
|
2737
|
+
return {
|
|
2738
|
+
matchedCount: _nullishCoalesce(r.matchedCount, () => ( 0)),
|
|
2739
|
+
modifiedCount: _nullishCoalesce(r.modifiedCount, () => ( 0)),
|
|
2740
|
+
upsertedCount: _nullishCoalesce(r.upsertedCount, () => ( 0)),
|
|
2741
|
+
upsertedId: r.upsertedId == null ? null : String(r.upsertedId)
|
|
2742
|
+
};
|
|
2743
|
+
}
|
|
2744
|
+
function mapBulkOp(op) {
|
|
2745
|
+
const [kind, body] = _nullishCoalesce(Object.entries(op)[0], () => ( []));
|
|
2746
|
+
if (!kind || body == null || typeof body !== "object") return op;
|
|
2747
|
+
const b = { ...body };
|
|
2748
|
+
if (b["filter"]) b["filter"] = mapFilter(b["filter"]);
|
|
2749
|
+
return { [kind]: b };
|
|
2750
|
+
}
|
|
2751
|
+
function createCollection(name, schema, options) {
|
|
2752
|
+
const tree = _chunkX2US4RAMcjs.normalizeSchema.call(void 0, schema, "collection", name);
|
|
2753
|
+
const base = mongoModel(name, tree, options);
|
|
2754
|
+
const longs = hasLong(tree);
|
|
2755
|
+
const toRecord = (doc) => {
|
|
2756
|
+
if (doc == null) return null;
|
|
2757
|
+
const rec = normalise(fromBson(doc));
|
|
2758
|
+
return longs ? castTree(rec, tree) : rec;
|
|
2759
|
+
};
|
|
2760
|
+
const model = async () => {
|
|
2761
|
+
const engine = _chunkX2US4RAMcjs.getDbEngine.call(void 0, );
|
|
2762
|
+
if (engine !== "mongodb") {
|
|
2763
|
+
throw new Error(
|
|
2764
|
+
`[EFC] ${name} is a MongoDB collection (defineCollection) but the app is connected to PostgreSQL \u2014 check DATABASE_URL / config.database, or use defineModel for a model that runs on both`
|
|
2765
|
+
);
|
|
2766
|
+
}
|
|
2767
|
+
return await base.raw();
|
|
2768
|
+
};
|
|
2769
|
+
const session = () => {
|
|
2770
|
+
const tx = _chunkX2US4RAMcjs.currentTx.call(void 0, );
|
|
2771
|
+
return _optionalChain([tx, 'optionalAccess', _72 => _72.engine]) === "mongodb" ? tx.session : null;
|
|
2772
|
+
};
|
|
2773
|
+
const sess = () => {
|
|
2774
|
+
const s = session();
|
|
2775
|
+
return s ? { session: s } : {};
|
|
2776
|
+
};
|
|
2777
|
+
const guard = async (fn) => {
|
|
2778
|
+
const M = await model();
|
|
2779
|
+
try {
|
|
2780
|
+
return await fn(M);
|
|
2781
|
+
} catch (err) {
|
|
2782
|
+
return translateError(name, err);
|
|
2783
|
+
}
|
|
2784
|
+
};
|
|
2785
|
+
const findOpts = (q2, opts) => {
|
|
2786
|
+
if (_optionalChain([opts, 'optionalAccess', _73 => _73.projection])) q2.select(opts.projection);
|
|
2787
|
+
if (_optionalChain([opts, 'optionalAccess', _74 => _74.sort])) {
|
|
2788
|
+
const meta = Object.values(opts.sort).some((v) => typeof v === "object");
|
|
2789
|
+
q2.sort(meta ? opts.sort : mapSort(opts.sort));
|
|
2790
|
+
}
|
|
2791
|
+
if (_optionalChain([opts, 'optionalAccess', _75 => _75.skip]) !== void 0) q2.skip(opts.skip);
|
|
2792
|
+
if (_optionalChain([opts, 'optionalAccess', _76 => _76.limit]) !== void 0) q2.limit(opts.limit);
|
|
2793
|
+
if (_optionalChain([opts, 'optionalAccess', _77 => _77.populate])) q2.populate(opts.populate);
|
|
2794
|
+
const collation = _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _78 => _78.collation]), () => ( options.collation));
|
|
2795
|
+
if (collation) q2.collation(collation);
|
|
2796
|
+
q2.session(session());
|
|
2797
|
+
return q2;
|
|
2798
|
+
};
|
|
2799
|
+
const isBadId = (err) => {
|
|
2800
|
+
const e = err;
|
|
2801
|
+
return _optionalChain([e, 'optionalAccess', _79 => _79.name]) === "CastError" && e.path === "_id";
|
|
2802
|
+
};
|
|
2803
|
+
const model$ = {
|
|
2804
|
+
name,
|
|
2805
|
+
find: (filter, opts) => guard(async (M) => {
|
|
2806
|
+
const docs = await findOpts(M.find(mapFilter(filter)), opts).lean();
|
|
2807
|
+
return docs.map(toRecord);
|
|
2808
|
+
}),
|
|
2809
|
+
findOne: (filter, opts) => guard(async (M) => toRecord(await findOpts(M.findOne(mapFilter(filter)), opts).lean())),
|
|
2810
|
+
findById: (id, opts) => guard(async (M) => {
|
|
2811
|
+
try {
|
|
2812
|
+
return toRecord(await findOpts(M.findById(id), opts).lean());
|
|
2813
|
+
} catch (err) {
|
|
2814
|
+
if (isBadId(err)) return null;
|
|
2815
|
+
throw err;
|
|
2816
|
+
}
|
|
2817
|
+
}),
|
|
2818
|
+
exists: (filter) => guard(async (M) => await M.exists(mapFilter(filter)).session(session()) !== null),
|
|
2819
|
+
countDocuments: (filter) => guard((M) => M.countDocuments(mapFilter(filter)).session(session()).exec()),
|
|
2820
|
+
estimatedDocumentCount: () => guard((M) => M.estimatedDocumentCount().exec()),
|
|
2821
|
+
distinct: (field, filter) => guard(async (M) => {
|
|
2822
|
+
const values = await M.distinct(field === "id" ? "_id" : field, mapFilter(filter)).session(
|
|
2823
|
+
session()
|
|
2824
|
+
);
|
|
2825
|
+
return values.map(
|
|
2826
|
+
(v) => v != null && v._bsontype === "ObjectId" ? String(v) : fromBson(v)
|
|
2827
|
+
);
|
|
2828
|
+
}),
|
|
2829
|
+
create: (data) => guard(async (M) => {
|
|
2830
|
+
const [doc] = await M.create([data], sess());
|
|
2831
|
+
return toRecord(doc.toObject({ flattenMaps: true }));
|
|
2832
|
+
}),
|
|
2833
|
+
insertMany: (data) => guard(async (M) => {
|
|
2834
|
+
if (data.length === 0) return [];
|
|
2835
|
+
const docs = await M.create(data, { ...sess(), ordered: true });
|
|
2836
|
+
return docs.map((d) => toRecord(d.toObject({ flattenMaps: true })));
|
|
2837
|
+
}),
|
|
2838
|
+
updateOne: (filter, update, opts) => guard(
|
|
2839
|
+
async (M) => writeResult(
|
|
2840
|
+
await M.updateOne(mapFilter(filter), update, {
|
|
2841
|
+
runValidators: true,
|
|
2842
|
+
upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _80 => _80.upsert]), () => ( false)),
|
|
2843
|
+
...sess()
|
|
2844
|
+
})
|
|
2845
|
+
)
|
|
2846
|
+
),
|
|
2847
|
+
updateMany: (filter, update, opts) => guard(
|
|
2848
|
+
async (M) => writeResult(
|
|
2849
|
+
await M.updateMany(mapFilter(filter), update, {
|
|
2850
|
+
runValidators: true,
|
|
2851
|
+
upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _81 => _81.upsert]), () => ( false)),
|
|
2852
|
+
...sess()
|
|
2853
|
+
})
|
|
2854
|
+
)
|
|
2855
|
+
),
|
|
2856
|
+
replaceOne: (filter, replacement, opts) => guard(
|
|
2857
|
+
async (M) => writeResult(
|
|
2858
|
+
await M.replaceOne(mapFilter(filter), replacement, {
|
|
2859
|
+
runValidators: true,
|
|
2860
|
+
upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _82 => _82.upsert]), () => ( false)),
|
|
2861
|
+
...sess()
|
|
2862
|
+
})
|
|
2863
|
+
)
|
|
2864
|
+
),
|
|
2865
|
+
findOneAndUpdate: (filter, update, opts) => guard(
|
|
2866
|
+
async (M) => toRecord(
|
|
2867
|
+
await M.findOneAndUpdate(mapFilter(filter), update, {
|
|
2868
|
+
runValidators: true,
|
|
2869
|
+
upsert: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _83 => _83.upsert]), () => ( false)),
|
|
2870
|
+
returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _84 => _84.returnDocument]), () => ( "before")),
|
|
2871
|
+
..._optionalChain([opts, 'optionalAccess', _85 => _85.projection]) && { projection: opts.projection },
|
|
2872
|
+
..._optionalChain([opts, 'optionalAccess', _86 => _86.sort]) && { sort: opts.sort },
|
|
2873
|
+
...sess()
|
|
2874
|
+
}).lean()
|
|
2875
|
+
)
|
|
2876
|
+
),
|
|
2877
|
+
findByIdAndUpdate: (id, update, opts) => guard(async (M) => {
|
|
2878
|
+
try {
|
|
2879
|
+
return toRecord(
|
|
2880
|
+
await M.findByIdAndUpdate(id, update, {
|
|
2881
|
+
runValidators: true,
|
|
2882
|
+
returnDocument: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _87 => _87.returnDocument]), () => ( "before")),
|
|
2883
|
+
...sess()
|
|
2884
|
+
}).lean()
|
|
2885
|
+
);
|
|
2886
|
+
} catch (err) {
|
|
2887
|
+
if (isBadId(err)) return null;
|
|
2888
|
+
throw err;
|
|
2889
|
+
}
|
|
2890
|
+
}),
|
|
2891
|
+
findOneAndDelete: (filter, opts) => guard(
|
|
2892
|
+
async (M) => toRecord(
|
|
2893
|
+
await M.findOneAndDelete(mapFilter(filter), {
|
|
2894
|
+
..._optionalChain([opts, 'optionalAccess', _88 => _88.sort]) && { sort: opts.sort },
|
|
2895
|
+
...sess()
|
|
2896
|
+
}).lean()
|
|
2897
|
+
)
|
|
2898
|
+
),
|
|
2899
|
+
findByIdAndDelete: (id) => guard(async (M) => {
|
|
2900
|
+
try {
|
|
2901
|
+
return toRecord(await M.findByIdAndDelete(id, sess()).lean());
|
|
2902
|
+
} catch (err) {
|
|
2903
|
+
if (isBadId(err)) return null;
|
|
2904
|
+
throw err;
|
|
2905
|
+
}
|
|
2906
|
+
}),
|
|
2907
|
+
deleteOne: (filter) => guard(async (M) => ({
|
|
2908
|
+
deletedCount: (await M.deleteOne(mapFilter(filter), sess())).deletedCount
|
|
2909
|
+
})),
|
|
2910
|
+
deleteMany: (filter) => guard(async (M) => ({
|
|
2911
|
+
deletedCount: (await M.deleteMany(mapFilter(filter), sess())).deletedCount
|
|
2912
|
+
})),
|
|
2913
|
+
aggregate: (pipeline) => guard(async (M) => {
|
|
2914
|
+
const agg = M.aggregate(pipeline);
|
|
2915
|
+
const s = session();
|
|
2916
|
+
if (s) agg.session(s);
|
|
2917
|
+
if (options.collation)
|
|
2918
|
+
agg.collation(options.collation);
|
|
2919
|
+
return (await agg).map(toRecord);
|
|
2920
|
+
}),
|
|
2921
|
+
bulkWrite: (ops, opts) => guard(async (M) => {
|
|
2922
|
+
if (ops.length === 0) {
|
|
2923
|
+
return {
|
|
2924
|
+
insertedCount: 0,
|
|
2925
|
+
matchedCount: 0,
|
|
2926
|
+
modifiedCount: 0,
|
|
2927
|
+
deletedCount: 0,
|
|
2928
|
+
upsertedCount: 0
|
|
2929
|
+
};
|
|
2930
|
+
}
|
|
2931
|
+
const r = await M.bulkWrite(
|
|
2932
|
+
ops.map(mapBulkOp),
|
|
2933
|
+
{
|
|
2934
|
+
ordered: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _89 => _89.ordered]), () => ( true)),
|
|
2935
|
+
runValidators: true,
|
|
2936
|
+
...sess()
|
|
2937
|
+
}
|
|
2938
|
+
);
|
|
2939
|
+
return {
|
|
2940
|
+
insertedCount: r.insertedCount,
|
|
2941
|
+
matchedCount: r.matchedCount,
|
|
2942
|
+
modifiedCount: r.modifiedCount,
|
|
2943
|
+
deletedCount: r.deletedCount,
|
|
2944
|
+
upsertedCount: r.upsertedCount
|
|
2945
|
+
};
|
|
2946
|
+
}),
|
|
2947
|
+
watch: (pipeline = [], opts) => {
|
|
2948
|
+
let stream;
|
|
2949
|
+
let closed = false;
|
|
2950
|
+
const open = async () => {
|
|
2951
|
+
const M = await model();
|
|
2952
|
+
stream ??= M.watch(pipeline, {
|
|
2953
|
+
..._optionalChain([opts, 'optionalAccess', _90 => _90.fullDocument]) && { fullDocument: opts.fullDocument }
|
|
2954
|
+
});
|
|
2955
|
+
return stream;
|
|
2956
|
+
};
|
|
2957
|
+
const close = async () => {
|
|
2958
|
+
closed = true;
|
|
2959
|
+
await _optionalChain([stream, 'optionalAccess', _91 => _91.close, 'call', _92 => _92()]);
|
|
2960
|
+
};
|
|
2961
|
+
return {
|
|
2962
|
+
close,
|
|
2963
|
+
async *[Symbol.asyncIterator]() {
|
|
2964
|
+
const s = await open();
|
|
2965
|
+
try {
|
|
2966
|
+
while (!closed) {
|
|
2967
|
+
const change = await s.next().catch((err) => {
|
|
2968
|
+
if (closed) return null;
|
|
2969
|
+
throw err;
|
|
2970
|
+
});
|
|
2971
|
+
if (!change) return;
|
|
2972
|
+
const key = change["documentKey"];
|
|
2973
|
+
yield {
|
|
2974
|
+
operationType: String(change["operationType"]),
|
|
2975
|
+
id: _optionalChain([key, 'optionalAccess', _93 => _93._id]) == null ? void 0 : String(key._id),
|
|
2976
|
+
...change["fullDocument"] != null && {
|
|
2977
|
+
fullDocument: toRecord(change["fullDocument"])
|
|
2978
|
+
},
|
|
2979
|
+
...change["updateDescription"] != null && {
|
|
2980
|
+
updateDescription: fromBson(change["updateDescription"])
|
|
2981
|
+
},
|
|
2982
|
+
raw: change
|
|
2983
|
+
};
|
|
2984
|
+
}
|
|
2985
|
+
} finally {
|
|
2986
|
+
await close();
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
};
|
|
2990
|
+
},
|
|
2991
|
+
raw: () => model(),
|
|
2992
|
+
sync: (opts) => model().then(() => base.sync(opts)),
|
|
2993
|
+
drop: () => model().then(() => base.drop())
|
|
2994
|
+
};
|
|
2995
|
+
_chunkVQSWSYK6cjs.traceOps.call(void 0,
|
|
2996
|
+
name,
|
|
2997
|
+
model$,
|
|
2998
|
+
Object.keys(model$).filter((op) => !["name", "raw", "sync", "drop", "watch"].includes(op))
|
|
2999
|
+
);
|
|
3000
|
+
_chunkX2US4RAMcjs.registerModel.call(void 0, {
|
|
3001
|
+
name,
|
|
3002
|
+
sync: model$.sync,
|
|
3003
|
+
plan: (opts) => model().then(() => base.plan(opts)),
|
|
3004
|
+
drop: model$.drop,
|
|
3005
|
+
findByIds: (ids) => model$.find({ _id: { $in: ids } }),
|
|
3006
|
+
pgTarget: () => {
|
|
3007
|
+
throw new Error(`[EFC] ${name} is a MongoDB collection (defineCollection)`);
|
|
3008
|
+
}
|
|
3009
|
+
});
|
|
3010
|
+
return model$;
|
|
3011
|
+
}
|
|
3012
|
+
function defineCollection(name, schema, options) {
|
|
3013
|
+
return createCollection(name, schema, _nullishCoalesce(options, () => ( {})));
|
|
3014
|
+
}
|
|
3015
|
+
|
|
2654
3016
|
// src/db/index.ts
|
|
2655
3017
|
var _client = null;
|
|
2656
3018
|
function setDbClient(client) {
|
|
@@ -2682,5 +3044,6 @@ var db = new Proxy({}, {
|
|
|
2682
3044
|
|
|
2683
3045
|
|
|
2684
3046
|
|
|
2685
|
-
|
|
2686
|
-
|
|
3047
|
+
|
|
3048
|
+
exports.connectMongo = connectMongo; exports.defineModel = defineModel; exports.transaction = transaction; exports.defineTable = defineTable; exports.defineCollection = defineCollection; exports.setDbClient = setDbClient; exports.getDbClient = getDbClient; exports.db = db;
|
|
3049
|
+
//# sourceMappingURL=chunk-RTF7PHS2.cjs.map
|