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.
- package/CHANGELOG.md +415 -146
- package/LICENSE +201 -21
- package/README.md +537 -928
- package/changelogs/README.md +160 -0
- package/changelogs/v2.0.0.md +222 -0
- package/dist/cjs/index.cjs +10600 -0
- package/dist/cjs/mongodb/common/transaction-aware.cjs +10 -0
- package/dist/cjs/transaction/CacheLockManager.cjs +100 -0
- package/dist/cjs/transaction/Transaction.cjs +158 -0
- package/dist/cjs/transaction/TransactionManager.cjs +298 -0
- package/dist/esm/index.mjs +10650 -0
- package/dist/types/base.d.ts +81 -0
- package/dist/types/collection.d.ts +1031 -0
- package/dist/types/expression.d.ts +115 -0
- package/dist/types/index.d.ts +23 -0
- package/dist/types/lock.d.ts +74 -0
- package/dist/types/model.d.ts +526 -0
- package/dist/types/mongodb.d.ts +49 -0
- package/dist/types/monsqlize.d.ts +491 -0
- package/dist/types/pool.d.ts +84 -0
- package/dist/types/runtime.d.ts +362 -0
- package/dist/types/saga.d.ts +143 -0
- package/dist/types/slow-query-log.d.ts +126 -0
- package/dist/types/sync.d.ts +103 -0
- package/dist/types/transaction.d.ts +132 -0
- package/package.json +69 -67
- package/index.d.ts +0 -1289
- package/lib/cache.js +0 -491
- package/lib/common/cursor.js +0 -58
- package/lib/common/docs-urls.js +0 -72
- package/lib/common/index-options.js +0 -222
- package/lib/common/log.js +0 -60
- package/lib/common/namespace.js +0 -21
- package/lib/common/normalize.js +0 -33
- package/lib/common/page-result.js +0 -42
- package/lib/common/runner.js +0 -56
- package/lib/common/server-features.js +0 -231
- package/lib/common/shape-builders.js +0 -26
- package/lib/common/validation.js +0 -112
- package/lib/connect.js +0 -76
- package/lib/constants.js +0 -54
- package/lib/count-queue.js +0 -187
- package/lib/distributed-cache-invalidator.js +0 -259
- package/lib/errors.js +0 -167
- package/lib/index.js +0 -461
- package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -211
- package/lib/infrastructure/ssh-tunnel.js +0 -40
- package/lib/infrastructure/uri-parser.js +0 -35
- package/lib/lock/Lock.js +0 -66
- package/lib/lock/errors.js +0 -27
- package/lib/lock/index.js +0 -12
- package/lib/logger.js +0 -224
- package/lib/model/examples/test.js +0 -114
- package/lib/mongodb/common/accessor-helpers.js +0 -58
- package/lib/mongodb/common/agg-pipeline.js +0 -32
- package/lib/mongodb/common/iid.js +0 -27
- package/lib/mongodb/common/lexicographic-expr.js +0 -52
- package/lib/mongodb/common/shape.js +0 -31
- package/lib/mongodb/common/sort.js +0 -38
- package/lib/mongodb/common/transaction-aware.js +0 -24
- package/lib/mongodb/connect.js +0 -233
- package/lib/mongodb/index.js +0 -591
- package/lib/mongodb/management/admin-ops.js +0 -199
- package/lib/mongodb/management/bookmark-ops.js +0 -166
- package/lib/mongodb/management/cache-ops.js +0 -49
- package/lib/mongodb/management/collection-ops.js +0 -386
- package/lib/mongodb/management/database-ops.js +0 -201
- package/lib/mongodb/management/index-ops.js +0 -474
- package/lib/mongodb/management/index.js +0 -16
- package/lib/mongodb/management/namespace.js +0 -30
- package/lib/mongodb/management/validation-ops.js +0 -267
- package/lib/mongodb/queries/aggregate.js +0 -142
- package/lib/mongodb/queries/chain.js +0 -630
- package/lib/mongodb/queries/count.js +0 -98
- package/lib/mongodb/queries/distinct.js +0 -77
- package/lib/mongodb/queries/find-and-count.js +0 -192
- package/lib/mongodb/queries/find-by-ids.js +0 -235
- package/lib/mongodb/queries/find-one-by-id.js +0 -170
- package/lib/mongodb/queries/find-one.js +0 -70
- package/lib/mongodb/queries/find-page.js +0 -577
- package/lib/mongodb/queries/find.js +0 -170
- package/lib/mongodb/queries/index.js +0 -50
- package/lib/mongodb/queries/watch.js +0 -537
- package/lib/mongodb/writes/delete-many.js +0 -190
- package/lib/mongodb/writes/delete-one.js +0 -182
- package/lib/mongodb/writes/find-one-and-delete.js +0 -202
- package/lib/mongodb/writes/find-one-and-replace.js +0 -238
- package/lib/mongodb/writes/find-one-and-update.js +0 -239
- package/lib/mongodb/writes/increment-one.js +0 -252
- package/lib/mongodb/writes/index.js +0 -41
- package/lib/mongodb/writes/insert-batch.js +0 -507
- package/lib/mongodb/writes/insert-many.js +0 -227
- package/lib/mongodb/writes/insert-one.js +0 -180
- package/lib/mongodb/writes/replace-one.js +0 -215
- package/lib/mongodb/writes/result-handler.js +0 -236
- package/lib/mongodb/writes/update-many.js +0 -221
- package/lib/mongodb/writes/update-one.js +0 -223
- package/lib/mongodb/writes/upsert-one.js +0 -206
- package/lib/multi-level-cache.js +0 -189
- package/lib/operators.js +0 -330
- package/lib/redis-cache-adapter.js +0 -237
- package/lib/slow-query-log/base-storage.js +0 -69
- package/lib/slow-query-log/batch-queue.js +0 -96
- package/lib/slow-query-log/config-manager.js +0 -195
- package/lib/slow-query-log/index.js +0 -237
- package/lib/slow-query-log/mongodb-storage.js +0 -323
- package/lib/slow-query-log/query-hash.js +0 -38
- package/lib/transaction/CacheLockManager.js +0 -161
- package/lib/transaction/DistributedCacheLockManager.js +0 -474
- package/lib/transaction/Transaction.js +0 -314
- package/lib/transaction/TransactionManager.js +0 -266
- package/lib/transaction/index.js +0 -10
- package/lib/utils/objectid-converter.js +0 -566
|
@@ -1,190 +0,0 @@
|
|
|
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
|
-
const { convertObjectIdStrings } = require('../../utils/objectid-converter');
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* 创建 deleteMany 操作
|
|
13
|
-
* @param {Object} context - 模块上下文
|
|
14
|
-
* @param {Object} context.db - MongoDB 数据库实例
|
|
15
|
-
* @param {Object} context.cache - 缓存实例
|
|
16
|
-
* @param {Object} context.logger - 日志实例
|
|
17
|
-
* @param {Object} context.defaults - 默认配置
|
|
18
|
-
* @param {string} context.collection - 集合名称
|
|
19
|
-
* @param {string} context.effectiveDbName - 数据库名称
|
|
20
|
-
* @param {string} context.instanceId - 实例ID
|
|
21
|
-
* @returns {Object} 包含 deleteMany 方法的对象
|
|
22
|
-
*/
|
|
23
|
-
function createDeleteManyOps(context) {
|
|
24
|
-
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
25
|
-
|
|
26
|
-
// 提取集合名称和原生 collection 对象
|
|
27
|
-
const collectionName = collection.collectionName;
|
|
28
|
-
const nativeCollection = collection;
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* 删除所有匹配的文档
|
|
32
|
-
* @param {Object} filter - 筛选条件(必需)
|
|
33
|
-
* @param {Object} [options] - 操作选项
|
|
34
|
-
* @param {Object} [options.collation] - 排序规则
|
|
35
|
-
* @param {Object} [options.hint] - 索引提示
|
|
36
|
-
* @param {number} [options.maxTimeMS] - 最大执行时间(毫秒)
|
|
37
|
-
* @param {Object} [options.writeConcern] - 写关注选项
|
|
38
|
-
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
39
|
-
* @returns {Promise<Object>} 返回删除结果 { deletedCount, acknowledged }
|
|
40
|
-
* @throws {Error} 当参数无效时
|
|
41
|
-
*
|
|
42
|
-
* @example
|
|
43
|
-
* // 删除所有匹配的文档
|
|
44
|
-
* const result = await collection("logs").deleteMany({
|
|
45
|
-
* createdAt: { $lt: new Date("2024-01-01") }
|
|
46
|
-
* });
|
|
47
|
-
* console.log("已删除:", result.deletedCount);
|
|
48
|
-
*
|
|
49
|
-
* @example
|
|
50
|
-
* // 删除所有文档(危险操作!)
|
|
51
|
-
* const result = await collection("temp_data").deleteMany({});
|
|
52
|
-
* console.log("已清空集合,删除:", result.deletedCount);
|
|
53
|
-
*
|
|
54
|
-
* @example
|
|
55
|
-
* // 使用索引提示优化删除性能
|
|
56
|
-
* const result = await collection("events").deleteMany(
|
|
57
|
-
* { status: "archived", createdAt: { $lt: someDate } },
|
|
58
|
-
* { hint: { status: 1, createdAt: 1 } }
|
|
59
|
-
* );
|
|
60
|
-
*/
|
|
61
|
-
const deleteMany = async function deleteMany(filter, options = {}) {
|
|
62
|
-
const startTime = Date.now();
|
|
63
|
-
|
|
64
|
-
// 1. 参数验证
|
|
65
|
-
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
|
|
66
|
-
throw createError(
|
|
67
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
68
|
-
'filter 必须是对象类型',
|
|
69
|
-
[{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// ✅ v1.3.0: 自动转换 ObjectId 字符串
|
|
74
|
-
const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
|
|
75
|
-
logger: context.logger,
|
|
76
|
-
excludeFields: context.autoConvertConfig?.excludeFields,
|
|
77
|
-
customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
|
|
78
|
-
maxDepth: context.autoConvertConfig?.maxDepth
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
// 2. 警告:空 filter 会删除所有文档
|
|
82
|
-
if (Object.keys(convertedFilter).length === 0) {
|
|
83
|
-
logger.warn('[deleteMany] 警告: 空 filter 将删除集合中的所有文档', {
|
|
84
|
-
ns: `${databaseName}.${collectionName}`,
|
|
85
|
-
comment: options.comment
|
|
86
|
-
});
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// 3. 构建操作上下文
|
|
90
|
-
const operation = 'deleteMany';
|
|
91
|
-
const ns = `${databaseName}.${collectionName}`;
|
|
92
|
-
|
|
93
|
-
try {
|
|
94
|
-
// 4. 执行删除操作
|
|
95
|
-
const result = await nativeCollection.deleteMany(convertedFilter, options);
|
|
96
|
-
|
|
97
|
-
// 5. 自动失效缓存(如果有文档被删除)
|
|
98
|
-
if (cache && result.deletedCount > 0) {
|
|
99
|
-
try {
|
|
100
|
-
const ns = {
|
|
101
|
-
iid: instanceId,
|
|
102
|
-
type: 'mongodb',
|
|
103
|
-
db: databaseName,
|
|
104
|
-
collection: collectionName
|
|
105
|
-
};
|
|
106
|
-
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
107
|
-
|
|
108
|
-
// 检查是否在事务中
|
|
109
|
-
if (isInTransaction(options)) {
|
|
110
|
-
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
111
|
-
const tx = getTransactionFromSession(options.session);
|
|
112
|
-
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
113
|
-
// 🚀 传递 metadata 支持文档级别锁
|
|
114
|
-
await tx.recordInvalidation(pattern, {
|
|
115
|
-
operation: 'write',
|
|
116
|
-
query: filter || {},
|
|
117
|
-
collection: collectionName
|
|
118
|
-
});
|
|
119
|
-
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
120
|
-
} else {
|
|
121
|
-
const deleted = await cache.delPattern(pattern);
|
|
122
|
-
if (deleted > 0) {
|
|
123
|
-
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
} else {
|
|
127
|
-
// 非事务:直接失效缓存
|
|
128
|
-
const deleted = await cache.delPattern(pattern);
|
|
129
|
-
if (deleted > 0) {
|
|
130
|
-
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
} catch (cacheErr) {
|
|
134
|
-
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// 6. 记录慢操作日志
|
|
139
|
-
const duration = Date.now() - startTime;
|
|
140
|
-
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
141
|
-
if (duration > slowQueryMs) {
|
|
142
|
-
logger.warn(`[${operation}] 慢操作警告`, {
|
|
143
|
-
ns,
|
|
144
|
-
duration,
|
|
145
|
-
threshold: slowQueryMs,
|
|
146
|
-
filterKeys: Object.keys(filter),
|
|
147
|
-
deletedCount: result.deletedCount,
|
|
148
|
-
comment: options.comment
|
|
149
|
-
});
|
|
150
|
-
} else {
|
|
151
|
-
logger.debug(`[${operation}] 操作完成`, {
|
|
152
|
-
ns,
|
|
153
|
-
duration,
|
|
154
|
-
deletedCount: result.deletedCount
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// 7. 返回结果
|
|
159
|
-
return {
|
|
160
|
-
deletedCount: result.deletedCount,
|
|
161
|
-
acknowledged: result.acknowledged
|
|
162
|
-
};
|
|
163
|
-
|
|
164
|
-
} catch (error) {
|
|
165
|
-
// 8. 错误处理
|
|
166
|
-
const duration = Date.now() - startTime;
|
|
167
|
-
|
|
168
|
-
logger.error(`[${operation}] 操作失败`, {
|
|
169
|
-
ns,
|
|
170
|
-
duration,
|
|
171
|
-
error: error.message,
|
|
172
|
-
code: error.code,
|
|
173
|
-
filterKeys: Object.keys(filter)
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
// 其他错误
|
|
177
|
-
throw createError(
|
|
178
|
-
ErrorCodes.WRITE_ERROR,
|
|
179
|
-
`deleteMany 操作失败: ${error.message}`,
|
|
180
|
-
null,
|
|
181
|
-
error
|
|
182
|
-
);
|
|
183
|
-
}
|
|
184
|
-
};
|
|
185
|
-
|
|
186
|
-
return { deleteMany };
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
module.exports = { createDeleteManyOps };
|
|
190
|
-
|
|
@@ -1,182 +0,0 @@
|
|
|
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
|
-
const { convertObjectIdStrings } = require('../../utils/objectid-converter');
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* 创建 deleteOne 操作
|
|
13
|
-
* @param {Object} context - 模块上下文
|
|
14
|
-
* @param {Object} context.db - MongoDB 数据库实例
|
|
15
|
-
* @param {Object} context.cache - 缓存实例
|
|
16
|
-
* @param {Object} context.logger - 日志实例
|
|
17
|
-
* @param {Object} context.defaults - 默认配置
|
|
18
|
-
* @param {string} context.collection - 集合名称
|
|
19
|
-
* @param {string} context.effectiveDbName - 数据库名称
|
|
20
|
-
* @param {string} context.instanceId - 实例ID
|
|
21
|
-
* @returns {Object} 包含 deleteOne 方法的对象
|
|
22
|
-
*/
|
|
23
|
-
function createDeleteOneOps(context) {
|
|
24
|
-
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
25
|
-
|
|
26
|
-
// 提取集合名称和原生 collection 对象
|
|
27
|
-
const collectionName = collection.collectionName;
|
|
28
|
-
const nativeCollection = collection;
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* 删除单个匹配的文档
|
|
32
|
-
* @param {Object} filter - 筛选条件(必需)
|
|
33
|
-
* @param {Object} [options] - 操作选项
|
|
34
|
-
* @param {Object} [options.collation] - 排序规则
|
|
35
|
-
* @param {Object} [options.hint] - 索引提示
|
|
36
|
-
* @param {number} [options.maxTimeMS] - 最大执行时间(毫秒)
|
|
37
|
-
* @param {Object} [options.writeConcern] - 写关注选项
|
|
38
|
-
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
39
|
-
* @returns {Promise<Object>} 返回删除结果 { deletedCount, acknowledged }
|
|
40
|
-
* @throws {Error} 当参数无效时
|
|
41
|
-
*
|
|
42
|
-
* @example
|
|
43
|
-
* // 删除单个文档
|
|
44
|
-
* const result = await collection("users").deleteOne({ userId: "user123" });
|
|
45
|
-
* console.log("已删除:", result.deletedCount); // 0 或 1
|
|
46
|
-
*
|
|
47
|
-
* @example
|
|
48
|
-
* // 使用 collation(不区分大小写)
|
|
49
|
-
* const result = await collection("users").deleteOne(
|
|
50
|
-
* { name: "alice" },
|
|
51
|
-
* { collation: { locale: "en", strength: 2 } }
|
|
52
|
-
* );
|
|
53
|
-
*
|
|
54
|
-
* @example
|
|
55
|
-
* // 使用索引提示
|
|
56
|
-
* const result = await collection("orders").deleteOne(
|
|
57
|
-
* { orderId: "order123" },
|
|
58
|
-
* { hint: { orderId: 1 } }
|
|
59
|
-
* );
|
|
60
|
-
*/
|
|
61
|
-
const deleteOne = async function deleteOne(filter, options = {}) {
|
|
62
|
-
const startTime = Date.now();
|
|
63
|
-
|
|
64
|
-
// 1. 参数验证
|
|
65
|
-
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
|
|
66
|
-
throw createError(
|
|
67
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
68
|
-
'filter 必须是对象类型',
|
|
69
|
-
[{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
|
|
70
|
-
);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// ✅ v1.3.0: 自动转换 ObjectId 字符串
|
|
74
|
-
const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
|
|
75
|
-
logger: context.logger,
|
|
76
|
-
excludeFields: context.autoConvertConfig?.excludeFields,
|
|
77
|
-
customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
|
|
78
|
-
maxDepth: context.autoConvertConfig?.maxDepth
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
// 2. 构建操作上下文
|
|
82
|
-
const operation = 'deleteOne';
|
|
83
|
-
const ns = `${databaseName}.${collectionName}`;
|
|
84
|
-
|
|
85
|
-
try {
|
|
86
|
-
// 3. 执行删除操作
|
|
87
|
-
const result = await nativeCollection.deleteOne(convertedFilter, options);
|
|
88
|
-
|
|
89
|
-
// 4. 自动失效缓存(如果有文档被删除)
|
|
90
|
-
if (cache && result.deletedCount > 0) {
|
|
91
|
-
try {
|
|
92
|
-
const ns = {
|
|
93
|
-
iid: instanceId,
|
|
94
|
-
type: 'mongodb',
|
|
95
|
-
db: databaseName,
|
|
96
|
-
collection: collectionName
|
|
97
|
-
};
|
|
98
|
-
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
99
|
-
|
|
100
|
-
// 检查是否在事务中
|
|
101
|
-
if (isInTransaction(options)) {
|
|
102
|
-
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
103
|
-
const tx = getTransactionFromSession(options.session);
|
|
104
|
-
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
105
|
-
// 🚀 传递 metadata 支持文档级别锁
|
|
106
|
-
await tx.recordInvalidation(pattern, {
|
|
107
|
-
operation: 'write',
|
|
108
|
-
query: filter || {},
|
|
109
|
-
collection: collectionName
|
|
110
|
-
});
|
|
111
|
-
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
112
|
-
} else {
|
|
113
|
-
const deleted = await cache.delPattern(pattern);
|
|
114
|
-
if (deleted > 0) {
|
|
115
|
-
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
} else {
|
|
119
|
-
// 非事务:直接失效缓存
|
|
120
|
-
const deleted = await cache.delPattern(pattern);
|
|
121
|
-
if (deleted > 0) {
|
|
122
|
-
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
} catch (cacheErr) {
|
|
126
|
-
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// 5. 记录慢操作日志
|
|
131
|
-
const duration = Date.now() - startTime;
|
|
132
|
-
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
133
|
-
if (duration > slowQueryMs) {
|
|
134
|
-
logger.warn(`[${operation}] 慢操作警告`, {
|
|
135
|
-
ns,
|
|
136
|
-
duration,
|
|
137
|
-
threshold: slowQueryMs,
|
|
138
|
-
filterKeys: Object.keys(filter),
|
|
139
|
-
deletedCount: result.deletedCount,
|
|
140
|
-
comment: options.comment
|
|
141
|
-
});
|
|
142
|
-
} else {
|
|
143
|
-
logger.debug(`[${operation}] 操作完成`, {
|
|
144
|
-
ns,
|
|
145
|
-
duration,
|
|
146
|
-
deletedCount: result.deletedCount
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
// 6. 返回结果
|
|
151
|
-
return {
|
|
152
|
-
deletedCount: result.deletedCount,
|
|
153
|
-
acknowledged: result.acknowledged
|
|
154
|
-
};
|
|
155
|
-
|
|
156
|
-
} catch (error) {
|
|
157
|
-
// 7. 错误处理
|
|
158
|
-
const duration = Date.now() - startTime;
|
|
159
|
-
|
|
160
|
-
logger.error(`[${operation}] 操作失败`, {
|
|
161
|
-
ns,
|
|
162
|
-
duration,
|
|
163
|
-
error: error.message,
|
|
164
|
-
code: error.code,
|
|
165
|
-
filterKeys: Object.keys(filter)
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
// 其他错误
|
|
169
|
-
throw createError(
|
|
170
|
-
ErrorCodes.WRITE_ERROR,
|
|
171
|
-
`deleteOne 操作失败: ${error.message}`,
|
|
172
|
-
null,
|
|
173
|
-
error
|
|
174
|
-
);
|
|
175
|
-
}
|
|
176
|
-
};
|
|
177
|
-
|
|
178
|
-
return { deleteOne };
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
module.exports = { createDeleteOneOps };
|
|
182
|
-
|
|
@@ -1,202 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* findOneAndDelete 操作实现
|
|
3
|
-
* 原子地查找并删除单个文档
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
const { createError, ErrorCodes } = require('../../errors');
|
|
7
|
-
const CacheFactory = require('../../cache');
|
|
8
|
-
const { handleFindOneAndResult, wasDocumentModified } = require('./result-handler');
|
|
9
|
-
const { isInTransaction, getTransactionFromSession } = require('../common/transaction-aware');
|
|
10
|
-
const { convertObjectIdStrings } = require('../../utils/objectid-converter');
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* 创建 findOneAndDelete 操作
|
|
14
|
-
* @param {Object} context - 模块上下文
|
|
15
|
-
* @param {Object} context.db - MongoDB 数据库实例
|
|
16
|
-
* @param {Object} context.cache - 缓存实例
|
|
17
|
-
* @param {Object} context.logger - 日志实例
|
|
18
|
-
* @param {Object} context.defaults - 默认配置
|
|
19
|
-
* @param {string} context.collection - 集合名称
|
|
20
|
-
* @param {string} context.effectiveDbName - 数据库名称
|
|
21
|
-
* @param {string} context.instanceId - 实例ID
|
|
22
|
-
* @returns {Object} 包含 findOneAndDelete 方法的对象
|
|
23
|
-
*/
|
|
24
|
-
function createFindOneAndDeleteOps(context) {
|
|
25
|
-
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
26
|
-
|
|
27
|
-
// 提取集合名称和原生 collection 对象
|
|
28
|
-
const collectionName = collection.collectionName;
|
|
29
|
-
const nativeCollection = collection;
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* 查找并删除单个文档(原子操作)
|
|
33
|
-
* @param {Object} filter - 筛选条件(必需)
|
|
34
|
-
* @param {Object} [options] - 操作选项
|
|
35
|
-
* @param {Object} [options.projection] - 字段投影
|
|
36
|
-
* @param {Object} [options.sort] - 排序条件
|
|
37
|
-
* @param {number} [options.maxTimeMS] - 最大执行时间
|
|
38
|
-
* @param {Object} [options.writeConcern] - 写关注选项
|
|
39
|
-
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
40
|
-
* @param {Object} [options.collation] - 排序规则
|
|
41
|
-
* @param {Object} [options.hint] - 索引提示
|
|
42
|
-
* @param {boolean} [options.includeResultMetadata=false] - 是否包含完整结果元数据
|
|
43
|
-
* @returns {Promise<Object|null>} 返回被删除的文档或 null(未找到);includeResultMetadata=true 时返回 { value, ok, lastErrorObject }
|
|
44
|
-
* @throws {Error} 当参数无效时
|
|
45
|
-
*
|
|
46
|
-
* @example
|
|
47
|
-
* // 删除单个文档并返回
|
|
48
|
-
* const deletedDoc = await collection("tasks").findOneAndDelete({
|
|
49
|
-
* taskId: "task123"
|
|
50
|
-
* });
|
|
51
|
-
* if (deletedDoc) {
|
|
52
|
-
* console.log("已删除任务:", deletedDoc.taskId);
|
|
53
|
-
* }
|
|
54
|
-
*
|
|
55
|
-
* @example
|
|
56
|
-
* // 删除最旧的待处理任务
|
|
57
|
-
* const oldestTask = await collection("queue").findOneAndDelete(
|
|
58
|
-
* { status: "pending" },
|
|
59
|
-
* { sort: { createdAt: 1 } }
|
|
60
|
-
* );
|
|
61
|
-
*
|
|
62
|
-
* @example
|
|
63
|
-
* // 使用 projection 仅返回需要的字段
|
|
64
|
-
* const deletedUser = await collection("users").findOneAndDelete(
|
|
65
|
-
* { userId: "user123" },
|
|
66
|
-
* { projection: { userId: 1, name: 1 } }
|
|
67
|
-
* );
|
|
68
|
-
*
|
|
69
|
-
* @example
|
|
70
|
-
* // 获取完整元数据
|
|
71
|
-
* const result = await collection("sessions").findOneAndDelete(
|
|
72
|
-
* { sessionId: "session123" },
|
|
73
|
-
* { includeResultMetadata: true }
|
|
74
|
-
* );
|
|
75
|
-
* console.log("删除成功:", result.ok);
|
|
76
|
-
* console.log("已删除的文档:", result.value);
|
|
77
|
-
*/
|
|
78
|
-
const findOneAndDelete = async function findOneAndDelete(filter, options = {}) {
|
|
79
|
-
const startTime = Date.now();
|
|
80
|
-
|
|
81
|
-
// 1. 参数验证
|
|
82
|
-
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
|
|
83
|
-
throw createError(
|
|
84
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
85
|
-
'filter 必须是对象类型',
|
|
86
|
-
[{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
|
|
87
|
-
);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
// ✅ v1.3.0: 自动转换 ObjectId 字符串
|
|
91
|
-
const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
|
|
92
|
-
logger: context.logger,
|
|
93
|
-
excludeFields: context.autoConvertConfig?.excludeFields,
|
|
94
|
-
customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
|
|
95
|
-
maxDepth: context.autoConvertConfig?.maxDepth
|
|
96
|
-
});
|
|
97
|
-
|
|
98
|
-
// 2. 构建操作上下文
|
|
99
|
-
const operation = 'findOneAndDelete';
|
|
100
|
-
const ns = `${databaseName}.${collectionName}`;
|
|
101
|
-
|
|
102
|
-
try {
|
|
103
|
-
// 3. 执行查找并删除操作
|
|
104
|
-
// MongoDB 驱动 6.x: 默认返回文档,需要 includeResultMetadata=true 获取完整元数据
|
|
105
|
-
const driverOptions = { ...options, includeResultMetadata: true };
|
|
106
|
-
const result = await nativeCollection.findOneAndDelete(convertedFilter, driverOptions);
|
|
107
|
-
|
|
108
|
-
// 4. 自动失效缓存(如果有文档被删除)
|
|
109
|
-
// 使用安全的修改判断函数
|
|
110
|
-
const documentWasDeleted = wasDocumentModified(result);
|
|
111
|
-
if (cache && documentWasDeleted) {
|
|
112
|
-
try {
|
|
113
|
-
const ns = {
|
|
114
|
-
iid: instanceId,
|
|
115
|
-
type: 'mongodb',
|
|
116
|
-
db: databaseName,
|
|
117
|
-
collection: collectionName
|
|
118
|
-
};
|
|
119
|
-
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
120
|
-
|
|
121
|
-
// 检查是否在事务中
|
|
122
|
-
if (isInTransaction(options)) {
|
|
123
|
-
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
124
|
-
const tx = getTransactionFromSession(options.session);
|
|
125
|
-
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
126
|
-
// 🚀 传递 metadata 支持文档级别锁
|
|
127
|
-
await tx.recordInvalidation(pattern, {
|
|
128
|
-
operation: 'write',
|
|
129
|
-
query: filter,
|
|
130
|
-
collection: collectionName
|
|
131
|
-
});
|
|
132
|
-
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
133
|
-
} else {
|
|
134
|
-
const deleted = await cache.delPattern(pattern);
|
|
135
|
-
if (deleted > 0) {
|
|
136
|
-
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
} else {
|
|
140
|
-
// 非事务:直接失效缓存
|
|
141
|
-
const deleted = await cache.delPattern(pattern);
|
|
142
|
-
if (deleted > 0) {
|
|
143
|
-
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
} catch (cacheErr) {
|
|
147
|
-
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// 5. 记录慢操作日志
|
|
152
|
-
const duration = Date.now() - startTime;
|
|
153
|
-
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
154
|
-
const found = result && result.value !== null && result.value !== undefined;
|
|
155
|
-
|
|
156
|
-
if (duration > slowQueryMs) {
|
|
157
|
-
logger.warn(`[${operation}] 慢操作警告`, {
|
|
158
|
-
ns,
|
|
159
|
-
duration,
|
|
160
|
-
threshold: slowQueryMs,
|
|
161
|
-
filterKeys: Object.keys(filter),
|
|
162
|
-
found,
|
|
163
|
-
comment: options.comment
|
|
164
|
-
});
|
|
165
|
-
} else {
|
|
166
|
-
logger.debug(`[${operation}] 操作完成`, {
|
|
167
|
-
ns,
|
|
168
|
-
duration,
|
|
169
|
-
found
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// 6. 返回结果(使用统一的返回值处理函数)
|
|
174
|
-
return handleFindOneAndResult(result, options, logger);
|
|
175
|
-
|
|
176
|
-
} catch (error) {
|
|
177
|
-
// 7. 错误处理
|
|
178
|
-
const duration = Date.now() - startTime;
|
|
179
|
-
|
|
180
|
-
logger.error(`[${operation}] 操作失败`, {
|
|
181
|
-
ns,
|
|
182
|
-
duration,
|
|
183
|
-
error: error.message,
|
|
184
|
-
code: error.code,
|
|
185
|
-
filterKeys: Object.keys(filter)
|
|
186
|
-
});
|
|
187
|
-
|
|
188
|
-
// 其他错误
|
|
189
|
-
throw createError(
|
|
190
|
-
ErrorCodes.WRITE_ERROR,
|
|
191
|
-
`findOneAndDelete 操作失败: ${error.message}`,
|
|
192
|
-
null,
|
|
193
|
-
error
|
|
194
|
-
);
|
|
195
|
-
}
|
|
196
|
-
};
|
|
197
|
-
|
|
198
|
-
return { findOneAndDelete };
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
module.exports = { createFindOneAndDeleteOps };
|
|
202
|
-
|