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,639 +0,0 @@
1
- // MongoDB connect/close moved to separate module for clarity
2
- const { connectMongo, closeMongo } = require('./connect');
3
- // Common runner and log shapers
4
- const { createCachedRunner } = require('../common/runner');
5
- const { genInstanceId } = require('./common/iid');
6
- const { resolveInstanceId: resolveNS } = require('../common/namespace');
7
- const { withSlowQueryLog } = require('../common/log');
8
- const { mongoSlowLogShaper, mongoKeyBuilder } = require('./common/accessor-helpers');
9
-
10
- // 模块化方法统一导入
11
- const {
12
- createFindOps,
13
- createFindOneOps,
14
- createFindOneByIdOps, // findOneById 快捷方法
15
- createFindByIdsOps, // findByIds 快捷方法
16
- createFindAndCountOps, // 新增:findAndCount 快捷方法
17
- createCountOps,
18
- createAggregateOps,
19
- createDistinctOps,
20
- createFindPageOps, // 分页查询工厂函数
21
- createWatchOps // 🆕 watch 方法
22
- } = require('./queries');
23
-
24
- const {
25
- createNamespaceOps,
26
- createCollectionOps,
27
- createCacheOps,
28
- createBookmarkOps,
29
- createIndexOps,
30
- createAdminOps,
31
- createDatabaseOps,
32
- createValidationOps
33
- } = require('./management');
34
-
35
- const {
36
- createInsertOneOps,
37
- createInsertManyOps,
38
- createInsertBatchOps,
39
- createUpdateOneOps,
40
- createUpdateManyOps,
41
- createUpdateBatchOps, // 🆕 批量更新
42
- createReplaceOneOps,
43
- createUpsertOneOps, // upsertOne 便利方法
44
- createIncrementOneOps, // 新增:incrementOne 便利方法
45
- createFindOneAndUpdateOps,
46
- createFindOneAndReplaceOps,
47
- createDeleteOneOps,
48
- createDeleteManyOps,
49
- createDeleteBatchOps, // 🆕 批量删除
50
- createFindOneAndDeleteOps
51
- } = require('./writes');
52
-
53
- const { EventEmitter } = require('events');
54
- module.exports = class {
55
-
56
- /**
57
- * 初始化MongoDB实例
58
- * @param {string} type - 数据库类型
59
- * @param {string} databaseName - MongoDB数据库名称
60
- * @param {Object} cache - 缓存实例,用于缓存查询结果
61
- * @param {Object} logger - 日志记录器对象,用于记录操作和错误信息
62
- * @param {Object} [defaults] - 统一默认配置(maxTimeMS、namespace.instanceId 等)
63
- */
64
- constructor(type, databaseName, cache, logger, defaults = {}) {
65
- this.type = type;
66
- this.cache = cache;
67
- this.logger = logger;
68
- this.databaseName = databaseName;
69
- this.defaults = defaults || {};
70
- // 事件:connected/closed/error/slow-query
71
- this._emitter = new EventEmitter();
72
- this.on = this._emitter.on.bind(this._emitter);
73
- this.once = this._emitter.once.bind(this._emitter);
74
- this.off = (this._emitter.off ? this._emitter.off.bind(this._emitter) : this._emitter.removeListener.bind(this._emitter));
75
- this.emit = this._emitter.emit.bind(this._emitter);
76
- }
77
-
78
- /**
79
- * 连接到MongoDB数据库
80
- * @param {Object} config - MongoDB连接配置
81
- * @param {string} config.uri - MongoDB连接URI
82
- * @param {Object} [config.options={}] - MongoDB连接选项
83
- * @returns {MongoClient} 返回MongoDB客户端连接实例
84
- * @throws {Error} 当连接失败时记录错误日志
85
- */
86
- async connect(config) {
87
- // 如果已有连接,直接返回
88
- if (this.client) {
89
- return this.client;
90
- }
91
-
92
- // 防止并发连接:使用连接锁
93
- if (this._connecting) {
94
- return this._connecting;
95
- }
96
-
97
- this.config = config;
98
-
99
- try {
100
- this._connecting = (async () => {
101
- const { client, db, sshTunnel } = await connectMongo({
102
- databaseName: this.databaseName,
103
- config: this.config,
104
- logger: this.logger,
105
- defaults: this.defaults,
106
- type: this.type,
107
- });
108
- this.client = client;
109
- this.db = db;
110
- this._sshTunnel = sshTunnel; // 🔴 保存SSH隧道实例
111
-
112
- // 🔴 初始化慢查询日志存储
113
- this._initializeSlowQueryLog();
114
-
115
-
116
- try { this.emit && this.emit('connected', { type: this.type, db: this.databaseName, scope: this.defaults?.namespace?.scope }); } catch (_) { }
117
- return this.client;
118
- })();
119
-
120
- const result = await this._connecting;
121
- this._connecting = null;
122
- return result;
123
- } catch (err) {
124
- this._connecting = null;
125
- try { this.emit && this.emit('error', { type: this.type, db: this.databaseName, error: String(err && (err.message || err)) }); } catch (_) { }
126
- throw err;
127
- }
128
- }
129
-
130
- /**
131
- * 解析命名空间实例 id(iid)
132
- * 优先级:namespace.instanceId(固定) > scope='connection'(按初始库) > 默认/ 'database'(按访问库)
133
- * @param {string} dbName - 当前访问的数据库名
134
- * @returns {string} 解析后的 iid
135
- */
136
- resolveInstanceId(dbName) {
137
- return resolveNS(
138
- { genInstanceId },
139
- this.defaults,
140
- dbName,
141
- this.databaseName,
142
- this.config?.uri
143
- );
144
- }
145
-
146
- // 使用通用 withSlowQueryLog(保留方法名兼容测试),仅做薄代理
147
- async _withSlowQueryLog(op, ns, options, fn) {
148
- const iid = (() => {
149
- try {
150
- return this.resolveInstanceId?.(ns.db);
151
- } catch (_) {
152
- return undefined;
153
- }
154
- })();
155
- return withSlowQueryLog(
156
- this.logger,
157
- this.defaults,
158
- op,
159
- { db: ns.db, coll: ns.coll, iid, type: this.type },
160
- options,
161
- fn,
162
- mongoSlowLogShaper,
163
- this.onSlowQueryEmit // 🔴 传递慢查询回调
164
- );
165
- }
166
-
167
- collection(databaseName, collectionName) {
168
- if (!this.client) {
169
- const err = new Error('MongoDB is not connected. Call connect() before accessing collections.');
170
- err.code = 'NOT_CONNECTED';
171
- throw err;
172
- }
173
-
174
- // 输入验证:集合名称必须是非空字符串
175
- if (!collectionName || typeof collectionName !== 'string' || collectionName.trim() === '') {
176
- const err = new Error('Collection name must be a non-empty string.');
177
- err.code = 'INVALID_COLLECTION_NAME';
178
- throw err;
179
- }
180
-
181
- // 输入验证:数据库名称如果提供,必须是非空字符串
182
- if (databaseName !== undefined && databaseName !== null && (typeof databaseName !== 'string' || databaseName.trim() === '')) {
183
- const err = new Error('Database name must be a non-empty string or null/undefined.');
184
- err.code = 'INVALID_DATABASE_NAME';
185
- throw err;
186
- }
187
-
188
- const effectiveDbName = databaseName || this.databaseName;
189
-
190
- // 🆕 v1.0.8: 如果配置了多连接池,将选择逻辑传递给运行器
191
- const poolManager = this.poolManager;
192
-
193
- const db = this.client.db(effectiveDbName);
194
- const collection = db.collection(collectionName);
195
- // 生成实例唯一指纹(支持 scope 策略与显式覆盖)
196
- this._iidCache = this._iidCache || new Map();
197
- let instanceId = this._iidCache.get(effectiveDbName);
198
- if (!instanceId) {
199
- instanceId = this.resolveInstanceId(effectiveDbName);
200
- this._iidCache.set(effectiveDbName, instanceId);
201
- }
202
-
203
- // 保存 instanceId 作为实例属性(供测试访问)
204
- this.instanceId = instanceId;
205
-
206
- // 统一执行器:使用通用 runner + 键构造与慢日志去敏形状注入
207
- const run = createCachedRunner(this.cache, {
208
- iid: instanceId,
209
- type: this.type,
210
- db: effectiveDbName,
211
- collection: collection.collectionName,
212
- }, this.logger, this.defaults, {
213
- keyBuilder: mongoKeyBuilder,
214
- slowLogShaper: mongoSlowLogShaper,
215
- onSlowQueryEmit: (meta) => {
216
- try {
217
- // 触发slow-query事件,由事件监听器处理保存
218
- this.emit && this.emit('slow-query', meta);
219
- } catch (_) { }
220
- },
221
- onQueryEmit: (meta) => { try { this.emit && this.emit('query', meta); } catch (_) { } }
222
- });
223
-
224
- // 保存 this 引用
225
- const self = this;
226
-
227
- // 准备模块化上下文(暂不包含 getCollectionMethods,稍后添加)
228
- const moduleContext = {
229
- collection,
230
- db,
231
- collectionName: collection.collectionName, // 🔴 修复:添加 collectionName
232
- defaults: this.defaults,
233
- run,
234
- instanceId,
235
- effectiveDbName,
236
- logger: this.logger,
237
- emit: this.emit,
238
- mongoSlowLogShaper,
239
- type: this.type,
240
- cache: this.cache,
241
- getCache: () => this.cache, // 动态获取 cache(支持测试时的临时替换)
242
- autoConvertConfig: this.autoConvertConfig, // ✅ v1.3.0: 传递 ObjectId 自动转换配置
243
- cacheAutoInvalidate: this.defaults.cacheAutoInvalidate // 🆕 v1.1.6: 从 defaults 读取精准失效配置
244
- };
245
-
246
- // ========================================
247
- // 集合访问器对象
248
- // ========================================
249
- const accessor = {
250
- // 命名空间与元数据
251
- ...createNamespaceOps(moduleContext),
252
- // 集合管理操作
253
- ...createCollectionOps(moduleContext),
254
- // 验证操作 (v0.3.0+)
255
- ...createValidationOps(moduleContext),
256
- // 缓存管理
257
- ...createCacheOps(moduleContext),
258
- // 索引管理操作
259
- ...createIndexOps(moduleContext, effectiveDbName, collection.collectionName, collection),
260
- // 基础查询方法
261
- ...createFindOneOps(moduleContext),
262
- ...createFindOneByIdOps(moduleContext), // findOneById 便利方法
263
- ...createFindByIdsOps(moduleContext), // findByIds 便利方法
264
- ...createFindAndCountOps(moduleContext), // 新增:findAndCount 便利方法
265
- ...createFindOps(moduleContext),
266
- // 聚合与统计方法
267
- ...createCountOps(moduleContext),
268
- ...createAggregateOps(moduleContext),
269
- ...createDistinctOps(moduleContext),
270
- // explain 功能已集成到 find() 的链式调用和 options 参数中
271
- // 分页查询
272
- ...createFindPageOps(moduleContext),
273
- // 🆕 watch 方法 - Change Streams (v1.1.0)
274
- ...createWatchOps(moduleContext),
275
- // 写操作方法 - Insert
276
- ...createInsertOneOps(moduleContext),
277
- ...createInsertManyOps(moduleContext),
278
- // 写操作方法 - Update
279
- ...createUpdateOneOps(moduleContext),
280
- ...createUpdateManyOps(moduleContext),
281
- ...createReplaceOneOps(moduleContext),
282
- ...createUpsertOneOps(moduleContext), // upsertOne 便利方法
283
- ...createIncrementOneOps(moduleContext), // 新增:incrementOne 便利方法
284
- // 写操作方法 - Find and Modify
285
- ...createFindOneAndUpdateOps(moduleContext),
286
- ...createFindOneAndReplaceOps(moduleContext),
287
- // 写操作方法 - Delete
288
- ...createDeleteOneOps(moduleContext),
289
- ...createDeleteManyOps(moduleContext),
290
- ...createFindOneAndDeleteOps(moduleContext)
291
- };
292
-
293
- // 🔑 关键:insertBatch 依赖 insertMany,所以在 accessor 创建后添加
294
- const insertBatchOps = createInsertBatchOps({
295
- ...moduleContext,
296
- insertMany: accessor.insertMany // 传入 insertMany 方法
297
- });
298
- Object.assign(accessor, insertBatchOps);
299
-
300
- // 🔑 关键:deleteBatch 依赖 find(流式查询),所以在 accessor 创建后添加
301
- const deleteBatchOps = createDeleteBatchOps({
302
- ...moduleContext,
303
- find: accessor.find // 传入 find 方法(用于流式查询)
304
- });
305
- Object.assign(accessor, deleteBatchOps);
306
-
307
- // 🔑 关键:updateBatch 依赖 find(流式查询),所以在 accessor 创建后添加
308
- const updateBatchOps = createUpdateBatchOps({
309
- ...moduleContext,
310
- find: accessor.find // 传入 find 方法(用于流式查询)
311
- });
312
- Object.assign(accessor, updateBatchOps);
313
-
314
- // 🔑 关键:现在 accessor 已完整创建(包含 findPage),再创建依赖它的 bookmarkOps
315
- moduleContext.getCollectionMethods = () => accessor;
316
- const bookmarkOps = createBookmarkOps(moduleContext);
317
-
318
- // 将 bookmark 方法添加到 accessor
319
- Object.assign(accessor, bookmarkOps);
320
-
321
- return accessor;
322
- }
323
-
324
- /**
325
- * 健康检查:返回连接状态与默认/缓存摘要
326
- */
327
- async health() {
328
- const cache = this.cache;
329
- const cacheStats = (cache && typeof cache.getStats === 'function') ? cache.getStats() : undefined;
330
- return {
331
- status: this.client ? 'up' : 'down',
332
- connected: !!this.client,
333
- defaults: this.defaults,
334
- cache: cacheStats ? { ...cacheStats } : undefined,
335
- driver: { connected: !!this.client },
336
- };
337
- }
338
-
339
- /**
340
- * 从指定 MongoClient 创建包装 collection(用于多连接池 Model 绑定场景)
341
- *
342
- * 当 Model 定义了 `connection.pool` 时,`msq.model()` 会调用此方法,
343
- * 将指定连接池的 MongoClient 传入,复用现有 collection() 的完整包装逻辑
344
- * (runner、缓存、慢查询等),避免重复实现。
345
- *
346
- * 线程安全说明:Node.js 单线程,临时替换 this.client 的同步操作无竞态风险。
347
- *
348
- * @param {import('mongodb').MongoClient} client - 指定连接池的 MongoClient 实例
349
- * @param {string} databaseName - 数据库名称
350
- * @param {string} collectionName - 集合名称
351
- * @returns {Object} monSQLize 包装 collection 对象
352
- * @since v1.2.2
353
- */
354
- collectionFromClient(client, databaseName, collectionName) {
355
- const originalClient = this.client;
356
- this.client = client;
357
- try {
358
- return this.collection(databaseName, collectionName);
359
- } finally {
360
- this.client = originalClient;
361
- }
362
- }
363
-
364
- /**
365
- * 关闭连接并释放资源
366
- */
367
- async close() {
368
- // 🔴 关闭慢查询日志管理器
369
- if (this.slowQueryLogManager) {
370
- try {
371
- await this.slowQueryLogManager.close();
372
- this.slowQueryLogManager = null;
373
- this.onSlowQueryEmit = null;
374
- } catch (err) {
375
- if (this.logger.error) {
376
- this.logger.error('[SlowQueryLog] Failed to close manager:', err);
377
- }
378
- }
379
- }
380
-
381
- if (this.client) {
382
- await closeMongo(this.client, this.logger);
383
- }
384
- this.client = null;
385
- this.db = null;
386
- this._connecting = null;
387
-
388
- // 清理实例ID缓存,防止内存泄漏
389
- if (this._iidCache) {
390
- this._iidCache.clear();
391
- this._iidCache = null;
392
- }
393
-
394
- try { this.emit && this.emit('closed', { type: this.type, db: this.databaseName }); } catch (_) { }
395
- return true;
396
- }
397
-
398
- /**
399
- * 创建 MongoDB 会话(用于事务)
400
- * @param {Object} [sessionOptions] - 会话选项
401
- * @returns {Promise<ClientSession>} MongoDB 会话对象
402
- */
403
- async startSession(sessionOptions = {}) {
404
- if (!this.client) {
405
- const err = new Error('MongoDB is not connected. Call connect() before starting a session.');
406
- err.code = 'NOT_CONNECTED';
407
- throw err;
408
- }
409
-
410
- // 调用 MongoDB 客户端的 startSession
411
- return this.client.startSession(sessionOptions);
412
- }
413
-
414
- // ========================================
415
- // 运维监控方法 (v0.3.0+)
416
- // ========================================
417
-
418
- /**
419
- * 检测数据库连接是否正常
420
- * @returns {Promise<boolean>} 连接正常返回 true,否则返回 false
421
- */
422
- async ping() {
423
- if (!this.db) {
424
- throw new Error('MongoDB is not connected. Call connect() first.');
425
- }
426
- const adminOps = createAdminOps({ adapter: this, logger: this.logger });
427
- return adminOps.ping();
428
- }
429
-
430
- /**
431
- * 获取 MongoDB 版本信息
432
- * @returns {Promise<Object>} 版本信息对象
433
- */
434
- async buildInfo() {
435
- if (!this.db) {
436
- throw new Error('MongoDB is not connected. Call connect() first.');
437
- }
438
- const adminOps = createAdminOps({ adapter: this, logger: this.logger });
439
- return adminOps.buildInfo();
440
- }
441
-
442
- /**
443
- * 获取服务器状态信息
444
- * @param {Object} [options] - 选项
445
- * @returns {Promise<Object>} 服务器状态对象
446
- */
447
- async serverStatus(options) {
448
- if (!this.db) {
449
- throw new Error('MongoDB is not connected. Call connect() first.');
450
- }
451
- const adminOps = createAdminOps({ adapter: this, logger: this.logger });
452
- return adminOps.serverStatus(options);
453
- }
454
-
455
- /**
456
- * 获取数据库统计信息
457
- * @param {Object} [options] - 选项
458
- * @returns {Promise<Object>} 数据库统计对象
459
- */
460
- async stats(options) {
461
- if (!this.db) {
462
- throw new Error('MongoDB is not connected. Call connect() first.');
463
- }
464
- const adminOps = createAdminOps({ adapter: this, logger: this.logger });
465
- return adminOps.stats(options);
466
- }
467
-
468
- // ========================================
469
- // 数据库管理方法 (v0.3.0+)
470
- // ========================================
471
-
472
- /**
473
- * 列出所有数据库
474
- * @param {Object} [options] - 选项
475
- * @returns {Promise<Array<Object>|Array<string>>} 数据库列表
476
- */
477
- async listDatabases(options) {
478
- if (!this.db) {
479
- throw new Error('MongoDB is not connected. Call connect() first.');
480
- }
481
- const databaseOps = createDatabaseOps({ adapter: this, logger: this.logger });
482
- return databaseOps.listDatabases(options);
483
- }
484
-
485
- /**
486
- * 删除整个数据库(危险操作)
487
- * @param {string} databaseName - 数据库名称
488
- * @param {Object} options - 选项(必须包含 confirm: true)
489
- * @returns {Promise<Object>} 删除结果
490
- */
491
- async dropDatabase(databaseName, options) {
492
- if (!this.db) {
493
- throw new Error('MongoDB is not connected. Call connect() first.');
494
- }
495
- const databaseOps = createDatabaseOps({ adapter: this, logger: this.logger });
496
- return databaseOps.dropDatabase(databaseName, options);
497
- }
498
-
499
- /**
500
- * 列出当前数据库中的所有集合
501
- * @param {Object} [options] - 选项
502
- * @returns {Promise<Array<Object>|Array<string>>} 集合列表
503
- */
504
- async listCollections(options) {
505
- if (!this.db) {
506
- throw new Error('MongoDB is not connected. Call connect() first.');
507
- }
508
- const collectionOps = createCollectionOps({
509
- db: this.db,
510
- collection: null,
511
- logger: this.logger
512
- });
513
- return collectionOps.listCollections(options);
514
- }
515
-
516
- /**
517
- * 执行任意 MongoDB 命令
518
- * @param {Object} command - MongoDB 命令对象
519
- * @param {Object} [options] - 选项
520
- * @returns {Promise<Object>} 命令执行结果
521
- */
522
- async runCommand(command, options) {
523
- if (!this.db) {
524
- throw new Error('MongoDB is not connected. Call connect() first.');
525
- }
526
- const collectionOps = createCollectionOps({
527
- db: this.db,
528
- collection: null,
529
- logger: this.logger
530
- });
531
- return collectionOps.runCommand(command, options);
532
- }
533
-
534
- /**
535
- * 🔴 初始化慢查询日志存储
536
- * @private
537
- */
538
- _initializeSlowQueryLog() {
539
- const slowQueryLogConfig = this.defaults?.slowQueryLog;
540
-
541
- // 支持 boolean 快捷配置
542
- if (!slowQueryLogConfig) {
543
- return;
544
- }
545
-
546
- try {
547
- const { SlowQueryLogManager, SlowQueryLogConfigManager } = require('../slow-query-log');
548
-
549
- // 使用配置管理器合并配置
550
- const mergedConfig = SlowQueryLogConfigManager.mergeConfig(
551
- slowQueryLogConfig,
552
- this.type // 业务库类型(用于自动推断storage.type)
553
- );
554
-
555
- // 验证配置
556
- SlowQueryLogConfigManager.validate(mergedConfig, this.type);
557
-
558
- // 如果未启用,直接返回
559
- if (!mergedConfig.enabled) {
560
- return;
561
- }
562
-
563
- // 创建慢查询日志管理器
564
- this.slowQueryLogManager = new SlowQueryLogManager(
565
- mergedConfig,
566
- this.client, // 传递MongoDB客户端(复用连接)
567
- this.type, // 业务库类型
568
- this.logger
569
- );
570
-
571
- // 🔴 使用事件监听器代替直接回调
572
- // 监听 'slow-query' 事件,自动保存慢查询日志
573
- this.on('slow-query', async (meta) => {
574
- if (this.slowQueryLogManager) {
575
- try {
576
- await this.slowQueryLogManager.save(meta);
577
- } catch (err) {
578
- // 保存失败不影响主流程
579
- if (this.logger.error) {
580
- this.logger.error('[SlowQueryLog] Save failed:', err);
581
- }
582
- }
583
- }
584
- });
585
-
586
- if (this.logger.info) {
587
- this.logger.info('[SlowQueryLog] Manager initialized');
588
- }
589
- } catch (err) {
590
- if (this.logger.error) {
591
- this.logger.error('[SlowQueryLog] Failed to initialize:', err);
592
- }
593
- // 初始化失败不影响主流程
594
- }
595
- }
596
-
597
- /**
598
- * 🔴 获取慢查询日志(查询接口)
599
- * @param {Object} filter - 查询条件
600
- * @param {Object} options - 查询选项
601
- * @returns {Promise<Object[]>}
602
- */
603
- async getSlowQueryLogs(filter, options) {
604
- if (!this.slowQueryLogManager) {
605
- throw new Error('Slow query log is not enabled');
606
- }
607
- return this.slowQueryLogManager.query(filter, options);
608
- }
609
-
610
- /**
611
- * 🔴 关闭MongoDB连接和SSH隧道
612
- * @param {boolean} [stopMemory=false] - 是否停止Memory Server
613
- */
614
- async close(stopMemory = false) {
615
- if (!this.client) {
616
- return;
617
- }
618
-
619
- try {
620
- await closeMongo(
621
- this.client,
622
- this.logger,
623
- stopMemory,
624
- this._sshTunnel // 传递SSH隧道实例
625
- );
626
-
627
- this.client = null;
628
- this.db = null;
629
- this._sshTunnel = null;
630
-
631
- this.emit?.('closed', { type: this.type, db: this.databaseName });
632
- } catch (err) {
633
- this.logger?.error?.('❌ Failed to close MongoDB connection', err);
634
- throw err;
635
- }
636
- }
637
-
638
- };
639
-