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