@cloudcome/utils-uni 1.30.4 → 1.31.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/dist/database.cjs CHANGED
@@ -1,636 +1,665 @@
1
- "use strict";
2
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const type = require("@cloudcome/utils-core/type");
4
- const _helpers = require("./_helpers.cjs");
5
- const error = require("./error.cjs");
6
- const object = require("@cloudcome/utils-core/object");
7
- const _try = require("@cloudcome/utils-core/try");
8
- class DbBaseCommand {
9
- constructor(_command, _parameter, _options) {
10
- this._command = _command;
11
- this._parameter = _parameter;
12
- this._options = _options;
13
- }
14
- _isQuery = false;
15
- _isMutate = false;
16
- static getValue(cmd, db) {
17
- if (cmd._options?.rewriteValue) {
18
- return cmd._options.rewriteValue(db, cmd._parameter);
19
- }
20
- return db.command[cmd._command].call(
21
- db.command,
22
- cmd._options?.formatParameter?.(db) || cmd._parameter
23
- );
24
- }
25
- static getExpression(cmd, fieldName) {
26
- return {
27
- [`$${cmd._command}`]: [fieldName, cmd._parameter]
28
- };
29
- }
30
- static isQueryCommand(cmd) {
31
- return cmd._isQuery;
32
- }
33
- static isMutateCommand(cmd) {
34
- return cmd._isMutate;
35
- }
36
- }
37
- class DbQueryCommand extends DbBaseCommand {
38
- _isQuery = true;
39
- }
40
- class DbMutateCommand extends DbBaseCommand {
41
- _isMutate = true;
42
- }
43
- const dbQuery = {
44
- /**
45
- * 等于操作符
46
- * @param value 比较值
47
- * @returns DbQueryCommand 查询命令对象
48
- */
49
- eq: (value) => new DbQueryCommand("eq", value),
50
- /**
51
- * 不等于操作符
52
- * @param value 比较值
53
- * @returns DbQueryCommand 查询命令对象
54
- */
55
- neq: (value) => new DbQueryCommand("neq", value),
56
- /**
57
- * 大于操作符
58
- * @param value 比较值
59
- * @returns DbQueryCommand 查询命令对象
60
- */
61
- gt: (value) => new DbQueryCommand("gt", value),
62
- /**
63
- * 大于等于操作符
64
- * @param value 比较值
65
- * @returns DbQueryCommand 查询命令对象
66
- */
67
- gte: (value) => new DbQueryCommand("gte", value),
68
- /**
69
- * 小于操作符
70
- * @param value 比较值
71
- * @returns DbQueryCommand 查询命令对象
72
- */
73
- lt: (value) => new DbQueryCommand("lt", value),
74
- /**
75
- * 小于等于操作符
76
- * @param value 比较值
77
- * @returns DbQueryCommand 查询命令对象
78
- */
79
- lte: (value) => new DbQueryCommand("lte", value),
80
- /**
81
- * 包含在数组中操作符
82
- * @param value 值数组
83
- * @returns DbQueryCommand 查询命令对象
84
- */
85
- in: (value) => new DbQueryCommand("in", value),
86
- /**
87
- * 不包含在数组中操作符
88
- * @param value 值数组
89
- * @returns DbQueryCommand 查询命令对象
90
- */
91
- nin: (value) => new DbQueryCommand("nin", value),
92
- /**
93
- * 数组长度匹配操作符
94
- * @param size 数组长度
95
- * @returns DbQueryCommand 查询命令对象
96
- */
97
- size: (size) => new DbQueryCommand("size", size),
98
- /**
99
- * 正则表达式匹配操作符
100
- * @param regExp 正则表达式
101
- * @returns DbQueryCommand 查询命令对象
102
- */
103
- regExp: (regExp) => new DbQueryCommand("regExp", regExp, {
104
- rewriteValue: (db, parameter) => parameter
105
- }),
106
- /**
107
- * 逻辑与操作符
108
- * @param conditions 查询条件参数
109
- * @returns DbQueryCommand 查询命令对象
110
- */
111
- and: (conditions) => new DbQueryCommand("and", conditions, {
112
- formatParameter: (db) => conditions.map((c) => DbBaseCommand.getValue(c, db))
113
- }),
114
- /**
115
- * 逻辑或操作符
116
- * @param conditions 查询条件参数
117
- * @returns DbQueryCommand 查询命令对象
118
- */
119
- or: (conditions) => new DbQueryCommand("or", conditions, {
120
- formatParameter: (db) => conditions.map((c) => DbBaseCommand.getValue(c, db))
121
- })
2
+ const require__helpers = require("./_helpers.cjs");
3
+ const require_cloud = require("./cloud.cjs");
4
+ let _cloudcome_utils_core_type = require("@cloudcome/utils-core/type");
5
+ let _cloudcome_utils_core_object = require("@cloudcome/utils-core/object");
6
+ let _cloudcome_utils_core_try = require("@cloudcome/utils-core/try");
7
+ //#region src/database/_command.class.ts
8
+ var DbBaseCommand = class {
9
+ _isQuery = false;
10
+ _isMutate = false;
11
+ constructor(_command, _parameter, _options) {
12
+ this._command = _command;
13
+ this._parameter = _parameter;
14
+ this._options = _options;
15
+ }
16
+ static getValue(cmd, db) {
17
+ if (cmd._options?.rewriteValue) return cmd._options.rewriteValue(db, cmd._parameter);
18
+ return db.command[cmd._command].call(db.command, cmd._options?.formatParameter?.(db) || cmd._parameter);
19
+ }
20
+ static getExpression(cmd, fieldName) {
21
+ return { [`$${cmd._command}`]: [fieldName, cmd._parameter] };
22
+ }
23
+ static isQueryCommand(cmd) {
24
+ return cmd._isQuery;
25
+ }
26
+ static isMutateCommand(cmd) {
27
+ return cmd._isMutate;
28
+ }
29
+ };
30
+ var DbQueryCommand = class extends DbBaseCommand {
31
+ _isQuery = true;
122
32
  };
123
- const dbMutate = {
124
- /**
125
- * 数值增加操作符
126
- * @param value 增加的数值
127
- * @returns DbMutateCommand 变更命令对象
128
- */
129
- inc: (value) => new DbMutateCommand("inc", value),
130
- /**
131
- * 数值乘法操作符
132
- * @param value 乘数
133
- * @returns DbMutateCommand 变更命令对象
134
- */
135
- mul: (value) => new DbMutateCommand("mul", value),
136
- /**
137
- * 设置字段值操作符
138
- * @param value 设置的值
139
- * @returns DbMutateCommand 变更命令对象
140
- */
141
- set: (value) => new DbMutateCommand("set", value),
142
- /**
143
- * 向数组末尾添加元素操作符
144
- * @param value 添加的值
145
- * @returns DbMutateCommand 变更命令对象
146
- */
147
- push: (value) => new DbMutateCommand("push", value),
148
- /**
149
- * 向数组开头添加元素操作符
150
- * @param value 添加的值
151
- * @returns DbMutateCommand 变更命令对象
152
- */
153
- unshift: (value) => new DbMutateCommand("unshift", value),
154
- /**
155
- * 从数组末尾移除元素操作符
156
- * @returns DbMutateCommand 变更命令对象
157
- */
158
- pop: () => new DbMutateCommand("pop", void 0),
159
- /**
160
- * 从数组开头移除元素操作符
161
- * @returns DbMutateCommand 变更命令对象
162
- */
163
- shift: () => new DbMutateCommand("shift", void 0),
164
- /**
165
- * 移除字段操作符
166
- * @returns DbMutateCommand 变更命令对象
167
- */
168
- remove: () => new DbMutateCommand("remove", void 0)
33
+ var DbMutateCommand = class extends DbBaseCommand {
34
+ _isMutate = true;
169
35
  };
170
- const dbAgg = uniCloud.database().command.aggregate;
171
- const db0 = uniCloud.database();
172
- let gid = 0;
173
- class Db {
174
- _host;
175
- /**
176
- * 是否为事务环境
177
- * - 查询条件只能是 id
178
- * - 不能聚合操作
179
- */
180
- _isTransaction = false;
181
- _options;
182
- /**
183
- * 构造函数,初始化数据库集合引用
184
- * @param collection 数据表名称
185
- * @param _mockDatabase 模拟数据库,用于单元测试
186
- */
187
- constructor(options) {
188
- this._options = options;
189
- this._host = options._mockDatabase || options.transaction?.collection(options.table) || db0.collection(options.table);
190
- this._isTransaction = !!options.transaction;
191
- }
192
- /**
193
- * 创建一个新的数据库实例,可选是否移除事务
194
- * @param withoutTransaction 是否移除事务,默认 false
195
- * @returns 新的数据库实例
196
- */
197
- clone(withoutTransaction) {
198
- return new Db({ ...this._options, transaction: withoutTransaction ? null : this._options.transaction });
199
- }
200
- get table() {
201
- return this._options.table;
202
- }
203
- get options() {
204
- return this._options;
205
- }
206
- get isTransaction() {
207
- return this._isTransaction;
208
- }
209
- /**
210
- * 获取聚合操作实例
211
- * @returns 聚合操作实例
212
- */
213
- aggregate() {
214
- return this._host.aggregate();
215
- }
216
- _hasWhere = void 0;
217
- _hasWhereId = void 0;
218
- _where = {};
219
- _doWhere(where, from) {
220
- if (this._hasWhere) throw new Error(`已调用过一次 db.${_toWhereMethod(this._hasWhere)} 了`);
221
- const realWhere = object.objectFilter(where, (value) => value !== void 0);
222
- const whereKeys = Object.keys(realWhere);
223
- const isWhereId = whereKeys.length === 1 && "_id" in realWhere && (type.isString(realWhere._id) || type.isNumber(realWhere._id));
224
- if (isWhereId && this._hasLimit) {
225
- throw new Error(`db.${_toWhereIdMethod(from)} 方法不能与 db.limit() 方法同时调用`);
226
- }
227
- this._hasWhere = from;
228
- this._where = realWhere;
229
- if (isWhereId) this._hasWhereId = from;
230
- return this;
231
- }
232
- /**
233
- * 设置查询条件
234
- * @param where 查询条件对象
235
- * @returns 当前Db实例,支持链式调用
236
- */
237
- where(where) {
238
- return this._doWhere(where, "where");
239
- }
240
- /**
241
- * 获取当前查询条件
242
- * @param plain 是否返回原始查询条件对象,默认 false
243
- * @returns 当前查询条件对象
244
- */
245
- getWhere(plain) {
246
- return plain ? object.objectOmit(this._where, Object.keys(this._lookupAs)) : this._where;
247
- }
248
- /**
249
- * 根据ID设置查询条件
250
- * @param id 记录ID
251
- * @returns 当前Db实例,支持链式调用
252
- */
253
- whereId(id) {
254
- return this._doWhere({ _id: id }, "whereId");
255
- }
256
- _hasSelect = 0;
257
- _select = {};
258
- /**
259
- * 指定要返回的字段
260
- * @param fields 要返回的字段对象,true表示返回,false表示不返回
261
- * @returns 当前Db实例,支持链式调用
262
- */
263
- select(fields) {
264
- if (this._hasSelect) throw new Error("db.select() 方法只能调用一次");
265
- this._hasSelect++;
266
- this._select = fields;
267
- return this;
268
- }
269
- _hasOrder = 0;
270
- _order = {};
271
- /**
272
- * 设置排序规则
273
- * @param order 排序规则对象,key为字段名,value为"asc"或"desc"
274
- * @returns 当前Db实例,支持链式调用
275
- */
276
- order(order) {
277
- this._hasOrder++;
278
- this._order = order;
279
- return this;
280
- }
281
- _hasSkip = 0;
282
- _skip = 0;
283
- /**
284
- * 跳过指定数量的记录
285
- * @param skip 要跳过的记录数
286
- * @returns 当前Db实例,支持链式调用
287
- */
288
- skip(skip) {
289
- if (this._hasSkip) throw new Error("db.skip() 方法只能调用一次");
290
- this._hasSkip++;
291
- this._skip = skip;
292
- return this;
293
- }
294
- _hasLimit = 0;
295
- _limit = 0;
296
- /**
297
- * 限制返回的记录数量
298
- * @param limit 最大返回记录数
299
- * @returns 当前Db实例,支持链式调用
300
- */
301
- limit(limit) {
302
- if (this._hasLimit) throw new Error("db.limit() 方法只能调用一次");
303
- if (this._hasWhereId) {
304
- throw new Error(`db.limit() 方法不能与 ${_toWhereIdMethod(this._hasWhereId)} 方法同时调用`);
305
- }
306
- this._hasLimit++;
307
- this._limit = limit;
308
- return this;
309
- }
310
- _hasLookup = 0;
311
- get hasLookup() {
312
- return this._hasLookup > 0;
313
- }
314
- _lookups = [];
315
- lookup(table, lookup) {
316
- table._hasLookup++;
317
- this._hasLookup++;
318
- this._lookups.push({
319
- ...lookup,
320
- table
321
- });
322
- return this;
323
- }
324
- _aggregated = false;
325
- _lookupAs = {};
326
- _endAggregate(aggRef) {
327
- if (this._aggregated) throw new Error(`相同的数据表实例(${this.table})不能重复使用`);
328
- this._aggregated = true;
329
- let returnAggRef = aggRef;
330
- const aggSelect = {};
331
- let hasAggUnselect = 0;
332
- const aggUnselect = {};
333
- for (const { relation: type2, as, foreignField, localField, table, unselect } of this._lookups) {
334
- const letName = `let${gid++}`;
335
- let pipeline = dbAgg.pipeline();
336
- pipeline = pipeline.match({
337
- $expr: {
338
- $and: [
339
- type2 === "n:1" ? { $in: [`$${foreignField}`, `$$${letName}`] } : { $eq: [`$${foreignField}`, `$$${letName}`] }
340
- ]
341
- }
342
- });
343
- pipeline = table._endAggregate(pipeline);
344
- pipeline = pipeline.done();
345
- returnAggRef = returnAggRef.lookup({
346
- let: {
347
- [letName]: `$${localField}`
348
- },
349
- as,
350
- from: table.table,
351
- pipeline
352
- });
353
- if (type2 === "1:1") {
354
- returnAggRef = returnAggRef.unwind({
355
- path: `$${as}`,
356
- preserveNullAndEmptyArrays: true
357
- });
358
- }
359
- if (unselect) {
360
- hasAggUnselect++;
361
- aggUnselect[as] = false;
362
- } else {
363
- aggSelect[as] = true;
364
- }
365
- this._lookupAs[as] = true;
366
- }
367
- if (this._hasWhere) returnAggRef = returnAggRef.match(_mapCommandRaw(this._where));
368
- if (this._hasOrder) returnAggRef = returnAggRef.sort(object.objectMap(this._order, (v) => v === "asc" ? 1 : -1));
369
- if (this._hasSkip) returnAggRef = returnAggRef.skip(this._skip);
370
- if (this._hasLimit) returnAggRef = returnAggRef.limit(this._limit);
371
- if (this._hasSelect) {
372
- returnAggRef = returnAggRef.project(_mergeSelect({ ...this._select, ...aggSelect }, this._order));
373
- } else if (hasAggUnselect) {
374
- returnAggRef = returnAggRef.project(aggUnselect);
375
- }
376
- return returnAggRef;
377
- }
378
- _endHost(action) {
379
- if (this._hasWhere) {
380
- if (action === "update" && this._isTransaction) {
381
- this._host = this._host.doc(this._where._id);
382
- } else {
383
- this._host = this._host.where(_mapCommandRaw(this._where));
384
- }
385
- }
386
- if (this._hasSelect) {
387
- this._host = this._host.field(_mergeSelect(this._select, this._order));
388
- }
389
- if (this._hasOrder) {
390
- object.objectEach(this._order, (val, key) => {
391
- this._host = this._host.orderBy(key, val);
392
- });
393
- }
394
- if (this._hasSkip) this._host = this._host.skip(this._skip);
395
- if (this._hasLimit && action === "query") this._host = this._host.limit(this._limit);
396
- else if (this._hasWhereId && action === "query") this._host = this._host.limit(1);
397
- }
398
- /**
399
- * 执行查询操作
400
- * @returns 查询结果
401
- */
402
- async many() {
403
- try {
404
- if (this._isTransaction) throw new Error("db.many() 方法不支持事务模式");
405
- let res;
406
- if (this._hasLookup) {
407
- const aggRef = this.aggregate();
408
- this._endAggregate(aggRef);
409
- res = await aggRef.end();
410
- } else {
411
- this._endHost("query");
412
- res = await this._host.get();
413
- }
414
- const { data } = _helpers.parseDatabaseOutput(res);
415
- return data;
416
- } catch (err) {
417
- const dbErr = err;
418
- throw this._options.parseError?.(dbErr) || dbErr;
419
- }
420
- }
421
- /**
422
- * 只查询一条,自动添加 limit(1) 条件
423
- * 如果没有匹配到记录,会抛出错误
424
- * @returns 查询结果
425
- */
426
- async firstOrThrow() {
427
- if (this._isTransaction) throw new Error("db.firstOrThrow() 方法不支持事务模式");
428
- if (this._hasLimit) throw new Error("db.firstOrThrow() 方法不支持 limit 条件");
429
- if (!this._hasWhereId) this.limit(1);
430
- const data = await this.many();
431
- const res = data.at(0);
432
- if (!res) throw error.createCloudObjectError("查询数据为空", "firstOrThrow");
433
- return res;
434
- }
435
- /**
436
- * 只查询一条,自动添加 limit(1) 条件
437
- * 如果没有匹配到记录,返回 null
438
- * @returns 查询结果或 null
439
- */
440
- async firstOrNull() {
441
- if (this._isTransaction) throw new Error("db.firstOrNull() 方法不支持事务模式");
442
- if (this._hasLimit) throw new Error("db.firstOrNull() 方法不支持 limit 条件");
443
- if (!this._hasWhereId) this.limit(1);
444
- const data = await this.many();
445
- return data.at(0) || null;
446
- }
447
- /**
448
- * 获取匹配记录的数量
449
- * @returns 记录总数
450
- */
451
- async count() {
452
- if (this._hasLookup) throw new Error("db.count() 方法不支持 lookup 聚合");
453
- if (this._hasSelect) throw new Error("db.count() 方法不支持 select 条件");
454
- if (this._hasOrder) throw new Error("db.count() 方法不支持 order 条件");
455
- if (this._hasSkip) throw new Error("db.count() 方法不支持 skip 条件");
456
- if (this._hasLimit) throw new Error("db.count() 方法不支持 limit 条件");
457
- try {
458
- this._endHost("count");
459
- const res = await this._host.count();
460
- const { total } = _helpers.parseDatabaseOutput(res);
461
- return total;
462
- } catch (err) {
463
- const dbErr = err;
464
- throw this._options.parseError?.(dbErr) || dbErr;
465
- }
466
- }
467
- /**
468
- * 创建新记录
469
- * @param data 要创建的数据
470
- * @returns 创建结果
471
- */
472
- async create(data) {
473
- if (this._hasLookup) throw new Error("db.create() 方法不支持 lookup 聚合");
474
- if (this._hasWhere) throw new Error("db.create() 方法不支持 where 条件");
475
- if (this._hasSelect) throw new Error("db.create() 方法不支持 select 条件");
476
- if (this._hasOrder) throw new Error("db.create() 方法不支持 order 条件");
477
- if (this._hasSkip) throw new Error("db.create() 方法不支持 skip 条件");
478
- if (this._hasLimit) throw new Error("db.create() 方法不支持 limit 条件");
479
- try {
480
- this._endHost("create");
481
- const res = await this._host.add(data);
482
- const { id } = _helpers.parseDatabaseOutput(res);
483
- return id;
484
- } catch (err) {
485
- const dbErr = err;
486
- throw this._options.parseError?.(dbErr) || dbErr;
487
- }
488
- }
489
- /**
490
- * 更新记录
491
- * @param data 要更新的数据
492
- * @returns 更新结果
493
- */
494
- async update(data) {
495
- if (this._hasLookup) throw new Error("db.update() 方法不支持 lookup 聚合");
496
- if (!this._hasWhere) throw new Error("设置 where 条件后才能执行 db.update() 方法");
497
- if (this._hasSelect) throw new Error("db.update() 方法不支持 select 条件");
498
- if (this._hasOrder) throw new Error("db.update() 方法不支持 order 条件");
499
- if (this._hasSkip) throw new Error("db.update() 方法不支持 skip 条件");
500
- if (this._hasLimit) throw new Error("db.update() 方法不支持 limit 条件");
501
- if (this._isTransaction && !this._hasWhereId) throw new Error("事务模式下 db.update() 的 where 条件必须是 _id");
502
- try {
503
- this._endHost("update");
504
- const res = await this._host.update(object.objectOmit(_mapCommandRaw(data), ["_id"]));
505
- const { updated } = _helpers.parseDatabaseOutput(res);
506
- return updated;
507
- } catch (err) {
508
- const dbErr = err;
509
- throw this._options.parseError?.(dbErr) || dbErr;
510
- }
511
- }
512
- /**
513
- * 删除记录
514
- * @returns 删除结果
515
- */
516
- async remove() {
517
- if (this._hasLookup) throw new Error("db.remove() 方法不支持 lookup 聚合");
518
- if (!this._hasWhere) throw new Error("设置 where 条件后才能执行 db.remove() 方法");
519
- if (this._hasSelect) throw new Error("db.remove() 方法不支持 select 条件");
520
- if (this._hasOrder) throw new Error("db.remove() 方法不支持 order 条件");
521
- if (this._hasSkip) throw new Error("db.remove() 方法不支持 skip 条件");
522
- if (this._hasLimit) throw new Error("db.remove() 方法不支持 limit 条件");
523
- if (this._isTransaction && !this._hasWhereId) throw new Error("事务模式下 db.remove() 的 where 条件必须是 _id");
524
- try {
525
- this._endHost("remove");
526
- const res = await this._host.remove();
527
- const { deleted } = _helpers.parseDatabaseOutput(res);
528
- return deleted;
529
- } catch (err) {
530
- const dbErr = err;
531
- throw this._options.parseError?.(dbErr) || dbErr;
532
- }
533
- }
36
+ //#endregion
37
+ //#region src/database/command.ts
38
+ /**
39
+ * 数据库查询命令对象,提供各种查询操作符
40
+ */
41
+ var dbQuery = {
42
+ /**
43
+ * 等于操作符
44
+ * @param value 比较值
45
+ * @returns DbQueryCommand 查询命令对象
46
+ */
47
+ eq: (value) => new DbQueryCommand("eq", value),
48
+ /**
49
+ * 不等于操作符
50
+ * @param value 比较值
51
+ * @returns DbQueryCommand 查询命令对象
52
+ */
53
+ neq: (value) => new DbQueryCommand("neq", value),
54
+ /**
55
+ * 大于操作符
56
+ * @param value 比较值
57
+ * @returns DbQueryCommand 查询命令对象
58
+ */
59
+ gt: (value) => new DbQueryCommand("gt", value),
60
+ /**
61
+ * 大于等于操作符
62
+ * @param value 比较值
63
+ * @returns DbQueryCommand 查询命令对象
64
+ */
65
+ gte: (value) => new DbQueryCommand("gte", value),
66
+ /**
67
+ * 小于操作符
68
+ * @param value 比较值
69
+ * @returns DbQueryCommand 查询命令对象
70
+ */
71
+ lt: (value) => new DbQueryCommand("lt", value),
72
+ /**
73
+ * 小于等于操作符
74
+ * @param value 比较值
75
+ * @returns DbQueryCommand 查询命令对象
76
+ */
77
+ lte: (value) => new DbQueryCommand("lte", value),
78
+ /**
79
+ * 包含在数组中操作符
80
+ * @param value 值数组
81
+ * @returns DbQueryCommand 查询命令对象
82
+ */
83
+ in: (value) => new DbQueryCommand("in", value),
84
+ /**
85
+ * 不包含在数组中操作符
86
+ * @param value 值数组
87
+ * @returns DbQueryCommand 查询命令对象
88
+ */
89
+ nin: (value) => new DbQueryCommand("nin", value),
90
+ /**
91
+ * 数组长度匹配操作符
92
+ * @param size 数组长度
93
+ * @returns DbQueryCommand 查询命令对象
94
+ */
95
+ size: (size) => new DbQueryCommand("size", size),
96
+ /**
97
+ * 正则表达式匹配操作符
98
+ * @param regExp 正则表达式
99
+ * @returns DbQueryCommand 查询命令对象
100
+ */
101
+ regExp: (regExp) => new DbQueryCommand("regExp", regExp, { rewriteValue: (_db, parameter) => parameter }),
102
+ /**
103
+ * 逻辑与操作符
104
+ * @param conditions 查询条件参数
105
+ * @returns DbQueryCommand 查询命令对象
106
+ */
107
+ and: (conditions) => new DbQueryCommand("and", conditions, { formatParameter: (db) => conditions.map((c) => DbBaseCommand.getValue(c, db)) }),
108
+ /**
109
+ * 逻辑或操作符
110
+ * @param conditions 查询条件参数
111
+ * @returns DbQueryCommand 查询命令对象
112
+ */
113
+ or: (conditions) => new DbQueryCommand("or", conditions, { formatParameter: (db) => conditions.map((c) => DbBaseCommand.getValue(c, db)) })
114
+ };
115
+ /**
116
+ * 数据库变更命令对象,提供各种数据更新操作符
117
+ */
118
+ var dbMutate = {
119
+ /**
120
+ * 数值增加操作符
121
+ * @param value 增加的数值
122
+ * @returns DbMutateCommand 变更命令对象
123
+ */
124
+ inc: (value) => new DbMutateCommand("inc", value),
125
+ /**
126
+ * 数值乘法操作符
127
+ * @param value 乘数
128
+ * @returns DbMutateCommand 变更命令对象
129
+ */
130
+ mul: (value) => new DbMutateCommand("mul", value),
131
+ /**
132
+ * 设置字段值操作符
133
+ * @param value 设置的值
134
+ * @returns DbMutateCommand 变更命令对象
135
+ */
136
+ set: (value) => new DbMutateCommand("set", value),
137
+ /**
138
+ * 向数组末尾添加元素操作符
139
+ * @param value 添加的值
140
+ * @returns DbMutateCommand 变更命令对象
141
+ */
142
+ push: (value) => new DbMutateCommand("push", value),
143
+ /**
144
+ * 向数组开头添加元素操作符
145
+ * @param value 添加的值
146
+ * @returns DbMutateCommand 变更命令对象
147
+ */
148
+ unshift: (value) => new DbMutateCommand("unshift", value),
149
+ /**
150
+ * 从数组末尾移除元素操作符
151
+ * @returns DbMutateCommand 变更命令对象
152
+ */
153
+ pop: () => new DbMutateCommand("pop", void 0),
154
+ /**
155
+ * 从数组开头移除元素操作符
156
+ * @returns DbMutateCommand 变更命令对象
157
+ */
158
+ shift: () => new DbMutateCommand("shift", void 0),
159
+ /**
160
+ * 移除字段操作符
161
+ * @returns DbMutateCommand 变更命令对象
162
+ */
163
+ remove: () => new DbMutateCommand("remove", void 0)
164
+ };
165
+ //#endregion
166
+ //#region src/database/paging.ts
167
+ /**
168
+ * 数据库分页查询函数
169
+ * @template T - 数据类型
170
+ * @param queryDb - 数据库查询实例
171
+ * @returns 包含数据列表和总数的对象
172
+ */
173
+ async function dbPaging(queryDb) {
174
+ const where = queryDb.getWhere(true);
175
+ const countDb = queryDb.clone();
176
+ return {
177
+ list: await queryDb.many(),
178
+ total: await countDb.where(where).count()
179
+ };
534
180
  }
181
+ //#endregion
182
+ //#region src/database/_db.class.ts
183
+ /**
184
+ * 数据库聚合操作符命令
185
+ */
186
+ var dbAgg = uniCloud.database().command.aggregate;
187
+ var db0 = uniCloud.database();
188
+ var gid = 0;
189
+ /**
190
+ * 数据库类
191
+ * @template D1 - 主表数据
192
+ * @template S1 - 主表筛选
193
+ * @template D2 - 副表数据
194
+ * @template W2 - 副表查询
195
+ */
196
+ var Db = class Db {
197
+ _host;
198
+ /**
199
+ * 是否为事务环境
200
+ * - 查询条件只能是 id
201
+ * - 不能聚合操作
202
+ */
203
+ _isTransaction = false;
204
+ _options;
205
+ /**
206
+ * 构造函数,初始化数据库集合引用
207
+ * @param collection 数据表名称
208
+ * @param _mockDatabase 模拟数据库,用于单元测试
209
+ */
210
+ constructor(options) {
211
+ this._options = options;
212
+ this._host = options._mockDatabase || options.transaction?.collection(options.table) || db0.collection(options.table);
213
+ this._isTransaction = !!options.transaction;
214
+ }
215
+ /**
216
+ * 创建一个新的数据库实例,可选是否移除事务
217
+ * @param withoutTransaction 是否移除事务,默认 false
218
+ * @returns 新的数据库实例
219
+ */
220
+ clone(withoutTransaction) {
221
+ return new Db({
222
+ ...this._options,
223
+ transaction: withoutTransaction ? null : this._options.transaction
224
+ });
225
+ }
226
+ get table() {
227
+ return this._options.table;
228
+ }
229
+ get options() {
230
+ return this._options;
231
+ }
232
+ get isTransaction() {
233
+ return this._isTransaction;
234
+ }
235
+ /**
236
+ * 获取聚合操作实例
237
+ * @returns 聚合操作实例
238
+ */
239
+ aggregate() {
240
+ return this._host.aggregate();
241
+ }
242
+ _hasWhere = void 0;
243
+ _hasWhereId = void 0;
244
+ _where = {};
245
+ _doWhere(where, from) {
246
+ if (this._hasWhere) throw new Error(`已调用过一次 db.${_toWhereMethod(this._hasWhere)} 了`);
247
+ const realWhere = (0, _cloudcome_utils_core_object.objectFilter)(where, (value) => value !== void 0);
248
+ const isWhereId = Object.keys(realWhere).length === 1 && "_id" in realWhere && ((0, _cloudcome_utils_core_type.isString)(realWhere._id) || (0, _cloudcome_utils_core_type.isNumber)(realWhere._id));
249
+ if (isWhereId && this._hasLimit) throw new Error(`db.${_toWhereIdMethod(from)} 方法不能与 db.limit() 方法同时调用`);
250
+ this._hasWhere = from;
251
+ this._where = realWhere;
252
+ if (isWhereId) this._hasWhereId = from;
253
+ return this;
254
+ }
255
+ /**
256
+ * 设置查询条件
257
+ * @param where 查询条件对象
258
+ * @returns 当前Db实例,支持链式调用
259
+ */
260
+ where(where) {
261
+ return this._doWhere(where, "where");
262
+ }
263
+ /**
264
+ * 获取当前查询条件
265
+ * @param plain 是否返回原始查询条件对象,默认 false
266
+ * @returns 当前查询条件对象
267
+ */
268
+ getWhere(plain) {
269
+ return plain ? (0, _cloudcome_utils_core_object.objectOmit)(this._where, Object.keys(this._lookupAs)) : this._where;
270
+ }
271
+ /**
272
+ * 根据ID设置查询条件
273
+ * @param id 记录ID
274
+ * @returns 当前Db实例,支持链式调用
275
+ */
276
+ whereId(id) {
277
+ return this._doWhere({ _id: id }, "whereId");
278
+ }
279
+ _hasSelect = 0;
280
+ _select = {};
281
+ /**
282
+ * 指定要返回的字段
283
+ * @param fields 要返回的字段对象,true表示返回,false表示不返回
284
+ * @returns 当前Db实例,支持链式调用
285
+ */
286
+ select(fields) {
287
+ if (this._hasSelect) throw new Error("db.select() 方法只能调用一次");
288
+ this._hasSelect++;
289
+ this._select = fields;
290
+ return this;
291
+ }
292
+ _hasOrder = 0;
293
+ _order = {};
294
+ /**
295
+ * 设置排序规则
296
+ * @param order 排序规则对象,key为字段名,value为"asc"或"desc"
297
+ * @returns 当前Db实例,支持链式调用
298
+ */
299
+ order(order) {
300
+ this._hasOrder++;
301
+ this._order = order;
302
+ return this;
303
+ }
304
+ _hasSkip = 0;
305
+ _skip = 0;
306
+ /**
307
+ * 跳过指定数量的记录
308
+ * @param skip 要跳过的记录数
309
+ * @returns 当前Db实例,支持链式调用
310
+ */
311
+ skip(skip) {
312
+ if (this._hasSkip) throw new Error("db.skip() 方法只能调用一次");
313
+ this._hasSkip++;
314
+ this._skip = skip;
315
+ return this;
316
+ }
317
+ _hasLimit = 0;
318
+ _limit = 0;
319
+ /**
320
+ * 限制返回的记录数量
321
+ * @param limit 最大返回记录数
322
+ * @returns 当前Db实例,支持链式调用
323
+ */
324
+ limit(limit) {
325
+ if (this._hasLimit) throw new Error("db.limit() 方法只能调用一次");
326
+ if (this._hasWhereId) throw new Error(`db.limit() 方法不能与 ${_toWhereIdMethod(this._hasWhereId)} 方法同时调用`);
327
+ this._hasLimit++;
328
+ this._limit = limit;
329
+ return this;
330
+ }
331
+ _hasLookup = 0;
332
+ get hasLookup() {
333
+ return this._hasLookup > 0;
334
+ }
335
+ _lookups = [];
336
+ lookup(table, lookup) {
337
+ table._hasLookup++;
338
+ this._hasLookup++;
339
+ this._lookups.push({
340
+ ...lookup,
341
+ table
342
+ });
343
+ return this;
344
+ }
345
+ _aggregated = false;
346
+ _lookupAs = {};
347
+ _endAggregate(aggRef) {
348
+ if (this._aggregated) throw new Error(`相同的数据表实例(${this.table})不能重复使用`);
349
+ this._aggregated = true;
350
+ let returnAggRef = aggRef;
351
+ let _hasAggSelect = 0;
352
+ const aggSelect = {};
353
+ let hasAggUnselect = 0;
354
+ const aggUnselect = {};
355
+ for (const { relation: type, as, foreignField, localField, table, unselect } of this._lookups) {
356
+ const letName = `let${gid++}`;
357
+ let pipeline = dbAgg.pipeline();
358
+ pipeline = pipeline.match({ $expr: { $and: [type === "n:1" ? { $in: [`$${foreignField}`, `$$${letName}`] } : { $eq: [`$${foreignField}`, `$$${letName}`] }] } });
359
+ pipeline = table._endAggregate(pipeline);
360
+ pipeline = pipeline.done();
361
+ returnAggRef = returnAggRef.lookup({
362
+ let: { [letName]: `$${localField}` },
363
+ as,
364
+ from: table.table,
365
+ pipeline
366
+ });
367
+ if (type === "1:1") returnAggRef = returnAggRef.unwind({
368
+ path: `$${as}`,
369
+ preserveNullAndEmptyArrays: true
370
+ });
371
+ if (unselect) {
372
+ hasAggUnselect++;
373
+ aggUnselect[as] = false;
374
+ } else {
375
+ _hasAggSelect++;
376
+ aggSelect[as] = true;
377
+ }
378
+ this._lookupAs[as] = true;
379
+ }
380
+ if (this._hasWhere) returnAggRef = returnAggRef.match(_mapCommandRaw(this._where));
381
+ if (this._hasOrder) returnAggRef = returnAggRef.sort((0, _cloudcome_utils_core_object.objectMap)(this._order, (v) => v === "asc" ? 1 : -1));
382
+ if (this._hasSkip) returnAggRef = returnAggRef.skip(this._skip);
383
+ if (this._hasLimit) returnAggRef = returnAggRef.limit(this._limit);
384
+ if (this._hasSelect) returnAggRef = returnAggRef.project(_mergeSelect({
385
+ ...this._select,
386
+ ...aggSelect
387
+ }, this._order));
388
+ else if (hasAggUnselect) returnAggRef = returnAggRef.project(aggUnselect);
389
+ return returnAggRef;
390
+ }
391
+ _endHost(action) {
392
+ if (this._hasWhere) if ((action === "update" || action === "remove") && this._isTransaction) this._host = this._host.doc(this._where._id);
393
+ else this._host = this._host.where(_mapCommandRaw(this._where));
394
+ if (this._hasSelect) this._host = this._host.field(_mergeSelect(this._select, this._order));
395
+ if (this._hasOrder) (0, _cloudcome_utils_core_object.objectEach)(this._order, (val, key) => {
396
+ this._host = this._host.orderBy(key, val);
397
+ });
398
+ if (this._hasSkip) this._host = this._host.skip(this._skip);
399
+ if (this._hasLimit && action === "query") this._host = this._host.limit(this._limit);
400
+ else if (this._hasWhereId && action === "query") this._host = this._host.limit(1);
401
+ }
402
+ /**
403
+ * 执行查询操作
404
+ * @returns 查询结果
405
+ */
406
+ async many() {
407
+ try {
408
+ if (this._isTransaction) throw new Error("db.many() 方法不支持事务模式");
409
+ let res;
410
+ if (this._hasLookup) {
411
+ const aggRef = this.aggregate();
412
+ this._endAggregate(aggRef);
413
+ res = await aggRef.end();
414
+ } else {
415
+ this._endHost("query");
416
+ res = await this._host.get();
417
+ }
418
+ const { data } = require__helpers.parseDatabaseOutput(res);
419
+ return data;
420
+ } catch (err) {
421
+ const dbErr = err;
422
+ throw this._options.parseError?.(dbErr) || dbErr;
423
+ }
424
+ }
425
+ /**
426
+ * 只查询一条,自动添加 limit(1) 条件
427
+ * 如果没有匹配到记录,会抛出错误
428
+ * @returns 查询结果
429
+ */
430
+ async firstOrThrow() {
431
+ if (this._isTransaction) throw new Error("db.firstOrThrow() 方法不支持事务模式");
432
+ if (this._hasLimit) throw new Error("db.firstOrThrow() 方法不支持 limit 条件");
433
+ if (!this._hasWhereId) this.limit(1);
434
+ const res = (await this.many()).at(0);
435
+ if (!res) throw require_cloud.createCloudObjectError("查询数据为空", "firstOrThrow");
436
+ return res;
437
+ }
438
+ /**
439
+ * 只查询一条,自动添加 limit(1) 条件
440
+ * 如果没有匹配到记录,返回 null
441
+ * @returns 查询结果或 null
442
+ */
443
+ async firstOrNull() {
444
+ if (this._isTransaction) throw new Error("db.firstOrNull() 方法不支持事务模式");
445
+ if (this._hasLimit) throw new Error("db.firstOrNull() 方法不支持 limit 条件");
446
+ if (!this._hasWhereId) this.limit(1);
447
+ return (await this.many()).at(0) || null;
448
+ }
449
+ /**
450
+ * 获取匹配记录的数量
451
+ * @returns 记录总数
452
+ */
453
+ async count() {
454
+ if (this._isTransaction) throw new Error("db.count() 方法不支持事务模式");
455
+ if (this._hasLookup) throw new Error("db.count() 方法不支持 lookup 聚合");
456
+ if (this._hasSelect) throw new Error("db.count() 方法不支持 select 条件");
457
+ if (this._hasOrder) throw new Error("db.count() 方法不支持 order 条件");
458
+ if (this._hasSkip) throw new Error("db.count() 方法不支持 skip 条件");
459
+ if (this._hasLimit) throw new Error("db.count() 方法不支持 limit 条件");
460
+ try {
461
+ this._endHost("count");
462
+ const { total } = require__helpers.parseDatabaseOutput(await this._host.count());
463
+ return total;
464
+ } catch (err) {
465
+ const dbErr = err;
466
+ throw this._options.parseError?.(dbErr) || dbErr;
467
+ }
468
+ }
469
+ /**
470
+ * 创建新记录
471
+ * @param data 要创建的数据
472
+ * @returns 创建结果
473
+ */
474
+ async create(data) {
475
+ if (this._hasLookup) throw new Error("db.create() 方法不支持 lookup 聚合");
476
+ if (this._hasWhere) throw new Error("db.create() 方法不支持 where 条件");
477
+ if (this._hasSelect) throw new Error("db.create() 方法不支持 select 条件");
478
+ if (this._hasOrder) throw new Error("db.create() 方法不支持 order 条件");
479
+ if (this._hasSkip) throw new Error("db.create() 方法不支持 skip 条件");
480
+ if (this._hasLimit) throw new Error("db.create() 方法不支持 limit 条件");
481
+ try {
482
+ this._endHost("create");
483
+ const { id } = require__helpers.parseDatabaseOutput(await this._host.add(data));
484
+ return id;
485
+ } catch (err) {
486
+ const dbErr = err;
487
+ throw this._options.parseError?.(dbErr) || dbErr;
488
+ }
489
+ }
490
+ /**
491
+ * 更新记录
492
+ * @param data 要更新的数据
493
+ * @returns 更新结果
494
+ */
495
+ async update(data) {
496
+ if (this._hasLookup) throw new Error("db.update() 方法不支持 lookup 聚合");
497
+ if (!this._hasWhere) throw new Error("设置 where 条件后才能执行 db.update() 方法");
498
+ if (this._hasSelect) throw new Error("db.update() 方法不支持 select 条件");
499
+ if (this._hasOrder) throw new Error("db.update() 方法不支持 order 条件");
500
+ if (this._hasSkip) throw new Error("db.update() 方法不支持 skip 条件");
501
+ if (this._hasLimit) throw new Error("db.update() 方法不支持 limit 条件");
502
+ if (this._isTransaction && !this._hasWhereId) throw new Error("事务模式下 db.update() 的 where 条件必须是 _id");
503
+ try {
504
+ this._endHost("update");
505
+ const { updated } = require__helpers.parseDatabaseOutput(await this._host.update((0, _cloudcome_utils_core_object.objectOmit)(_mapCommandRaw(data), ["_id"])));
506
+ return updated;
507
+ } catch (err) {
508
+ const dbErr = err;
509
+ throw this._options.parseError?.(dbErr) || dbErr;
510
+ }
511
+ }
512
+ /**
513
+ * 删除记录
514
+ * @returns 删除结果
515
+ */
516
+ async remove() {
517
+ if (this._hasLookup) throw new Error("db.remove() 方法不支持 lookup 聚合");
518
+ if (!this._hasWhere) throw new Error("设置 where 条件后才能执行 db.remove() 方法");
519
+ if (this._hasSelect) throw new Error("db.remove() 方法不支持 select 条件");
520
+ if (this._hasOrder) throw new Error("db.remove() 方法不支持 order 条件");
521
+ if (this._hasSkip) throw new Error("db.remove() 方法不支持 skip 条件");
522
+ if (this._hasLimit) throw new Error("db.remove() 方法不支持 limit 条件");
523
+ if (this._isTransaction && !this._hasWhereId) throw new Error("事务模式下 db.remove() 的 where 条件必须是 _id");
524
+ try {
525
+ this._endHost("remove");
526
+ const { deleted } = require__helpers.parseDatabaseOutput(await this._host.remove());
527
+ return deleted;
528
+ } catch (err) {
529
+ const dbErr = err;
530
+ throw this._options.parseError?.(dbErr) || dbErr;
531
+ }
532
+ }
533
+ };
535
534
  function _toWhereMethod(whereFrom) {
536
- return whereFrom === "where" ? "where({...})" : "whereId(id)";
535
+ return whereFrom === "where" ? "where({...})" : "whereId(id)";
537
536
  }
538
537
  function _toWhereIdMethod(whereFrom) {
539
- return whereFrom === "where" ? "where({ _id })" : "whereId(id)";
538
+ return whereFrom === "where" ? "where({ _id })" : "whereId(id)";
540
539
  }
541
540
  function _mapCommandRaw(data) {
542
- const map = (val) => {
543
- if (!type.isObject(val)) return val;
544
- if (val instanceof DbBaseCommand) return DbBaseCommand.getValue(val, db0);
545
- return object.objectMap(val, map);
546
- };
547
- return object.objectMap(data, map);
541
+ const map = (val) => {
542
+ if (!(0, _cloudcome_utils_core_type.isObject)(val)) return val;
543
+ if (val instanceof DbBaseCommand) return DbBaseCommand.getValue(val, db0);
544
+ return (0, _cloudcome_utils_core_object.objectMap)(val, map);
545
+ };
546
+ return (0, _cloudcome_utils_core_object.objectMap)(data, map);
548
547
  }
549
548
  function _mapOrderSelect(order) {
550
- return object.objectMap(order, (val, key) => true);
549
+ return (0, _cloudcome_utils_core_object.objectMap)(order, (_val, _key) => true);
551
550
  }
552
551
  function _mergeSelect(select, order) {
553
- const noSelect = Object.keys(select).length === 0;
554
- if (noSelect) return select;
555
- const onlyOmitId = Object.keys(select).length === 1 && "_id" in select && select._id === false;
556
- if (onlyOmitId) return select;
557
- return {
558
- ...select,
559
- ..._mapOrderSelect(order)
560
- };
552
+ if (Object.keys(select).length === 0) return select;
553
+ if (Object.keys(select).length === 1 && "_id" in select && select._id === false) return select;
554
+ return {
555
+ ...select,
556
+ ..._mapOrderSelect(order)
557
+ };
561
558
  }
559
+ //#endregion
560
+ //#region src/database/proxy.ts
561
+ /**
562
+ * 创建一个数据库代理对象,用于延迟实例化数据库操作类
563
+ * @template D1 - 主表数据
564
+ * @template S1 - 主表筛选
565
+ * @param name - 数据库表名
566
+ * @returns 返回一个代理对象,该对象会将属性访问转发到实际的数据库操作实例
567
+ */
562
568
  function dbProxy(name, options) {
563
- return new Proxy(
564
- {},
565
- {
566
- get(target, prop) {
567
- if (prop === "_isProxy") return true;
568
- const table = new Db({ table: name, ...options });
569
- const tableProp = prop;
570
- const ref = table[tableProp];
571
- return type.isFunction(ref) ? ref.bind(table) : ref;
572
- }
573
- }
574
- );
569
+ return new Proxy({}, { get(_target, prop) {
570
+ if (prop === "_isProxy") return true;
571
+ const table = new Db({
572
+ table: name,
573
+ ...options
574
+ });
575
+ const ref = table[prop];
576
+ return (0, _cloudcome_utils_core_type.isFunction)(ref) ? ref.bind(table) : ref;
577
+ } });
578
+ }
579
+ //#endregion
580
+ //#region src/database/transaction.ts
581
+ /**
582
+ * 在数据库事务中执行操作
583
+ *
584
+ * @template K - 事务操作返回值类型
585
+ * @param transacting - 事务执行函数,接收事务数据库实例作为参数
586
+ * @param _mockDatabase - 用于测试的模拟数据库对象
587
+ * @param _mockDbInstance - 用于测试的模拟数据库实例
588
+ * @returns 事务操作的返回结果
589
+ *
590
+ * @example
591
+ * ```typescript
592
+ * const result = await dbTransaction(async (withTransaction) => {
593
+ * const userId = await withTransaction(db.table('user')).create({ name: 'John' });
594
+ * const order = await withTransaction(db.table('orders')).create({ userId, amount: 100 });
595
+ * return { user, order };
596
+ * });
597
+ * ```
598
+ */
599
+ async function dbTransaction(transacting, _mockDatabase, _mockDbInstance) {
600
+ const [err1, transaction] = await (0, _cloudcome_utils_core_try.tryFlatten)((_mockDatabase || uniCloud.database()).startTransaction());
601
+ if (err1) throw err1;
602
+ const withTransaction = (db) => {
603
+ return _mockDbInstance || new Db({
604
+ ...db.options,
605
+ transaction
606
+ });
607
+ };
608
+ const [err2, result] = await (0, _cloudcome_utils_core_try.tryFlatten)(async () => {
609
+ const result = await transacting(withTransaction);
610
+ await transaction.commit();
611
+ return result;
612
+ });
613
+ if (err2) {
614
+ await (0, _cloudcome_utils_core_try.tryFlatten)(transaction.rollback());
615
+ throw err2;
616
+ }
617
+ return result;
575
618
  }
619
+ //#endregion
620
+ //#region src/database/upsert.ts
576
621
  async function dbUpsert(db, options) {
577
- const { create, update, onBeforeCreate, onAfterCreate, onBeforeUpdate, onAfterUpdate, _mockDbInstance } = options;
578
- const _mutateDb = _mockDbInstance || db.clone();
579
- const _queryDb = _mockDbInstance || db.clone(true);
580
- const exist = await _queryDb.where(db.getWhere(true)).firstOrNull();
581
- if (exist) {
582
- const skipUpdate = await onBeforeUpdate?.(exist) === false;
583
- if (skipUpdate) {
584
- return { id: exist._id, updated: false, created: false };
585
- }
586
- const updateData = type.isFunction(update) ? update(exist) : update;
587
- await _mutateDb.whereId(exist._id).update(updateData);
588
- onAfterUpdate?.(updateData, exist);
589
- return { id: exist._id, updated: true, created: false };
590
- }
591
- await onBeforeCreate?.();
592
- const createdId = await _mutateDb.create(create);
593
- await onAfterCreate?.(createdId);
594
- return { id: createdId, updated: false, created: true };
622
+ const { create, update, onBeforeCreate, onAfterCreate, onBeforeUpdate, onAfterUpdate, _mockDbInstance } = options;
623
+ const _mutateDb = _mockDbInstance || db.clone();
624
+ const exist = await (_mockDbInstance || db.clone(true)).where(db.getWhere(true)).firstOrNull();
625
+ if (exist) {
626
+ if (await onBeforeUpdate?.(exist) === false) return {
627
+ id: exist._id,
628
+ updated: false,
629
+ created: false
630
+ };
631
+ const updateData = (0, _cloudcome_utils_core_type.isFunction)(update) ? update(exist) : update;
632
+ await _mutateDb.whereId(exist._id).update(updateData);
633
+ onAfterUpdate?.(updateData, exist);
634
+ return {
635
+ id: exist._id,
636
+ updated: true,
637
+ created: false
638
+ };
639
+ }
640
+ await onBeforeCreate?.();
641
+ const createdId = await _mutateDb.create(create);
642
+ await onAfterCreate?.(createdId);
643
+ return {
644
+ id: createdId,
645
+ updated: false,
646
+ created: true
647
+ };
595
648
  }
649
+ //#endregion
650
+ //#region src/database/unique.ts
596
651
  async function dbUnique(db, options) {
597
- const { id, created } = await dbUpsert(db, {
598
- ...options,
599
- // @ts-ignore
600
- update: {},
601
- onBeforeUpdate: () => false
602
- });
603
- return { id, created };
604
- }
605
- async function dbTransaction(transacting, _mockDatabase, _mockDbInstance) {
606
- const transactionDb = _mockDatabase || uniCloud.database();
607
- const [err1, transaction] = await _try.tryFlatten(transactionDb.startTransaction());
608
- if (err1) throw err1;
609
- const withTransaction = (db) => {
610
- return _mockDbInstance || new Db({ ...db.options, transaction });
611
- };
612
- const [err2, result] = await _try.tryFlatten(async () => {
613
- const result2 = await transacting(withTransaction);
614
- await transaction.commit();
615
- return result2;
616
- });
617
- if (err2) {
618
- await _try.tryFlatten(transaction.rollback());
619
- throw err2;
620
- }
621
- return result;
622
- }
623
- async function dbPaging(queryDb) {
624
- const where = queryDb.getWhere(true);
625
- const countDb = queryDb.clone();
626
- const list = await queryDb.many();
627
- const total = await countDb.where(where).count();
628
- return {
629
- list,
630
- total
631
- };
652
+ const { id, created } = await dbUpsert(db, {
653
+ ...options,
654
+ update: {},
655
+ onBeforeUpdate: () => false
656
+ });
657
+ return {
658
+ id,
659
+ created
660
+ };
632
661
  }
633
- exports.parseDatabaseOutput = _helpers.parseDatabaseOutput;
662
+ //#endregion
634
663
  exports.dbMutate = dbMutate;
635
664
  exports.dbPaging = dbPaging;
636
665
  exports.dbProxy = dbProxy;
@@ -638,4 +667,6 @@ exports.dbQuery = dbQuery;
638
667
  exports.dbTransaction = dbTransaction;
639
668
  exports.dbUnique = dbUnique;
640
669
  exports.dbUpsert = dbUpsert;
641
- //# sourceMappingURL=database.cjs.map
670
+ exports.parseDatabaseOutput = require__helpers.parseDatabaseOutput;
671
+
672
+ //# sourceMappingURL=database.cjs.map