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,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* insertMany 操作实现
|
|
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
|
+
* 创建 insertMany 操作
|
|
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} 包含 insertMany 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createInsertManyOps(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 {Array<Object>} documents - 要插入的文档数组(必需)
|
|
32
|
+
* @param {Object} [options] - 操作选项
|
|
33
|
+
* @param {boolean} [options.ordered=true] - 是否按顺序插入(遇到错误是否继续)
|
|
34
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
35
|
+
* @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
|
|
36
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
37
|
+
* @returns {Promise<Object>} 插入结果 { acknowledged, insertedCount, insertedIds }
|
|
38
|
+
* @throws {Error} 当 documents 参数无效时
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* const result = await collection('users').insertMany([
|
|
42
|
+
* { name: 'Alice', age: 25 },
|
|
43
|
+
* { name: 'Bob', age: 30 }
|
|
44
|
+
* ]);
|
|
45
|
+
* console.log('Inserted count:', result.insertedCount);
|
|
46
|
+
* console.log('Inserted IDs:', result.insertedIds);
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* // 使用 options 参数
|
|
50
|
+
* const result = await collection('users').insertMany(
|
|
51
|
+
* [
|
|
52
|
+
* { name: 'Charlie', age: 35 },
|
|
53
|
+
* { name: 'David', age: 40 }
|
|
54
|
+
* ],
|
|
55
|
+
* { ordered: false, comment: 'batch insert' }
|
|
56
|
+
* );
|
|
57
|
+
*/
|
|
58
|
+
const insertMany = async function insertMany(documents, options = {}) {
|
|
59
|
+
const startTime = Date.now();
|
|
60
|
+
|
|
61
|
+
// 1. 参数验证
|
|
62
|
+
if (!Array.isArray(documents)) {
|
|
63
|
+
throw createError(
|
|
64
|
+
ErrorCodes.DOCUMENTS_REQUIRED,
|
|
65
|
+
"documents 必须是数组类型",
|
|
66
|
+
[{ field: "documents", type: "array.required", message: "documents 是必需参数且必须是数组" }]
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (documents.length === 0) {
|
|
71
|
+
throw createError(
|
|
72
|
+
ErrorCodes.DOCUMENTS_REQUIRED,
|
|
73
|
+
"documents 数组不能为空",
|
|
74
|
+
[{ field: "documents", type: "array.min", message: "documents 至少需要包含一个文档" }]
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 验证每个文档都是对象
|
|
79
|
+
const invalidDocs = documents.filter((doc, index) => {
|
|
80
|
+
return !doc || typeof doc !== "object" || Array.isArray(doc);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
if (invalidDocs.length > 0) {
|
|
84
|
+
throw createError(
|
|
85
|
+
ErrorCodes.DOCUMENTS_REQUIRED,
|
|
86
|
+
"documents 中的所有元素必须是对象类型",
|
|
87
|
+
invalidDocs.map((doc, idx) => ({
|
|
88
|
+
field: `documents[${idx}]`,
|
|
89
|
+
type: "object.required",
|
|
90
|
+
message: "必须是对象类型"
|
|
91
|
+
}))
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 2. 构建操作上下文
|
|
96
|
+
const operation = 'insertMany';
|
|
97
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
98
|
+
const docCount = documents.length;
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
// 3. 执行批量插入操作
|
|
102
|
+
const result = await nativeCollection.insertMany(documents, options);
|
|
103
|
+
|
|
104
|
+
// 4. 自动失效缓存
|
|
105
|
+
if (cache) {
|
|
106
|
+
try {
|
|
107
|
+
// 使用标准命名空间模式删除该集合的所有缓存
|
|
108
|
+
const nsObj = {
|
|
109
|
+
iid: instanceId,
|
|
110
|
+
type: "mongodb",
|
|
111
|
+
db: databaseName,
|
|
112
|
+
collection: collectionName
|
|
113
|
+
};
|
|
114
|
+
const pattern = CacheFactory.buildNamespacePattern(nsObj);
|
|
115
|
+
|
|
116
|
+
// 检查是否在事务中
|
|
117
|
+
if (isInTransaction(options)) {
|
|
118
|
+
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
119
|
+
const tx = getTransactionFromSession(options.session);
|
|
120
|
+
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
121
|
+
// 🚀 传递 metadata 支持文档级别锁
|
|
122
|
+
await tx.recordInvalidation(pattern, {
|
|
123
|
+
operation: 'write',
|
|
124
|
+
query: {},
|
|
125
|
+
collection: collectionName
|
|
126
|
+
});
|
|
127
|
+
logger.debug(`[${operation}] 事务中失效缓存: ${nsObj.db}.${nsObj.collection}`);
|
|
128
|
+
} else {
|
|
129
|
+
const deleted = await cache.delPattern(pattern);
|
|
130
|
+
if (deleted > 0) {
|
|
131
|
+
logger.debug(`[${operation}] 自动失效缓存: ${nsObj.db}.${nsObj.collection}, 删除 ${deleted} 个缓存键`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
} else {
|
|
135
|
+
// 非事务:直接失效缓存
|
|
136
|
+
const deleted = await cache.delPattern(pattern);
|
|
137
|
+
if (deleted > 0) {
|
|
138
|
+
logger.debug(`[${operation}] 自动失效缓存: ${nsObj.db}.${nsObj.collection}, 删除 ${deleted} 个缓存键`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
} catch (cacheErr) {
|
|
142
|
+
// 缓存失效失败不影响写操作
|
|
143
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// 5. 记录慢操作日志
|
|
148
|
+
const duration = Date.now() - startTime;
|
|
149
|
+
const slowQueryMs = defaults.slowQueryMs ?? 1000;
|
|
150
|
+
if (duration > slowQueryMs) {
|
|
151
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
152
|
+
ns,
|
|
153
|
+
duration,
|
|
154
|
+
threshold: slowQueryMs,
|
|
155
|
+
documentCount: docCount,
|
|
156
|
+
insertedCount: result.insertedCount,
|
|
157
|
+
ordered: options.ordered !== false,
|
|
158
|
+
comment: options.comment
|
|
159
|
+
});
|
|
160
|
+
} else {
|
|
161
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
162
|
+
ns,
|
|
163
|
+
duration,
|
|
164
|
+
documentCount: docCount,
|
|
165
|
+
insertedCount: result.insertedCount
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return result;
|
|
170
|
+
|
|
171
|
+
} catch (error) {
|
|
172
|
+
// 6. 错误处理
|
|
173
|
+
const duration = Date.now() - startTime;
|
|
174
|
+
|
|
175
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
176
|
+
ns,
|
|
177
|
+
duration,
|
|
178
|
+
error: error.message,
|
|
179
|
+
code: error.code,
|
|
180
|
+
documentCount: docCount,
|
|
181
|
+
ordered: options.ordered !== false
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// 识别特定错误类型
|
|
185
|
+
if (error.code === 11000) {
|
|
186
|
+
// MongoDB 重复键错误
|
|
187
|
+
throw createError(
|
|
188
|
+
ErrorCodes.DUPLICATE_KEY,
|
|
189
|
+
"批量插入失败:违反唯一性约束",
|
|
190
|
+
[{ message: error.message, writeErrors: error.writeErrors }],
|
|
191
|
+
error
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// 部分成功的情况(ordered=false 时可能发生)
|
|
196
|
+
if (error.result && error.result.insertedCount > 0) {
|
|
197
|
+
logger.warn(`[${operation}] 部分成功`, {
|
|
198
|
+
ns,
|
|
199
|
+
insertedCount: error.result.insertedCount,
|
|
200
|
+
totalCount: docCount,
|
|
201
|
+
failedCount: docCount - error.result.insertedCount
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// 其他错误
|
|
206
|
+
throw createError(
|
|
207
|
+
ErrorCodes.WRITE_ERROR,
|
|
208
|
+
`insertMany 操作失败: ${error.message}`,
|
|
209
|
+
error.writeErrors || null,
|
|
210
|
+
error
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
return { insertMany };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
module.exports = { createInsertManyOps };
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* insertOne 操作实现
|
|
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
|
+
* 创建 insertOne 操作
|
|
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.collectionName - 集合名称
|
|
18
|
+
* @param {string} context.databaseName - 数据库名称
|
|
19
|
+
* @param {string} context.instanceId - 实例ID
|
|
20
|
+
* @returns {Object} 包含 insertOne 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createInsertOneOps(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} document - 要插入的文档(必需)
|
|
32
|
+
* @param {Object} [options] - 操作选项
|
|
33
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
34
|
+
* @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
|
|
35
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
36
|
+
* @returns {Promise<Object>} 插入结果 { acknowledged, insertedId }
|
|
37
|
+
* @throws {Error} 当 document 参数无效时
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* const result = await collection('users').insertOne(
|
|
41
|
+
* { name: 'Alice', age: 25 }
|
|
42
|
+
* );
|
|
43
|
+
* console.log('Inserted ID:', result.insertedId);
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* // 使用 options 参数
|
|
47
|
+
* const result = await collection('users').insertOne(
|
|
48
|
+
* { name: 'Bob', age: 30 },
|
|
49
|
+
* { bypassDocumentValidation: true, comment: 'test insert' }
|
|
50
|
+
* );
|
|
51
|
+
*/
|
|
52
|
+
const insertOne = async function insertOne(document, options = {}) {
|
|
53
|
+
const startTime = Date.now();
|
|
54
|
+
|
|
55
|
+
// 1. 参数验证
|
|
56
|
+
if (!document || typeof document !== "object" || Array.isArray(document)) {
|
|
57
|
+
throw createError(
|
|
58
|
+
ErrorCodes.DOCUMENT_REQUIRED,
|
|
59
|
+
"document 必须是对象类型",
|
|
60
|
+
[{ field: "document", type: "object.required", message: "document 是必需参数且必须是对象" }]
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 2. 构建操作上下文
|
|
65
|
+
const operation = 'insertOne';
|
|
66
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
// 3. 执行插入操作
|
|
70
|
+
const result = await nativeCollection.insertOne(document, options);
|
|
71
|
+
|
|
72
|
+
// 4. 自动失效缓存
|
|
73
|
+
if (cache) {
|
|
74
|
+
try {
|
|
75
|
+
// 使用标准命名空间模式删除该集合的所有缓存
|
|
76
|
+
const ns = {
|
|
77
|
+
iid: instanceId,
|
|
78
|
+
type: "mongodb",
|
|
79
|
+
db: databaseName,
|
|
80
|
+
collection: collectionName
|
|
81
|
+
};
|
|
82
|
+
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
83
|
+
|
|
84
|
+
// 检查是否在事务中
|
|
85
|
+
if (isInTransaction(options)) {
|
|
86
|
+
// 事务中:调用 Transaction 的 recordInvalidation 方法
|
|
87
|
+
const tx = getTransactionFromSession(options.session);
|
|
88
|
+
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
89
|
+
// 🚀 传递 metadata 支持文档级别锁
|
|
90
|
+
await tx.recordInvalidation(pattern, {
|
|
91
|
+
operation: 'write',
|
|
92
|
+
query: { _id: result.insertedId },
|
|
93
|
+
collection: collectionName
|
|
94
|
+
});
|
|
95
|
+
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
96
|
+
} else {
|
|
97
|
+
const deleted = await cache.delPattern(pattern);
|
|
98
|
+
if (deleted > 0) {
|
|
99
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} else {
|
|
103
|
+
// 非事务:直接失效缓存
|
|
104
|
+
const deleted = await cache.delPattern(pattern);
|
|
105
|
+
if (deleted > 0) {
|
|
106
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
} catch (cacheErr) {
|
|
110
|
+
// 缓存失效失败不影响写操作
|
|
111
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 5. 记录慢操作日志
|
|
116
|
+
const duration = Date.now() - startTime;
|
|
117
|
+
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
118
|
+
if (duration > slowQueryMs) {
|
|
119
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
120
|
+
ns,
|
|
121
|
+
duration,
|
|
122
|
+
threshold: slowQueryMs,
|
|
123
|
+
documentKeys: Object.keys(document),
|
|
124
|
+
insertedId: result.insertedId,
|
|
125
|
+
comment: options.comment
|
|
126
|
+
});
|
|
127
|
+
} else {
|
|
128
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
129
|
+
ns,
|
|
130
|
+
duration,
|
|
131
|
+
insertedId: result.insertedId
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return result;
|
|
136
|
+
|
|
137
|
+
} catch (error) {
|
|
138
|
+
// 6. 错误处理
|
|
139
|
+
const duration = Date.now() - startTime;
|
|
140
|
+
|
|
141
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
142
|
+
ns,
|
|
143
|
+
duration,
|
|
144
|
+
error: error.message,
|
|
145
|
+
code: error.code,
|
|
146
|
+
documentKeys: Object.keys(document)
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// 识别特定错误类型
|
|
150
|
+
if (error.code === 11000) {
|
|
151
|
+
// MongoDB 重复键错误
|
|
152
|
+
throw createError(
|
|
153
|
+
ErrorCodes.DUPLICATE_KEY,
|
|
154
|
+
"文档插入失败:违反唯一性约束",
|
|
155
|
+
[{ field: "_id", message: error.message }],
|
|
156
|
+
error
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// 其他错误
|
|
161
|
+
throw createError(
|
|
162
|
+
ErrorCodes.WRITE_ERROR,
|
|
163
|
+
`insertOne 操作失败: ${error.message}`,
|
|
164
|
+
null,
|
|
165
|
+
error
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
return { insertOne };
|
|
171
|
+
} module.exports = { createInsertOneOps };
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* replaceOne 操作实现
|
|
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
|
+
* 创建 replaceOne 操作
|
|
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} 包含 replaceOne 方法的对象
|
|
21
|
+
*/
|
|
22
|
+
function createReplaceOneOps(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} replacement - 替换文档(必需,不能包含更新操作符)
|
|
33
|
+
* @param {Object} [options] - 操作选项
|
|
34
|
+
* @param {boolean} [options.upsert=false] - 不存在时是否插入
|
|
35
|
+
* @param {Object} [options.writeConcern] - 写关注选项
|
|
36
|
+
* @param {boolean} [options.bypassDocumentValidation] - 是否绕过文档验证
|
|
37
|
+
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
38
|
+
* @param {Object} [options.collation] - 排序规则
|
|
39
|
+
* @param {Object} [options.hint] - 索引提示
|
|
40
|
+
* @returns {Promise<Object>} 替换结果 { acknowledged, matchedCount, modifiedCount, upsertedId?, upsertedCount? }
|
|
41
|
+
* @throws {Error} 当参数无效时
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* const result = await collection("users").replaceOne(
|
|
45
|
+
* { userId: "user123" },
|
|
46
|
+
* { userId: "user123", name: "Alice", age: 25, status: "active" }
|
|
47
|
+
* );
|
|
48
|
+
* console.log("Modified:", result.modifiedCount);
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* // 使用 upsert 选项
|
|
52
|
+
* const result = await collection("users").replaceOne(
|
|
53
|
+
* { userId: "user456" },
|
|
54
|
+
* { userId: "user456", name: "Bob", age: 30 },
|
|
55
|
+
* { upsert: true }
|
|
56
|
+
* );
|
|
57
|
+
*/
|
|
58
|
+
const replaceOne = async function replaceOne(filter, replacement, options = {}) {
|
|
59
|
+
const startTime = Date.now();
|
|
60
|
+
|
|
61
|
+
// 1. 参数验证
|
|
62
|
+
if (!filter || typeof filter !== "object" || Array.isArray(filter)) {
|
|
63
|
+
throw createError(
|
|
64
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
65
|
+
"filter 必须是对象类型",
|
|
66
|
+
[{ field: "filter", type: "object.required", message: "filter 是必需参数且必须是对象" }]
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (!replacement || typeof replacement !== "object" || Array.isArray(replacement)) {
|
|
71
|
+
throw createError(
|
|
72
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
73
|
+
"replacement 必须是对象类型",
|
|
74
|
+
[{ field: "replacement", type: "object.required", message: "replacement 是必需参数且必须是对象" }]
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// 验证 replacement 不包含更新操作符(防止误用)
|
|
79
|
+
const replacementKeys = Object.keys(replacement);
|
|
80
|
+
if (replacementKeys.some(key => key.startsWith("$"))) {
|
|
81
|
+
throw createError(
|
|
82
|
+
ErrorCodes.INVALID_ARGUMENT,
|
|
83
|
+
"replacement 不能包含更新操作符(如 $set, $inc 等)",
|
|
84
|
+
[{ field: "replacement", type: "object.invalid", message: "replaceOne 用于完整替换文档,请使用 updateOne 进行部分更新" }]
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// 2. 构建操作上下文
|
|
89
|
+
const operation = "replaceOne";
|
|
90
|
+
const ns = `${databaseName}.${collectionName}`;
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
// 3. 执行替换操作
|
|
94
|
+
const result = await nativeCollection.replaceOne(filter, replacement, options);
|
|
95
|
+
|
|
96
|
+
// 4. 自动失效缓存
|
|
97
|
+
if (cache && result.modifiedCount > 0) {
|
|
98
|
+
try {
|
|
99
|
+
// 使用标准命名空间模式删除该集合的所有缓存
|
|
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
|
+
await tx.recordInvalidation(pattern);
|
|
114
|
+
logger.debug(`[${operation}] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
115
|
+
} else {
|
|
116
|
+
const deleted = await cache.delPattern(pattern);
|
|
117
|
+
if (deleted > 0) {
|
|
118
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
} else {
|
|
122
|
+
// 非事务:直接失效缓存
|
|
123
|
+
const deleted = await cache.delPattern(pattern);
|
|
124
|
+
if (deleted > 0) {
|
|
125
|
+
logger.debug(`[${operation}] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
} catch (cacheErr) {
|
|
129
|
+
// 缓存失效失败不影响写操作
|
|
130
|
+
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// 5. 记录慢操作日志
|
|
135
|
+
const duration = Date.now() - startTime;
|
|
136
|
+
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
137
|
+
if (duration > slowQueryMs) {
|
|
138
|
+
logger.warn(`[${operation}] 慢操作警告`, {
|
|
139
|
+
ns,
|
|
140
|
+
duration,
|
|
141
|
+
threshold: slowQueryMs,
|
|
142
|
+
filterKeys: Object.keys(filter),
|
|
143
|
+
replacementKeys: Object.keys(replacement),
|
|
144
|
+
matchedCount: result.matchedCount,
|
|
145
|
+
modifiedCount: result.modifiedCount,
|
|
146
|
+
upserted: result.upsertedId ? true : false,
|
|
147
|
+
comment: options.comment
|
|
148
|
+
});
|
|
149
|
+
} else {
|
|
150
|
+
logger.debug(`[${operation}] 操作完成`, {
|
|
151
|
+
ns,
|
|
152
|
+
duration,
|
|
153
|
+
matchedCount: result.matchedCount,
|
|
154
|
+
modifiedCount: result.modifiedCount,
|
|
155
|
+
upserted: result.upsertedId ? true : false
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return result;
|
|
160
|
+
|
|
161
|
+
} catch (error) {
|
|
162
|
+
// 6. 错误处理
|
|
163
|
+
const duration = Date.now() - startTime;
|
|
164
|
+
|
|
165
|
+
logger.error(`[${operation}] 操作失败`, {
|
|
166
|
+
ns,
|
|
167
|
+
duration,
|
|
168
|
+
error: error.message,
|
|
169
|
+
code: error.code,
|
|
170
|
+
filterKeys: Object.keys(filter),
|
|
171
|
+
replacementKeys: Object.keys(replacement)
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
// 识别特定错误类型
|
|
175
|
+
if (error.code === 11000) {
|
|
176
|
+
// MongoDB 重复键错误(可能在 upsert 时发生)
|
|
177
|
+
throw createError(
|
|
178
|
+
ErrorCodes.DUPLICATE_KEY,
|
|
179
|
+
"替换失败:违反唯一性约束",
|
|
180
|
+
[{ field: "_id", message: error.message }],
|
|
181
|
+
error
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// 其他错误
|
|
186
|
+
throw createError(
|
|
187
|
+
ErrorCodes.WRITE_ERROR,
|
|
188
|
+
`replaceOne 操作失败: ${error.message}`,
|
|
189
|
+
null,
|
|
190
|
+
error
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
return { replaceOne };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
module.exports = { createReplaceOneOps };
|
|
199
|
+
|