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.
- package/CHANGELOG.md +2474 -0
- package/LICENSE +21 -0
- package/README.md +1368 -0
- package/index.d.ts +1052 -0
- package/lib/cache.js +491 -0
- package/lib/common/cursor.js +58 -0
- package/lib/common/docs-urls.js +72 -0
- package/lib/common/index-options.js +222 -0
- package/lib/common/log.js +60 -0
- package/lib/common/namespace.js +21 -0
- package/lib/common/normalize.js +33 -0
- package/lib/common/page-result.js +42 -0
- package/lib/common/runner.js +56 -0
- package/lib/common/server-features.js +231 -0
- package/lib/common/shape-builders.js +26 -0
- package/lib/common/validation.js +49 -0
- package/lib/connect.js +76 -0
- package/lib/constants.js +54 -0
- package/lib/count-queue.js +187 -0
- package/lib/distributed-cache-invalidator.js +259 -0
- package/lib/errors.js +157 -0
- package/lib/index.js +352 -0
- package/lib/logger.js +224 -0
- package/lib/model/examples/test.js +114 -0
- package/lib/mongodb/common/accessor-helpers.js +44 -0
- package/lib/mongodb/common/agg-pipeline.js +32 -0
- package/lib/mongodb/common/iid.js +27 -0
- package/lib/mongodb/common/lexicographic-expr.js +52 -0
- package/lib/mongodb/common/shape.js +31 -0
- package/lib/mongodb/common/sort.js +38 -0
- package/lib/mongodb/common/transaction-aware.js +24 -0
- package/lib/mongodb/connect.js +178 -0
- package/lib/mongodb/index.js +458 -0
- package/lib/mongodb/management/admin-ops.js +199 -0
- package/lib/mongodb/management/bookmark-ops.js +166 -0
- package/lib/mongodb/management/cache-ops.js +49 -0
- package/lib/mongodb/management/collection-ops.js +386 -0
- package/lib/mongodb/management/database-ops.js +201 -0
- package/lib/mongodb/management/index-ops.js +474 -0
- package/lib/mongodb/management/index.js +16 -0
- package/lib/mongodb/management/namespace.js +30 -0
- package/lib/mongodb/management/validation-ops.js +267 -0
- package/lib/mongodb/queries/aggregate.js +133 -0
- package/lib/mongodb/queries/chain.js +623 -0
- package/lib/mongodb/queries/count.js +88 -0
- package/lib/mongodb/queries/distinct.js +68 -0
- package/lib/mongodb/queries/find-and-count.js +183 -0
- package/lib/mongodb/queries/find-by-ids.js +235 -0
- package/lib/mongodb/queries/find-one-by-id.js +170 -0
- package/lib/mongodb/queries/find-one.js +61 -0
- package/lib/mongodb/queries/find-page.js +565 -0
- package/lib/mongodb/queries/find.js +161 -0
- package/lib/mongodb/queries/index.js +49 -0
- package/lib/mongodb/writes/delete-many.js +181 -0
- package/lib/mongodb/writes/delete-one.js +173 -0
- package/lib/mongodb/writes/find-one-and-delete.js +193 -0
- package/lib/mongodb/writes/find-one-and-replace.js +222 -0
- package/lib/mongodb/writes/find-one-and-update.js +223 -0
- package/lib/mongodb/writes/increment-one.js +243 -0
- package/lib/mongodb/writes/index.js +41 -0
- package/lib/mongodb/writes/insert-batch.js +498 -0
- package/lib/mongodb/writes/insert-many.js +218 -0
- package/lib/mongodb/writes/insert-one.js +171 -0
- package/lib/mongodb/writes/replace-one.js +199 -0
- package/lib/mongodb/writes/result-handler.js +236 -0
- package/lib/mongodb/writes/update-many.js +205 -0
- package/lib/mongodb/writes/update-one.js +207 -0
- package/lib/mongodb/writes/upsert-one.js +190 -0
- package/lib/multi-level-cache.js +189 -0
- package/lib/operators.js +330 -0
- package/lib/redis-cache-adapter.js +237 -0
- package/lib/transaction/CacheLockManager.js +161 -0
- package/lib/transaction/DistributedCacheLockManager.js +239 -0
- package/lib/transaction/Transaction.js +314 -0
- package/lib/transaction/TransactionManager.js +266 -0
- package/lib/transaction/index.js +10 -0
- package/package.json +111 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* find 查询模块
|
|
3
|
+
* @description 提供多条记录查询功能,支持投影、排序、分页、缓存和流式返回
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { normalizeProjection, normalizeSort } = require('../../common/normalize');
|
|
7
|
+
const { FindChain } = require('./chain');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 创建 find 查询操作
|
|
11
|
+
* @param {Object} context - 上下文对象
|
|
12
|
+
* @param {Object} context.collection - MongoDB 集合实例
|
|
13
|
+
* @param {Object} context.defaults - 默认配置
|
|
14
|
+
* @param {Function} context.run - 缓存执行器
|
|
15
|
+
* @param {string} context.instanceId - 实例ID
|
|
16
|
+
* @param {string} context.effectiveDbName - 数据库名
|
|
17
|
+
* @param {Object} context.logger - 日志器
|
|
18
|
+
* @param {Function} context.emit - 事件发射器
|
|
19
|
+
* @param {Object} context.mongoSlowLogShaper - 慢查询日志格式化器
|
|
20
|
+
* @returns {Object} 包含 find 和 stream 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createFindOps(context) {
|
|
23
|
+
const {
|
|
24
|
+
collection,
|
|
25
|
+
defaults,
|
|
26
|
+
run,
|
|
27
|
+
instanceId,
|
|
28
|
+
effectiveDbName,
|
|
29
|
+
logger,
|
|
30
|
+
emit,
|
|
31
|
+
mongoSlowLogShaper
|
|
32
|
+
} = context;
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
/**
|
|
36
|
+
* 查询多条记录
|
|
37
|
+
* @param {Object} [query={}] - 查询条件,使用 MongoDB 查询语法
|
|
38
|
+
* @param {Object} [options={}] - 查询选项 { projection, sort, limit, skip, cache, maxTimeMS, stream, explain }
|
|
39
|
+
* @param {Object|Array} [options.projection] - 字段投影配置
|
|
40
|
+
* @param {Object} [options.sort] - 排序配置
|
|
41
|
+
* @param {number} [options.limit] - 限制返回数量
|
|
42
|
+
* @param {number} [options.skip] - 跳过记录数
|
|
43
|
+
* @param {number} [options.cache] - 缓存时间(毫秒)
|
|
44
|
+
* @param {number} [options.maxTimeMS] - 查询超时时间(毫秒)
|
|
45
|
+
* @param {boolean} [options.stream] - 是否使用流式返回
|
|
46
|
+
* @param {number} [options.batchSize] - 批处理大小
|
|
47
|
+
* @param {boolean|string} [options.explain] - 是否返回查询执行计划,可选值:true/'queryPlanner'/'executionStats'/'allPlansExecution'
|
|
48
|
+
* @param {string} [options.hint] - 索引提示
|
|
49
|
+
* @param {Object} [options.collation] - 排序规则
|
|
50
|
+
* @param {string} [options.comment] - 查询注释
|
|
51
|
+
* @returns {Promise<Array>|ReadableStream|FindChain} 记录数组或可读流(当 stream: true 时);当 explain=true 时返回执行计划;默认返回 FindChain 实例支持链式调用
|
|
52
|
+
*/
|
|
53
|
+
find: (query = {}, options = {}) => {
|
|
54
|
+
// 如果没有提供 options 或 options 为空对象,返回 FindChain 以支持完整的链式调用
|
|
55
|
+
const hasOptions = options && Object.keys(options).length > 0;
|
|
56
|
+
|
|
57
|
+
if (!hasOptions) {
|
|
58
|
+
// 返回 FindChain 实例,支持 .limit().skip().sort() 等链式调用
|
|
59
|
+
return new FindChain(context, query, {});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 如果提供了 options,执行原有逻辑(向后兼容)
|
|
63
|
+
options.projection = normalizeProjection(options.projection);
|
|
64
|
+
const {
|
|
65
|
+
projection,
|
|
66
|
+
limit = defaults.findLimit,
|
|
67
|
+
skip,
|
|
68
|
+
maxTimeMS = defaults.maxTimeMS,
|
|
69
|
+
stream = false,
|
|
70
|
+
batchSize,
|
|
71
|
+
explain,
|
|
72
|
+
comment
|
|
73
|
+
} = options;
|
|
74
|
+
const sort = normalizeSort(options.sort);
|
|
75
|
+
|
|
76
|
+
const driverOpts = { projection, sort, skip, maxTimeMS, ...(options.hint ? { hint: options.hint } : {}), ...(options.collation ? { collation: options.collation } : {}) };
|
|
77
|
+
if (limit !== undefined) driverOpts.limit = limit;
|
|
78
|
+
if (batchSize !== undefined) driverOpts.batchSize = batchSize;
|
|
79
|
+
if (comment) driverOpts.comment = comment;
|
|
80
|
+
|
|
81
|
+
// 如果启用 explain,直接返回执行计划(不缓存)
|
|
82
|
+
if (explain) {
|
|
83
|
+
const verbosity = typeof explain === 'string' ? explain : 'queryPlanner';
|
|
84
|
+
const cursor = collection.find(query, driverOpts);
|
|
85
|
+
return cursor.explain(verbosity);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// 如果启用流式返回,直接返回 MongoDB 游标流
|
|
89
|
+
if (stream) {
|
|
90
|
+
const cursor = collection.find(query, driverOpts);
|
|
91
|
+
const readableStream = cursor.stream();
|
|
92
|
+
|
|
93
|
+
// 添加慢查询日志支持
|
|
94
|
+
const startTime = Date.now();
|
|
95
|
+
let docCount = 0;
|
|
96
|
+
|
|
97
|
+
readableStream.on('data', () => {
|
|
98
|
+
docCount++;
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
readableStream.on('end', () => {
|
|
102
|
+
const durationMs = Date.now() - startTime;
|
|
103
|
+
const slowQueryMs = defaults?.slowQueryMs || 500;
|
|
104
|
+
|
|
105
|
+
if (durationMs >= slowQueryMs) {
|
|
106
|
+
try {
|
|
107
|
+
const meta = {
|
|
108
|
+
op: 'stream',
|
|
109
|
+
durationMs,
|
|
110
|
+
docCount,
|
|
111
|
+
iid: instanceId,
|
|
112
|
+
type: context.type,
|
|
113
|
+
db: effectiveDbName,
|
|
114
|
+
collection: collection.collectionName,
|
|
115
|
+
query: mongoSlowLogShaper?.sanitize ? mongoSlowLogShaper.sanitize(query) : query,
|
|
116
|
+
limit,
|
|
117
|
+
};
|
|
118
|
+
logger?.warn?.('🐌 Slow stream query', meta);
|
|
119
|
+
emit?.('slow-query', meta);
|
|
120
|
+
} catch (_) { }
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
return readableStream;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 执行查询的 Promise
|
|
128
|
+
const resultPromise = run(
|
|
129
|
+
'find',
|
|
130
|
+
{ query, ...options },
|
|
131
|
+
async () => collection.find(query, driverOpts).toArray()
|
|
132
|
+
);
|
|
133
|
+
|
|
134
|
+
// 添加 explain 方法支持链式调用(与原生 MongoDB 一致)
|
|
135
|
+
resultPromise.explain = async (verbosity = 'queryPlanner') => {
|
|
136
|
+
const cursor = collection.find(query, driverOpts);
|
|
137
|
+
return cursor.explain(verbosity);
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
return resultPromise;
|
|
141
|
+
},
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 流式查询多条记录(语法糖方法)
|
|
145
|
+
* @description 这是 find(query, {...options, stream: true}) 的便捷方法
|
|
146
|
+
* @param {Object} [query={}] - 查询条件
|
|
147
|
+
* @param {Object} [options={}] - { projection, sort, limit, skip, maxTimeMS, batchSize }
|
|
148
|
+
* @returns {ReadableStream} MongoDB 游标流
|
|
149
|
+
*/
|
|
150
|
+
stream: (query = {}, options = {}) => {
|
|
151
|
+
// 注意:这里需要通过回调获取完整的 collection 方法对象
|
|
152
|
+
// 在主文件中会重写这个方法
|
|
153
|
+
return context.getCollectionMethods().find(query, {
|
|
154
|
+
...options,
|
|
155
|
+
stream: true
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
module.exports = createFindOps;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 查询模块统一导出
|
|
3
|
+
* @module queries
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { createFindPage, bookmarkKey, buildKeyDimsAuto } = require('./find-page');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 创建 findPage 操作(工厂函数包装)
|
|
10
|
+
* @param {Object} context - 上下文对象
|
|
11
|
+
* @returns {Object} 包含 findPage 方法
|
|
12
|
+
*/
|
|
13
|
+
function createFindPageOps(context) {
|
|
14
|
+
const { collection, getCache, instanceId, type, effectiveDbName, defaults, logger, run } = context;
|
|
15
|
+
|
|
16
|
+
// 预构建 ns 字符串,确保书签键稳定
|
|
17
|
+
const nsStr = `${instanceId}:${type}:${effectiveDbName}:${collection.collectionName}`;
|
|
18
|
+
|
|
19
|
+
const findPageImpl = createFindPage({
|
|
20
|
+
collection,
|
|
21
|
+
getCache, // 直接传递 getCache 回调
|
|
22
|
+
getNamespace: () => ({ ns: nsStr, db: effectiveDbName, coll: collection.collectionName }),
|
|
23
|
+
defaults,
|
|
24
|
+
logger,
|
|
25
|
+
databaseName: effectiveDbName,
|
|
26
|
+
collectionName: collection.collectionName,
|
|
27
|
+
run
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
findPage: async (options = {}) => findPageImpl(options)
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = {
|
|
36
|
+
createFindOps: require('./find'),
|
|
37
|
+
createFindOneOps: require('./find-one'),
|
|
38
|
+
createFindOneByIdOps: require('./find-one-by-id').createFindOneByIdOps, // findOneById 便利方法
|
|
39
|
+
createFindByIdsOps: require('./find-by-ids').createFindByIdsOps, // findByIds 便利方法
|
|
40
|
+
createFindAndCountOps: require('./find-and-count').createFindAndCountOps, // 新增:findAndCount 便利方法
|
|
41
|
+
createCountOps: require('./count'),
|
|
42
|
+
createAggregateOps: require('./aggregate'),
|
|
43
|
+
createDistinctOps: require('./distinct'),
|
|
44
|
+
createFindPageOps, // 新增工厂函数
|
|
45
|
+
// 导出原始函数和辅助函数供 bookmark 模块使用
|
|
46
|
+
createFindPage,
|
|
47
|
+
bookmarkKey,
|
|
48
|
+
buildKeyDimsAuto
|
|
49
|
+
};
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* deleteMany 操作实现
|
|
3
|
+
* 删除所有匹配的文档
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { createError, ErrorCodes } = require("../../errors");
|
|
7
|
+
const CacheFactory = require("../../cache");
|
|
8
|
+
const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 创建 deleteMany 操作
|
|
12
|
+
* @param {Object} context - 模块上下文
|
|
13
|
+
* @param {Object} context.db - MongoDB 数据库实例
|
|
14
|
+
* @param {Object} context.cache - 缓存实例
|
|
15
|
+
* @param {Object} context.logger - 日志实例
|
|
16
|
+
* @param {Object} context.defaults - 默认配置
|
|
17
|
+
* @param {string} context.collection - 集合名称
|
|
18
|
+
* @param {string} context.effectiveDbName - 数据库名称
|
|
19
|
+
* @param {string} context.instanceId - 实例ID
|
|
20
|
+
* @returns {Object} 包含 deleteMany 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createDeleteManyOps(context) {
|
|
23
|
+
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
24
|
+
|
|
25
|
+
// 提取集合名称和原生 collection 对象
|
|
26
|
+
const collectionName = collection.collectionName;
|
|
27
|
+
const nativeCollection = collection;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 删除所有匹配的文档
|
|
31
|
+
* @param {Object} filter - 筛选条件(必需)
|
|
32
|
+
* @param {Object} [options] - 操作选项
|
|
33
|
+
* @param {Object} [options.collation] - 排序规则
|
|
34
|
+
* @param {Object} [options.hint] - 索引提示
|
|
35
|
+
* @param {number} [options.maxTimeMS] - 最大执行时间(毫秒)
|
|
36
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
37
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
38
|
+
* @returns {Promise<Object>} 返回删除结果 { deletedCount, acknowledged }
|
|
39
|
+
* @throws {Error} 当参数无效时
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* // 删除所有匹配的文档
|
|
43
|
+
* const result = await collection("logs").deleteMany({
|
|
44
|
+
* createdAt: { $lt: new Date("2024-01-01") }
|
|
45
|
+
* });
|
|
46
|
+
* console.log("已删除:", result.deletedCount);
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* // 删除所有文档(危险操作!)
|
|
50
|
+
* const result = await collection("temp_data").deleteMany({});
|
|
51
|
+
* console.log("已清空集合,删除:", result.deletedCount);
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* // 使用索引提示优化删除性能
|
|
55
|
+
* const result = await collection("events").deleteMany(
|
|
56
|
+
* { status: "archived", createdAt: { $lt: someDate } },
|
|
57
|
+
* { hint: { status: 1, createdAt: 1 } }
|
|
58
|
+
* );
|
|
59
|
+
*/
|
|
60
|
+
const deleteMany = async function deleteMany(filter, options = {}) {
|
|
61
|
+
const startTime = Date.now();
|
|
62
|
+
|
|
63
|
+
// 1. 参数验证
|
|
64
|
+
if (!filter || typeof filter !== "object" || Array.isArray(filter)) {
|
|
65
|
+
throw createError(
|
|
66
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
67
|
+
"filter 必须是对象类型",
|
|
68
|
+
[{ field: "filter", type: "object.required", message: "filter 是必需参数且必须是对象" }]
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 2. 警告:空 filter 会删除所有文档
|
|
73
|
+
if (Object.keys(filter).length === 0) {
|
|
74
|
+
logger.warn(`[deleteMany] 警告: 空 filter 将删除集合中的所有文档`, {
|
|
75
|
+
ns: `${databaseName}.${collectionName}`,
|
|
76
|
+
comment: options.comment
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 3. 构建操作上下文
|
|
81
|
+
const operation = "deleteMany";
|
|
82
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
// 4. 执行删除操作
|
|
86
|
+
const result = await nativeCollection.deleteMany(filter, options);
|
|
87
|
+
|
|
88
|
+
// 5. 自动失效缓存(如果有文档被删除)
|
|
89
|
+
if (cache && result.deletedCount > 0) {
|
|
90
|
+
try {
|
|
91
|
+
const ns = {
|
|
92
|
+
iid: instanceId,
|
|
93
|
+
type: "mongodb",
|
|
94
|
+
db: databaseName,
|
|
95
|
+
collection: collectionName
|
|
96
|
+
};
|
|
97
|
+
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
98
|
+
|
|
99
|
+
// 检查是否在事务中
|
|
100
|
+
if (isInTransaction(options)) {
|
|
101
|
+
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
102
|
+
const tx = getTransactionFromSession(options.session);
|
|
103
|
+
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
104
|
+
// 🚀 传递 metadata 支持文档级别锁
|
|
105
|
+
await tx.recordInvalidation(pattern, {
|
|
106
|
+
operation: 'write',
|
|
107
|
+
query: filter || {},
|
|
108
|
+
collection: collectionName
|
|
109
|
+
});
|
|
110
|
+
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
111
|
+
} else {
|
|
112
|
+
const deleted = await cache.delPattern(pattern);
|
|
113
|
+
if (deleted > 0) {
|
|
114
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
} else {
|
|
118
|
+
// 非事务:直接失效缓存
|
|
119
|
+
const deleted = await cache.delPattern(pattern);
|
|
120
|
+
if (deleted > 0) {
|
|
121
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} catch (cacheErr) {
|
|
125
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 6. 记录慢操作日志
|
|
130
|
+
const duration = Date.now() - startTime;
|
|
131
|
+
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
132
|
+
if (duration > slowQueryMs) {
|
|
133
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
134
|
+
ns,
|
|
135
|
+
duration,
|
|
136
|
+
threshold: slowQueryMs,
|
|
137
|
+
filterKeys: Object.keys(filter),
|
|
138
|
+
deletedCount: result.deletedCount,
|
|
139
|
+
comment: options.comment
|
|
140
|
+
});
|
|
141
|
+
} else {
|
|
142
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
143
|
+
ns,
|
|
144
|
+
duration,
|
|
145
|
+
deletedCount: result.deletedCount
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 7. 返回结果
|
|
150
|
+
return {
|
|
151
|
+
deletedCount: result.deletedCount,
|
|
152
|
+
acknowledged: result.acknowledged
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
} catch (error) {
|
|
156
|
+
// 8. 错误处理
|
|
157
|
+
const duration = Date.now() - startTime;
|
|
158
|
+
|
|
159
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
160
|
+
ns,
|
|
161
|
+
duration,
|
|
162
|
+
error: error.message,
|
|
163
|
+
code: error.code,
|
|
164
|
+
filterKeys: Object.keys(filter)
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// 其他错误
|
|
168
|
+
throw createError(
|
|
169
|
+
ErrorCodes.WRITE_ERROR,
|
|
170
|
+
`deleteMany 操作失败: ${error.message}`,
|
|
171
|
+
null,
|
|
172
|
+
error
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
return { deleteMany };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
module.exports = { createDeleteManyOps };
|
|
181
|
+
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* deleteOne 操作实现
|
|
3
|
+
* 删除单个匹配的文档
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const { createError, ErrorCodes } = require("../../errors");
|
|
7
|
+
const CacheFactory = require("../../cache");
|
|
8
|
+
const { isInTransaction, getTransactionFromSession } = require("../common/transaction-aware");
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 创建 deleteOne 操作
|
|
12
|
+
* @param {Object} context - 模块上下文
|
|
13
|
+
* @param {Object} context.db - MongoDB 数据库实例
|
|
14
|
+
* @param {Object} context.cache - 缓存实例
|
|
15
|
+
* @param {Object} context.logger - 日志实例
|
|
16
|
+
* @param {Object} context.defaults - 默认配置
|
|
17
|
+
* @param {string} context.collection - 集合名称
|
|
18
|
+
* @param {string} context.effectiveDbName - 数据库名称
|
|
19
|
+
* @param {string} context.instanceId - 实例ID
|
|
20
|
+
* @returns {Object} 包含 deleteOne 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createDeleteOneOps(context) {
|
|
23
|
+
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
24
|
+
|
|
25
|
+
// 提取集合名称和原生 collection 对象
|
|
26
|
+
const collectionName = collection.collectionName;
|
|
27
|
+
const nativeCollection = collection;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 删除单个匹配的文档
|
|
31
|
+
* @param {Object} filter - 筛选条件(必需)
|
|
32
|
+
* @param {Object} [options] - 操作选项
|
|
33
|
+
* @param {Object} [options.collation] - 排序规则
|
|
34
|
+
* @param {Object} [options.hint] - 索引提示
|
|
35
|
+
* @param {number} [options.maxTimeMS] - 最大执行时间(毫秒)
|
|
36
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
37
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
38
|
+
* @returns {Promise<Object>} 返回删除结果 { deletedCount, acknowledged }
|
|
39
|
+
* @throws {Error} 当参数无效时
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* // 删除单个文档
|
|
43
|
+
* const result = await collection("users").deleteOne({ userId: "user123" });
|
|
44
|
+
* console.log("已删除:", result.deletedCount); // 0 或 1
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* // 使用 collation(不区分大小写)
|
|
48
|
+
* const result = await collection("users").deleteOne(
|
|
49
|
+
* { name: "alice" },
|
|
50
|
+
* { collation: { locale: "en", strength: 2 } }
|
|
51
|
+
* );
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* // 使用索引提示
|
|
55
|
+
* const result = await collection("orders").deleteOne(
|
|
56
|
+
* { orderId: "order123" },
|
|
57
|
+
* { hint: { orderId: 1 } }
|
|
58
|
+
* );
|
|
59
|
+
*/
|
|
60
|
+
const deleteOne = async function deleteOne(filter, options = {}) {
|
|
61
|
+
const startTime = Date.now();
|
|
62
|
+
|
|
63
|
+
// 1. 参数验证
|
|
64
|
+
if (!filter || typeof filter !== "object" || Array.isArray(filter)) {
|
|
65
|
+
throw createError(
|
|
66
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
67
|
+
"filter 必须是对象类型",
|
|
68
|
+
[{ field: "filter", type: "object.required", message: "filter 是必需参数且必须是对象" }]
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 2. 构建操作上下文
|
|
73
|
+
const operation = "deleteOne";
|
|
74
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
// 3. 执行删除操作
|
|
78
|
+
const result = await nativeCollection.deleteOne(filter, options);
|
|
79
|
+
|
|
80
|
+
// 4. 自动失效缓存(如果有文档被删除)
|
|
81
|
+
if (cache && result.deletedCount > 0) {
|
|
82
|
+
try {
|
|
83
|
+
const ns = {
|
|
84
|
+
iid: instanceId,
|
|
85
|
+
type: "mongodb",
|
|
86
|
+
db: databaseName,
|
|
87
|
+
collection: collectionName
|
|
88
|
+
};
|
|
89
|
+
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
90
|
+
|
|
91
|
+
// 检查是否在事务中
|
|
92
|
+
if (isInTransaction(options)) {
|
|
93
|
+
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
94
|
+
const tx = getTransactionFromSession(options.session);
|
|
95
|
+
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
96
|
+
// 🚀 传递 metadata 支持文档级别锁
|
|
97
|
+
await tx.recordInvalidation(pattern, {
|
|
98
|
+
operation: 'write',
|
|
99
|
+
query: filter || {},
|
|
100
|
+
collection: collectionName
|
|
101
|
+
});
|
|
102
|
+
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
103
|
+
} else {
|
|
104
|
+
const deleted = await cache.delPattern(pattern);
|
|
105
|
+
if (deleted > 0) {
|
|
106
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
} else {
|
|
110
|
+
// 非事务:直接失效缓存
|
|
111
|
+
const deleted = await cache.delPattern(pattern);
|
|
112
|
+
if (deleted > 0) {
|
|
113
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} catch (cacheErr) {
|
|
117
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// 5. 记录慢操作日志
|
|
122
|
+
const duration = Date.now() - startTime;
|
|
123
|
+
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
124
|
+
if (duration > slowQueryMs) {
|
|
125
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
126
|
+
ns,
|
|
127
|
+
duration,
|
|
128
|
+
threshold: slowQueryMs,
|
|
129
|
+
filterKeys: Object.keys(filter),
|
|
130
|
+
deletedCount: result.deletedCount,
|
|
131
|
+
comment: options.comment
|
|
132
|
+
});
|
|
133
|
+
} else {
|
|
134
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
135
|
+
ns,
|
|
136
|
+
duration,
|
|
137
|
+
deletedCount: result.deletedCount
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// 6. 返回结果
|
|
142
|
+
return {
|
|
143
|
+
deletedCount: result.deletedCount,
|
|
144
|
+
acknowledged: result.acknowledged
|
|
145
|
+
};
|
|
146
|
+
|
|
147
|
+
} catch (error) {
|
|
148
|
+
// 7. 错误处理
|
|
149
|
+
const duration = Date.now() - startTime;
|
|
150
|
+
|
|
151
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
152
|
+
ns,
|
|
153
|
+
duration,
|
|
154
|
+
error: error.message,
|
|
155
|
+
code: error.code,
|
|
156
|
+
filterKeys: Object.keys(filter)
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// 其他错误
|
|
160
|
+
throw createError(
|
|
161
|
+
ErrorCodes.WRITE_ERROR,
|
|
162
|
+
`deleteOne 操作失败: ${error.message}`,
|
|
163
|
+
null,
|
|
164
|
+
error
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
return { deleteOne };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
module.exports = { createDeleteOneOps };
|
|
173
|
+
|