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,223 +0,0 @@
1
- /**
2
- * insertMany 操作实现
3
- * 批量插入多个文档到集合
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
- const { convertObjectIdStrings } = require('../../utils/objectid-converter');
10
-
11
- /**
12
- * 创建 insertMany 操作
13
- * @param {Object} context - 模块上下文
14
- * @param {Object} context.db - MongoDB 数据库实例
15
- * @param {Object} context.cache - 缓存实例
16
- * @param {Object} context.logger - 日志实例
17
- * @param {Object} context.defaults - 默认配置
18
- * @param {string} context.collection - 集合名称
19
- * @param {string} context.effectiveDbName - 数据库名称
20
- * @param {string} context.instanceId - 实例ID
21
- * @returns {Object} 包含 insertMany 方法的对象
22
- */
23
- function createInsertManyOps(context) {
24
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
25
-
26
- // 提取集合名称和原生 collection 对象
27
- const collectionName = collection.collectionName;
28
- const nativeCollection = collection;
29
-
30
- /**
31
- * 批量插入多个文档
32
- * @param {Array<Object>} documents - 要插入的文档数组(必需)
33
- * @param {Object} [options] - 操作选项
34
- * @param {boolean} [options.ordered=true] - 是否按顺序插入(遇到错误是否继续)
35
- * @param {Object} [options.writeConcern] - 写关注选项
36
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
37
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
38
- * @returns {Promise<Object>} 插入结果 { acknowledged, insertedCount, insertedIds }
39
- * @throws {Error} 当 documents 参数无效时
40
- *
41
- * @example
42
- * const result = await collection('users').insertMany([
43
- * { name: 'Alice', age: 25 },
44
- * { name: 'Bob', age: 30 }
45
- * ]);
46
- * console.log('Inserted count:', result.insertedCount);
47
- * console.log('Inserted IDs:', result.insertedIds);
48
- *
49
- * @example
50
- * // 使用 options 参数
51
- * const result = await collection('users').insertMany(
52
- * [
53
- * { name: 'Charlie', age: 35 },
54
- * { name: 'David', age: 40 }
55
- * ],
56
- * { ordered: false, comment: 'batch insert' }
57
- * );
58
- */
59
- const insertMany = async function insertMany(documents, options = {}) {
60
- const startTime = Date.now();
61
-
62
- // 1. 参数验证
63
- if (!Array.isArray(documents)) {
64
- throw createError(
65
- ErrorCodes.DOCUMENTS_REQUIRED,
66
- 'documents 必须是数组类型',
67
- [{ field: 'documents', type: 'array.required', message: 'documents 是必需参数且必须是数组' }]
68
- );
69
- }
70
-
71
- if (documents.length === 0) {
72
- throw createError(
73
- ErrorCodes.DOCUMENTS_REQUIRED,
74
- 'documents 数组不能为空',
75
- [{ field: 'documents', type: 'array.min', message: 'documents 至少需要包含一个文档' }]
76
- );
77
- }
78
-
79
- // 验证每个文档都是对象
80
- const invalidDocs = documents.filter((doc, index) => {
81
- return !doc || typeof doc !== 'object' || Array.isArray(doc);
82
- });
83
-
84
- if (invalidDocs.length > 0) {
85
- throw createError(
86
- ErrorCodes.DOCUMENTS_REQUIRED,
87
- 'documents 中的所有元素必须是对象类型',
88
- invalidDocs.map((doc, idx) => ({
89
- field: `documents[${idx}]`,
90
- type: 'object.required',
91
- message: '必须是对象类型'
92
- }))
93
- );
94
- }
95
-
96
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
97
- const convertedDocuments = documents.map(doc => convertObjectIdStrings(doc, 'document', 0, new WeakSet(), {
98
- logger: context.logger,
99
- excludeFields: context.autoConvertConfig?.excludeFields,
100
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
101
- maxDepth: context.autoConvertConfig?.maxDepth
102
- }));
103
-
104
- // 2. 构建操作上下文
105
- const operation = 'insertMany';
106
- const ns = `${databaseName}.${collectionName}`;
107
- const docCount = documents.length;
108
-
109
- try {
110
- // 3. 执行批量插入操作
111
- const result = await nativeCollection.insertMany(convertedDocuments, options);
112
-
113
- // 4. 自动失效缓存
114
- if (cache) {
115
- try {
116
- // 🆕 v1.1.6: 解析精准失效配置
117
- const instanceAuto = context.cacheAutoInvalidate || false;
118
- const queryAuto = options.autoInvalidate;
119
- const shouldAuto = queryAuto !== undefined ? queryAuto : instanceAuto;
120
-
121
-
122
- if (shouldAuto) {
123
- // 精准失效:对每个插入的文档执行失效
124
- const CacheInvalidationEngine = require('../../cache-invalidation');
125
- let totalDeleted = 0;
126
-
127
- for (const doc of convertedDocuments) {
128
- const deleted = await CacheInvalidationEngine.invalidatePrecise(cache, {
129
- instanceId,
130
- type: 'mongodb',
131
- db: databaseName,
132
- collection: collectionName,
133
- document: doc,
134
- operation: 'insertMany'
135
- });
136
- totalDeleted += deleted;
137
- }
138
-
139
- if (totalDeleted > 0) {
140
- logger.debug(`[${operation}] 精准失效缓存: ${databaseName}.${collectionName}, 删除 ${totalDeleted} 个缓存键`);
141
- }
142
- } else {
143
- logger.debug(`[${operation}] 跳过自动失效(autoInvalidate=false)`);
144
- }
145
- } catch (cacheErr) {
146
- // 缓存失效失败不影响写操作
147
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
148
- }
149
- }
150
-
151
- // 5. 记录慢操作日志
152
- const duration = Date.now() - startTime;
153
- const slowQueryMs = defaults.slowQueryMs ?? 1000;
154
- if (duration > slowQueryMs) {
155
- logger.warn(`[${operation}] 慢操作警告`, {
156
- ns,
157
- duration,
158
- threshold: slowQueryMs,
159
- documentCount: docCount,
160
- insertedCount: result.insertedCount,
161
- ordered: options.ordered !== false,
162
- comment: options.comment
163
- });
164
- } else {
165
- logger.debug(`[${operation}] 操作完成`, {
166
- ns,
167
- duration,
168
- documentCount: docCount,
169
- insertedCount: result.insertedCount
170
- });
171
- }
172
-
173
- return result;
174
-
175
- } catch (error) {
176
- // 6. 错误处理
177
- const duration = Date.now() - startTime;
178
-
179
- logger.error(`[${operation}] 操作失败`, {
180
- ns,
181
- duration,
182
- error: error.message,
183
- code: error.code,
184
- documentCount: docCount,
185
- ordered: options.ordered !== false
186
- });
187
-
188
- // 识别特定错误类型
189
- if (error.code === 11000) {
190
- // MongoDB 重复键错误
191
- throw createError(
192
- ErrorCodes.DUPLICATE_KEY,
193
- '批量插入失败:违反唯一性约束',
194
- [{ message: error.message, writeErrors: error.writeErrors }],
195
- error
196
- );
197
- }
198
-
199
- // 部分成功的情况(ordered=false 时可能发生)
200
- if (error.result && error.result.insertedCount > 0) {
201
- logger.warn(`[${operation}] 部分成功`, {
202
- ns,
203
- insertedCount: error.result.insertedCount,
204
- totalCount: docCount,
205
- failedCount: docCount - error.result.insertedCount
206
- });
207
- }
208
-
209
- // 其他错误
210
- throw createError(
211
- ErrorCodes.WRITE_ERROR,
212
- `insertMany 操作失败: ${error.message}`,
213
- error.writeErrors || null,
214
- error
215
- );
216
- }
217
- };
218
-
219
- return { insertMany };
220
- }
221
-
222
- module.exports = { createInsertManyOps };
223
-
@@ -1,169 +0,0 @@
1
- /**
2
- * insertOne 操作实现
3
- * 插入单个文档到集合
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
- const { convertObjectIdStrings } = require('../../utils/objectid-converter');
10
-
11
- /**
12
- * 创建 insertOne 操作
13
- * @param {Object} context - 模块上下文
14
- * @param {Object} context.db - MongoDB 数据库实例
15
- * @param {Object} context.cache - 缓存实例
16
- * @param {Object} context.logger - 日志实例
17
- * @param {Object} context.defaults - 默认配置
18
- * @param {string} context.collectionName - 集合名称
19
- * @param {string} context.databaseName - 数据库名称
20
- * @param {string} context.instanceId - 实例ID
21
- * @returns {Object} 包含 insertOne 方法的对象
22
- */
23
- function createInsertOneOps(context) {
24
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
25
-
26
- // 提取集合名称和原生 collection 对象
27
- const collectionName = collection.collectionName;
28
- const nativeCollection = collection;
29
-
30
- /**
31
- * 插入单个文档
32
- * @param {Object} document - 要插入的文档(必需)
33
- * @param {Object} [options] - 操作选项
34
- * @param {Object} [options.writeConcern] - 写关注选项
35
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
36
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
37
- * @returns {Promise<Object>} 插入结果 { acknowledged, insertedId }
38
- * @throws {Error} 当 document 参数无效时
39
- *
40
- * @example
41
- * const result = await collection('users').insertOne(
42
- * { name: 'Alice', age: 25 }
43
- * );
44
- * console.log('Inserted ID:', result.insertedId);
45
- *
46
- * @example
47
- * // 使用 options 参数
48
- * const result = await collection('users').insertOne(
49
- * { name: 'Bob', age: 30 },
50
- * { bypassDocumentValidation: true, comment: 'test insert' }
51
- * );
52
- */
53
- const insertOne = async function insertOne(document, options = {}) {
54
- const startTime = Date.now();
55
-
56
- // 1. 参数验证
57
- if (!document || typeof document !== 'object' || Array.isArray(document)) {
58
- throw createError(
59
- ErrorCodes.DOCUMENT_REQUIRED,
60
- 'document 必须是对象类型',
61
- [{ field: 'document', type: 'object.required', message: 'document 是必需参数且必须是对象' }]
62
- );
63
- }
64
-
65
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
66
- const convertedDocument = convertObjectIdStrings(document, 'document', 0, new WeakSet(), {
67
- logger: context.logger,
68
- excludeFields: context.autoConvertConfig?.excludeFields,
69
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
70
- maxDepth: context.autoConvertConfig?.maxDepth
71
- });
72
-
73
- // 2. 构建操作上下文
74
- const operation = 'insertOne';
75
- const ns = `${databaseName}.${collectionName}`;
76
-
77
- try {
78
- // 3. 执行插入操作
79
- const result = await nativeCollection.insertOne(convertedDocument, options);
80
-
81
- // 4. 自动失效缓存
82
- if (cache) {
83
- try {
84
- // 🆕 v1.1.6: 解析精准失效配置
85
- const instanceAuto = context.cacheAutoInvalidate || false;
86
- const queryAuto = options.autoInvalidate;
87
- const shouldAuto = queryAuto !== undefined ? queryAuto : instanceAuto;
88
-
89
- if (shouldAuto) {
90
- // 精准失效
91
- const CacheInvalidationEngine = require('../../cache-invalidation');
92
- const deleted = await CacheInvalidationEngine.invalidatePrecise(cache, {
93
- instanceId,
94
- type: 'mongodb',
95
- db: databaseName,
96
- collection: collectionName,
97
- document: convertedDocument,
98
- operation: 'insertOne'
99
- });
100
- if (deleted > 0) {
101
- logger.debug(`[${operation}] 精准失效缓存: ${databaseName}.${collectionName}, 删除 ${deleted} 个缓存键`);
102
- }
103
- } else {
104
- logger.debug(`[${operation}] 跳过自动失效(autoInvalidate=false)`);
105
- }
106
- } catch (cacheErr) {
107
- // 缓存失效失败不影响写操作
108
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
109
- }
110
- }
111
-
112
- // 5. 记录慢操作日志
113
- const duration = Date.now() - startTime;
114
- const slowQueryMs = defaults.slowQueryMs || 1000;
115
- if (duration > slowQueryMs) {
116
- logger.warn(`[${operation}] 慢操作警告`, {
117
- ns,
118
- duration,
119
- threshold: slowQueryMs,
120
- documentKeys: Object.keys(document),
121
- insertedId: result.insertedId,
122
- comment: options.comment
123
- });
124
- } else {
125
- logger.debug(`[${operation}] 操作完成`, {
126
- ns,
127
- duration,
128
- insertedId: result.insertedId
129
- });
130
- }
131
-
132
- return result;
133
-
134
- } catch (error) {
135
- // 6. 错误处理
136
- const duration = Date.now() - startTime;
137
-
138
- logger.error(`[${operation}] 操作失败`, {
139
- ns,
140
- duration,
141
- error: error.message,
142
- code: error.code,
143
- documentKeys: Object.keys(document)
144
- });
145
-
146
- // 识别特定错误类型
147
- if (error.code === 11000) {
148
- // MongoDB 重复键错误
149
- throw createError(
150
- ErrorCodes.DUPLICATE_KEY,
151
- '文档插入失败:违反唯一性约束',
152
- [{ field: '_id', message: error.message }],
153
- error
154
- );
155
- }
156
-
157
- // 其他错误
158
- throw createError(
159
- ErrorCodes.WRITE_ERROR,
160
- `insertOne 操作失败: ${error.message}`,
161
- null,
162
- error
163
- );
164
- }
165
- };
166
-
167
- return { insertOne };
168
- } module.exports = { createInsertOneOps };
169
-
@@ -1,226 +0,0 @@
1
- /**
2
- * replaceOne 操作实现
3
- * 完整替换单个匹配的文档
4
- */
5
-
6
- const { createError, ErrorCodes } = require('../../errors');
7
- const CacheFactory = require('../../cache');
8
- const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
9
- const { convertObjectIdStrings } = require('../../utils/objectid-converter');
10
-
11
- /**
12
- * 创建 replaceOne 操作
13
- * @param {Object} context - 模块上下文
14
- * @param {Object} context.db - MongoDB 数据库实例
15
- * @param {Object} context.cache - 缓存实例
16
- * @param {Object} context.logger - 日志实例
17
- * @param {Object} context.defaults - 默认配置
18
- * @param {string} context.collection - 集合名称
19
- * @param {string} context.effectiveDbName - 数据库名称
20
- * @param {string} context.instanceId - 实例ID
21
- * @returns {Object} 包含 replaceOne 方法的对象
22
- */
23
- function createReplaceOneOps(context) {
24
- const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
25
-
26
- // 提取集合名称和原生 collection 对象
27
- const collectionName = collection.collectionName;
28
- const nativeCollection = collection;
29
-
30
- /**
31
- * 替换单个文档(完整替换,不使用更新操作符)
32
- * @param {Object} filter - 筛选条件(必需)
33
- * @param {Object} replacement - 替换文档(必需,不能包含更新操作符)
34
- * @param {Object} [options] - 操作选项
35
- * @param {boolean} [options.upsert=false] - 不存在时是否插入
36
- * @param {Object} [options.writeConcern] - 写关注选项
37
- * @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
38
- * @param {string} [options.comment] - 操作注释(用于日志追踪)
39
- * @param {Object} [options.collation] - 排序规则
40
- * @param {Object} [options.hint] - 索引提示
41
- * @returns {Promise<Object>} 替换结果 { acknowledged, matchedCount, modifiedCount, upsertedId?, upsertedCount? }
42
- * @throws {Error} 当参数无效时
43
- *
44
- * @example
45
- * const result = await collection("users").replaceOne(
46
- * { userId: "user123" },
47
- * { userId: "user123", name: "Alice", age: 25, status: "active" }
48
- * );
49
- * console.log("Modified:", result.modifiedCount);
50
- *
51
- * @example
52
- * // 使用 upsert 选项
53
- * const result = await collection("users").replaceOne(
54
- * { userId: "user456" },
55
- * { userId: "user456", name: "Bob", age: 30 },
56
- * { upsert: true }
57
- * );
58
- */
59
- const replaceOne = async function replaceOne(filter, replacement, options = {}) {
60
- const startTime = Date.now();
61
-
62
- // 1. 参数验证
63
- if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
64
- throw createError(
65
- ErrorCodes.INVALID_ARGUMENT,
66
- 'filter 必须是对象类型',
67
- [{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
68
- );
69
- }
70
-
71
- if (!replacement || typeof replacement !== 'object' || Array.isArray(replacement)) {
72
- throw createError(
73
- ErrorCodes.INVALID_ARGUMENT,
74
- 'replacement 必须是对象类型',
75
- [{ field: 'replacement', type: 'object.required', message: 'replacement 是必需参数且必须是对象' }]
76
- );
77
- }
78
-
79
- // 验证 replacement 不包含更新操作符(防止误用)
80
- const replacementKeys = Object.keys(replacement);
81
- if (replacementKeys.some(key => key.startsWith('$'))) {
82
- throw createError(
83
- ErrorCodes.INVALID_ARGUMENT,
84
- 'replacement 不能包含更新操作符(如 $set, $inc 等)',
85
- [{ field: 'replacement', type: 'object.invalid', message: 'replaceOne 用于完整替换文档,请使用 updateOne 进行部分更新' }]
86
- );
87
- }
88
-
89
- // ✅ v1.3.0: 自动转换 ObjectId 字符串
90
- const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
91
- logger: context.logger,
92
- excludeFields: context.autoConvertConfig?.excludeFields,
93
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
94
- maxDepth: context.autoConvertConfig?.maxDepth
95
- });
96
-
97
- const convertedReplacement = convertObjectIdStrings(replacement, 'document', 0, new WeakSet(), {
98
- logger: context.logger,
99
- excludeFields: context.autoConvertConfig?.excludeFields,
100
- customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
101
- maxDepth: context.autoConvertConfig?.maxDepth
102
- });
103
-
104
- // 2. 构建操作上下文
105
- const operation = 'replaceOne';
106
- const ns = `${databaseName}.${collectionName}`;
107
-
108
- try {
109
- // 3. 执行替换操作
110
- const result = await nativeCollection.replaceOne(convertedFilter, convertedReplacement, options);
111
-
112
- // 4. 自动失效缓存
113
- // ✅ v1.1.6: 修复 upsert 场景的缓存失效问题 - 检查 modifiedCount 或 upsertedId
114
- if (cache && (result.modifiedCount > 0 || result.upsertedId)) {
115
- try {
116
- // 使用标准命名空间模式删除该集合的所有缓存
117
- const ns = {
118
- iid: instanceId,
119
- type: 'mongodb',
120
- db: databaseName,
121
- collection: collectionName
122
- };
123
- const pattern = CacheFactory.buildNamespacePattern(ns);
124
-
125
- // 检查是否在事务中
126
- if (isInTransaction(options)) {
127
- // 事务中:调用 Transaction 的 recordInvalidation 方法
128
- const tx = getTransactionFromSession(options.session);
129
- if (tx && typeof tx.recordInvalidation === 'function') {
130
- await tx.recordInvalidation(pattern, {
131
- operation: 'write',
132
- query: filter,
133
- collection: collectionName,
134
- upserted: !!result.upsertedId
135
- });
136
- logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}${result.upsertedId ? ' (upsert)' : ''}`);
137
- } else {
138
- const deleted = await cache.delPattern(pattern);
139
- if (deleted > 0) {
140
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键${result.upsertedId ? ' (upsert)' : ''}`);
141
- }
142
- }
143
- } else {
144
- // 非事务:直接失效缓存
145
- const deleted = await cache.delPattern(pattern);
146
- if (deleted > 0) {
147
- logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键${result.upsertedId ? ' (upsert)' : ''}`);
148
- }
149
- }
150
- } catch (cacheErr) {
151
- // 缓存失效失败不影响写操作
152
- logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, {
153
- ns: `${databaseName}.${collectionName}`,
154
- error: cacheErr,
155
- upserted: !!result.upsertedId
156
- });
157
- }
158
- }
159
-
160
- // 5. 记录慢操作日志
161
- const duration = Date.now() - startTime;
162
- const slowQueryMs = defaults.slowQueryMs || 1000;
163
- if (duration > slowQueryMs) {
164
- logger.warn(`[${operation}] 慢操作警告`, {
165
- ns,
166
- duration,
167
- threshold: slowQueryMs,
168
- filterKeys: Object.keys(filter),
169
- replacementKeys: Object.keys(replacement),
170
- matchedCount: result.matchedCount,
171
- modifiedCount: result.modifiedCount,
172
- upserted: result.upsertedId ? true : false,
173
- comment: options.comment
174
- });
175
- } else {
176
- logger.debug(`[${operation}] 操作完成`, {
177
- ns,
178
- duration,
179
- matchedCount: result.matchedCount,
180
- modifiedCount: result.modifiedCount,
181
- upserted: result.upsertedId ? true : false
182
- });
183
- }
184
-
185
- return result;
186
-
187
- } catch (error) {
188
- // 6. 错误处理
189
- const duration = Date.now() - startTime;
190
-
191
- logger.error(`[${operation}] 操作失败`, {
192
- ns,
193
- duration,
194
- error: error.message,
195
- code: error.code,
196
- filterKeys: Object.keys(filter),
197
- replacementKeys: Object.keys(replacement)
198
- });
199
-
200
- // 识别特定错误类型
201
- if (error.code === 11000) {
202
- // MongoDB 重复键错误(可能在 upsert 时发生)
203
- throw createError(
204
- ErrorCodes.DUPLICATE_KEY,
205
- '替换失败:违反唯一性约束',
206
- [{ field: '_id', message: error.message }],
207
- error
208
- );
209
- }
210
-
211
- // 其他错误
212
- throw createError(
213
- ErrorCodes.WRITE_ERROR,
214
- `replaceOne 操作失败: ${error.message}`,
215
- null,
216
- error
217
- );
218
- }
219
- };
220
-
221
- return { replaceOne };
222
- }
223
-
224
- module.exports = { createReplaceOneOps };
225
-
226
-