@cloudcome/utils-uni 1.31.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/database.mjs CHANGED
@@ -1,642 +1,702 @@
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/each.ts
166
+ /**
167
+ * 遍历表中的每一行数据并执行回调函数
168
+ *
169
+ * 采用分批查询策略,每批查询 100 条记录,通过 skip/limit 实现分页遍历,
170
+ * 避免一次性加载大量数据导致内存溢出。
171
+ *
172
+ * 迭代器按顺序串行执行,即每一行数据的迭代器完成后才会处理下一行。
173
+ *
174
+ * @template T - 数据行类型
175
+ * @param table 数据库表代理对象
176
+ * @param where 查询条件
177
+ * @param iterator 对每一行数据执行的异步迭代器函数
178
+ * @param maxCount 最大遍历数量,默认值为 Number.MAX_SAFE_INTEGER。
179
+ * 注意:由于分批查询机制(每批 100 条),实际遍历的行数可能略大于 maxCount,
180
+ * 例如 maxCount=150 时,会分两批查询(0-99、100-199),实际遍历 200 行。
181
+ * @example
182
+ * ```ts
183
+ * // 遍历所有状态为 active 的用户
184
+ * await dbEach(userTable, { status: 'active' }, async (user) => {
185
+ * await sendEmail(user.email);
186
+ * });
187
+ *
188
+ * // 限制最多遍历 500 条记录
189
+ * await dbEach(orderTable, { status: 'pending' }, async (order) => {
190
+ * await processOrder(order);
191
+ * }, 500);
192
+ * ```
193
+ */
194
+ async function dbEach(table, where, iterator, maxCount = Number.MAX_SAFE_INTEGER) {
195
+ const count = Math.min(await table.where(where).count(), maxCount);
196
+ const limit = 100;
197
+ for (let skip = 0; skip < count; skip += limit) {
198
+ const rows = await table.where(where).limit(limit).skip(skip).many();
199
+ for (const row of rows) await iterator(row);
200
+ }
201
+ }
202
+ //#endregion
203
+ //#region src/database/paging.ts
204
+ /**
205
+ * 数据库分页查询函数
206
+ * @template T - 数据类型
207
+ * @param queryDb - 数据库查询实例
208
+ * @returns 包含数据列表和总数的对象
209
+ */
210
+ async function dbPaging(queryDb) {
211
+ const where = queryDb.getWhere(true);
212
+ const countDb = queryDb.clone();
213
+ return {
214
+ list: await queryDb.many(),
215
+ total: await countDb.where(where).count()
216
+ };
533
217
  }
218
+ //#endregion
219
+ //#region src/database/_db.class.ts
220
+ /**
221
+ * 数据库聚合操作符命令
222
+ */
223
+ var dbAgg = uniCloud.database().command.aggregate;
224
+ var db0 = uniCloud.database();
225
+ var gid = 0;
226
+ /**
227
+ * 数据库类
228
+ * @template D1 - 主表数据
229
+ * @template S1 - 主表筛选
230
+ * @template D2 - 副表数据
231
+ * @template W2 - 副表查询
232
+ */
233
+ var Db = class Db {
234
+ _host;
235
+ /**
236
+ * 是否为事务环境
237
+ * - 查询条件只能是 id
238
+ * - 不能聚合操作
239
+ */
240
+ _isTransaction = false;
241
+ _options;
242
+ /**
243
+ * 构造函数,初始化数据库集合引用
244
+ * @param collection 数据表名称
245
+ * @param _mockDatabase 模拟数据库,用于单元测试
246
+ */
247
+ constructor(options) {
248
+ this._options = options;
249
+ this._host = options._mockDatabase || options.transaction?.collection(options.table) || db0.collection(options.table);
250
+ this._isTransaction = !!options.transaction;
251
+ }
252
+ /**
253
+ * 创建一个新的数据库实例,可选是否移除事务
254
+ * @param withoutTransaction 是否移除事务,默认 false
255
+ * @returns 新的数据库实例
256
+ */
257
+ clone(withoutTransaction) {
258
+ return new Db({
259
+ ...this._options,
260
+ transaction: withoutTransaction ? null : this._options.transaction
261
+ });
262
+ }
263
+ get table() {
264
+ return this._options.table;
265
+ }
266
+ get options() {
267
+ return this._options;
268
+ }
269
+ get isTransaction() {
270
+ return this._isTransaction;
271
+ }
272
+ /**
273
+ * 获取聚合操作实例
274
+ * @returns 聚合操作实例
275
+ */
276
+ aggregate() {
277
+ return this._host.aggregate();
278
+ }
279
+ _hasWhere = void 0;
280
+ _hasWhereId = void 0;
281
+ _where = {};
282
+ _doWhere(where, from) {
283
+ if (this._hasWhere) throw new Error(`已调用过一次 db.${_toWhereMethod(this._hasWhere)} 了`);
284
+ const realWhere = objectFilter(where, (value) => value !== void 0);
285
+ const isWhereId = Object.keys(realWhere).length === 1 && "_id" in realWhere && (isString(realWhere._id) || isNumber(realWhere._id));
286
+ if (isWhereId && this._hasLimit) throw new Error(`db.${_toWhereIdMethod(from)} 方法不能与 db.limit() 方法同时调用`);
287
+ this._hasWhere = from;
288
+ this._where = realWhere;
289
+ if (isWhereId) this._hasWhereId = from;
290
+ return this;
291
+ }
292
+ /**
293
+ * 设置查询条件
294
+ * @param where 查询条件对象
295
+ * @returns 当前Db实例,支持链式调用
296
+ */
297
+ where(where) {
298
+ return this._doWhere(where, "where");
299
+ }
300
+ /**
301
+ * 获取当前查询条件
302
+ * @param plain 是否返回原始查询条件对象,默认 false
303
+ * @returns 当前查询条件对象
304
+ */
305
+ getWhere(plain) {
306
+ return plain ? objectOmit(this._where, Object.keys(this._lookupAs)) : this._where;
307
+ }
308
+ /**
309
+ * 根据ID设置查询条件
310
+ * @param id 记录ID
311
+ * @returns 当前Db实例,支持链式调用
312
+ */
313
+ whereId(id) {
314
+ return this._doWhere({ _id: id }, "whereId");
315
+ }
316
+ _hasSelect = 0;
317
+ _select = {};
318
+ /**
319
+ * 指定要返回的字段
320
+ * @param fields 要返回的字段对象,true表示返回,false表示不返回
321
+ * @returns 当前Db实例,支持链式调用
322
+ */
323
+ select(fields) {
324
+ if (this._hasSelect) throw new Error("db.select() 方法只能调用一次");
325
+ this._hasSelect++;
326
+ this._select = fields;
327
+ return this;
328
+ }
329
+ _hasOrder = 0;
330
+ _order = {};
331
+ /**
332
+ * 设置排序规则
333
+ * @param order 排序规则对象,key为字段名,value为"asc"或"desc"
334
+ * @returns 当前Db实例,支持链式调用
335
+ */
336
+ order(order) {
337
+ this._hasOrder++;
338
+ this._order = order;
339
+ return this;
340
+ }
341
+ _hasSkip = 0;
342
+ _skip = 0;
343
+ /**
344
+ * 跳过指定数量的记录
345
+ * @param skip 要跳过的记录数
346
+ * @returns 当前Db实例,支持链式调用
347
+ */
348
+ skip(skip) {
349
+ if (this._hasSkip) throw new Error("db.skip() 方法只能调用一次");
350
+ this._hasSkip++;
351
+ this._skip = skip;
352
+ return this;
353
+ }
354
+ _hasLimit = 0;
355
+ _limit = 0;
356
+ /**
357
+ * 限制返回的记录数量
358
+ * @param limit 最大返回记录数
359
+ * @returns 当前Db实例,支持链式调用
360
+ */
361
+ limit(limit) {
362
+ if (this._hasLimit) throw new Error("db.limit() 方法只能调用一次");
363
+ if (this._hasWhereId) throw new Error(`db.limit() 方法不能与 ${_toWhereIdMethod(this._hasWhereId)} 方法同时调用`);
364
+ this._hasLimit++;
365
+ this._limit = limit;
366
+ return this;
367
+ }
368
+ _hasLookup = 0;
369
+ get hasLookup() {
370
+ return this._hasLookup > 0;
371
+ }
372
+ _lookups = [];
373
+ lookup(table, lookup) {
374
+ table._hasLookup++;
375
+ this._hasLookup++;
376
+ this._lookups.push({
377
+ ...lookup,
378
+ table
379
+ });
380
+ return this;
381
+ }
382
+ _aggregated = false;
383
+ _lookupAs = {};
384
+ _endAggregate(aggRef) {
385
+ if (this._aggregated) throw new Error(`相同的数据表实例(${this.table})不能重复使用`);
386
+ this._aggregated = true;
387
+ let returnAggRef = aggRef;
388
+ let _hasAggSelect = 0;
389
+ const aggSelect = {};
390
+ let hasAggUnselect = 0;
391
+ const aggUnselect = {};
392
+ for (const { relation: type, as, foreignField, localField, table, unselect } of this._lookups) {
393
+ const letName = `let${gid++}`;
394
+ let pipeline = dbAgg.pipeline();
395
+ pipeline = pipeline.match({ $expr: { $and: [type === "n:1" ? { $in: [`$${foreignField}`, `$$${letName}`] } : { $eq: [`$${foreignField}`, `$$${letName}`] }] } });
396
+ pipeline = table._endAggregate(pipeline);
397
+ pipeline = pipeline.done();
398
+ returnAggRef = returnAggRef.lookup({
399
+ let: { [letName]: `$${localField}` },
400
+ as,
401
+ from: table.table,
402
+ pipeline
403
+ });
404
+ if (type === "1:1") returnAggRef = returnAggRef.unwind({
405
+ path: `$${as}`,
406
+ preserveNullAndEmptyArrays: true
407
+ });
408
+ if (unselect) {
409
+ hasAggUnselect++;
410
+ aggUnselect[as] = false;
411
+ } else {
412
+ _hasAggSelect++;
413
+ aggSelect[as] = true;
414
+ }
415
+ this._lookupAs[as] = true;
416
+ }
417
+ if (this._hasWhere) returnAggRef = returnAggRef.match(_mapCommandRaw(this._where));
418
+ if (this._hasOrder) returnAggRef = returnAggRef.sort(objectMap(this._order, (v) => v === "asc" ? 1 : -1));
419
+ if (this._hasSkip) returnAggRef = returnAggRef.skip(this._skip);
420
+ if (this._hasLimit) returnAggRef = returnAggRef.limit(this._limit);
421
+ if (this._hasSelect) returnAggRef = returnAggRef.project(_mergeSelect({
422
+ ...this._select,
423
+ ...aggSelect
424
+ }, this._order));
425
+ else if (hasAggUnselect) returnAggRef = returnAggRef.project(aggUnselect);
426
+ return returnAggRef;
427
+ }
428
+ _endHost(action) {
429
+ if (this._hasWhere) if ((action === "update" || action === "remove") && this._isTransaction) this._host = this._host.doc(this._where._id);
430
+ else this._host = this._host.where(_mapCommandRaw(this._where));
431
+ if (this._hasSelect) this._host = this._host.field(_mergeSelect(this._select, this._order));
432
+ if (this._hasOrder) objectEach(this._order, (val, key) => {
433
+ this._host = this._host.orderBy(key, val);
434
+ });
435
+ if (this._hasSkip) this._host = this._host.skip(this._skip);
436
+ if (this._hasLimit && action === "query") this._host = this._host.limit(this._limit);
437
+ else if (this._hasWhereId && action === "query") this._host = this._host.limit(1);
438
+ }
439
+ /**
440
+ * 执行查询操作
441
+ * @returns 查询结果
442
+ */
443
+ async many() {
444
+ try {
445
+ if (this._isTransaction) throw new Error("db.many() 方法不支持事务模式");
446
+ let res;
447
+ if (this._hasLookup) {
448
+ const aggRef = this.aggregate();
449
+ this._endAggregate(aggRef);
450
+ res = await aggRef.end();
451
+ } else {
452
+ this._endHost("query");
453
+ res = await this._host.get();
454
+ }
455
+ const { data } = parseDatabaseOutput(res);
456
+ return data;
457
+ } catch (err) {
458
+ const dbErr = err;
459
+ throw this._options.parseError?.(dbErr) || dbErr;
460
+ }
461
+ }
462
+ /**
463
+ * 只查询一条,自动添加 limit(1) 条件
464
+ * 如果没有匹配到记录,会抛出错误
465
+ * @returns 查询结果
466
+ */
467
+ async firstOrThrow() {
468
+ if (this._isTransaction) throw new Error("db.firstOrThrow() 方法不支持事务模式");
469
+ if (this._hasLimit) throw new Error("db.firstOrThrow() 方法不支持 limit 条件");
470
+ if (!this._hasWhereId) this.limit(1);
471
+ const res = (await this.many()).at(0);
472
+ if (!res) throw createCloudObjectError("查询数据为空", "firstOrThrow");
473
+ return res;
474
+ }
475
+ /**
476
+ * 只查询一条,自动添加 limit(1) 条件
477
+ * 如果没有匹配到记录,返回 null
478
+ * @returns 查询结果或 null
479
+ */
480
+ async firstOrNull() {
481
+ if (this._isTransaction) throw new Error("db.firstOrNull() 方法不支持事务模式");
482
+ if (this._hasLimit) throw new Error("db.firstOrNull() 方法不支持 limit 条件");
483
+ if (!this._hasWhereId) this.limit(1);
484
+ return (await this.many()).at(0) || null;
485
+ }
486
+ /**
487
+ * 获取匹配记录的数量
488
+ * @returns 记录总数
489
+ */
490
+ async count() {
491
+ if (this._isTransaction) throw new Error("db.count() 方法不支持事务模式");
492
+ if (this._hasLookup) throw new Error("db.count() 方法不支持 lookup 聚合");
493
+ if (this._hasSelect) throw new Error("db.count() 方法不支持 select 条件");
494
+ if (this._hasOrder) throw new Error("db.count() 方法不支持 order 条件");
495
+ if (this._hasSkip) throw new Error("db.count() 方法不支持 skip 条件");
496
+ if (this._hasLimit) throw new Error("db.count() 方法不支持 limit 条件");
497
+ try {
498
+ this._endHost("count");
499
+ const { total } = parseDatabaseOutput(await this._host.count());
500
+ return total;
501
+ } catch (err) {
502
+ const dbErr = err;
503
+ throw this._options.parseError?.(dbErr) || dbErr;
504
+ }
505
+ }
506
+ /**
507
+ * 创建新记录
508
+ * @param data 要创建的数据
509
+ * @returns 创建结果
510
+ */
511
+ async create(data) {
512
+ if (this._hasLookup) throw new Error("db.create() 方法不支持 lookup 聚合");
513
+ if (this._hasWhere) throw new Error("db.create() 方法不支持 where 条件");
514
+ if (this._hasSelect) throw new Error("db.create() 方法不支持 select 条件");
515
+ if (this._hasOrder) throw new Error("db.create() 方法不支持 order 条件");
516
+ if (this._hasSkip) throw new Error("db.create() 方法不支持 skip 条件");
517
+ if (this._hasLimit) throw new Error("db.create() 方法不支持 limit 条件");
518
+ try {
519
+ this._endHost("create");
520
+ const { id } = parseDatabaseOutput(await this._host.add(data));
521
+ return id;
522
+ } catch (err) {
523
+ const dbErr = err;
524
+ throw this._options.parseError?.(dbErr) || dbErr;
525
+ }
526
+ }
527
+ /**
528
+ * 更新记录
529
+ * @param data 要更新的数据
530
+ * @returns 更新结果
531
+ */
532
+ async update(data) {
533
+ if (this._hasLookup) throw new Error("db.update() 方法不支持 lookup 聚合");
534
+ if (!this._hasWhere) throw new Error("设置 where 条件后才能执行 db.update() 方法");
535
+ if (this._hasSelect) throw new Error("db.update() 方法不支持 select 条件");
536
+ if (this._hasOrder) throw new Error("db.update() 方法不支持 order 条件");
537
+ if (this._hasSkip) throw new Error("db.update() 方法不支持 skip 条件");
538
+ if (this._hasLimit) throw new Error("db.update() 方法不支持 limit 条件");
539
+ if (this._isTransaction && !this._hasWhereId) throw new Error("事务模式下 db.update() 的 where 条件必须是 _id");
540
+ try {
541
+ this._endHost("update");
542
+ const { updated } = parseDatabaseOutput(await this._host.update(objectOmit(_mapCommandRaw(data), ["_id"])));
543
+ return updated;
544
+ } catch (err) {
545
+ const dbErr = err;
546
+ throw this._options.parseError?.(dbErr) || dbErr;
547
+ }
548
+ }
549
+ /**
550
+ * 删除记录
551
+ * @returns 删除结果
552
+ */
553
+ async remove() {
554
+ if (this._hasLookup) throw new Error("db.remove() 方法不支持 lookup 聚合");
555
+ if (!this._hasWhere) throw new Error("设置 where 条件后才能执行 db.remove() 方法");
556
+ if (this._hasSelect) throw new Error("db.remove() 方法不支持 select 条件");
557
+ if (this._hasOrder) throw new Error("db.remove() 方法不支持 order 条件");
558
+ if (this._hasSkip) throw new Error("db.remove() 方法不支持 skip 条件");
559
+ if (this._hasLimit) throw new Error("db.remove() 方法不支持 limit 条件");
560
+ if (this._isTransaction && !this._hasWhereId) throw new Error("事务模式下 db.remove() 的 where 条件必须是 _id");
561
+ try {
562
+ this._endHost("remove");
563
+ const { deleted } = parseDatabaseOutput(await this._host.remove());
564
+ return deleted;
565
+ } catch (err) {
566
+ const dbErr = err;
567
+ throw this._options.parseError?.(dbErr) || dbErr;
568
+ }
569
+ }
570
+ };
534
571
  function _toWhereMethod(whereFrom) {
535
- return whereFrom === "where" ? "where({...})" : "whereId(id)";
572
+ return whereFrom === "where" ? "where({...})" : "whereId(id)";
536
573
  }
537
574
  function _toWhereIdMethod(whereFrom) {
538
- return whereFrom === "where" ? "where({ _id })" : "whereId(id)";
575
+ return whereFrom === "where" ? "where({ _id })" : "whereId(id)";
539
576
  }
540
577
  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);
578
+ const map = (val) => {
579
+ if (!isObject(val)) return val;
580
+ if (val instanceof DbBaseCommand) return DbBaseCommand.getValue(val, db0);
581
+ return objectMap(val, map);
582
+ };
583
+ return objectMap(data, map);
547
584
  }
548
585
  function _mapOrderSelect(order) {
549
- return objectMap(order, (val, key) => true);
586
+ return objectMap(order, (_val, _key) => true);
550
587
  }
551
588
  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
- };
589
+ if (Object.keys(select).length === 0) return select;
590
+ if (Object.keys(select).length === 1 && "_id" in select && select._id === false) return select;
591
+ return {
592
+ ...select,
593
+ ..._mapOrderSelect(order)
594
+ };
560
595
  }
596
+ //#endregion
597
+ //#region src/database/proxy.ts
598
+ /**
599
+ * 创建一个数据库代理对象,用于延迟实例化数据库操作类
600
+ * @template D1 - 主表数据
601
+ * @template S1 - 主表筛选
602
+ * @param name - 数据库表名
603
+ * @returns 返回一个代理对象,该对象会将属性访问转发到实际的数据库操作实例
604
+ */
561
605
  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
- );
606
+ return new Proxy({}, { get(_target, prop) {
607
+ if (prop === "_isProxy") return true;
608
+ const table = new Db({
609
+ table: name,
610
+ ...options
611
+ });
612
+ const ref = table[prop];
613
+ return isFunction(ref) ? ref.bind(table) : ref;
614
+ } });
615
+ }
616
+ //#endregion
617
+ //#region src/database/transaction.ts
618
+ /**
619
+ * 在数据库事务中执行操作
620
+ *
621
+ * @template K - 事务操作返回值类型
622
+ * @param transacting - 事务执行函数,接收事务数据库实例作为参数
623
+ * @param _mockDatabase - 用于测试的模拟数据库对象
624
+ * @param _mockDbInstance - 用于测试的模拟数据库实例
625
+ * @returns 事务操作的返回结果
626
+ *
627
+ * @example
628
+ * ```typescript
629
+ * const result = await dbTransaction(async (withTransaction) => {
630
+ * const userId = await withTransaction(db.table('user')).create({ name: 'John' });
631
+ * const order = await withTransaction(db.table('orders')).create({ userId, amount: 100 });
632
+ * return { user, order };
633
+ * });
634
+ * ```
635
+ */
636
+ async function dbTransaction(transacting, _mockDatabase, _mockDbInstance) {
637
+ const [err1, transaction] = await tryFlatten((_mockDatabase || uniCloud.database()).startTransaction());
638
+ if (err1) throw err1;
639
+ const withTransaction = (db) => {
640
+ return _mockDbInstance || new Db({
641
+ ...db.options,
642
+ transaction
643
+ });
644
+ };
645
+ const [err2, result] = await tryFlatten(async () => {
646
+ const result = await transacting(withTransaction);
647
+ await transaction.commit();
648
+ return result;
649
+ });
650
+ if (err2) {
651
+ await tryFlatten(transaction.rollback());
652
+ throw err2;
653
+ }
654
+ return result;
574
655
  }
656
+ //#endregion
657
+ //#region src/database/upsert.ts
575
658
  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 };
659
+ const { create, update, onBeforeCreate, onAfterCreate, onBeforeUpdate, onAfterUpdate, _mockDbInstance } = options;
660
+ const _mutateDb = _mockDbInstance || db.clone();
661
+ const exist = await (_mockDbInstance || db.clone(true)).where(db.getWhere(true)).firstOrNull();
662
+ if (exist) {
663
+ if (await onBeforeUpdate?.(exist) === false) return {
664
+ id: exist._id,
665
+ updated: false,
666
+ created: false
667
+ };
668
+ const updateData = isFunction(update) ? update(exist) : update;
669
+ await _mutateDb.whereId(exist._id).update(updateData);
670
+ onAfterUpdate?.(updateData, exist);
671
+ return {
672
+ id: exist._id,
673
+ updated: true,
674
+ created: false
675
+ };
676
+ }
677
+ await onBeforeCreate?.();
678
+ const createdId = await _mutateDb.create(create);
679
+ await onAfterCreate?.(createdId);
680
+ return {
681
+ id: createdId,
682
+ updated: false,
683
+ created: true
684
+ };
594
685
  }
686
+ //#endregion
687
+ //#region src/database/unique.ts
595
688
  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;
621
- }
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
- };
689
+ const { id, created } = await dbUpsert(db, {
690
+ ...options,
691
+ update: {},
692
+ onBeforeUpdate: () => false
693
+ });
694
+ return {
695
+ id,
696
+ created
697
+ };
631
698
  }
632
- export {
633
- dbMutate,
634
- dbPaging,
635
- dbProxy,
636
- dbQuery,
637
- dbTransaction,
638
- dbUnique,
639
- dbUpsert,
640
- parseDatabaseOutput
641
- };
642
- //# sourceMappingURL=database.mjs.map
699
+ //#endregion
700
+ export { dbEach, dbMutate, dbPaging, dbProxy, dbQuery, dbTransaction, dbUnique, dbUpsert, parseDatabaseOutput };
701
+
702
+ //# sourceMappingURL=database.mjs.map