monsqlize 1.3.1 → 2.0.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.
Files changed (113) hide show
  1. package/CHANGELOG.md +415 -146
  2. package/LICENSE +201 -21
  3. package/README.md +537 -928
  4. package/changelogs/README.md +160 -0
  5. package/changelogs/v2.0.0.md +222 -0
  6. package/dist/cjs/index.cjs +10600 -0
  7. package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
  8. package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
  9. package/dist/cjs/transaction/Transaction.cjs +158 -0
  10. package/dist/cjs/transaction/TransactionManager.cjs +298 -0
  11. package/dist/esm/index.mjs +10650 -0
  12. package/dist/types/base.d.ts +81 -0
  13. package/dist/types/collection.d.ts +1031 -0
  14. package/dist/types/expression.d.ts +115 -0
  15. package/dist/types/index.d.ts +23 -0
  16. package/dist/types/lock.d.ts +74 -0
  17. package/dist/types/model.d.ts +526 -0
  18. package/dist/types/mongodb.d.ts +49 -0
  19. package/dist/types/monsqlize.d.ts +491 -0
  20. package/dist/types/pool.d.ts +84 -0
  21. package/dist/types/runtime.d.ts +362 -0
  22. package/dist/types/saga.d.ts +143 -0
  23. package/dist/types/slow-query-log.d.ts +126 -0
  24. package/dist/types/sync.d.ts +103 -0
  25. package/dist/types/transaction.d.ts +132 -0
  26. package/package.json +69 -67
  27. package/index.d.ts +0 -1289
  28. package/lib/cache.js +0 -491
  29. package/lib/common/cursor.js +0 -58
  30. package/lib/common/docs-urls.js +0 -72
  31. package/lib/common/index-options.js +0 -222
  32. package/lib/common/log.js +0 -60
  33. package/lib/common/namespace.js +0 -21
  34. package/lib/common/normalize.js +0 -33
  35. package/lib/common/page-result.js +0 -42
  36. package/lib/common/runner.js +0 -56
  37. package/lib/common/server-features.js +0 -231
  38. package/lib/common/shape-builders.js +0 -26
  39. package/lib/common/validation.js +0 -112
  40. package/lib/connect.js +0 -76
  41. package/lib/constants.js +0 -54
  42. package/lib/count-queue.js +0 -187
  43. package/lib/distributed-cache-invalidator.js +0 -259
  44. package/lib/errors.js +0 -167
  45. package/lib/index.js +0 -461
  46. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -211
  47. package/lib/infrastructure/ssh-tunnel.js +0 -40
  48. package/lib/infrastructure/uri-parser.js +0 -35
  49. package/lib/lock/Lock.js +0 -66
  50. package/lib/lock/errors.js +0 -27
  51. package/lib/lock/index.js +0 -12
  52. package/lib/logger.js +0 -224
  53. package/lib/model/examples/test.js +0 -114
  54. package/lib/mongodb/common/accessor-helpers.js +0 -58
  55. package/lib/mongodb/common/agg-pipeline.js +0 -32
  56. package/lib/mongodb/common/iid.js +0 -27
  57. package/lib/mongodb/common/lexicographic-expr.js +0 -52
  58. package/lib/mongodb/common/shape.js +0 -31
  59. package/lib/mongodb/common/sort.js +0 -38
  60. package/lib/mongodb/common/transaction-aware.js +0 -24
  61. package/lib/mongodb/connect.js +0 -233
  62. package/lib/mongodb/index.js +0 -591
  63. package/lib/mongodb/management/admin-ops.js +0 -199
  64. package/lib/mongodb/management/bookmark-ops.js +0 -166
  65. package/lib/mongodb/management/cache-ops.js +0 -49
  66. package/lib/mongodb/management/collection-ops.js +0 -386
  67. package/lib/mongodb/management/database-ops.js +0 -201
  68. package/lib/mongodb/management/index-ops.js +0 -474
  69. package/lib/mongodb/management/index.js +0 -16
  70. package/lib/mongodb/management/namespace.js +0 -30
  71. package/lib/mongodb/management/validation-ops.js +0 -267
  72. package/lib/mongodb/queries/aggregate.js +0 -142
  73. package/lib/mongodb/queries/chain.js +0 -630
  74. package/lib/mongodb/queries/count.js +0 -98
  75. package/lib/mongodb/queries/distinct.js +0 -77
  76. package/lib/mongodb/queries/find-and-count.js +0 -192
  77. package/lib/mongodb/queries/find-by-ids.js +0 -235
  78. package/lib/mongodb/queries/find-one-by-id.js +0 -170
  79. package/lib/mongodb/queries/find-one.js +0 -70
  80. package/lib/mongodb/queries/find-page.js +0 -577
  81. package/lib/mongodb/queries/find.js +0 -170
  82. package/lib/mongodb/queries/index.js +0 -50
  83. package/lib/mongodb/queries/watch.js +0 -537
  84. package/lib/mongodb/writes/delete-many.js +0 -190
  85. package/lib/mongodb/writes/delete-one.js +0 -182
  86. package/lib/mongodb/writes/find-one-and-delete.js +0 -202
  87. package/lib/mongodb/writes/find-one-and-replace.js +0 -238
  88. package/lib/mongodb/writes/find-one-and-update.js +0 -239
  89. package/lib/mongodb/writes/increment-one.js +0 -252
  90. package/lib/mongodb/writes/index.js +0 -41
  91. package/lib/mongodb/writes/insert-batch.js +0 -507
  92. package/lib/mongodb/writes/insert-many.js +0 -227
  93. package/lib/mongodb/writes/insert-one.js +0 -180
  94. package/lib/mongodb/writes/replace-one.js +0 -215
  95. package/lib/mongodb/writes/result-handler.js +0 -236
  96. package/lib/mongodb/writes/update-many.js +0 -221
  97. package/lib/mongodb/writes/update-one.js +0 -223
  98. package/lib/mongodb/writes/upsert-one.js +0 -206
  99. package/lib/multi-level-cache.js +0 -189
  100. package/lib/operators.js +0 -330
  101. package/lib/redis-cache-adapter.js +0 -237
  102. package/lib/slow-query-log/base-storage.js +0 -69
  103. package/lib/slow-query-log/batch-queue.js +0 -96
  104. package/lib/slow-query-log/config-manager.js +0 -195
  105. package/lib/slow-query-log/index.js +0 -237
  106. package/lib/slow-query-log/mongodb-storage.js +0 -323
  107. package/lib/slow-query-log/query-hash.js +0 -38
  108. package/lib/transaction/CacheLockManager.js +0 -161
  109. package/lib/transaction/DistributedCacheLockManager.js +0 -474
  110. package/lib/transaction/Transaction.js +0 -314
  111. package/lib/transaction/TransactionManager.js +0 -266
  112. package/lib/transaction/index.js +0 -10
  113. package/lib/utils/objectid-converter.js +0 -566
@@ -1,630 +0,0 @@
1
- /**
2
- * 链式调用构建器
3
- * @description 提供 MongoDB 风格的链式调用 API,最终执行时会合并所有选项并利用缓存
4
- */
5
-
6
- const { createErrorMessage } = require('../../common/docs-urls');
7
- const { convertObjectIdStrings, convertAggregationPipeline } = require('../../utils/objectid-converter');
8
-
9
- /**
10
- * FindChain 类 - find 查询的链式调用构建器
11
- */
12
- class FindChain {
13
- /**
14
- * 创建 FindChain 实例
15
- * @param {Object} context - 上下文对象
16
- * @param {Object} context.collection - MongoDB 集合实例
17
- * @param {Object} context.defaults - 默认配置
18
- * @param {Function} context.run - 缓存执行器
19
- * @param {string} context.instanceId - 实例ID
20
- * @param {string} context.effectiveDbName - 数据库名
21
- * @param {Object} context.logger - 日志器
22
- * @param {Function} context.emit - 事件发射器
23
- * @param {Object} context.mongoSlowLogShaper - 慢查询日志格式化器
24
- * @param {Object} query - 查询条件
25
- * @param {Object} initialOptions - 初始查询选项
26
- */
27
- constructor(context, query = {}, initialOptions = {}) {
28
- this._context = context;
29
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
30
- this._query = convertObjectIdStrings(query, 'filter', 0, new WeakSet(), {
31
- logger: context.logger,
32
- excludeFields: context.autoConvertConfig?.excludeFields,
33
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
34
- maxDepth: context.autoConvertConfig?.maxDepth
35
- });
36
- this._options = { ...initialOptions };
37
- this._executed = false;
38
- }
39
-
40
- /**
41
- * 设置返回文档数量限制
42
- * @param {number} value - 限制数量
43
- * @returns {FindChain} 返回自身以支持链式调用
44
- */
45
- limit(value) {
46
- if (this._executed) {
47
- throw new Error(createErrorMessage(
48
- 'Cannot call .limit() after query execution.\n' +
49
- 'Tip: Create a new chain for another query:\n' +
50
- " const results = await collection('products').find({}).limit(10);",
51
- 'chaining.limit'
52
- ));
53
- }
54
- if (typeof value !== 'number' || value < 0) {
55
- throw new Error(createErrorMessage(
56
- `limit() requires a non-negative number, got: ${typeof value} (${value})\n` +
57
- 'Usage: .limit(10)',
58
- 'chaining.limit'
59
- ));
60
- }
61
- this._options.limit = value;
62
- return this;
63
- }
64
-
65
- /**
66
- * 设置跳过的文档数量
67
- * @param {number} value - 跳过数量
68
- * @returns {FindChain} 返回自身以支持链式调用
69
- */
70
- skip(value) {
71
- if (this._executed) {
72
- throw new Error(createErrorMessage(
73
- 'Cannot call .skip() after query execution.\n' +
74
- 'Tip: Create a new chain for another query.',
75
- 'chaining.skip'
76
- ));
77
- }
78
- if (typeof value !== 'number' || value < 0) {
79
- throw new Error(createErrorMessage(
80
- `skip() requires a non-negative number, got: ${typeof value} (${value})\n` +
81
- 'Usage: .skip(10)',
82
- 'chaining.skip'
83
- ));
84
- }
85
- this._options.skip = value;
86
- return this;
87
- }
88
-
89
- /**
90
- * 设置排序规则
91
- * @param {Object|Array} value - 排序配置,如 { field: 1 } 或 [['field', 1]]
92
- * @returns {FindChain} 返回自身以支持链式调用
93
- */
94
- sort(value) {
95
- if (this._executed) {
96
- throw new Error(createErrorMessage(
97
- 'Cannot call .sort() after query execution.',
98
- 'chaining.sort'
99
- ));
100
- }
101
- if (!value || (typeof value !== 'object')) {
102
- throw new Error(createErrorMessage(
103
- `sort() requires an object or array, got: ${typeof value}\n` +
104
- 'Usage: .sort({ price: -1, name: 1 })\n' +
105
- 'Note: Use 1 for ascending, -1 for descending',
106
- 'chaining.sort'
107
- ));
108
- }
109
- this._options.sort = value;
110
- return this;
111
- }
112
-
113
- /**
114
- * 设置字段投影
115
- * @param {Object|Array} value - 投影配置
116
- * @returns {FindChain} 返回自身以支持链式调用
117
- */
118
- project(value) {
119
- if (this._executed) {
120
- throw new Error(createErrorMessage(
121
- 'Cannot call .project() after query execution.',
122
- 'chaining.project'
123
- ));
124
- }
125
- if (!value || typeof value !== 'object') {
126
- throw new Error(createErrorMessage(
127
- `project() requires an object or array, got: ${typeof value}\n` +
128
- 'Usage: .project({ name: 1, price: 1 })',
129
- 'chaining.project'
130
- ));
131
- }
132
- this._options.projection = value;
133
- return this;
134
- }
135
-
136
- /**
137
- * 设置索引提示
138
- * @param {Object|string} value - 索引名称或索引规格
139
- * @returns {FindChain} 返回自身以支持链式调用
140
- */
141
- hint(value) {
142
- if (this._executed) {
143
- throw new Error(createErrorMessage(
144
- 'Cannot call .hint() after query execution.',
145
- 'chaining.hint'
146
- ));
147
- }
148
- if (!value) {
149
- throw new Error(createErrorMessage(
150
- 'hint() requires an index name or specification\n' +
151
- 'Usage: .hint({ category: 1, price: -1 }) or .hint(\'category_1_price_-1\')',
152
- 'chaining.hint'
153
- ));
154
- }
155
- this._options.hint = value;
156
- return this;
157
- }
158
-
159
- /**
160
- * 设置排序规则
161
- * @param {Object} value - 排序规则配置
162
- * @returns {FindChain} 返回自身以支持链式调用
163
- */
164
- collation(value) {
165
- if (this._executed) {
166
- throw new Error(createErrorMessage(
167
- 'Cannot call .collation() after query execution.',
168
- 'chaining.collation'
169
- ));
170
- }
171
- if (!value || typeof value !== 'object') {
172
- throw new Error(createErrorMessage(
173
- `collation() requires an object, got: ${typeof value}\n` +
174
- 'Usage: .collation({ locale: \'zh\', strength: 2 })',
175
- 'chaining.collation'
176
- ));
177
- }
178
- this._options.collation = value;
179
- return this;
180
- }
181
-
182
- /**
183
- * 设置查询注释
184
- * @param {string} value - 注释内容
185
- * @returns {FindChain} 返回自身以支持链式调用
186
- */
187
- comment(value) {
188
- if (this._executed) {
189
- throw new Error(createErrorMessage(
190
- 'Cannot call .comment() after query execution.',
191
- 'chaining.comment'
192
- ));
193
- }
194
- if (typeof value !== 'string') {
195
- throw new Error(createErrorMessage(
196
- `comment() requires a string, got: ${typeof value}\n` +
197
- 'Usage: .comment(\'UserAPI:getProducts:user_123\')',
198
- 'chaining.comment'
199
- ));
200
- }
201
- this._options.comment = value;
202
- return this;
203
- }
204
-
205
- /**
206
- * 设置查询超时时间
207
- * @param {number} value - 超时时间(毫秒)
208
- * @returns {FindChain} 返回自身以支持链式调用
209
- */
210
- maxTimeMS(value) {
211
- if (this._executed) {
212
- throw new Error(createErrorMessage(
213
- 'Cannot call .maxTimeMS() after query execution.',
214
- 'chaining.maxTimeMS'
215
- ));
216
- }
217
- if (typeof value !== 'number' || value < 0) {
218
- throw new Error(createErrorMessage(
219
- `maxTimeMS() requires a non-negative number, got: ${typeof value} (${value})\n` +
220
- 'Usage: .maxTimeMS(5000) // 5 seconds',
221
- 'chaining.maxTimeMS'
222
- ));
223
- }
224
- this._options.maxTimeMS = value;
225
- return this;
226
- }
227
-
228
- /**
229
- * 设置批处理大小
230
- * @param {number} value - 批处理大小
231
- * @returns {FindChain} 返回自身以支持链式调用
232
- */
233
- batchSize(value) {
234
- if (this._executed) {
235
- throw new Error(createErrorMessage(
236
- 'Cannot call .batchSize() after query execution.',
237
- 'chaining.batchSize'
238
- ));
239
- }
240
- if (typeof value !== 'number' || value < 0) {
241
- throw new Error(createErrorMessage(
242
- `batchSize() requires a non-negative number, got: ${typeof value} (${value})\n` +
243
- 'Usage: .batchSize(1000)',
244
- 'chaining.batchSize'
245
- ));
246
- }
247
- this._options.batchSize = value;
248
- return this;
249
- }
250
-
251
- /**
252
- * 返回查询执行计划
253
- * @param {string} [verbosity='queryPlanner'] - 详细级别
254
- * @returns {Promise<Object>} 执行计划
255
- */
256
- async explain(verbosity = 'queryPlanner') {
257
- const { normalizeProjection, normalizeSort } = require('../../common/normalize');
258
- const { collection, defaults } = this._context;
259
-
260
- // 标准化选项
261
- const projection = normalizeProjection(this._options.projection);
262
- const sort = normalizeSort(this._options.sort);
263
- const limit = this._options.limit !== undefined ? this._options.limit : defaults.findLimit;
264
- const skip = this._options.skip;
265
- const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
266
-
267
- const driverOpts = { projection, sort, skip, maxTimeMS };
268
- if (this._options.hint) driverOpts.hint = this._options.hint;
269
- if (this._options.collation) driverOpts.collation = this._options.collation;
270
- if (limit !== undefined) driverOpts.limit = limit;
271
- if (this._options.batchSize !== undefined) driverOpts.batchSize = this._options.batchSize;
272
- if (this._options.comment) driverOpts.comment = this._options.comment;
273
-
274
- const cursor = collection.find(this._query, driverOpts);
275
- return cursor.explain(verbosity);
276
- }
277
-
278
- /**
279
- * 返回流式结果
280
- * @returns {ReadableStream} MongoDB 游标流
281
- */
282
- stream() {
283
- const { normalizeProjection, normalizeSort } = require('../../common/normalize');
284
- const { collection, defaults } = this._context;
285
-
286
- // 标准化选项
287
- const projection = normalizeProjection(this._options.projection);
288
- const sort = normalizeSort(this._options.sort);
289
- const limit = this._options.limit !== undefined ? this._options.limit : defaults.findLimit;
290
- const skip = this._options.skip;
291
- const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
292
-
293
- const driverOpts = { projection, sort, skip, maxTimeMS };
294
- if (this._options.hint) driverOpts.hint = this._options.hint;
295
- if (this._options.collation) driverOpts.collation = this._options.collation;
296
- if (limit !== undefined) driverOpts.limit = limit;
297
- if (this._options.batchSize !== undefined) driverOpts.batchSize = this._options.batchSize;
298
- if (this._options.comment) driverOpts.comment = this._options.comment;
299
-
300
- const cursor = collection.find(this._query, driverOpts);
301
- return cursor.stream();
302
- }
303
-
304
- /**
305
- * 执行查询并返回结果数组
306
- * @returns {Promise<Array>} 查询结果数组
307
- */
308
- async toArray() {
309
- if (this._executed) {
310
- throw new Error(createErrorMessage(
311
- 'Query already executed. Create a new chain for another query.\n' +
312
- 'Tip: Each chain can only be executed once:\n' +
313
- " const results1 = await collection('products').find({}).limit(10);\n" +
314
- " const results2 = await collection('products').find({}).limit(20); // Create new chain",
315
- 'chaining.toArray'
316
- ));
317
- }
318
-
319
- const { normalizeProjection, normalizeSort } = require('../../common/normalize');
320
- const { collection, defaults, run } = this._context;
321
-
322
- // 标准化选项
323
- this._options.projection = normalizeProjection(this._options.projection);
324
- const sort = normalizeSort(this._options.sort);
325
- const limit = this._options.limit !== undefined ? this._options.limit : defaults.findLimit;
326
- const skip = this._options.skip;
327
- const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
328
-
329
- const driverOpts = {
330
- projection: this._options.projection,
331
- sort,
332
- skip,
333
- maxTimeMS
334
- };
335
- if (this._options.hint) driverOpts.hint = this._options.hint;
336
- if (this._options.collation) driverOpts.collation = this._options.collation;
337
- if (limit !== undefined) driverOpts.limit = limit;
338
- if (this._options.batchSize !== undefined) driverOpts.batchSize = this._options.batchSize;
339
- if (this._options.comment) driverOpts.comment = this._options.comment;
340
-
341
- this._executed = true;
342
-
343
- // 使用 run 执行器(支持缓存)
344
- return run(
345
- 'find',
346
- { query: this._query, ...this._options },
347
- async () => collection.find(this._query, driverOpts).toArray()
348
- );
349
- }
350
-
351
- /**
352
- * 使 FindChain 可以作为 Promise 使用
353
- * @returns {Promise<Array>} 查询结果数组
354
- */
355
- then(resolve, reject) {
356
- return this.toArray().then(resolve, reject);
357
- }
358
-
359
- /**
360
- * 支持 catch 方法
361
- */
362
- catch(reject) {
363
- return this.toArray().catch(reject);
364
- }
365
-
366
- /**
367
- * 支持 finally 方法
368
- */
369
- finally(fn) {
370
- return this.toArray().finally(fn);
371
- }
372
- }
373
-
374
- /**
375
- * AggregateChain 类 - aggregate 查询的链式调用构建器
376
- */
377
- class AggregateChain {
378
- /**
379
- * 创建 AggregateChain 实例
380
- * @param {Object} context - 上下文对象
381
- * @param {Array} pipeline - 聚合管道
382
- * @param {Object} initialOptions - 初始选项
383
- */
384
- constructor(context, pipeline = [], initialOptions = {}) {
385
- this._context = context;
386
- this._pipeline = pipeline;
387
- this._options = { ...initialOptions };
388
- this._executed = false;
389
- }
390
-
391
- /**
392
- * 设置索引提示
393
- * @param {Object|string} value - 索引名称或索引规格
394
- * @returns {AggregateChain} 返回自身以支持链式调用
395
- */
396
- hint(value) {
397
- if (this._executed) {
398
- throw new Error(createErrorMessage(
399
- 'Cannot call .hint() after query execution.',
400
- 'chaining.hint'
401
- ));
402
- }
403
- if (!value) {
404
- throw new Error(createErrorMessage(
405
- 'hint() requires an index name or specification\n' +
406
- 'Usage: .hint({ status: 1, createdAt: -1 })',
407
- 'chaining.hint'
408
- ));
409
- }
410
- this._options.hint = value;
411
- return this;
412
- }
413
-
414
- /**
415
- * 设置排序规则
416
- * @param {Object} value - 排序规则配置
417
- * @returns {AggregateChain} 返回自身以支持链式调用
418
- */
419
- collation(value) {
420
- if (this._executed) {
421
- throw new Error(createErrorMessage(
422
- 'Cannot call .collation() after query execution.',
423
- 'chaining.collation'
424
- ));
425
- }
426
- if (!value || typeof value !== 'object') {
427
- throw new Error(createErrorMessage(
428
- `collation() requires an object, got: ${typeof value}\n` +
429
- 'Usage: .collation({ locale: \'zh\', strength: 2 })',
430
- 'chaining.collation'
431
- ));
432
- }
433
- this._options.collation = value;
434
- return this;
435
- }
436
-
437
- /**
438
- * 设置查询注释
439
- * @param {string} value - 注释内容
440
- * @returns {AggregateChain} 返回自身以支持链式调用
441
- */
442
- comment(value) {
443
- if (this._executed) {
444
- throw new Error(createErrorMessage(
445
- 'Cannot call .comment() after query execution.',
446
- 'chaining.comment'
447
- ));
448
- }
449
- if (typeof value !== 'string') {
450
- throw new Error(createErrorMessage(
451
- `comment() requires a string, got: ${typeof value}\n` +
452
- 'Usage: .comment(\'OrderAPI:aggregateSales\')',
453
- 'chaining.comment'
454
- ));
455
- }
456
- this._options.comment = value;
457
- return this;
458
- }
459
-
460
- /**
461
- * 设置查询超时时间
462
- * @param {number} value - 超时时间(毫秒)
463
- * @returns {AggregateChain} 返回自身以支持链式调用
464
- */
465
- maxTimeMS(value) {
466
- if (this._executed) {
467
- throw new Error(createErrorMessage(
468
- 'Cannot call .maxTimeMS() after query execution.',
469
- 'chaining.maxTimeMS'
470
- ));
471
- }
472
- if (typeof value !== 'number' || value < 0) {
473
- throw new Error(createErrorMessage(
474
- `maxTimeMS() requires a non-negative number, got: ${typeof value} (${value})\n` +
475
- 'Usage: .maxTimeMS(10000) // 10 seconds',
476
- 'chaining.maxTimeMS'
477
- ));
478
- }
479
- this._options.maxTimeMS = value;
480
- return this;
481
- }
482
-
483
- /**
484
- * 设置是否允许使用磁盘
485
- * @param {boolean} value - 是否允许
486
- * @returns {AggregateChain} 返回自身以支持链式调用
487
- */
488
- allowDiskUse(value) {
489
- if (this._executed) {
490
- throw new Error(createErrorMessage(
491
- 'Cannot call .allowDiskUse() after query execution.',
492
- 'chaining.allowDiskUse'
493
- ));
494
- }
495
- if (typeof value !== 'boolean') {
496
- throw new Error(createErrorMessage(
497
- `allowDiskUse() requires a boolean, got: ${typeof value}\n` +
498
- 'Usage: .allowDiskUse(true)',
499
- 'chaining.allowDiskUse'
500
- ));
501
- }
502
- this._options.allowDiskUse = value;
503
- return this;
504
- }
505
-
506
- /**
507
- * 设置批处理大小
508
- * @param {number} value - 批处理大小
509
- * @returns {AggregateChain} 返回自身以支持链式调用
510
- */
511
- batchSize(value) {
512
- if (this._executed) {
513
- throw new Error(createErrorMessage(
514
- 'Cannot call .batchSize() after query execution.',
515
- 'chaining.batchSize'
516
- ));
517
- }
518
- if (typeof value !== 'number' || value < 0) {
519
- throw new Error(createErrorMessage(
520
- `batchSize() requires a non-negative number, got: ${typeof value} (${value})\n` +
521
- 'Usage: .batchSize(1000)',
522
- 'chaining.batchSize'
523
- ));
524
- }
525
- this._options.batchSize = value;
526
- return this;
527
- }
528
-
529
- /**
530
- * 返回查询执行计划
531
- * @param {string} [verbosity='queryPlanner'] - 详细级别
532
- * @returns {Promise<Object>} 执行计划
533
- */
534
- async explain(verbosity = 'queryPlanner') {
535
- const { collection, defaults } = this._context;
536
-
537
- const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
538
- const allowDiskUse = this._options.allowDiskUse !== undefined ? this._options.allowDiskUse : false;
539
-
540
- const aggOptions = { maxTimeMS, allowDiskUse };
541
- if (this._options.collation) aggOptions.collation = this._options.collation;
542
- if (this._options.hint) aggOptions.hint = this._options.hint;
543
- if (this._options.comment) aggOptions.comment = this._options.comment;
544
- if (this._options.batchSize !== undefined) aggOptions.batchSize = this._options.batchSize;
545
-
546
- const cursor = collection.aggregate(this._pipeline, aggOptions);
547
- return cursor.explain(verbosity);
548
- }
549
-
550
- /**
551
- * 返回流式结果
552
- * @returns {ReadableStream} MongoDB 游标流
553
- */
554
- stream() {
555
- const { collection, defaults } = this._context;
556
-
557
- const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
558
- const allowDiskUse = this._options.allowDiskUse !== undefined ? this._options.allowDiskUse : false;
559
-
560
- const aggOptions = { maxTimeMS, allowDiskUse };
561
- if (this._options.collation) aggOptions.collation = this._options.collation;
562
- if (this._options.hint) aggOptions.hint = this._options.hint;
563
- if (this._options.comment) aggOptions.comment = this._options.comment;
564
- if (this._options.batchSize !== undefined) aggOptions.batchSize = this._options.batchSize;
565
-
566
- const cursor = collection.aggregate(this._pipeline, aggOptions);
567
- return cursor.stream();
568
- }
569
-
570
- /**
571
- * 执行聚合并返回结果数组
572
- * @returns {Promise<Array>} 聚合结果数组
573
- */
574
- async toArray() {
575
- if (this._executed) {
576
- throw new Error(createErrorMessage(
577
- 'Query already executed. Create a new chain for another query.\n' +
578
- 'Tip: Each chain can only be executed once:\n' +
579
- " const results1 = await collection('orders').aggregate([...]).allowDiskUse(true);\n" +
580
- " const results2 = await collection('orders').aggregate([...]).maxTimeMS(5000); // Create new chain",
581
- 'chaining.toArray'
582
- ));
583
- }
584
-
585
- const { collection, defaults, run } = this._context;
586
-
587
- const maxTimeMS = this._options.maxTimeMS !== undefined ? this._options.maxTimeMS : defaults.maxTimeMS;
588
- const allowDiskUse = this._options.allowDiskUse !== undefined ? this._options.allowDiskUse : false;
589
-
590
- const aggOptions = { maxTimeMS, allowDiskUse };
591
- if (this._options.collation) aggOptions.collation = this._options.collation;
592
- if (this._options.hint) aggOptions.hint = this._options.hint;
593
- if (this._options.comment) aggOptions.comment = this._options.comment;
594
- if (this._options.batchSize !== undefined) aggOptions.batchSize = this._options.batchSize;
595
-
596
- this._executed = true;
597
-
598
- // 使用 run 执行器(支持缓存)
599
- return run(
600
- 'aggregate',
601
- this._options,
602
- async () => collection.aggregate(this._pipeline, aggOptions).toArray()
603
- );
604
- }
605
-
606
- /**
607
- * 使 AggregateChain 可以作为 Promise 使用
608
- * @returns {Promise<Array>} 聚合结果数组
609
- */
610
- then(resolve, reject) {
611
- return this.toArray().then(resolve, reject);
612
- }
613
-
614
- /**
615
- * 支持 catch 方法
616
- */
617
- catch(reject) {
618
- return this.toArray().catch(reject);
619
- }
620
-
621
- /**
622
- * 支持 finally 方法
623
- */
624
- finally(fn) {
625
- return this.toArray().finally(fn);
626
- }
627
- }
628
-
629
- module.exports = { FindChain, AggregateChain };
630
-