monsqlize 1.3.0 → 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 +56 -60
- package/LICENSE +201 -21
- package/README.md +537 -1828
- 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 +67 -69
- package/index.d.ts +0 -206
- package/index.mjs +0 -52
- package/lib/cache-invalidation.js +0 -279
- package/lib/cache.js +0 -530
- package/lib/common/cursor.js +0 -59
- package/lib/common/docs-urls.js +0 -73
- package/lib/common/index-options.js +0 -223
- package/lib/common/log.js +0 -61
- package/lib/common/namespace.js +0 -22
- package/lib/common/normalize.js +0 -34
- package/lib/common/page-result.js +0 -43
- package/lib/common/runner.js +0 -57
- package/lib/common/server-features.js +0 -232
- package/lib/common/shape-builders.js +0 -27
- package/lib/common/validation.js +0 -113
- package/lib/connect.js +0 -99
- package/lib/constants.js +0 -55
- package/lib/count-queue.js +0 -188
- package/lib/distributed-cache-invalidator.js +0 -260
- package/lib/errors.js +0 -168
- package/lib/expression/cache/ExpressionCache.js +0 -114
- package/lib/expression/compiler/ExpressionCompiler.js +0 -1090
- package/lib/expression/compiler/ExpressionCompilerExtensions.js +0 -531
- package/lib/expression/detector.js +0 -84
- package/lib/expression/factory.js +0 -29
- package/lib/expression/index.js +0 -19
- package/lib/function-cache.js +0 -533
- package/lib/index.js +0 -1251
- package/lib/infrastructure/ConnectionPoolManager.js +0 -464
- package/lib/infrastructure/HealthChecker.js +0 -281
- package/lib/infrastructure/PoolConfig.js +0 -199
- package/lib/infrastructure/PoolSelector.js +0 -225
- package/lib/infrastructure/PoolStats.js +0 -244
- package/lib/infrastructure/ssh-tunnel-ssh2.js +0 -212
- package/lib/infrastructure/ssh-tunnel.js +0 -41
- package/lib/infrastructure/uri-parser.js +0 -36
- package/lib/lock/Lock.js +0 -67
- package/lib/lock/errors.js +0 -28
- package/lib/lock/index.js +0 -13
- package/lib/logger.js +0 -225
- package/lib/model/examples/test.js +0 -311
- package/lib/model/features/defaults.js +0 -161
- package/lib/model/features/populate.js +0 -568
- package/lib/model/features/relations.js +0 -120
- package/lib/model/features/soft-delete.js +0 -349
- package/lib/model/features/version.js +0 -157
- package/lib/model/features/virtuals.js +0 -219
- package/lib/model/index.js +0 -1265
- package/lib/mongodb/common/accessor-helpers.js +0 -59
- package/lib/mongodb/common/agg-pipeline.js +0 -36
- package/lib/mongodb/common/aggregation-validator.js +0 -127
- package/lib/mongodb/common/iid.js +0 -28
- package/lib/mongodb/common/lexicographic-expr.js +0 -53
- package/lib/mongodb/common/shape.js +0 -32
- package/lib/mongodb/common/sort.js +0 -39
- package/lib/mongodb/common/transaction-aware.js +0 -25
- package/lib/mongodb/connect.js +0 -234
- package/lib/mongodb/index.js +0 -639
- package/lib/mongodb/management/admin-ops.js +0 -200
- package/lib/mongodb/management/bookmark-ops.js +0 -167
- package/lib/mongodb/management/cache-ops.js +0 -50
- package/lib/mongodb/management/collection-ops.js +0 -387
- package/lib/mongodb/management/database-ops.js +0 -202
- package/lib/mongodb/management/index-ops.js +0 -475
- package/lib/mongodb/management/index.js +0 -17
- package/lib/mongodb/management/namespace.js +0 -31
- package/lib/mongodb/management/validation-ops.js +0 -268
- package/lib/mongodb/queries/aggregate.js +0 -172
- package/lib/mongodb/queries/chain.js +0 -631
- package/lib/mongodb/queries/count.js +0 -99
- package/lib/mongodb/queries/distinct.js +0 -78
- package/lib/mongodb/queries/find-and-count.js +0 -193
- package/lib/mongodb/queries/find-by-ids.js +0 -236
- package/lib/mongodb/queries/find-one-by-id.js +0 -171
- package/lib/mongodb/queries/find-one.js +0 -71
- package/lib/mongodb/queries/find-page.js +0 -618
- package/lib/mongodb/queries/find.js +0 -171
- package/lib/mongodb/queries/index.js +0 -51
- package/lib/mongodb/queries/watch.js +0 -538
- package/lib/mongodb/writes/common/batch-retry.js +0 -65
- package/lib/mongodb/writes/delete-batch.js +0 -323
- package/lib/mongodb/writes/delete-many.js +0 -181
- package/lib/mongodb/writes/delete-one.js +0 -173
- package/lib/mongodb/writes/find-one-and-delete.js +0 -203
- package/lib/mongodb/writes/find-one-and-replace.js +0 -239
- package/lib/mongodb/writes/find-one-and-update.js +0 -240
- package/lib/mongodb/writes/increment-one.js +0 -259
- package/lib/mongodb/writes/index.js +0 -46
- package/lib/mongodb/writes/insert-batch.js +0 -508
- package/lib/mongodb/writes/insert-many.js +0 -223
- package/lib/mongodb/writes/insert-one.js +0 -169
- package/lib/mongodb/writes/replace-one.js +0 -226
- package/lib/mongodb/writes/result-handler.js +0 -237
- package/lib/mongodb/writes/update-batch.js +0 -416
- package/lib/mongodb/writes/update-many.js +0 -275
- package/lib/mongodb/writes/update-one.js +0 -273
- package/lib/mongodb/writes/upsert-one.js +0 -203
- package/lib/multi-level-cache.js +0 -244
- package/lib/operators.js +0 -330
- package/lib/redis-cache-adapter.js +0 -267
- package/lib/saga/SagaContext.js +0 -67
- package/lib/saga/SagaDefinition.js +0 -32
- package/lib/saga/SagaExecutor.js +0 -201
- package/lib/saga/SagaOrchestrator.js +0 -186
- package/lib/saga/index.js +0 -11
- package/lib/slow-query-log/base-storage.js +0 -70
- package/lib/slow-query-log/batch-queue.js +0 -97
- package/lib/slow-query-log/config-manager.js +0 -196
- package/lib/slow-query-log/index.js +0 -238
- package/lib/slow-query-log/mongodb-storage.js +0 -324
- package/lib/slow-query-log/query-hash.js +0 -39
- package/lib/sync/ChangeStreamSyncManager.js +0 -405
- package/lib/sync/ResumeTokenStore.js +0 -192
- package/lib/sync/SyncConfig.js +0 -127
- package/lib/sync/SyncTarget.js +0 -240
- package/lib/sync/index.js +0 -20
- package/lib/transaction/CacheLockManager.js +0 -162
- package/lib/transaction/DistributedCacheLockManager.js +0 -475
- package/lib/transaction/Transaction.js +0 -315
- package/lib/transaction/TransactionManager.js +0 -267
- package/lib/transaction/index.js +0 -11
- package/lib/utils/objectid-converter.js +0 -632
- package/types/README.md +0 -122
- package/types/base.ts +0 -94
- package/types/batch.ts +0 -187
- package/types/cache.ts +0 -71
- package/types/chain.ts +0 -254
- package/types/collection.ts +0 -357
- package/types/expression.ts +0 -109
- package/types/function-cache.d.ts +0 -135
- package/types/lock.ts +0 -95
- package/types/model/definition.ts +0 -152
- package/types/model/index.ts +0 -10
- package/types/model/instance.ts +0 -121
- package/types/model/relations.ts +0 -121
- package/types/model/virtuals.ts +0 -32
- package/types/monsqlize.ts +0 -245
- package/types/options.ts +0 -192
- package/types/pagination.ts +0 -154
- package/types/pool.ts +0 -125
- package/types/query.ts +0 -71
- package/types/saga.ts +0 -125
- package/types/stream.ts +0 -64
- package/types/sync.ts +0 -79
- package/types/transaction.ts +0 -79
- package/types/write.ts +0 -77
|
@@ -1,323 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* deleteBatch 操作实现
|
|
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
|
-
const { executeBatchWithRetry } = require('./common/batch-retry');
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* 创建 deleteBatch 操作
|
|
14
|
-
* @param {Object} context - 模块上下文
|
|
15
|
-
* @returns {Object} 包含 deleteBatch 方法的对象
|
|
16
|
-
*/
|
|
17
|
-
function createDeleteBatchOps(context) {
|
|
18
|
-
const { db, cache, logger, defaults, collection, effectiveDbName: databaseName, instanceId } = context;
|
|
19
|
-
|
|
20
|
-
const collectionName = collection.collectionName;
|
|
21
|
-
const nativeCollection = collection;
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* 分批删除大量匹配的文档
|
|
25
|
-
* @param {Object} filter - 筛选条件(必需)
|
|
26
|
-
* @param {Object} [options] - 操作选项
|
|
27
|
-
* @param {number} [options.batchSize=1000] - 每批删除的文档数量
|
|
28
|
-
* @param {boolean} [options.estimateProgress=true] - 是否预先 count 获取总数
|
|
29
|
-
* @param {Function} [options.onProgress] - 进度回调函数 (progress) => {}
|
|
30
|
-
* @param {string} [options.onError='stop'] - 错误处理策略: 'stop'/'skip'/'collect'/'retry'
|
|
31
|
-
* @param {number} [options.retryAttempts=3] - 失败批次最大重试次数
|
|
32
|
-
* @param {number} [options.retryDelay=1000] - 重试延迟时间(毫秒)
|
|
33
|
-
* @param {Function} [options.onRetry] - 重试回调函数 (retryInfo) => {}
|
|
34
|
-
* @param {Object} [options.writeConcern] - 写关注选项
|
|
35
|
-
* @param {string} [options.comment] - 操作注释(用于日志追踪)
|
|
36
|
-
* @returns {Promise<Object>} 删除结果
|
|
37
|
-
*
|
|
38
|
-
* @example
|
|
39
|
-
* const result = await collection('logs').deleteBatch(
|
|
40
|
-
* { createdAt: { $lt: new Date('2024-01-01') } },
|
|
41
|
-
* {
|
|
42
|
-
* batchSize: 1000,
|
|
43
|
-
* estimateProgress: true,
|
|
44
|
-
* onProgress: (p) => console.log(`进度: ${p.percentage}%`)
|
|
45
|
-
* }
|
|
46
|
-
* );
|
|
47
|
-
*/
|
|
48
|
-
const deleteBatch = async function deleteBatch(filter, options = {}) {
|
|
49
|
-
const startTime = Date.now();
|
|
50
|
-
|
|
51
|
-
// 1. 参数验证
|
|
52
|
-
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
|
|
53
|
-
throw createError(
|
|
54
|
-
ErrorCodes.INVALID_ARGUMENT,
|
|
55
|
-
'filter 必须是对象类型',
|
|
56
|
-
[{ field: 'filter', type: 'object.required', message: 'filter 是必需参数且必须是对象' }]
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// 自动转换 ObjectId 字符串
|
|
61
|
-
const convertedFilter = convertObjectIdStrings(filter, 'filter', 0, new WeakSet(), {
|
|
62
|
-
logger: context.logger,
|
|
63
|
-
excludeFields: context.autoConvertConfig?.excludeFields,
|
|
64
|
-
customFieldPatterns: context.autoConvertConfig?.customFieldPatterns,
|
|
65
|
-
maxDepth: context.autoConvertConfig?.maxDepth
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
// 解构选项
|
|
69
|
-
const {
|
|
70
|
-
batchSize = 1000,
|
|
71
|
-
estimateProgress = true,
|
|
72
|
-
onProgress,
|
|
73
|
-
onError = 'stop',
|
|
74
|
-
retryAttempts = 3,
|
|
75
|
-
retryDelay = 1000,
|
|
76
|
-
onRetry,
|
|
77
|
-
writeConcern,
|
|
78
|
-
comment
|
|
79
|
-
} = options;
|
|
80
|
-
|
|
81
|
-
// 2. 预先 count(可选)
|
|
82
|
-
const totalCount = estimateProgress
|
|
83
|
-
? await nativeCollection.countDocuments(convertedFilter)
|
|
84
|
-
: null;
|
|
85
|
-
|
|
86
|
-
// 3. 初始化结果
|
|
87
|
-
const result = {
|
|
88
|
-
acknowledged: true,
|
|
89
|
-
totalCount,
|
|
90
|
-
deletedCount: 0,
|
|
91
|
-
batchCount: 0,
|
|
92
|
-
errors: [],
|
|
93
|
-
retries: []
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
// 4. 🔴 关键:直接调用 context 的 find 流式方法
|
|
97
|
-
const stream = await context.find(convertedFilter, {
|
|
98
|
-
stream: true,
|
|
99
|
-
batchSize,
|
|
100
|
-
limit: 0, // 🔴 重要:禁用默认的 limit,否则只会查询默认的 10 条
|
|
101
|
-
comment: comment ? `${comment}:deleteBatch` : 'deleteBatch'
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
let batch = [];
|
|
105
|
-
|
|
106
|
-
return new Promise((resolve, reject) => {
|
|
107
|
-
// 5. 监听数据事件
|
|
108
|
-
stream.on('data', async (doc) => {
|
|
109
|
-
batch.push(doc._id);
|
|
110
|
-
|
|
111
|
-
// 达到批次大小,执行删除
|
|
112
|
-
if (batch.length >= batchSize) {
|
|
113
|
-
stream.pause();
|
|
114
|
-
|
|
115
|
-
try {
|
|
116
|
-
// 🔴 带重试的批量删除
|
|
117
|
-
const batchResult = await executeBatchWithRetry(
|
|
118
|
-
() => nativeCollection.deleteMany(
|
|
119
|
-
{ _id: { $in: batch } },
|
|
120
|
-
{ writeConcern }
|
|
121
|
-
),
|
|
122
|
-
{ onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
|
|
123
|
-
);
|
|
124
|
-
|
|
125
|
-
result.deletedCount += batchResult.result.deletedCount;
|
|
126
|
-
result.batchCount++;
|
|
127
|
-
|
|
128
|
-
// 记录重试信息
|
|
129
|
-
if (batchResult.attempts > 0) {
|
|
130
|
-
result.retries.push({
|
|
131
|
-
batchIndex: result.batchCount - 1,
|
|
132
|
-
attempts: batchResult.attempts,
|
|
133
|
-
success: true
|
|
134
|
-
});
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
batch = [];
|
|
138
|
-
|
|
139
|
-
// 🔴 进度回调
|
|
140
|
-
if (onProgress) {
|
|
141
|
-
onProgress({
|
|
142
|
-
currentBatch: result.batchCount,
|
|
143
|
-
totalBatches: totalCount ? Math.ceil(totalCount / batchSize) : null,
|
|
144
|
-
deleted: result.deletedCount,
|
|
145
|
-
total: totalCount,
|
|
146
|
-
percentage: totalCount ? Math.round((result.deletedCount / totalCount) * 100) : null,
|
|
147
|
-
errors: result.errors.length,
|
|
148
|
-
retries: result.retries.length
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
stream.resume();
|
|
153
|
-
|
|
154
|
-
} catch (error) {
|
|
155
|
-
// 🔴 错误处理
|
|
156
|
-
result.errors.push({
|
|
157
|
-
batchIndex: result.batchCount,
|
|
158
|
-
batchSize: batch.length,
|
|
159
|
-
error: error,
|
|
160
|
-
message: error.message
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
if (onError === 'stop') {
|
|
164
|
-
stream.destroy();
|
|
165
|
-
reject(createError(
|
|
166
|
-
ErrorCodes.WRITE_ERROR,
|
|
167
|
-
`deleteBatch 操作失败: ${error.message}`,
|
|
168
|
-
null,
|
|
169
|
-
error
|
|
170
|
-
));
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
// skip 或 collect:清空批次,继续
|
|
175
|
-
batch = [];
|
|
176
|
-
result.batchCount++;
|
|
177
|
-
stream.resume();
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
// 6. 监听流结束事件
|
|
183
|
-
stream.on('end', async () => {
|
|
184
|
-
// 处理剩余的批次
|
|
185
|
-
if (batch.length > 0) {
|
|
186
|
-
try {
|
|
187
|
-
const batchResult = await executeBatchWithRetry(
|
|
188
|
-
() => nativeCollection.deleteMany(
|
|
189
|
-
{ _id: { $in: batch } },
|
|
190
|
-
{ writeConcern }
|
|
191
|
-
),
|
|
192
|
-
{ onError, retryAttempts, retryDelay, onRetry, batchIndex: result.batchCount }
|
|
193
|
-
);
|
|
194
|
-
|
|
195
|
-
result.deletedCount += batchResult.result.deletedCount;
|
|
196
|
-
result.batchCount++;
|
|
197
|
-
|
|
198
|
-
if (batchResult.attempts > 0) {
|
|
199
|
-
result.retries.push({
|
|
200
|
-
batchIndex: result.batchCount - 1,
|
|
201
|
-
attempts: batchResult.attempts,
|
|
202
|
-
success: true
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// 最后一批的进度回调
|
|
207
|
-
if (onProgress) {
|
|
208
|
-
onProgress({
|
|
209
|
-
currentBatch: result.batchCount,
|
|
210
|
-
deleted: result.deletedCount,
|
|
211
|
-
total: totalCount,
|
|
212
|
-
percentage: totalCount ? 100 : null,
|
|
213
|
-
errors: result.errors.length,
|
|
214
|
-
retries: result.retries.length
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
} catch (error) {
|
|
219
|
-
result.errors.push({
|
|
220
|
-
batchIndex: result.batchCount,
|
|
221
|
-
batchSize: batch.length,
|
|
222
|
-
error: error,
|
|
223
|
-
message: error.message
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// 7. 最终缓存失效
|
|
229
|
-
if (cache && result.deletedCount > 0) {
|
|
230
|
-
try {
|
|
231
|
-
const ns = {
|
|
232
|
-
iid: instanceId,
|
|
233
|
-
type: 'mongodb',
|
|
234
|
-
db: databaseName,
|
|
235
|
-
collection: collectionName
|
|
236
|
-
};
|
|
237
|
-
const pattern = CacheFactory.buildNamespacePattern(ns);
|
|
238
|
-
|
|
239
|
-
// 检查是否在事务中
|
|
240
|
-
if (isInTransaction(options)) {
|
|
241
|
-
const tx = getTransactionFromSession(options.session);
|
|
242
|
-
if (tx && typeof tx.recordInvalidation === 'function') {
|
|
243
|
-
await tx.recordInvalidation(pattern, {
|
|
244
|
-
operation: 'write',
|
|
245
|
-
query: filter || {},
|
|
246
|
-
collection: collectionName
|
|
247
|
-
});
|
|
248
|
-
logger.debug(`[deleteBatch] 事务中失效缓存: ${ns.db}.${ns.collection}`);
|
|
249
|
-
} else {
|
|
250
|
-
const deleted = await cache.delPattern(pattern);
|
|
251
|
-
if (deleted > 0) {
|
|
252
|
-
logger.debug(`[deleteBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
} else {
|
|
256
|
-
const deleted = await cache.delPattern(pattern);
|
|
257
|
-
if (deleted > 0) {
|
|
258
|
-
logger.debug(`[deleteBatch] 自动失效缓存: ${ns.db}.${ns.collection}, 删除 ${deleted} 个缓存键`);
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
} catch (cacheErr) {
|
|
262
|
-
logger.warn(`[deleteBatch] 缓存失效失败: ${cacheErr.message}`);
|
|
263
|
-
}
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// 8. 慢查询日志
|
|
267
|
-
const duration = Date.now() - startTime;
|
|
268
|
-
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
269
|
-
|
|
270
|
-
if (duration > slowQueryMs) {
|
|
271
|
-
logger.warn(`[deleteBatch] 慢操作警告`, {
|
|
272
|
-
ns: `${databaseName}.${collectionName}`,
|
|
273
|
-
duration,
|
|
274
|
-
threshold: slowQueryMs,
|
|
275
|
-
totalCount,
|
|
276
|
-
deletedCount: result.deletedCount,
|
|
277
|
-
batchCount: result.batchCount,
|
|
278
|
-
errorCount: result.errors.length,
|
|
279
|
-
retryCount: result.retries.length,
|
|
280
|
-
comment
|
|
281
|
-
});
|
|
282
|
-
} else {
|
|
283
|
-
logger.debug(`[deleteBatch] 操作完成`, {
|
|
284
|
-
ns: `${databaseName}.${collectionName}`,
|
|
285
|
-
duration,
|
|
286
|
-
deletedCount: result.deletedCount,
|
|
287
|
-
batchCount: result.batchCount
|
|
288
|
-
});
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
resolve(result);
|
|
292
|
-
});
|
|
293
|
-
|
|
294
|
-
// 9. 监听流错误事件
|
|
295
|
-
stream.on('error', (error) => {
|
|
296
|
-
logger.error(`[deleteBatch] 流式查询错误`, {
|
|
297
|
-
ns: `${databaseName}.${collectionName}`,
|
|
298
|
-
error: error.message,
|
|
299
|
-
code: error.code
|
|
300
|
-
});
|
|
301
|
-
|
|
302
|
-
result.errors.push({
|
|
303
|
-
batchIndex: result.batchCount,
|
|
304
|
-
error: error,
|
|
305
|
-
message: `流式查询错误: ${error.message}`
|
|
306
|
-
});
|
|
307
|
-
|
|
308
|
-
reject(createError(
|
|
309
|
-
ErrorCodes.WRITE_ERROR,
|
|
310
|
-
`deleteBatch 流式查询失败: ${error.message}`,
|
|
311
|
-
null,
|
|
312
|
-
error
|
|
313
|
-
));
|
|
314
|
-
});
|
|
315
|
-
});
|
|
316
|
-
};
|
|
317
|
-
|
|
318
|
-
return { deleteBatch };
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
module.exports = { createDeleteBatchOps };
|
|
322
|
-
|
|
323
|
-
|
|
@@ -1,181 +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
|
-
// 🆕 v1.1.6: 解析精准失效配置
|
|
101
|
-
const instanceAuto = context.cacheAutoInvalidate || false;
|
|
102
|
-
const queryAuto = options.autoInvalidate;
|
|
103
|
-
const shouldAuto = queryAuto !== undefined ? queryAuto : instanceAuto;
|
|
104
|
-
|
|
105
|
-
if (shouldAuto) {
|
|
106
|
-
// 精准失效:deleteMany 使用 filter 作为文档
|
|
107
|
-
const CacheInvalidationEngine = require('../../cache-invalidation');
|
|
108
|
-
const deleted = await CacheInvalidationEngine.invalidatePrecise(cache, {
|
|
109
|
-
instanceId,
|
|
110
|
-
type: 'mongodb',
|
|
111
|
-
db: databaseName,
|
|
112
|
-
collection: collectionName,
|
|
113
|
-
document: convertedFilter,
|
|
114
|
-
operation: 'deleteMany'
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
if (deleted > 0) {
|
|
118
|
-
logger.debug(`[${operation}] 精准失效缓存: ${databaseName}.${collectionName}, 删除 ${deleted} 个缓存键`);
|
|
119
|
-
}
|
|
120
|
-
} else {
|
|
121
|
-
logger.debug(`[${operation}] 跳过自动失效(autoInvalidate=false)`);
|
|
122
|
-
}
|
|
123
|
-
} catch (cacheErr) {
|
|
124
|
-
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// 6. 记录慢操作日志
|
|
129
|
-
const duration = Date.now() - startTime;
|
|
130
|
-
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
131
|
-
if (duration > slowQueryMs) {
|
|
132
|
-
logger.warn(`[${operation}] 慢操作警告`, {
|
|
133
|
-
ns,
|
|
134
|
-
duration,
|
|
135
|
-
threshold: slowQueryMs,
|
|
136
|
-
filterKeys: Object.keys(filter),
|
|
137
|
-
deletedCount: result.deletedCount,
|
|
138
|
-
comment: options.comment
|
|
139
|
-
});
|
|
140
|
-
} else {
|
|
141
|
-
logger.debug(`[${operation}] 操作完成`, {
|
|
142
|
-
ns,
|
|
143
|
-
duration,
|
|
144
|
-
deletedCount: result.deletedCount
|
|
145
|
-
});
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
// 7. 返回结果
|
|
149
|
-
return {
|
|
150
|
-
deletedCount: result.deletedCount,
|
|
151
|
-
acknowledged: result.acknowledged
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
} catch (error) {
|
|
155
|
-
// 8. 错误处理
|
|
156
|
-
const duration = Date.now() - startTime;
|
|
157
|
-
|
|
158
|
-
logger.error(`[${operation}] 操作失败`, {
|
|
159
|
-
ns,
|
|
160
|
-
duration,
|
|
161
|
-
error: error.message,
|
|
162
|
-
code: error.code,
|
|
163
|
-
filterKeys: Object.keys(filter)
|
|
164
|
-
});
|
|
165
|
-
|
|
166
|
-
// 其他错误
|
|
167
|
-
throw createError(
|
|
168
|
-
ErrorCodes.WRITE_ERROR,
|
|
169
|
-
`deleteMany 操作失败: ${error.message}`,
|
|
170
|
-
null,
|
|
171
|
-
error
|
|
172
|
-
);
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
|
|
176
|
-
return { deleteMany };
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
module.exports = { createDeleteManyOps };
|
|
180
|
-
|
|
181
|
-
|
|
@@ -1,173 +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
|
-
// 🆕 v1.1.6: 解析精准失效配置
|
|
93
|
-
const instanceAuto = context.cacheAutoInvalidate || false;
|
|
94
|
-
const queryAuto = options.autoInvalidate;
|
|
95
|
-
const shouldAuto = queryAuto !== undefined ? queryAuto : instanceAuto;
|
|
96
|
-
|
|
97
|
-
if (shouldAuto) {
|
|
98
|
-
// 精准失效:deleteOne 使用 filter 作为文档
|
|
99
|
-
const CacheInvalidationEngine = require('../../cache-invalidation');
|
|
100
|
-
const deleted = await CacheInvalidationEngine.invalidatePrecise(cache, {
|
|
101
|
-
instanceId,
|
|
102
|
-
type: 'mongodb',
|
|
103
|
-
db: databaseName,
|
|
104
|
-
collection: collectionName,
|
|
105
|
-
document: convertedFilter,
|
|
106
|
-
operation: 'deleteOne'
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
if (deleted > 0) {
|
|
110
|
-
logger.debug(`[${operation}] 精准失效缓存: ${databaseName}.${collectionName}, 删除 ${deleted} 个缓存键`);
|
|
111
|
-
}
|
|
112
|
-
} else {
|
|
113
|
-
logger.debug(`[${operation}] 跳过自动失效(autoInvalidate=false)`);
|
|
114
|
-
}
|
|
115
|
-
} catch (cacheErr) {
|
|
116
|
-
logger.warn(`[${operation}] 缓存失效失败: ${cacheErr.message}`, { ns: `${databaseName}.${collectionName}`, error: cacheErr });
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
// 5. 记录慢操作日志
|
|
121
|
-
const duration = Date.now() - startTime;
|
|
122
|
-
const slowQueryMs = defaults.slowQueryMs || 1000;
|
|
123
|
-
if (duration > slowQueryMs) {
|
|
124
|
-
logger.warn(`[${operation}] 慢操作警告`, {
|
|
125
|
-
ns,
|
|
126
|
-
duration,
|
|
127
|
-
threshold: slowQueryMs,
|
|
128
|
-
filterKeys: Object.keys(filter),
|
|
129
|
-
deletedCount: result.deletedCount,
|
|
130
|
-
comment: options.comment
|
|
131
|
-
});
|
|
132
|
-
} else {
|
|
133
|
-
logger.debug(`[${operation}] 操作完成`, {
|
|
134
|
-
ns,
|
|
135
|
-
duration,
|
|
136
|
-
deletedCount: result.deletedCount
|
|
137
|
-
});
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// 6. 返回结果
|
|
141
|
-
return {
|
|
142
|
-
deletedCount: result.deletedCount,
|
|
143
|
-
acknowledged: result.acknowledged
|
|
144
|
-
};
|
|
145
|
-
|
|
146
|
-
} catch (error) {
|
|
147
|
-
// 7. 错误处理
|
|
148
|
-
const duration = Date.now() - startTime;
|
|
149
|
-
|
|
150
|
-
logger.error(`[${operation}] 操作失败`, {
|
|
151
|
-
ns,
|
|
152
|
-
duration,
|
|
153
|
-
error: error.message,
|
|
154
|
-
code: error.code,
|
|
155
|
-
filterKeys: Object.keys(filter)
|
|
156
|
-
});
|
|
157
|
-
|
|
158
|
-
// 其他错误
|
|
159
|
-
throw createError(
|
|
160
|
-
ErrorCodes.WRITE_ERROR,
|
|
161
|
-
`deleteOne 操作失败: ${error.message}`,
|
|
162
|
-
null,
|
|
163
|
-
error
|
|
164
|
-
);
|
|
165
|
-
}
|
|
166
|
-
};
|
|
167
|
-
|
|
168
|
-
return { deleteOne };
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
module.exports = { createDeleteOneOps };
|
|
172
|
-
|
|
173
|
-
|