monsqlize 1.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 (77) hide show
  1. package/CHANGELOG.md +2474 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1368 -0
  4. package/index.d.ts +1052 -0
  5. package/lib/cache.js +491 -0
  6. package/lib/common/cursor.js +58 -0
  7. package/lib/common/docs-urls.js +72 -0
  8. package/lib/common/index-options.js +222 -0
  9. package/lib/common/log.js +60 -0
  10. package/lib/common/namespace.js +21 -0
  11. package/lib/common/normalize.js +33 -0
  12. package/lib/common/page-result.js +42 -0
  13. package/lib/common/runner.js +56 -0
  14. package/lib/common/server-features.js +231 -0
  15. package/lib/common/shape-builders.js +26 -0
  16. package/lib/common/validation.js +49 -0
  17. package/lib/connect.js +76 -0
  18. package/lib/constants.js +54 -0
  19. package/lib/count-queue.js +187 -0
  20. package/lib/distributed-cache-invalidator.js +259 -0
  21. package/lib/errors.js +157 -0
  22. package/lib/index.js +352 -0
  23. package/lib/logger.js +224 -0
  24. package/lib/model/examples/test.js +114 -0
  25. package/lib/mongodb/common/accessor-helpers.js +44 -0
  26. package/lib/mongodb/common/agg-pipeline.js +32 -0
  27. package/lib/mongodb/common/iid.js +27 -0
  28. package/lib/mongodb/common/lexicographic-expr.js +52 -0
  29. package/lib/mongodb/common/shape.js +31 -0
  30. package/lib/mongodb/common/sort.js +38 -0
  31. package/lib/mongodb/common/transaction-aware.js +24 -0
  32. package/lib/mongodb/connect.js +178 -0
  33. package/lib/mongodb/index.js +458 -0
  34. package/lib/mongodb/management/admin-ops.js +199 -0
  35. package/lib/mongodb/management/bookmark-ops.js +166 -0
  36. package/lib/mongodb/management/cache-ops.js +49 -0
  37. package/lib/mongodb/management/collection-ops.js +386 -0
  38. package/lib/mongodb/management/database-ops.js +201 -0
  39. package/lib/mongodb/management/index-ops.js +474 -0
  40. package/lib/mongodb/management/index.js +16 -0
  41. package/lib/mongodb/management/namespace.js +30 -0
  42. package/lib/mongodb/management/validation-ops.js +267 -0
  43. package/lib/mongodb/queries/aggregate.js +133 -0
  44. package/lib/mongodb/queries/chain.js +623 -0
  45. package/lib/mongodb/queries/count.js +88 -0
  46. package/lib/mongodb/queries/distinct.js +68 -0
  47. package/lib/mongodb/queries/find-and-count.js +183 -0
  48. package/lib/mongodb/queries/find-by-ids.js +235 -0
  49. package/lib/mongodb/queries/find-one-by-id.js +170 -0
  50. package/lib/mongodb/queries/find-one.js +61 -0
  51. package/lib/mongodb/queries/find-page.js +565 -0
  52. package/lib/mongodb/queries/find.js +161 -0
  53. package/lib/mongodb/queries/index.js +49 -0
  54. package/lib/mongodb/writes/delete-many.js +181 -0
  55. package/lib/mongodb/writes/delete-one.js +173 -0
  56. package/lib/mongodb/writes/find-one-and-delete.js +193 -0
  57. package/lib/mongodb/writes/find-one-and-replace.js +222 -0
  58. package/lib/mongodb/writes/find-one-and-update.js +223 -0
  59. package/lib/mongodb/writes/increment-one.js +243 -0
  60. package/lib/mongodb/writes/index.js +41 -0
  61. package/lib/mongodb/writes/insert-batch.js +498 -0
  62. package/lib/mongodb/writes/insert-many.js +218 -0
  63. package/lib/mongodb/writes/insert-one.js +171 -0
  64. package/lib/mongodb/writes/replace-one.js +199 -0
  65. package/lib/mongodb/writes/result-handler.js +236 -0
  66. package/lib/mongodb/writes/update-many.js +205 -0
  67. package/lib/mongodb/writes/update-one.js +207 -0
  68. package/lib/mongodb/writes/upsert-one.js +190 -0
  69. package/lib/multi-level-cache.js +189 -0
  70. package/lib/operators.js +330 -0
  71. package/lib/redis-cache-adapter.js +237 -0
  72. package/lib/transaction/CacheLockManager.js +161 -0
  73. package/lib/transaction/DistributedCacheLockManager.js +239 -0
  74. package/lib/transaction/Transaction.js +314 -0
  75. package/lib/transaction/TransactionManager.js +266 -0
  76. package/lib/transaction/index.js +10 -0
  77. package/package.json +111 -0
@@ -0,0 +1,243 @@
1
+ /**
2
+ * incrementOne 写操作模块
3
+ * @description 便利方法:原子递增/递减字段值
4
+ */
5
+
6
+ const { ObjectId } = require('mongodb');
7
+ const { createError, ErrorCodes } = require('../../errors');
8
+ const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
9
+ const { handleFindOneAndResult, wasDocumentModified } = require("./result-handler");
10
+
11
+ /**
12
+ * 创建 incrementOne 操作
13
+ * @param {Object} context - 上下文对象
14
+ * @returns {Function} incrementOne 方法
15
+ */
16
+ function createIncrementOneOps(context) {
17
+ const {
18
+ collection,
19
+ defaults,
20
+ instanceId,
21
+ effectiveDbName,
22
+ logger,
23
+ emit,
24
+ mongoSlowLogShaper,
25
+ cache,
26
+ type
27
+ } = context;
28
+
29
+ /**
30
+ * 原子递增/递减单个字段
31
+ * @param {Object} filter - 查询条件
32
+ * @param {string|Object} field - 字段名或字段-增量对象
33
+ * @param {number} [increment=1] - 增量(正数递增,负数递减)
34
+ * @param {Object} [options={}] - 操作选项
35
+ * @param {number} [options.maxTimeMS] - 操作超时(毫秒)
36
+ * @param {string} [options.comment] - 查询注释
37
+ * @param {boolean} [options.returnDocument='after'] - 返回文档时机('before' | 'after')
38
+ * @param {Object} [options.projection] - 字段投影
39
+ * @returns {Promise<Object>} 操作结果
40
+ *
41
+ * @example
42
+ * // 基础用法(递增 1)
43
+ * const result = await collection('users').incrementOne(
44
+ * { userId: 'user123' },
45
+ * 'loginCount'
46
+ * );
47
+ *
48
+ * @example
49
+ * // 指定增量
50
+ * const result = await collection('users').incrementOne(
51
+ * { userId: 'user123' },
52
+ * 'points',
53
+ * 10
54
+ * );
55
+ *
56
+ * @example
57
+ * // 递减(负数)
58
+ * const result = await collection('users').incrementOne(
59
+ * { userId: 'user123' },
60
+ * 'credits',
61
+ * -5
62
+ * );
63
+ *
64
+ * @example
65
+ * // 多字段递增
66
+ * const result = await collection('users').incrementOne(
67
+ * { userId: 'user123' },
68
+ * { loginCount: 1, points: 10, credits: -5 }
69
+ * );
70
+ */
71
+ const incrementOne = async function incrementOne(filter, field, increment, options) {
72
+ const startTime = Date.now();
73
+
74
+ // 1. 参数解析和验证
75
+ let actualIncrement = increment;
76
+ let actualOptions = options;
77
+
78
+ // 支持 incrementOne(filter, field, options) 形式(省略 increment,默认 1)
79
+ if (typeof increment === 'object' && increment !== null && !Array.isArray(increment) && actualOptions === undefined) {
80
+ actualOptions = increment;
81
+ actualIncrement = 1;
82
+ }
83
+
84
+ actualOptions = actualOptions || {};
85
+
86
+ if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
87
+ throw createError(
88
+ ErrorCodes.INVALID_ARGUMENT,
89
+ 'filter 必须是非空对象',
90
+ [{ field: 'filter', type: 'type', message: 'filter 必须是对象', received: typeof filter }]
91
+ );
92
+ }
93
+
94
+ // 2. 构建 $inc 更新对象
95
+ let incUpdate;
96
+
97
+ if (typeof field === 'string') {
98
+ // 单字段递增
99
+ if (actualIncrement === undefined) {
100
+ actualIncrement = 1;
101
+ }
102
+
103
+ if (typeof actualIncrement !== 'number' || isNaN(actualIncrement)) {
104
+ throw createError(
105
+ ErrorCodes.INVALID_ARGUMENT,
106
+ 'increment 必须是数字',
107
+ [{ field: 'increment', type: 'type', message: 'increment 必须是数字', received: typeof actualIncrement }]
108
+ );
109
+ }
110
+
111
+ incUpdate = { $inc: { [field]: actualIncrement } };
112
+ } else if (typeof field === 'object' && field !== null && !Array.isArray(field)) {
113
+ // 多字段递增
114
+ const incFields = {};
115
+ for (const [key, value] of Object.entries(field)) {
116
+ if (typeof value !== 'number' || isNaN(value)) {
117
+ throw createError(
118
+ ErrorCodes.INVALID_ARGUMENT,
119
+ `字段 ${key} 的增量必须是数字`,
120
+ [{ field: key, type: 'type', message: '增量必须是数字', received: typeof value }]
121
+ );
122
+ }
123
+ incFields[key] = value;
124
+ }
125
+ incUpdate = { $inc: incFields };
126
+ } else {
127
+ throw createError(
128
+ ErrorCodes.INVALID_ARGUMENT,
129
+ 'field 必须是字符串或对象',
130
+ [{ field: 'field', type: 'type', message: 'field 必须是字符串或对象', received: typeof field }]
131
+ );
132
+ }
133
+
134
+ // 3. 构建选项
135
+ const maxTimeMS = actualOptions.maxTimeMS !== undefined ? actualOptions.maxTimeMS : defaults.maxTimeMS;
136
+ const comment = actualOptions.comment;
137
+ const returnDocument = actualOptions.returnDocument || 'after';
138
+ const projection = actualOptions.projection;
139
+
140
+ const updateOptions = {
141
+ returnDocument: returnDocument,
142
+ includeResultMetadata: true,
143
+ maxTimeMS
144
+ };
145
+ if (projection) updateOptions.projection = projection;
146
+ if (comment) updateOptions.comment = comment;
147
+
148
+ // 4. 执行 findOneAndUpdate 操作
149
+ let result;
150
+ try {
151
+ result = await collection.findOneAndUpdate(filter, incUpdate, updateOptions);
152
+ } catch (error) {
153
+ throw error;
154
+ }
155
+
156
+ // 5. 自动失效缓存
157
+ const wasModified = result.lastErrorObject && result.lastErrorObject.n > 0;
158
+
159
+ if (cache && wasModified) {
160
+ try {
161
+ const namespace = `${instanceId}:${type}:${effectiveDbName}:${collection.collectionName}`;
162
+ const pattern = `${namespace}:*`;
163
+
164
+ // 检查是否在事务中
165
+ if (isInTransaction(actualOptions)) {
166
+ // 事务中:调用 Transaction 的 recordInvalidation 方法
167
+ const tx = getTransactionFromSession(actualOptions.session);
168
+ if (tx && typeof tx.recordInvalidation === 'function') {
169
+ // 🚀 传递 metadata 支持文档级别锁
170
+ await tx.recordInvalidation(pattern, {
171
+ operation: 'write',
172
+ query: filter,
173
+ collection: collection.collectionName
174
+ });
175
+ logger?.debug?.(`[incrementOne] 事务中失效缓存: ${collection.collectionName}`);
176
+ } else {
177
+ const deleted = await cache.delPattern(pattern);
178
+ if (deleted > 0) {
179
+ logger?.debug?.(`[incrementOne] 自动失效缓存: ${collection.collectionName}, 删除 ${deleted} 个缓存键`);
180
+ }
181
+ }
182
+ } else {
183
+ // 非事务:直接失效缓存
184
+ const deleted = await cache.delPattern(pattern);
185
+ if (deleted > 0) {
186
+ logger?.debug?.(`[incrementOne] 自动失效缓存: ${collection.collectionName}, 删除 ${deleted} 个缓存键`);
187
+ }
188
+ }
189
+ } catch (cacheError) {
190
+ logger?.warn?.('[incrementOne] 缓存失效失败', { error: cacheError.message });
191
+ }
192
+ }
193
+
194
+ // 6. 慢查询日志
195
+ const duration = Date.now() - startTime;
196
+ const slowQueryMs = defaults?.slowQueryMs || 1000;
197
+
198
+ if (duration >= slowQueryMs) {
199
+ try {
200
+ const meta = {
201
+ operation: 'incrementOne',
202
+ durationMs: duration,
203
+ iid: instanceId,
204
+ type: type,
205
+ db: effectiveDbName,
206
+ collection: collection.collectionName,
207
+ found: result.value !== null,
208
+ filter: mongoSlowLogShaper?.sanitize ? mongoSlowLogShaper.sanitize(filter) : filter,
209
+ update: mongoSlowLogShaper?.sanitize ? mongoSlowLogShaper.sanitize(incUpdate) : incUpdate,
210
+ comment: comment
211
+ };
212
+ logger?.warn?.('🐌 Slow query: incrementOne', meta);
213
+ emit?.('slow-query', meta);
214
+ } catch (_) {
215
+ // 忽略日志错误
216
+ }
217
+ }
218
+
219
+ // 7. 日志记录
220
+ logger?.debug?.('[incrementOne] 操作完成', {
221
+ ns: `${effectiveDbName}.${collection.collectionName}`,
222
+ duration: duration,
223
+ found: result && result.value !== null,
224
+ modified: wasDocumentModified(result)
225
+ });
226
+
227
+ // 8. 返回结果 - 使用标准的返回值处理函数(兼容不同 MongoDB 驱动版本)
228
+ // 默认返回完整元数据格式(包含 value, acknowledged, matchedCount 等)
229
+ const processedResult = handleFindOneAndResult(result, { includeResultMetadata: true }, logger);
230
+
231
+ return {
232
+ acknowledged: true,
233
+ matchedCount: processedResult.lastErrorObject?.n || 0,
234
+ modifiedCount: wasDocumentModified(processedResult) ? 1 : 0,
235
+ value: processedResult.value
236
+ };
237
+ };
238
+
239
+ return { incrementOne };
240
+ }
241
+
242
+ module.exports = { createIncrementOneOps };
243
+
@@ -0,0 +1,41 @@
1
+ /**
2
+ * MongoDB 写操作模块入口
3
+ * 统一导出所有写操作的工厂函数
4
+ */
5
+
6
+ const { createInsertOneOps } = require("./insert-one");
7
+ const { createInsertManyOps } = require("./insert-many");
8
+ const { createInsertBatchOps } = require("./insert-batch");
9
+ const { createUpdateOneOps } = require("./update-one");
10
+ const { createUpdateManyOps } = require("./update-many");
11
+ const { createReplaceOneOps } = require("./replace-one");
12
+ const { createUpsertOneOps } = require("./upsert-one"); // upsertOne 便利方法
13
+ const { createIncrementOneOps } = require("./increment-one"); // 新增:incrementOne 便利方法
14
+ const { createFindOneAndUpdateOps } = require("./find-one-and-update");
15
+ const { createFindOneAndReplaceOps } = require("./find-one-and-replace");
16
+ const { createDeleteOneOps } = require("./delete-one");
17
+ const { createDeleteManyOps } = require("./delete-many");
18
+ const { createFindOneAndDeleteOps } = require("./find-one-and-delete");
19
+
20
+ module.exports = {
21
+ // Insert 操作
22
+ createInsertOneOps,
23
+ createInsertManyOps,
24
+ createInsertBatchOps,
25
+
26
+ // Update 操作
27
+ createUpdateOneOps,
28
+ createUpdateManyOps,
29
+ createReplaceOneOps,
30
+ createUpsertOneOps, // upsertOne 便利方法
31
+ createIncrementOneOps, // 新增:incrementOne 便利方法
32
+
33
+ // Find and Modify 操作
34
+ createFindOneAndUpdateOps,
35
+ createFindOneAndReplaceOps,
36
+
37
+ // Delete 操作
38
+ createDeleteOneOps,
39
+ createDeleteManyOps,
40
+ createFindOneAndDeleteOps,
41
+ };