monsqlize 1.3.0 → 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 (172) hide show
  1. package/CHANGELOG.md +56 -60
  2. package/LICENSE +201 -21
  3. package/README.md +537 -1828
  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 +67 -69
  27. package/index.d.ts +0 -206
  28. package/index.mjs +0 -52
  29. package/lib/cache-invalidation.js +0 -279
  30. package/lib/cache.js +0 -530
  31. package/lib/common/cursor.js +0 -59
  32. package/lib/common/docs-urls.js +0 -73
  33. package/lib/common/index-options.js +0 -223
  34. package/lib/common/log.js +0 -61
  35. package/lib/common/namespace.js +0 -22
  36. package/lib/common/normalize.js +0 -34
  37. package/lib/common/page-result.js +0 -43
  38. package/lib/common/runner.js +0 -57
  39. package/lib/common/server-features.js +0 -232
  40. package/lib/common/shape-builders.js +0 -27
  41. package/lib/common/validation.js +0 -113
  42. package/lib/connect.js +0 -99
  43. package/lib/constants.js +0 -55
  44. package/lib/count-queue.js +0 -188
  45. package/lib/distributed-cache-invalidator.js +0 -260
  46. package/lib/errors.js +0 -168
  47. package/lib/expression/cache/ExpressionCache.js +0 -114
  48. package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
  49. package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
  50. package/lib/expression/detector.js +0 -84
  51. package/lib/expression/factory.js +0 -29
  52. package/lib/expression/index.js +0 -19
  53. package/lib/function-cache.js +0 -533
  54. package/lib/index.js +0 -1251
  55. package/lib/infrastructure/ConnectionPoolManager.js +0 -464
  56. package/lib/infrastructure/HealthChecker.js +0 -281
  57. package/lib/infrastructure/PoolConfig.js +0 -199
  58. package/lib/infrastructure/PoolSelector.js +0 -225
  59. package/lib/infrastructure/PoolStats.js +0 -244
  60. package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
  61. package/lib/infrastructure/ssh-tunnel.js +0 -41
  62. package/lib/infrastructure/uri-parser.js +0 -36
  63. package/lib/lock/Lock.js +0 -67
  64. package/lib/lock/errors.js +0 -28
  65. package/lib/lock/index.js +0 -13
  66. package/lib/logger.js +0 -225
  67. package/lib/model/examples/test.js +0 -311
  68. package/lib/model/features/defaults.js +0 -161
  69. package/lib/model/features/populate.js +0 -568
  70. package/lib/model/features/relations.js +0 -120
  71. package/lib/model/features/soft-delete.js +0 -349
  72. package/lib/model/features/version.js +0 -157
  73. package/lib/model/features/virtuals.js +0 -219
  74. package/lib/model/index.js +0 -1265
  75. package/lib/mongodb/common/accessor-helpers.js +0 -59
  76. package/lib/mongodb/common/agg-pipeline.js +0 -36
  77. package/lib/mongodb/common/aggregation-validator.js +0 -127
  78. package/lib/mongodb/common/iid.js +0 -28
  79. package/lib/mongodb/common/lexicographic-expr.js +0 -53
  80. package/lib/mongodb/common/shape.js +0 -32
  81. package/lib/mongodb/common/sort.js +0 -39
  82. package/lib/mongodb/common/transaction-aware.js +0 -25
  83. package/lib/mongodb/connect.js +0 -234
  84. package/lib/mongodb/index.js +0 -639
  85. package/lib/mongodb/management/admin-ops.js +0 -200
  86. package/lib/mongodb/management/bookmark-ops.js +0 -167
  87. package/lib/mongodb/management/cache-ops.js +0 -50
  88. package/lib/mongodb/management/collection-ops.js +0 -387
  89. package/lib/mongodb/management/database-ops.js +0 -202
  90. package/lib/mongodb/management/index-ops.js +0 -475
  91. package/lib/mongodb/management/index.js +0 -17
  92. package/lib/mongodb/management/namespace.js +0 -31
  93. package/lib/mongodb/management/validation-ops.js +0 -268
  94. package/lib/mongodb/queries/aggregate.js +0 -172
  95. package/lib/mongodb/queries/chain.js +0 -631
  96. package/lib/mongodb/queries/count.js +0 -99
  97. package/lib/mongodb/queries/distinct.js +0 -78
  98. package/lib/mongodb/queries/find-and-count.js +0 -193
  99. package/lib/mongodb/queries/find-by-ids.js +0 -236
  100. package/lib/mongodb/queries/find-one-by-id.js +0 -171
  101. package/lib/mongodb/queries/find-one.js +0 -71
  102. package/lib/mongodb/queries/find-page.js +0 -618
  103. package/lib/mongodb/queries/find.js +0 -171
  104. package/lib/mongodb/queries/index.js +0 -51
  105. package/lib/mongodb/queries/watch.js +0 -538
  106. package/lib/mongodb/writes/common/batch-retry.js +0 -65
  107. package/lib/mongodb/writes/delete-batch.js +0 -323
  108. package/lib/mongodb/writes/delete-many.js +0 -181
  109. package/lib/mongodb/writes/delete-one.js +0 -173
  110. package/lib/mongodb/writes/find-one-and-delete.js +0 -203
  111. package/lib/mongodb/writes/find-one-and-replace.js +0 -239
  112. package/lib/mongodb/writes/find-one-and-update.js +0 -240
  113. package/lib/mongodb/writes/increment-one.js +0 -259
  114. package/lib/mongodb/writes/index.js +0 -46
  115. package/lib/mongodb/writes/insert-batch.js +0 -508
  116. package/lib/mongodb/writes/insert-many.js +0 -223
  117. package/lib/mongodb/writes/insert-one.js +0 -169
  118. package/lib/mongodb/writes/replace-one.js +0 -226
  119. package/lib/mongodb/writes/result-handler.js +0 -237
  120. package/lib/mongodb/writes/update-batch.js +0 -416
  121. package/lib/mongodb/writes/update-many.js +0 -275
  122. package/lib/mongodb/writes/update-one.js +0 -273
  123. package/lib/mongodb/writes/upsert-one.js +0 -203
  124. package/lib/multi-level-cache.js +0 -244
  125. package/lib/operators.js +0 -330
  126. package/lib/redis-cache-adapter.js +0 -267
  127. package/lib/saga/SagaContext.js +0 -67
  128. package/lib/saga/SagaDefinition.js +0 -32
  129. package/lib/saga/SagaExecutor.js +0 -201
  130. package/lib/saga/SagaOrchestrator.js +0 -186
  131. package/lib/saga/index.js +0 -11
  132. package/lib/slow-query-log/base-storage.js +0 -70
  133. package/lib/slow-query-log/batch-queue.js +0 -97
  134. package/lib/slow-query-log/config-manager.js +0 -196
  135. package/lib/slow-query-log/index.js +0 -238
  136. package/lib/slow-query-log/mongodb-storage.js +0 -324
  137. package/lib/slow-query-log/query-hash.js +0 -39
  138. package/lib/sync/ChangeStreamSyncManager.js +0 -405
  139. package/lib/sync/ResumeTokenStore.js +0 -192
  140. package/lib/sync/SyncConfig.js +0 -127
  141. package/lib/sync/SyncTarget.js +0 -240
  142. package/lib/sync/index.js +0 -20
  143. package/lib/transaction/CacheLockManager.js +0 -162
  144. package/lib/transaction/DistributedCacheLockManager.js +0 -475
  145. package/lib/transaction/Transaction.js +0 -315
  146. package/lib/transaction/TransactionManager.js +0 -267
  147. package/lib/transaction/index.js +0 -11
  148. package/lib/utils/objectid-converter.js +0 -632
  149. package/types/README.md +0 -122
  150. package/types/base.ts +0 -94
  151. package/types/batch.ts +0 -187
  152. package/types/cache.ts +0 -71
  153. package/types/chain.ts +0 -254
  154. package/types/collection.ts +0 -357
  155. package/types/expression.ts +0 -109
  156. package/types/function-cache.d.ts +0 -135
  157. package/types/lock.ts +0 -95
  158. package/types/model/definition.ts +0 -152
  159. package/types/model/index.ts +0 -10
  160. package/types/model/instance.ts +0 -121
  161. package/types/model/relations.ts +0 -121
  162. package/types/model/virtuals.ts +0 -32
  163. package/types/monsqlize.ts +0 -245
  164. package/types/options.ts +0 -192
  165. package/types/pagination.ts +0 -154
  166. package/types/pool.ts +0 -125
  167. package/types/query.ts +0 -71
  168. package/types/saga.ts +0 -125
  169. package/types/stream.ts +0 -64
  170. package/types/sync.ts +0 -79
  171. package/types/transaction.ts +0 -79
  172. package/types/write.ts +0 -77
@@ -1,259 +0,0 @@
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
- const { convertObjectIdStrings } = require('../../utils/objectid-converter');
11
-
12
- /**
13
- * 创建 incrementOne 操作
14
- * @param {Object} context - 上下文对象
15
- * @returns {Function} incrementOne 方法
16
- */
17
- function createIncrementOneOps(context) {
18
- const {
19
- collection,
20
- defaults,
21
- instanceId,
22
- effectiveDbName,
23
- logger,
24
- emit,
25
- mongoSlowLogShaper,
26
- cache,
27
- type
28
- } = context;
29
-
30
- /**
31
- * 原子递增/递减单个字段
32
- * @param {Object} filter - 查询条件
33
- * @param {string|Object} field - 字段名或字段-增量对象
34
- * @param {number} [increment=1] - 增量(正数递增,负数递减)
35
- * @param {Object} [options={}] - 操作选项
36
- * @param {number} [options.maxTimeMS] - 操作超时(毫秒)
37
- * @param {string} [options.comment] - 查询注释
38
- * @param {boolean} [options.returnDocument='after'] - 返回文档时机('before' | 'after')
39
- * @param {Object} [options.projection] - 字段投影
40
- * @returns {Promise<Object>} 操作结果
41
- *
42
- * @example
43
- * // 基础用法(递增 1)
44
- * const result = await collection('users').incrementOne(
45
- * { userId: 'user123' },
46
- * 'loginCount'
47
- * );
48
- *
49
- * @example
50
- * // 指定增量
51
- * const result = await collection('users').incrementOne(
52
- * { userId: 'user123' },
53
- * 'points',
54
- * 10
55
- * );
56
- *
57
- * @example
58
- * // 递减(负数)
59
- * const result = await collection('users').incrementOne(
60
- * { userId: 'user123' },
61
- * 'credits',
62
- * -5
63
- * );
64
- *
65
- * @example
66
- * // 多字段递增
67
- * const result = await collection('users').incrementOne(
68
- * { userId: 'user123' },
69
- * { loginCount: 1, points: 10, credits: -5 }
70
- * );
71
- */
72
- const incrementOne = async function incrementOne(filter, field, increment, options) {
73
- const startTime = Date.now();
74
-
75
- // 1. 参数解析和验证
76
- let actualIncrement = increment;
77
- let actualOptions = options;
78
-
79
- // 支持 incrementOne(filter, field, options) 形式(省略 increment,默认 1)
80
- if (typeof increment === 'object' && increment !== null && !Array.isArray(increment) && actualOptions === undefined) {
81
- actualOptions = increment;
82
- actualIncrement = 1;
83
- }
84
-
85
- actualOptions = actualOptions || {};
86
-
87
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
88
- throw createError(
89
- ErrorCodes.INVALID_ARGUMENT,
90
- 'filter 必须是非空对象',
91
- [{ field: 'filter', type: 'type', message: 'filter 必须是对象', received: typeof filter }]
92
- );
93
- }
94
-
95
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
96
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
97
- logger: context.logger,
98
- excludeFields: context.autoConvertConfig?.excludeFields,
99
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
100
- maxDepth: context.autoConvertConfig?.maxDepth
101
- });
102
-
103
- // 2. 构建 $inc 更新对象
104
- let incUpdate;
105
-
106
- if (typeof field === 'string') {
107
- // 单字段递增
108
- if (actualIncrement === undefined) {
109
- actualIncrement = 1;
110
- }
111
-
112
- if (typeof actualIncrement !== 'number' || isNaN(actualIncrement)) {
113
- throw createError(
114
- ErrorCodes.INVALID_ARGUMENT,
115
- 'increment 必须是数字',
116
- [{ field: 'increment', type: 'type', message: 'increment 必须是数字', received: typeof actualIncrement }]
117
- );
118
- }
119
-
120
- incUpdate = { $inc: { [field]: actualIncrement } };
121
- } else if (typeof field === 'object' && field !== null && !Array.isArray(field)) {
122
- // 多字段递增
123
- const incFields = {};
124
- for (const [key, value] of Object.entries(field)) {
125
- if (typeof value !== 'number' || isNaN(value)) {
126
- throw createError(
127
- ErrorCodes.INVALID_ARGUMENT,
128
- `字段 ${key} 的增量必须是数字`,
129
- [{ field: key, type: 'type', message: '增量必须是数字', received: typeof value }]
130
- );
131
- }
132
- incFields[key] = value;
133
- }
134
- incUpdate = { $inc: incFields };
135
- } else {
136
- throw createError(
137
- ErrorCodes.INVALID_ARGUMENT,
138
- 'field 必须是字符串或对象',
139
- [{ field: 'field', type: 'type', message: 'field 必须是字符串或对象', received: typeof field }]
140
- );
141
- }
142
-
143
- // 3. 构建选项
144
- const maxTimeMS = actualOptions.maxTimeMS !== undefined ? actualOptions.maxTimeMS : defaults.maxTimeMS;
145
- const comment = actualOptions.comment;
146
- const returnDocument = actualOptions.returnDocument || 'after';
147
- const projection = actualOptions.projection;
148
-
149
- // 🔧 Model 层 timestamps 支持:从 options.$set 读取额外的字段更新
150
- if (actualOptions.$set && typeof actualOptions.$set === 'object') {
151
- // 合并到 incUpdate
152
- incUpdate.$set = actualOptions.$set;
153
- }
154
-
155
- const updateOptions = {
156
- returnDocument,
157
- includeResultMetadata: true,
158
- maxTimeMS
159
- };
160
- if (projection) updateOptions.projection = projection;
161
- if (comment) updateOptions.comment = comment;
162
-
163
- // 4. 执行 findOneAndUpdate 操作
164
- let result;
165
- try {
166
- result = await collection.findOneAndUpdate(convertedFilter, incUpdate, updateOptions);
167
- } catch (error) {
168
- throw error;
169
- }
170
-
171
- // 5. 自动失效缓存
172
- const wasModified = result.lastErrorObject && result.lastErrorObject.n > 0;
173
-
174
- if (cache && wasModified) {
175
- try {
176
- const namespace = `${instanceId}:${type}:${effectiveDbName}:${collection.collectionName}`;
177
- const pattern = `${namespace}:*`;
178
-
179
- // 检查是否在事务中
180
- if (isInTransaction(actualOptions)) {
181
- // 事务中:调用 Transaction 的 recordInvalidation 方法
182
- const tx = getTransactionFromSession(actualOptions.session);
183
- if (tx && typeof tx.recordInvalidation === 'function') {
184
- // 🚀 传递 metadata 支持文档级别锁
185
- await tx.recordInvalidation(pattern, {
186
- operation: 'write',
187
- query: filter,
188
- collection: collection.collectionName
189
- });
190
- logger?.debug?.(`[incrementOne] 事务中失效缓存: ${collection.collectionName}`);
191
- } else {
192
- const deleted = await cache.delPattern(pattern);
193
- if (deleted > 0) {
194
- logger?.debug?.(`[incrementOne] 自动失效缓存: ${collection.collectionName}, 删除 ${deleted} 个缓存键`);
195
- }
196
- }
197
- } else {
198
- // 非事务:直接失效缓存
199
- const deleted = await cache.delPattern(pattern);
200
- if (deleted > 0) {
201
- logger?.debug?.(`[incrementOne] 自动失效缓存: ${collection.collectionName}, 删除 ${deleted} 个缓存键`);
202
- }
203
- }
204
- } catch (cacheError) {
205
- logger?.warn?.('[incrementOne] 缓存失效失败', { error: cacheError.message });
206
- }
207
- }
208
-
209
- // 6. 慢查询日志
210
- const duration = Date.now() - startTime;
211
- const slowQueryMs = defaults?.slowQueryMs || 1000;
212
-
213
- if (duration >= slowQueryMs) {
214
- try {
215
- const meta = {
216
- operation: 'incrementOne',
217
- durationMs: duration,
218
- iid: instanceId,
219
- type,
220
- db: effectiveDbName,
221
- collection: collection.collectionName,
222
- found: result.value !== null,
223
- filter: mongoSlowLogShaper?.sanitize ? mongoSlowLogShaper.sanitize(filter) : filter,
224
- update: mongoSlowLogShaper?.sanitize ? mongoSlowLogShaper.sanitize(incUpdate) : incUpdate,
225
- comment
226
- };
227
- logger?.warn?.('🐌 Slow query: incrementOne', meta);
228
- emit?.('slow-query', meta);
229
- } catch (_) {
230
- // 忽略日志错误
231
- }
232
- }
233
-
234
- // 7. 日志记录
235
- logger?.debug?.('[incrementOne] 操作完成', {
236
- ns: `${effectiveDbName}.${collection.collectionName}`,
237
- duration,
238
- found: result && result.value !== null,
239
- modified: wasDocumentModified(result)
240
- });
241
-
242
- // 8. 返回结果 - 使用标准的返回值处理函数(兼容不同 MongoDB 驱动版本)
243
- // 默认返回完整元数据格式(包含 value, acknowledged, matchedCount 等)
244
- const processedResult = handleFindOneAndResult(result, { includeResultMetadata: true }, logger);
245
-
246
- return {
247
- acknowledged: true,
248
- matchedCount: processedResult.lastErrorObject?.n || 0,
249
- modifiedCount: wasDocumentModified(processedResult) ? 1 : 0,
250
- value: processedResult.value
251
- };
252
- };
253
-
254
- return { incrementOne };
255
- }
256
-
257
- module.exports = { createIncrementOneOps };
258
-
259
-
@@ -1,46 +0,0 @@
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 { createUpdateBatchOps } = require('./update-batch'); // 🆕 批量更新
12
- const { createReplaceOneOps } = require('./replace-one');
13
- const { createUpsertOneOps } = require('./upsert-one'); // upsertOne 便利方法
14
- const { createIncrementOneOps } = require('./increment-one'); // 新增:incrementOne 便利方法
15
- const { createFindOneAndUpdateOps } = require('./find-one-and-update');
16
- const { createFindOneAndReplaceOps } = require('./find-one-and-replace');
17
- const { createDeleteOneOps } = require('./delete-one');
18
- const { createDeleteManyOps } = require('./delete-many');
19
- const { createDeleteBatchOps } = require('./delete-batch'); // 🆕 批量删除
20
- const { createFindOneAndDeleteOps } = require('./find-one-and-delete');
21
-
22
- module.exports = {
23
- // Insert 操作
24
- createInsertOneOps,
25
- createInsertManyOps,
26
- createInsertBatchOps,
27
-
28
- // Update 操作
29
- createUpdateOneOps,
30
- createUpdateManyOps,
31
- createUpdateBatchOps, // 🆕 批量更新
32
- createReplaceOneOps,
33
- createUpsertOneOps, // upsertOne 便利方法
34
- createIncrementOneOps, // 新增:incrementOne 便利方法
35
-
36
- // Find and Modify 操作
37
- createFindOneAndUpdateOps,
38
- createFindOneAndReplaceOps,
39
-
40
- // Delete 操作
41
- createDeleteOneOps,
42
- createDeleteManyOps,
43
- createDeleteBatchOps, // 🆕 批量删除
44
- createFindOneAndDeleteOps,
45
- };
46
-