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