-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathMongoDbStore.cs
More file actions
483 lines (419 loc) · 20 KB
/
Copy pathMongoDbStore.cs
File metadata and controls
483 lines (419 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
using System.Linq.Expressions;
using Elsa.Common.Entities;
using Elsa.Common.Multitenancy;
using Elsa.Extensions;
using Elsa.Persistence.MongoDb.Extensions;
using JetBrains.Annotations;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace Elsa.Persistence.MongoDb.Common;
/// <summary>
/// A generic repository class around MongoDb for accessing documents.
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
[PublicAPI]
public class MongoDbStore<TDocument>(IMongoCollection<TDocument> collection, ITenantAccessor tenantAccessor)
where TDocument : class
{
/// <summary>
/// Returns a queryable collection of documents.
/// </summary>
public IMongoCollection<TDocument> GetCollection() => collection;
/// <summary>
/// Saves the document.
/// </summary>
/// <param name="document">The document to save.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public async Task<TDocument> AddAsync(TDocument document, CancellationToken cancellationToken = default)
{
ApplyTenantId(document);
await collection.InsertOneAsync(document, new InsertOneOptions(), cancellationToken);
return document;
}
/// <summary>
/// Saves a list of documents.
/// </summary>
/// <param name="documents">The documents to save.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public async Task AddManyAsync(IEnumerable<TDocument> documents, CancellationToken cancellationToken = default)
{
var documentsList = documents.ToList();
if (!documentsList.Any())
return;
ApplyTenantId(documentsList);
await collection.InsertManyAsync(documentsList, new InsertManyOptions(), cancellationToken);
}
/// <summary>
/// Saves the document.
/// </summary>
/// <param name="document">The document to save.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public async Task<TDocument> SaveAsync(TDocument document, CancellationToken cancellationToken = default)
{
ApplyTenantId(document);
return await collection.FindOneAndReplaceAsync(document.BuildIdFilter(), document, new FindOneAndReplaceOptions<TDocument>
{
ReturnDocument = ReturnDocument.After,
IsUpsert = true
}, cancellationToken);
}
/// <summary>
/// Saves the document.
/// </summary>
/// <param name="document">The document to save.</param>
/// <param name="selector">The selector to use.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public async Task<TDocument> SaveAsync<TResult>(TDocument document, Expression<Func<TDocument, TResult>> selector, CancellationToken cancellationToken = default)
{
ApplyTenantId(document);
return await collection.FindOneAndReplaceAsync(document.BuildExpression(selector), document, new FindOneAndReplaceOptions<TDocument>
{
ReturnDocument = ReturnDocument.After,
IsUpsert = true
}, cancellationToken);
}
/// <summary>
/// Saves the specified documents.
/// </summary>
/// <param name="documents">The documents to save.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public async Task SaveManyAsync(IEnumerable<TDocument> documents, CancellationToken cancellationToken = default)
{
var documentsList = documents.ToList();
ApplyTenantId(documentsList);
var writes = new List<WriteModel<TDocument>>();
foreach (var document in documentsList)
{
var replacement = new ReplaceOneModel<TDocument>(document.BuildIdFilter(), document)
{
IsUpsert = true
};
writes.Add(replacement);
}
if (!writes.Any())
return;
await collection.BulkWriteAsync(writes, cancellationToken: cancellationToken);
}
/// <summary>
/// Saves the specified documents.
/// </summary>
/// <param name="documents">The documents to save.</param>
/// <param name="primaryKey">The primary key to use.</param>
/// <param name="cancellationToken">The cancellation token.</param>
public async Task SaveManyAsync(IEnumerable<TDocument> documents, string primaryKey = nameof(Entity.Id), CancellationToken cancellationToken = default)
{
var documentsList = documents.ToList();
ApplyTenantId(documentsList);
var writes = new List<WriteModel<TDocument>>();
foreach (var document in documentsList)
{
var replacement = new ReplaceOneModel<TDocument>(document.BuildFilter(primaryKey), document)
{
IsUpsert = true
};
writes.Add(replacement);
}
if (!writes.Any())
return;
await collection.BulkWriteAsync(writes, cancellationToken: cancellationToken);
}
public async Task<bool> UpdatePartialAsync(
string id,
IDictionary<string, object> updatedFields,
string primaryKey = nameof(Entity.Id),
bool throwIfNotFound = true,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentNullException(nameof(id));
if (updatedFields == null || updatedFields.Count == 0)
throw new ArgumentException("No fields to update were provided.", nameof(updatedFields));
var filter = Builders<TDocument>.Filter.Eq(primaryKey, id);
var updateDefinition = Builders<TDocument>.Update.Combine(
updatedFields.Select(field => Builders<TDocument>.Update.Set(field.Key, field.Value))
);
var updateResult = await collection.UpdateOneAsync(filter, updateDefinition, cancellationToken: cancellationToken);
if (updateResult.MatchedCount == 0)
{
if (!throwIfNotFound)
return false;
throw new InvalidOperationException($"No document found with ID '{id}'.");
}
return updateResult.ModifiedCount > 0;
}
/// <summary>
/// Finds the document matching the specified predicate
/// </summary>
/// <param name="predicate">The predicate to use.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The document if found, otherwise <c>null</c>.</returns>
public async Task<TDocument?> FindAsync(Expression<Func<TDocument, bool>> predicate, CancellationToken cancellationToken = default)
{
return await FindAsync(predicate, false, cancellationToken);
}
/// <summary>
/// Finds the document matching the specified predicate
/// </summary>
/// <param name="predicate">The predicate to use.</param>
/// <param name="tenantAgnostic">Whether to include results across tenants.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The document if found, otherwise <c>null</c>.</returns>
public async Task<TDocument?> FindAsync(Expression<Func<TDocument, bool>> predicate, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await queryable.Where(predicate).FirstOrDefaultAsync(cancellationToken);
}
/// <summary>
/// Finds a single document using a query
/// </summary>
/// <param name="query">The query to use</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The document if found, otherwise <c>null</c></returns>
public async Task<TDocument?> FindAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, CancellationToken cancellationToken = default)
{
return await FindAsync(query, false, cancellationToken);
}
/// <summary>
/// Finds a single document using a query
/// </summary>
/// <param name="query">The query to use</param>
/// <param name="tenantAgnostic">Whether to include results across tenants</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns>The document if found, otherwise <c>null</c></returns>
public async Task<TDocument?> FindAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await query(queryable).FirstOrDefaultAsync(cancellationToken);
}
/// <summary>
/// Finds a list of documents matching the specified predicate
/// </summary>
public async Task<IEnumerable<TDocument>> FindManyAsync(Expression<Func<TDocument, bool>> predicate, CancellationToken cancellationToken = default)
{
return await FindManyAsync(predicate, false, cancellationToken);
}
/// <summary>
/// Finds a list of documents matching the specified predicate
/// </summary>
public async Task<IEnumerable<TDocument>> FindManyAsync(Expression<Func<TDocument, bool>> predicate, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await queryable.Where(predicate).ToListAsync(cancellationToken);
}
/// <summary>
/// Queries the database using a query and a selector.
/// </summary>
public async Task<IEnumerable<TResult>> FindManyAsync<TResult>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TResult>> selector, CancellationToken cancellationToken = default)
{
return await FindManyAsync(query, selector, false, cancellationToken);
}
/// <summary>
/// Queries the database using a query and a selector.
/// </summary>
public async Task<IEnumerable<TResult>> FindManyAsync<TResult>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TResult>> selector, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await query(queryable).Select(selector).ToListAsync(cancellationToken);
}
/// <summary>
/// Finds a list of documents using a query
/// </summary>
public async Task<IEnumerable<TDocument>> FindManyAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, CancellationToken cancellationToken = default)
{
return await FindManyAsync(query, false, cancellationToken);
}
/// <summary>
/// Finds a list of documents using a query
/// </summary>
public async Task<IEnumerable<TDocument>> FindManyAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await query(queryable).ToListAsync(cancellationToken);
}
/// <summary>
/// Queries the database using a query and a selector.
/// </summary>
public async Task<IEnumerable<TResult>> FindMany<TResult>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TResult>> selector, CancellationToken cancellationToken = default)
{
return await FindMany(query, selector, false, cancellationToken);
}
/// <summary>
/// Queries the database using a query and a selector.
/// </summary>
public async Task<IEnumerable<TResult>> FindMany<TResult>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TResult>> selector, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await query(queryable).Select(selector).ToListAsync(cancellationToken);
}
/// <summary>
/// Counts documents in the collection using a filter.
/// </summary>
public async Task<long> CountAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, CancellationToken cancellationToken = default)
{
return await CountAsync(query, false, cancellationToken);
}
/// <summary>
/// Counts documents in the collection using a filter.
/// </summary>
public async Task<long> CountAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await query(queryable).LongCountAsync(cancellationToken);
}
/// <summary>
/// Counts documents in the collection using a filter and distinct by a key selector.
/// </summary>
public async Task<long> CountAsync<TProperty>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TProperty>> propertySelector, CancellationToken cancellationToken = default)
{
return await CountAsync(query, propertySelector, false, cancellationToken);
}
/// <summary>
/// Counts documents in the collection using a filter and distinct by a key selector.
/// </summary>
public async Task<long> CountAsync<TProperty>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TProperty>> propertySelector, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await query(queryable.DistinctBy(propertySelector)).LongCountAsync(cancellationToken);
}
/// <summary>
/// Lists all documents.
/// </summary>
public async Task<IEnumerable<TDocument>> ListAsync(bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await queryable.ToListAsync(cancellationToken);
}
/// <summary>
/// Checks if any documents exist.
/// </summary>
public async Task<bool> AnyAsync(Expression<Func<TDocument, bool>> predicate, CancellationToken cancellationToken = default)
{
return await AnyAsync(predicate, false, cancellationToken);
}
/// <summary>
/// Checks if any documents exist.
/// </summary>
public async Task<bool> AnyAsync(Expression<Func<TDocument, bool>> predicate, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
return await queryable.Where(predicate).AnyAsync(cancellationToken);
}
/// <summary>
/// Deletes documents using a predicate.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync(Expression<Func<TDocument, bool>> predicate, CancellationToken cancellationToken = default)
{
return await DeleteWhereAsync(predicate, false, cancellationToken);
}
/// <summary>
/// Deletes documents using a predicate.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync(Expression<Func<TDocument, bool>> predicate, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
return await DeleteWhereAsync(predicate, nameof(Entity.Id), tenantAgnostic, cancellationToken);
}
/// <summary>
/// Deletes documents using a predicate.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync(Expression<Func<TDocument, bool>> predicate, string key, CancellationToken cancellationToken = default)
{
return await DeleteWhereAsync(predicate, key, false, cancellationToken);
}
/// <summary>
/// Deletes documents using a predicate.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync(Expression<Func<TDocument, bool>> predicate, string key, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
var documentsToDelete = await queryable.Where(predicate).ToListAsync(cancellationToken);
var count = documentsToDelete.LongCount();
var filter = documentsToDelete.BuildIdFilterForList(key);
await collection.DeleteManyAsync(filter, cancellationToken);
return count;
}
/// <summary>
/// Deletes documents using a query.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync<TKey>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TKey>> keySelector, CancellationToken cancellationToken = default)
{
return await DeleteWhereAsync(query, keySelector, false, cancellationToken);
}
/// <summary>
/// Deletes documents using a query.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync<TKey>(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, Expression<Func<TDocument, TKey>> keySelector, bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var key = keySelector.GetPropertyName();
return await DeleteWhereAsync(query, key, tenantAgnostic, cancellationToken);
}
/// <summary>
/// Deletes documents using a query.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, string key = nameof(Entity.Id), CancellationToken cancellationToken = default)
{
return await DeleteWhereAsync(query, key, false, cancellationToken);
}
/// <summary>
/// Deletes documents using a query.
/// </summary>
/// <returns>The number of documents deleted.</returns>
public async Task<long> DeleteWhereAsync(Func<IQueryable<TDocument>, IQueryable<TDocument>> query, string key = nameof(Entity.Id), bool tenantAgnostic = false, CancellationToken cancellationToken = default)
{
var queryable = GetQueryableCollection(tenantAgnostic);
var documentsToDelete = await query(queryable).ToListAsync(cancellationToken);
var count = documentsToDelete.LongCount();
var filter = documentsToDelete.BuildIdFilterForList(key);
await collection.DeleteManyAsync(filter, cancellationToken);
return count;
}
private IQueryable<TDocument> GetQueryableCollection(bool tenantAgnostic = false)
{
var queryable = collection.AsQueryable();
if (tenantAgnostic)
return queryable;
if (typeof(Entity).IsAssignableFrom(typeof(TDocument)))
{
var tenant = tenantAccessor.Tenant;
var tenantId = tenant?.Id.EmptyToNull();
queryable = ApplyTenantFilter(queryable, tenantId);
}
return queryable;
}
internal static IQueryable<TDocument> ApplyTenantFilter(IQueryable<TDocument> queryable, string? tenantId)
{
return queryable.Where(x => (x as Entity)!.TenantId == tenantId || (x as Entity)!.TenantId == Tenant.AgnosticTenantId);
}
private void ApplyTenantId(TDocument document)
{
var tenant = tenantAccessor.Tenant;
var tenantId = tenant?.Id;
if (document is Entity tenantDocument)
ApplyTenantId(tenantDocument, tenantId);
}
private void ApplyTenantId(IEnumerable<TDocument> documents)
{
var tenant = tenantAccessor.Tenant;
var tenantId = tenant?.Id;
foreach (var document in documents)
{
if (document is Entity tenantDocument)
ApplyTenantId(tenantDocument, tenantId);
}
}
private static void ApplyTenantId(Entity tenantDocument, string? tenantId)
{
if (tenantDocument.TenantId == Tenant.AgnosticTenantId)
return;
// Preserve explicitly scoped entities and only stamp ambient tenant IDs on unscoped entities.
if (tenantDocument.TenantId != null)
return;
tenantDocument.TenantId = tenantId.EmptyToNull();
}
}