monsqlize 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +2474 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1368 -0
  4. package/index.d.ts +1052 -0
  5. package/lib/cache.js +491 -0
  6. package/lib/common/cursor.js +58 -0
  7. package/lib/common/docs-urls.js +72 -0
  8. package/lib/common/index-options.js +222 -0
  9. package/lib/common/log.js +60 -0
  10. package/lib/common/namespace.js +21 -0
  11. package/lib/common/normalize.js +33 -0
  12. package/lib/common/page-result.js +42 -0
  13. package/lib/common/runner.js +56 -0
  14. package/lib/common/server-features.js +231 -0
  15. package/lib/common/shape-builders.js +26 -0
  16. package/lib/common/validation.js +49 -0
  17. package/lib/connect.js +76 -0
  18. package/lib/constants.js +54 -0
  19. package/lib/count-queue.js +187 -0
  20. package/lib/distributed-cache-invalidator.js +259 -0
  21. package/lib/errors.js +157 -0
  22. package/lib/index.js +352 -0
  23. package/lib/logger.js +224 -0
  24. package/lib/model/examples/test.js +114 -0
  25. package/lib/mongodb/common/accessor-helpers.js +44 -0
  26. package/lib/mongodb/common/agg-pipeline.js +32 -0
  27. package/lib/mongodb/common/iid.js +27 -0
  28. package/lib/mongodb/common/lexicographic-expr.js +52 -0
  29. package/lib/mongodb/common/shape.js +31 -0
  30. package/lib/mongodb/common/sort.js +38 -0
  31. package/lib/mongodb/common/transaction-aware.js +24 -0
  32. package/lib/mongodb/connect.js +178 -0
  33. package/lib/mongodb/index.js +458 -0
  34. package/lib/mongodb/management/admin-ops.js +199 -0
  35. package/lib/mongodb/management/bookmark-ops.js +166 -0
  36. package/lib/mongodb/management/cache-ops.js +49 -0
  37. package/lib/mongodb/management/collection-ops.js +386 -0
  38. package/lib/mongodb/management/database-ops.js +201 -0
  39. package/lib/mongodb/management/index-ops.js +474 -0
  40. package/lib/mongodb/management/index.js +16 -0
  41. package/lib/mongodb/management/namespace.js +30 -0
  42. package/lib/mongodb/management/validation-ops.js +267 -0
  43. package/lib/mongodb/queries/aggregate.js +133 -0
  44. package/lib/mongodb/queries/chain.js +623 -0
  45. package/lib/mongodb/queries/count.js +88 -0
  46. package/lib/mongodb/queries/distinct.js +68 -0
  47. package/lib/mongodb/queries/find-and-count.js +183 -0
  48. package/lib/mongodb/queries/find-by-ids.js +235 -0
  49. package/lib/mongodb/queries/find-one-by-id.js +170 -0
  50. package/lib/mongodb/queries/find-one.js +61 -0
  51. package/lib/mongodb/queries/find-page.js +565 -0
  52. package/lib/mongodb/queries/find.js +161 -0
  53. package/lib/mongodb/queries/index.js +49 -0
  54. package/lib/mongodb/writes/delete-many.js +181 -0
  55. package/lib/mongodb/writes/delete-one.js +173 -0
  56. package/lib/mongodb/writes/find-one-and-delete.js +193 -0
  57. package/lib/mongodb/writes/find-one-and-replace.js +222 -0
  58. package/lib/mongodb/writes/find-one-and-update.js +223 -0
  59. package/lib/mongodb/writes/increment-one.js +243 -0
  60. package/lib/mongodb/writes/index.js +41 -0
  61. package/lib/mongodb/writes/insert-batch.js +498 -0
  62. package/lib/mongodb/writes/insert-many.js +218 -0
  63. package/lib/mongodb/writes/insert-one.js +171 -0
  64. package/lib/mongodb/writes/replace-one.js +199 -0
  65. package/lib/mongodb/writes/result-handler.js +236 -0
  66. package/lib/mongodb/writes/update-many.js +205 -0
  67. package/lib/mongodb/writes/update-one.js +207 -0
  68. package/lib/mongodb/writes/upsert-one.js +190 -0
  69. package/lib/multi-level-cache.js +189 -0
  70. package/lib/operators.js +330 -0
  71. package/lib/redis-cache-adapter.js +237 -0
  72. package/lib/transaction/CacheLockManager.js +161 -0
  73. package/lib/transaction/DistributedCacheLockManager.js +239 -0
  74. package/lib/transaction/Transaction.js +314 -0
  75. package/lib/transaction/TransactionManager.js +266 -0
  76. package/lib/transaction/index.js +10 -0
  77. package/package.json +111 -0
@@ -0,0 +1,178 @@
1
+ const { MongoClient } = require('mongodb');
2
+
3
+ // 懒加载 MongoDB Memory Server(仅在需要时加载)
4
+ let MongoMemoryServer;
5
+ let MongoMemoryReplSet;
6
+ let memoryServerInstance; // 单例实例
7
+
8
+ function buildLogContext({ type, databaseName, defaults, config }) {
9
+ const scope = defaults?.namespace?.scope;
10
+ let uriHost;
11
+ try { uriHost = new URL(config?.uri || '').hostname; } catch (_) { uriHost = undefined; }
12
+ return { type, db: databaseName, scope, uriHost };
13
+ }
14
+
15
+ /**
16
+ * 启动 MongoDB Memory Server(单例模式)
17
+ * @param {Object} logger - 日志记录器
18
+ * @param {Object} [memoryServerOptions] - Memory Server 配置选项
19
+ * @returns {Promise<string>} 返回内存数据库的连接 URI
20
+ */
21
+ async function startMemoryServer(logger, memoryServerOptions = {}) {
22
+ if (memoryServerInstance) {
23
+ const uri = memoryServerInstance.getUri();
24
+ try { logger && logger.debug && logger.debug('📌 Using existing MongoDB Memory Server', { uri }); } catch (_) { }
25
+ return uri;
26
+ }
27
+
28
+ try {
29
+ // 检查是否需要副本集
30
+ const needsReplSet = memoryServerOptions?.instance?.replSet;
31
+
32
+ if (needsReplSet) {
33
+ // 使用副本集模式
34
+ if (!MongoMemoryReplSet) {
35
+ MongoMemoryReplSet = require('mongodb-memory-server').MongoMemoryReplSet;
36
+ }
37
+
38
+ try { logger && logger.info && logger.info('🚀 Starting MongoDB Memory Server (Replica Set)...', { replSet: needsReplSet }); } catch (_) { }
39
+
40
+ const replSetConfig = {
41
+ replSet: {
42
+ name: needsReplSet,
43
+ count: 1, // 单节点副本集(足以支持事务)
44
+ storageEngine: 'wiredTiger'
45
+ },
46
+ binary: {
47
+ version: '6.0.12'
48
+ }
49
+ };
50
+
51
+ memoryServerInstance = await MongoMemoryReplSet.create(replSetConfig);
52
+ const uri = memoryServerInstance.getUri();
53
+ try { logger && logger.info && logger.info('✅ MongoDB Memory Server (Replica Set) started', { uri, replSet: needsReplSet }); } catch (_) { }
54
+ return uri;
55
+ } else {
56
+ // 使用单实例模式
57
+ if (!MongoMemoryServer) {
58
+ MongoMemoryServer = require('mongodb-memory-server').MongoMemoryServer;
59
+ }
60
+
61
+ try { logger && logger.info && logger.info('🚀 Starting MongoDB Memory Server...'); } catch (_) { }
62
+
63
+ const defaultConfig = {
64
+ instance: {
65
+ port: undefined,
66
+ dbName: 'test_db',
67
+ storageEngine: 'ephemeralForTest',
68
+ },
69
+ binary: {
70
+ version: '6.0.12',
71
+ },
72
+ };
73
+
74
+ const config = {
75
+ ...defaultConfig,
76
+ ...memoryServerOptions,
77
+ instance: {
78
+ ...defaultConfig.instance,
79
+ ...(memoryServerOptions.instance || {})
80
+ },
81
+ binary: {
82
+ ...defaultConfig.binary,
83
+ ...(memoryServerOptions.binary || {})
84
+ }
85
+ };
86
+
87
+ memoryServerInstance = await MongoMemoryServer.create(config);
88
+ const uri = memoryServerInstance.getUri();
89
+ try { logger && logger.info && logger.info('✅ MongoDB Memory Server started', { uri }); } catch (_) { }
90
+ return uri;
91
+ }
92
+ } catch (err) {
93
+ try { logger && logger.error && logger.error('❌ Failed to start MongoDB Memory Server', err); } catch (_) { }
94
+ throw new Error(`Failed to start MongoDB Memory Server: ${err.message}`);
95
+ }
96
+ }
97
+
98
+ /**
99
+ * 停止 MongoDB Memory Server
100
+ * @param {Object} logger - 日志记录器
101
+ */
102
+ async function stopMemoryServer(logger) {
103
+ if (!memoryServerInstance) {
104
+ return;
105
+ }
106
+
107
+ try {
108
+ try { logger && logger.info && logger.info('🛑 Stopping MongoDB Memory Server...'); } catch (_) { }
109
+ await memoryServerInstance.stop();
110
+ memoryServerInstance = null;
111
+ try { logger && logger.info && logger.info('✅ MongoDB Memory Server stopped'); } catch (_) { }
112
+ } catch (err) {
113
+ try { logger && logger.warn && logger.warn('⚠️ Error stopping MongoDB Memory Server', err); } catch (_) { }
114
+ memoryServerInstance = null;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * 建立 MongoDB 连接(适配器内部使用)
120
+ * @param {{ databaseName: string, config: { uri?: string, options?: object, useMemoryServer?: boolean, readPreference?: string }, logger: any, defaults: object, type?: string }} params
121
+ * @returns {Promise<{ client: import('mongodb').MongoClient, db: any }>} 返回已连接的 client 与默认 db 句柄(若可用)
122
+ */
123
+ async function connectMongo({ databaseName, config, logger, defaults, type = 'mongodb' }) {
124
+ let { uri, options = {}, useMemoryServer, memoryServerOptions, readPreference } = config || {};
125
+
126
+ // 🔑 根据 config.useMemoryServer 决定是否使用内存数据库
127
+ if (useMemoryServer === true) {
128
+ try {
129
+ uri = await startMemoryServer(logger, memoryServerOptions);
130
+ } catch (err) {
131
+ // 如果启动内存服务器失败,且没有提供 uri,抛出错误
132
+ if (!uri) {
133
+ throw new Error('Failed to start Memory Server and no URI provided');
134
+ }
135
+ try { logger && logger.warn && logger.warn('Failed to start Memory Server, using provided URI', { uri }); } catch (_) { }
136
+ }
137
+ }
138
+
139
+ if (!uri) throw new Error('MongoDB connect requires config.uri or config.useMemoryServer');
140
+
141
+ // 🔑 合并 readPreference 到 MongoClient options
142
+ const clientOptions = { ...options };
143
+ if (readPreference) {
144
+ clientOptions.readPreference = readPreference;
145
+ }
146
+
147
+ const client = new MongoClient(uri, clientOptions);
148
+ try {
149
+ await client.connect();
150
+ let db = null;
151
+ try { db = client.db(databaseName); } catch (_) { db = null; }
152
+ const ctx = buildLogContext({ type, databaseName, defaults, config });
153
+ // try { logger && logger.info && logger.info('✅ MongoDB connected', ctx); } catch (_) {}
154
+ return { client, db };
155
+ } catch (err) {
156
+ const ctx = buildLogContext({ type, databaseName, defaults, config });
157
+ try { logger && logger.error && logger.error('❌ MongoDB connection failed', ctx, err); } catch (_) { }
158
+ throw err;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * 关闭 MongoDB 连接
164
+ * @param {import('mongodb').MongoClient} client
165
+ * @param {any} logger
166
+ * @param {boolean} [stopMemory=false] - 是否同时停止内存服务器
167
+ */
168
+ async function closeMongo(client, logger, stopMemory = false) {
169
+ if (!client) return;
170
+ try { await client.close(); } catch (e) { try { logger && logger.warn && logger.warn('MongoDB close error', e && (e.stack || e)); } catch (_) { } }
171
+
172
+ // 如果指定停止内存服务器
173
+ if (stopMemory) {
174
+ await stopMemoryServer(logger);
175
+ }
176
+ }
177
+
178
+ module.exports = { connectMongo, closeMongo, stopMemoryServer };
@@ -0,0 +1,458 @@
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
+ } = require('./queries');
22
+
23
+ const {
24
+ createNamespaceOps,
25
+ createCollectionOps,
26
+ createCacheOps,
27
+ createBookmarkOps,
28
+ createIndexOps,
29
+ createAdminOps,
30
+ createDatabaseOps,
31
+ createValidationOps
32
+ } = require('./management');
33
+
34
+ const {
35
+ createInsertOneOps,
36
+ createInsertManyOps,
37
+ createInsertBatchOps,
38
+ createUpdateOneOps,
39
+ createUpdateManyOps,
40
+ createReplaceOneOps,
41
+ createUpsertOneOps, // upsertOne 便利方法
42
+ createIncrementOneOps, // 新增:incrementOne 便利方法
43
+ createFindOneAndUpdateOps,
44
+ createFindOneAndReplaceOps,
45
+ createDeleteOneOps,
46
+ createDeleteManyOps,
47
+ createFindOneAndDeleteOps
48
+ } = require("./writes");
49
+
50
+ const { EventEmitter } = require('events');
51
+ module.exports = class {
52
+
53
+ /**
54
+ * 初始化MongoDB实例
55
+ * @param {string} type - 数据库类型
56
+ * @param {string} databaseName - MongoDB数据库名称
57
+ * @param {Object} cache - 缓存实例,用于缓存查询结果
58
+ * @param {Object} logger - 日志记录器对象,用于记录操作和错误信息
59
+ * @param {Object} [defaults] - 统一默认配置(maxTimeMS、namespace.instanceId 等)
60
+ */
61
+ constructor(type, databaseName, cache, logger, defaults = {}) {
62
+ this.type = type;
63
+ this.cache = cache;
64
+ this.logger = logger;
65
+ this.databaseName = databaseName;
66
+ this.defaults = defaults || {};
67
+ // 事件:connected/closed/error/slow-query
68
+ this._emitter = new EventEmitter();
69
+ this.on = this._emitter.on.bind(this._emitter);
70
+ this.once = this._emitter.once.bind(this._emitter);
71
+ this.off = (this._emitter.off ? this._emitter.off.bind(this._emitter) : this._emitter.removeListener.bind(this._emitter));
72
+ this.emit = this._emitter.emit.bind(this._emitter);
73
+ }
74
+
75
+ /**
76
+ * 连接到MongoDB数据库
77
+ * @param {Object} config - MongoDB连接配置
78
+ * @param {string} config.uri - MongoDB连接URI
79
+ * @param {Object} [config.options={}] - MongoDB连接选项
80
+ * @returns {MongoClient} 返回MongoDB客户端连接实例
81
+ * @throws {Error} 当连接失败时记录错误日志
82
+ */
83
+ async connect(config) {
84
+ // 如果已有连接,直接返回
85
+ if (this.client) {
86
+ return this.client;
87
+ }
88
+
89
+ // 防止并发连接:使用连接锁
90
+ if (this._connecting) {
91
+ return this._connecting;
92
+ }
93
+
94
+ this.config = config;
95
+
96
+ try {
97
+ this._connecting = (async () => {
98
+ const { client, db } = await connectMongo({
99
+ databaseName: this.databaseName,
100
+ config: this.config,
101
+ logger: this.logger,
102
+ defaults: this.defaults,
103
+ type: this.type,
104
+ });
105
+ this.client = client;
106
+ this.db = db;
107
+ try { this.emit && this.emit('connected', { type: this.type, db: this.databaseName, scope: this.defaults?.namespace?.scope }); } catch (_) { }
108
+ return this.client;
109
+ })();
110
+
111
+ const result = await this._connecting;
112
+ this._connecting = null;
113
+ return result;
114
+ } catch (err) {
115
+ this._connecting = null;
116
+ try { this.emit && this.emit('error', { type: this.type, db: this.databaseName, error: String(err && (err.message || err)) }); } catch (_) { }
117
+ throw err;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * 解析命名空间实例 id(iid)
123
+ * 优先级:namespace.instanceId(固定) > scope='connection'(按初始库) > 默认/ 'database'(按访问库)
124
+ * @param {string} dbName - 当前访问的数据库名
125
+ * @returns {string} 解析后的 iid
126
+ */
127
+ resolveInstanceId(dbName) {
128
+ return resolveNS(
129
+ { genInstanceId },
130
+ this.defaults,
131
+ dbName,
132
+ this.databaseName,
133
+ this.config?.uri
134
+ );
135
+ }
136
+
137
+ // 使用通用 withSlowQueryLog(保留方法名兼容测试),仅做薄代理
138
+ async _withSlowQueryLog(op, ns, options, fn) {
139
+ const iid = (() => {
140
+ try {
141
+ return this.resolveInstanceId?.(ns.db);
142
+ } catch (_) {
143
+ return undefined;
144
+ }
145
+ })();
146
+ return withSlowQueryLog(
147
+ this.logger,
148
+ this.defaults,
149
+ op,
150
+ { db: ns.db, coll: ns.coll, iid, type: this.type },
151
+ options,
152
+ fn,
153
+ mongoSlowLogShaper
154
+ );
155
+ }
156
+
157
+ collection(databaseName, collectionName) {
158
+ if (!this.client) {
159
+ const err = new Error('MongoDB is not connected. Call connect() before accessing collections.');
160
+ err.code = 'NOT_CONNECTED';
161
+ throw err;
162
+ }
163
+
164
+ // 输入验证:集合名称必须是非空字符串
165
+ if (!collectionName || typeof collectionName !== 'string' || collectionName.trim() === '') {
166
+ const err = new Error('Collection name must be a non-empty string.');
167
+ err.code = 'INVALID_COLLECTION_NAME';
168
+ throw err;
169
+ }
170
+
171
+ // 输入验证:数据库名称如果提供,必须是非空字符串
172
+ if (databaseName !== undefined && databaseName !== null && (typeof databaseName !== 'string' || databaseName.trim() === '')) {
173
+ const err = new Error('Database name must be a non-empty string or null/undefined.');
174
+ err.code = 'INVALID_DATABASE_NAME';
175
+ throw err;
176
+ }
177
+
178
+ const effectiveDbName = databaseName || this.databaseName;
179
+ const db = this.client.db(effectiveDbName);
180
+ const collection = db.collection(collectionName);
181
+ // 生成实例唯一指纹(支持 scope 策略与显式覆盖)
182
+ this._iidCache = this._iidCache || new Map();
183
+ let instanceId = this._iidCache.get(effectiveDbName);
184
+ if (!instanceId) {
185
+ instanceId = this.resolveInstanceId(effectiveDbName);
186
+ this._iidCache.set(effectiveDbName, instanceId);
187
+ }
188
+
189
+ // 保存 instanceId 作为实例属性(供测试访问)
190
+ this.instanceId = instanceId;
191
+
192
+ // 统一执行器:使用通用 runner + 键构造与慢日志去敏形状注入
193
+ const run = createCachedRunner(this.cache, {
194
+ iid: instanceId,
195
+ type: this.type,
196
+ db: effectiveDbName,
197
+ collection: collection.collectionName,
198
+ }, this.logger, this.defaults, {
199
+ keyBuilder: mongoKeyBuilder,
200
+ slowLogShaper: mongoSlowLogShaper,
201
+ onSlowQueryEmit: (meta) => { try { this.emit && this.emit('slow-query', meta); } catch (_) { } },
202
+ onQueryEmit: (meta) => { try { this.emit && this.emit('query', meta); } catch (_) { } }
203
+ });
204
+
205
+ // 保存 this 引用
206
+ const self = this;
207
+
208
+ // 准备模块化上下文(暂不包含 getCollectionMethods,稍后添加)
209
+ const moduleContext = {
210
+ collection,
211
+ db,
212
+ defaults: this.defaults,
213
+ run,
214
+ instanceId,
215
+ effectiveDbName,
216
+ logger: this.logger,
217
+ emit: this.emit,
218
+ mongoSlowLogShaper,
219
+ type: this.type,
220
+ cache: this.cache,
221
+ getCache: () => this.cache // 动态获取 cache(支持测试时的临时替换)
222
+ };
223
+
224
+ // ========================================
225
+ // 集合访问器对象
226
+ // ========================================
227
+ const accessor = {
228
+ // 命名空间与元数据
229
+ ...createNamespaceOps(moduleContext),
230
+ // 集合管理操作
231
+ ...createCollectionOps(moduleContext),
232
+ // 验证操作 (v0.3.0+)
233
+ ...createValidationOps(moduleContext),
234
+ // 缓存管理
235
+ ...createCacheOps(moduleContext),
236
+ // 索引管理操作
237
+ ...createIndexOps(moduleContext, effectiveDbName, collection.collectionName, collection),
238
+ // 基础查询方法
239
+ ...createFindOneOps(moduleContext),
240
+ ...createFindOneByIdOps(moduleContext), // findOneById 便利方法
241
+ ...createFindByIdsOps(moduleContext), // findByIds 便利方法
242
+ ...createFindAndCountOps(moduleContext), // 新增:findAndCount 便利方法
243
+ ...createFindOps(moduleContext),
244
+ // 聚合与统计方法
245
+ ...createCountOps(moduleContext),
246
+ ...createAggregateOps(moduleContext),
247
+ ...createDistinctOps(moduleContext),
248
+ // explain 功能已集成到 find() 的链式调用和 options 参数中
249
+ // 分页查询
250
+ ...createFindPageOps(moduleContext),
251
+ // 写操作方法 - Insert
252
+ ...createInsertOneOps(moduleContext),
253
+ ...createInsertManyOps(moduleContext),
254
+ // 写操作方法 - Update
255
+ ...createUpdateOneOps(moduleContext),
256
+ ...createUpdateManyOps(moduleContext),
257
+ ...createReplaceOneOps(moduleContext),
258
+ ...createUpsertOneOps(moduleContext), // upsertOne 便利方法
259
+ ...createIncrementOneOps(moduleContext), // 新增:incrementOne 便利方法
260
+ // 写操作方法 - Find and Modify
261
+ ...createFindOneAndUpdateOps(moduleContext),
262
+ ...createFindOneAndReplaceOps(moduleContext),
263
+ // 写操作方法 - Delete
264
+ ...createDeleteOneOps(moduleContext),
265
+ ...createDeleteManyOps(moduleContext),
266
+ ...createFindOneAndDeleteOps(moduleContext)
267
+ };
268
+
269
+ // 🔑 关键:insertBatch 依赖 insertMany,所以在 accessor 创建后添加
270
+ const insertBatchOps = createInsertBatchOps({
271
+ ...moduleContext,
272
+ insertMany: accessor.insertMany // 传入 insertMany 方法
273
+ });
274
+ Object.assign(accessor, insertBatchOps);
275
+
276
+ // 🔑 关键:现在 accessor 已完整创建(包含 findPage),再创建依赖它的 bookmarkOps
277
+ moduleContext.getCollectionMethods = () => accessor;
278
+ const bookmarkOps = createBookmarkOps(moduleContext);
279
+
280
+ // 将 bookmark 方法添加到 accessor
281
+ Object.assign(accessor, bookmarkOps);
282
+
283
+ return accessor;
284
+ }
285
+
286
+ /**
287
+ * 健康检查:返回连接状态与默认/缓存摘要
288
+ */
289
+ async health() {
290
+ const cache = this.cache;
291
+ const cacheStats = (cache && typeof cache.getStats === 'function') ? cache.getStats() : undefined;
292
+ return {
293
+ status: this.client ? 'up' : 'down',
294
+ connected: !!this.client,
295
+ defaults: this.defaults,
296
+ cache: cacheStats ? { ...cacheStats } : undefined,
297
+ driver: { connected: !!this.client },
298
+ };
299
+ }
300
+
301
+ /**
302
+ * 关闭连接并释放资源
303
+ */
304
+ async close() {
305
+ if (this.client) {
306
+ await closeMongo(this.client, this.logger);
307
+ }
308
+ this.client = null;
309
+ this.db = null;
310
+ this._connecting = null;
311
+
312
+ // 清理实例ID缓存,防止内存泄漏
313
+ if (this._iidCache) {
314
+ this._iidCache.clear();
315
+ this._iidCache = null;
316
+ }
317
+
318
+ try { this.emit && this.emit('closed', { type: this.type, db: this.databaseName }); } catch (_) { }
319
+ return true;
320
+ }
321
+
322
+ /**
323
+ * 创建 MongoDB 会话(用于事务)
324
+ * @param {Object} [sessionOptions] - 会话选项
325
+ * @returns {Promise<ClientSession>} MongoDB 会话对象
326
+ */
327
+ async startSession(sessionOptions = {}) {
328
+ if (!this.client) {
329
+ const err = new Error('MongoDB is not connected. Call connect() before starting a session.');
330
+ err.code = 'NOT_CONNECTED';
331
+ throw err;
332
+ }
333
+
334
+ // 调用 MongoDB 客户端的 startSession
335
+ return this.client.startSession(sessionOptions);
336
+ }
337
+
338
+ // ========================================
339
+ // 运维监控方法 (v0.3.0+)
340
+ // ========================================
341
+
342
+ /**
343
+ * 检测数据库连接是否正常
344
+ * @returns {Promise<boolean>} 连接正常返回 true,否则返回 false
345
+ */
346
+ async ping() {
347
+ if (!this.db) {
348
+ throw new Error('MongoDB is not connected. Call connect() first.');
349
+ }
350
+ const adminOps = createAdminOps({ adapter: this, logger: this.logger });
351
+ return adminOps.ping();
352
+ }
353
+
354
+ /**
355
+ * 获取 MongoDB 版本信息
356
+ * @returns {Promise<Object>} 版本信息对象
357
+ */
358
+ async buildInfo() {
359
+ if (!this.db) {
360
+ throw new Error('MongoDB is not connected. Call connect() first.');
361
+ }
362
+ const adminOps = createAdminOps({ adapter: this, logger: this.logger });
363
+ return adminOps.buildInfo();
364
+ }
365
+
366
+ /**
367
+ * 获取服务器状态信息
368
+ * @param {Object} [options] - 选项
369
+ * @returns {Promise<Object>} 服务器状态对象
370
+ */
371
+ async serverStatus(options) {
372
+ if (!this.db) {
373
+ throw new Error('MongoDB is not connected. Call connect() first.');
374
+ }
375
+ const adminOps = createAdminOps({ adapter: this, logger: this.logger });
376
+ return adminOps.serverStatus(options);
377
+ }
378
+
379
+ /**
380
+ * 获取数据库统计信息
381
+ * @param {Object} [options] - 选项
382
+ * @returns {Promise<Object>} 数据库统计对象
383
+ */
384
+ async stats(options) {
385
+ if (!this.db) {
386
+ throw new Error('MongoDB is not connected. Call connect() first.');
387
+ }
388
+ const adminOps = createAdminOps({ adapter: this, logger: this.logger });
389
+ return adminOps.stats(options);
390
+ }
391
+
392
+ // ========================================
393
+ // 数据库管理方法 (v0.3.0+)
394
+ // ========================================
395
+
396
+ /**
397
+ * 列出所有数据库
398
+ * @param {Object} [options] - 选项
399
+ * @returns {Promise<Array<Object>|Array<string>>} 数据库列表
400
+ */
401
+ async listDatabases(options) {
402
+ if (!this.db) {
403
+ throw new Error('MongoDB is not connected. Call connect() first.');
404
+ }
405
+ const databaseOps = createDatabaseOps({ adapter: this, logger: this.logger });
406
+ return databaseOps.listDatabases(options);
407
+ }
408
+
409
+ /**
410
+ * 删除整个数据库(危险操作)
411
+ * @param {string} databaseName - 数据库名称
412
+ * @param {Object} options - 选项(必须包含 confirm: true)
413
+ * @returns {Promise<Object>} 删除结果
414
+ */
415
+ async dropDatabase(databaseName, options) {
416
+ if (!this.db) {
417
+ throw new Error('MongoDB is not connected. Call connect() first.');
418
+ }
419
+ const databaseOps = createDatabaseOps({ adapter: this, logger: this.logger });
420
+ return databaseOps.dropDatabase(databaseName, options);
421
+ }
422
+
423
+ /**
424
+ * 列出当前数据库中的所有集合
425
+ * @param {Object} [options] - 选项
426
+ * @returns {Promise<Array<Object>|Array<string>>} 集合列表
427
+ */
428
+ async listCollections(options) {
429
+ if (!this.db) {
430
+ throw new Error('MongoDB is not connected. Call connect() first.');
431
+ }
432
+ const collectionOps = createCollectionOps({
433
+ db: this.db,
434
+ collection: null,
435
+ logger: this.logger
436
+ });
437
+ return collectionOps.listCollections(options);
438
+ }
439
+
440
+ /**
441
+ * 执行任意 MongoDB 命令
442
+ * @param {Object} command - MongoDB 命令对象
443
+ * @param {Object} [options] - 选项
444
+ * @returns {Promise<Object>} 命令执行结果
445
+ */
446
+ async runCommand(command, options) {
447
+ if (!this.db) {
448
+ throw new Error('MongoDB is not connected. Call connect() first.');
449
+ }
450
+ const collectionOps = createCollectionOps({
451
+ db: this.db,
452
+ collection: null,
453
+ logger: this.logger
454
+ });
455
+ return collectionOps.runCommand(command, options);
456
+ }
457
+
458
+ }