-
-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathDapperRepository.cs
582 lines (473 loc) · 25.6 KB
/
DapperRepository.cs
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
using System.Data.Common;
using Dapper;
using DapperExample.AtomicOperations;
using DapperExample.TranslationToSql;
using DapperExample.TranslationToSql.Builders;
using DapperExample.TranslationToSql.DataModel;
using DapperExample.TranslationToSql.TreeNodes;
using JsonApiDotNetCore;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Queries;
using JsonApiDotNetCore.Queries.Expressions;
using JsonApiDotNetCore.Repositories;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
namespace DapperExample.Repositories;
/// <summary>
/// A JsonApiDotNetCore resource repository that converts <see cref="QueryLayer" /> into SQL and uses <see href="https://github.com/DapperLib/Dapper" />
/// to execute the SQL and materialize result sets into JSON:API resources.
/// </summary>
/// <typeparam name="TResource">
/// The resource type.
/// </typeparam>
/// <typeparam name="TId">
/// The resource identifier type.
/// </typeparam>
/// <remarks>
/// This implementation has the following limitations:
/// <list type="bullet">
/// <item>
/// <description>
/// No pagination. Surprisingly, this is insanely complicated and requires non-standard, vendor-specific SQL.
/// </description>
/// </item>
/// <item>
/// <description>
/// No many-to-many relationships. It requires additional information about the database model but should be possible to implement.
/// </description>
/// </item>
/// <item>
/// <description>
/// No resource inheritance. Requires additional information about the database and is complex to implement.
/// </description>
/// </item>
/// <item>
/// <description>
/// No composite primary/foreign keys. It could be implemented, but it's a corner case that few people use.
/// </description>
/// </item>
/// <item>
/// <description>
/// Only parameterless constructors in resource classes. This is because materialization is performed by Dapper, which doesn't support constructors with
/// parameters.
/// </description>
/// </item>
/// <item>
/// <description>
/// Simple change detection in write operations. It includes scalar properties, but relationships go only one level deep. This is sufficient for
/// JSON:API.
/// </description>
/// </item>
/// <item>
/// <description>
/// The database table/column/key name mapping is based on hardcoded conventions. This could be generalized but wasn't done to keep it simple.
/// </description>
/// </item>
/// <item>
/// <description>
/// Cascading deletes are assumed to occur inside the database, which SQL Server does not support very well. This is a lot of work to implement.
/// </description>
/// </item>
/// <item>
/// <description>
/// No [EagerLoad] support. It could be done, but it's rarely used.
/// </description>
/// </item>
/// <item>
/// <description>
/// Untested with self-referencing resources and relationship cycles.
/// </description>
/// </item>
/// <item>
/// <description>
/// No support for <see cref="IResourceDefinition{TResource,TId}.OnRegisterQueryableHandlersForQueryStringParameters" />. Because no
/// <see cref="IQueryable" /> is used, it doesn't apply.
/// </description>
/// </item>
/// </list>
/// </remarks>
public sealed class DapperRepository<TResource, TId> : IResourceRepository<TResource, TId>, IRepositorySupportsTransaction
where TResource : class, IIdentifiable<TId>
{
private readonly ITargetedFields _targetedFields;
private readonly IResourceGraph _resourceGraph;
private readonly IResourceFactory _resourceFactory;
private readonly IResourceDefinitionAccessor _resourceDefinitionAccessor;
private readonly AmbientTransactionFactory _transactionFactory;
private readonly IDataModelService _dataModelService;
private readonly SqlCaptureStore _captureStore;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger<DapperRepository<TResource, TId>> _logger;
private readonly CollectionConverter _collectionConverter = new();
private readonly ParameterFormatter _parameterFormatter = new();
private readonly DapperFacade _dapperFacade;
private ResourceType ResourceType => _resourceGraph.GetResourceType<TResource>();
public string? TransactionId => _transactionFactory.AmbientTransaction?.TransactionId;
public DapperRepository(ITargetedFields targetedFields, IResourceGraph resourceGraph, IResourceFactory resourceFactory,
IResourceDefinitionAccessor resourceDefinitionAccessor, AmbientTransactionFactory transactionFactory, IDataModelService dataModelService,
SqlCaptureStore captureStore, ILoggerFactory loggerFactory)
{
ArgumentGuard.NotNull(targetedFields);
ArgumentGuard.NotNull(resourceGraph);
ArgumentGuard.NotNull(resourceFactory);
ArgumentGuard.NotNull(resourceDefinitionAccessor);
ArgumentGuard.NotNull(transactionFactory);
ArgumentGuard.NotNull(dataModelService);
ArgumentGuard.NotNull(captureStore);
ArgumentGuard.NotNull(loggerFactory);
_targetedFields = targetedFields;
_resourceGraph = resourceGraph;
_resourceFactory = resourceFactory;
_resourceDefinitionAccessor = resourceDefinitionAccessor;
_transactionFactory = transactionFactory;
_dataModelService = dataModelService;
_captureStore = captureStore;
_loggerFactory = loggerFactory;
_logger = loggerFactory.CreateLogger<DapperRepository<TResource, TId>>();
_dapperFacade = new DapperFacade(dataModelService);
}
/// <inheritdoc />
public async Task<IReadOnlyCollection<TResource>> GetAsync(QueryLayer queryLayer, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(queryLayer);
var mapper = new ResultSetMapper<TResource, TId>(queryLayer.Include);
var selectBuilder = new SelectStatementBuilder(_dataModelService, _loggerFactory);
SelectNode selectNode = selectBuilder.Build(queryLayer, SelectShape.Columns);
CommandDefinition sqlCommand = _dapperFacade.GetSqlCommand(selectNode, cancellationToken);
LogSqlCommand(sqlCommand);
IReadOnlyCollection<TResource> resources = await ExecuteQueryAsync(async connection =>
{
// Reads must occur within the active transaction, when in an atomic:operations request.
sqlCommand = sqlCommand.Associate(_transactionFactory.AmbientTransaction);
// Unfortunately, there's no CancellationToken support. See https://github.com/DapperLib/Dapper/issues/1181.
_ = await connection.QueryAsync(sqlCommand.CommandText, mapper.ResourceClrTypes, mapper.Map, sqlCommand.Parameters, sqlCommand.Transaction);
return mapper.GetResources();
}, cancellationToken);
return resources;
}
/// <inheritdoc />
public async Task<int> CountAsync(FilterExpression? filter, CancellationToken cancellationToken)
{
var queryLayer = new QueryLayer(ResourceType)
{
Filter = filter
};
var selectBuilder = new SelectStatementBuilder(_dataModelService, _loggerFactory);
SelectNode selectNode = selectBuilder.Build(queryLayer, SelectShape.Count);
CommandDefinition sqlCommand = _dapperFacade.GetSqlCommand(selectNode, cancellationToken);
LogSqlCommand(sqlCommand);
return await ExecuteQueryAsync(async connection => await connection.ExecuteScalarAsync<int>(sqlCommand), cancellationToken);
}
/// <inheritdoc />
public Task<TResource> GetForCreateAsync(Type resourceClrType, TId id, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(resourceClrType);
var resource = (TResource)_resourceFactory.CreateInstance(resourceClrType);
resource.Id = id;
return Task.FromResult(resource);
}
/// <inheritdoc />
public async Task CreateAsync(TResource resourceFromRequest, TResource resourceForDatabase, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(resourceFromRequest);
ArgumentGuard.NotNull(resourceForDatabase);
var changeDetector = new ResourceChangeDetector(ResourceType, _dataModelService);
await ApplyTargetedFieldsAsync(resourceFromRequest, resourceForDatabase, WriteOperationKind.CreateResource, cancellationToken);
await _resourceDefinitionAccessor.OnWritingAsync(resourceForDatabase, WriteOperationKind.CreateResource, cancellationToken);
changeDetector.CaptureNewValues(resourceForDatabase);
IReadOnlyCollection<CommandDefinition> preSqlCommands =
_dapperFacade.BuildSqlCommandsForOneToOneRelationshipsChangedToNotNull(changeDetector, cancellationToken);
CommandDefinition insertCommand = _dapperFacade.BuildSqlCommandForCreate(changeDetector, cancellationToken);
await ExecuteInTransactionAsync(async transaction =>
{
foreach (CommandDefinition sqlCommand in preSqlCommands)
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected > 1)
{
throw new DataStoreUpdateException(new Exception("Multiple rows found."));
}
}
LogSqlCommand(insertCommand);
resourceForDatabase.Id = (await transaction.Connection!.ExecuteScalarAsync<TId>(insertCommand.Associate(transaction)))!;
IReadOnlyCollection<CommandDefinition> postSqlCommands =
_dapperFacade.BuildSqlCommandsForChangedRelationshipsHavingForeignKeyAtRightSide(changeDetector, resourceForDatabase.Id, cancellationToken);
foreach (CommandDefinition sqlCommand in postSqlCommands)
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected == 0)
{
throw new DataStoreUpdateException(new Exception("Row does not exist."));
}
}
}, cancellationToken);
await _resourceDefinitionAccessor.OnWriteSucceededAsync(resourceForDatabase, WriteOperationKind.CreateResource, cancellationToken);
}
private async Task ApplyTargetedFieldsAsync(TResource resourceFromRequest, TResource resourceInDatabase, WriteOperationKind writeOperation,
CancellationToken cancellationToken)
{
foreach (RelationshipAttribute relationship in _targetedFields.Relationships)
{
object? rightValue = relationship.GetValue(resourceFromRequest);
object? rightValueEvaluated = await VisitSetRelationshipAsync(resourceInDatabase, relationship, rightValue, writeOperation, cancellationToken);
relationship.SetValue(resourceInDatabase, rightValueEvaluated);
}
foreach (AttrAttribute attribute in _targetedFields.Attributes)
{
attribute.SetValue(resourceInDatabase, attribute.GetValue(resourceFromRequest));
}
}
private async Task<object?> VisitSetRelationshipAsync(TResource leftResource, RelationshipAttribute relationship, object? rightValue,
WriteOperationKind writeOperation, CancellationToken cancellationToken)
{
if (relationship is HasOneAttribute hasOneRelationship)
{
return await _resourceDefinitionAccessor.OnSetToOneRelationshipAsync(leftResource, hasOneRelationship, (IIdentifiable?)rightValue, writeOperation,
cancellationToken);
}
if (relationship is HasManyAttribute hasManyRelationship)
{
HashSet<IIdentifiable> rightResourceIds = _collectionConverter.ExtractResources(rightValue).ToHashSet(IdentifiableComparer.Instance);
await _resourceDefinitionAccessor.OnSetToManyRelationshipAsync(leftResource, hasManyRelationship, rightResourceIds, writeOperation,
cancellationToken);
return _collectionConverter.CopyToTypedCollection(rightResourceIds, relationship.Property.PropertyType);
}
return rightValue;
}
/// <inheritdoc />
public async Task<TResource?> GetForUpdateAsync(QueryLayer queryLayer, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(queryLayer);
IReadOnlyCollection<TResource> resources = await GetAsync(queryLayer, cancellationToken);
return resources.FirstOrDefault();
}
/// <inheritdoc />
public async Task UpdateAsync(TResource resourceFromRequest, TResource resourceFromDatabase, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(resourceFromRequest);
ArgumentGuard.NotNull(resourceFromDatabase);
var changeDetector = new ResourceChangeDetector(ResourceType, _dataModelService);
changeDetector.CaptureCurrentValues(resourceFromDatabase);
await ApplyTargetedFieldsAsync(resourceFromRequest, resourceFromDatabase, WriteOperationKind.UpdateResource, cancellationToken);
await _resourceDefinitionAccessor.OnWritingAsync(resourceFromDatabase, WriteOperationKind.UpdateResource, cancellationToken);
changeDetector.CaptureNewValues(resourceFromDatabase);
changeDetector.AssertIsNotClearingAnyRequiredToOneRelationships(ResourceType.PublicName);
IReadOnlyCollection<CommandDefinition> preSqlCommands =
_dapperFacade.BuildSqlCommandsForOneToOneRelationshipsChangedToNotNull(changeDetector, cancellationToken);
CommandDefinition? updateCommand = _dapperFacade.BuildSqlCommandForUpdate(changeDetector, resourceFromDatabase.Id, cancellationToken);
IReadOnlyCollection<CommandDefinition> postSqlCommands =
_dapperFacade.BuildSqlCommandsForChangedRelationshipsHavingForeignKeyAtRightSide(changeDetector, resourceFromDatabase.Id, cancellationToken);
if (preSqlCommands.Any() || updateCommand != null || postSqlCommands.Any())
{
await ExecuteInTransactionAsync(async transaction =>
{
foreach (CommandDefinition sqlCommand in preSqlCommands)
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected > 1)
{
throw new DataStoreUpdateException(new Exception("Multiple rows found."));
}
}
if (updateCommand != null)
{
LogSqlCommand(updateCommand.Value);
int rowsAffected = await transaction.Connection!.ExecuteAsync(updateCommand.Value.Associate(transaction));
if (rowsAffected != 1)
{
throw new DataStoreUpdateException(new Exception("Row does not exist or multiple rows found."));
}
}
foreach (CommandDefinition sqlCommand in postSqlCommands)
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected == 0)
{
throw new DataStoreUpdateException(new Exception("Row does not exist."));
}
}
}, cancellationToken);
await _resourceDefinitionAccessor.OnWriteSucceededAsync(resourceFromDatabase, WriteOperationKind.UpdateResource, cancellationToken);
}
}
/// <inheritdoc />
public async Task DeleteAsync(TResource? resourceFromDatabase, TId id, CancellationToken cancellationToken)
{
TResource placeholderResource = resourceFromDatabase ?? _resourceFactory.CreateInstance<TResource>();
placeholderResource.Id = id;
await _resourceDefinitionAccessor.OnWritingAsync(placeholderResource, WriteOperationKind.DeleteResource, cancellationToken);
var deleteBuilder = new DeleteResourceStatementBuilder(_dataModelService);
DeleteNode deleteNode = deleteBuilder.Build(ResourceType, placeholderResource.Id!);
CommandDefinition sqlCommand = _dapperFacade.GetSqlCommand(deleteNode, cancellationToken);
await ExecuteInTransactionAsync(async transaction =>
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected != 1)
{
throw new DataStoreUpdateException(new Exception("Row does not exist or multiple rows found."));
}
}, cancellationToken);
await _resourceDefinitionAccessor.OnWriteSucceededAsync(placeholderResource, WriteOperationKind.DeleteResource, cancellationToken);
}
/// <inheritdoc />
public async Task SetRelationshipAsync(TResource leftResource, object? rightValue, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(leftResource);
RelationshipAttribute relationship = _targetedFields.Relationships.Single();
var changeDetector = new ResourceChangeDetector(ResourceType, _dataModelService);
changeDetector.CaptureCurrentValues(leftResource);
object? rightValueEvaluated =
await VisitSetRelationshipAsync(leftResource, relationship, rightValue, WriteOperationKind.SetRelationship, cancellationToken);
relationship.SetValue(leftResource, rightValueEvaluated);
await _resourceDefinitionAccessor.OnWritingAsync(leftResource, WriteOperationKind.SetRelationship, cancellationToken);
changeDetector.CaptureNewValues(leftResource);
changeDetector.AssertIsNotClearingAnyRequiredToOneRelationships(ResourceType.PublicName);
IReadOnlyCollection<CommandDefinition> preSqlCommands =
_dapperFacade.BuildSqlCommandsForOneToOneRelationshipsChangedToNotNull(changeDetector, cancellationToken);
CommandDefinition? updateCommand = _dapperFacade.BuildSqlCommandForUpdate(changeDetector, leftResource.Id, cancellationToken);
IReadOnlyCollection<CommandDefinition> postSqlCommands =
_dapperFacade.BuildSqlCommandsForChangedRelationshipsHavingForeignKeyAtRightSide(changeDetector, leftResource.Id, cancellationToken);
if (preSqlCommands.Any() || updateCommand != null || postSqlCommands.Any())
{
await ExecuteInTransactionAsync(async transaction =>
{
foreach (CommandDefinition sqlCommand in preSqlCommands)
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected > 1)
{
throw new DataStoreUpdateException(new Exception("Multiple rows found."));
}
}
if (updateCommand != null)
{
LogSqlCommand(updateCommand.Value);
int rowsAffected = await transaction.Connection!.ExecuteAsync(updateCommand.Value.Associate(transaction));
if (rowsAffected != 1)
{
throw new DataStoreUpdateException(new Exception("Row does not exist or multiple rows found."));
}
}
foreach (CommandDefinition sqlCommand in postSqlCommands)
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected == 0)
{
throw new DataStoreUpdateException(new Exception("Row does not exist."));
}
}
}, cancellationToken);
await _resourceDefinitionAccessor.OnWriteSucceededAsync(leftResource, WriteOperationKind.SetRelationship, cancellationToken);
}
}
/// <inheritdoc />
public async Task AddToToManyRelationshipAsync(TResource? leftResource, TId leftId, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(rightResourceIds);
var relationship = (HasManyAttribute)_targetedFields.Relationships.Single();
TResource leftPlaceholderResource = leftResource ?? _resourceFactory.CreateInstance<TResource>();
leftPlaceholderResource.Id = leftId;
await _resourceDefinitionAccessor.OnAddToRelationshipAsync(leftPlaceholderResource, relationship, rightResourceIds, cancellationToken);
relationship.SetValue(leftPlaceholderResource, _collectionConverter.CopyToTypedCollection(rightResourceIds, relationship.Property.PropertyType));
await _resourceDefinitionAccessor.OnWritingAsync(leftPlaceholderResource, WriteOperationKind.AddToRelationship, cancellationToken);
if (rightResourceIds.Any())
{
RelationshipForeignKey foreignKey = _dataModelService.GetForeignKey(relationship);
object[] rightResourceIdValues = rightResourceIds.Select(resource => resource.GetTypedId()).ToArray();
CommandDefinition sqlCommand =
_dapperFacade.BuildSqlCommandForAddToToMany(foreignKey, leftPlaceholderResource.Id!, rightResourceIdValues, cancellationToken);
await ExecuteInTransactionAsync(async transaction =>
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected != rightResourceIdValues.Length)
{
throw new DataStoreUpdateException(new Exception("Row does not exist or multiple rows found."));
}
}, cancellationToken);
await _resourceDefinitionAccessor.OnWriteSucceededAsync(leftPlaceholderResource, WriteOperationKind.AddToRelationship, cancellationToken);
}
}
/// <inheritdoc />
public async Task RemoveFromToManyRelationshipAsync(TResource leftResource, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken)
{
ArgumentGuard.NotNull(leftResource);
ArgumentGuard.NotNull(rightResourceIds);
var relationship = (HasManyAttribute)_targetedFields.Relationships.Single();
await _resourceDefinitionAccessor.OnRemoveFromRelationshipAsync(leftResource, relationship, rightResourceIds, cancellationToken);
relationship.SetValue(leftResource, _collectionConverter.CopyToTypedCollection(rightResourceIds, relationship.Property.PropertyType));
await _resourceDefinitionAccessor.OnWritingAsync(leftResource, WriteOperationKind.RemoveFromRelationship, cancellationToken);
if (rightResourceIds.Any())
{
RelationshipForeignKey foreignKey = _dataModelService.GetForeignKey(relationship);
object[] rightResourceIdValues = rightResourceIds.Select(resource => resource.GetTypedId()).ToArray();
CommandDefinition sqlCommand = _dapperFacade.BuildSqlCommandForRemoveFromToMany(foreignKey, rightResourceIdValues, cancellationToken);
await ExecuteInTransactionAsync(async transaction =>
{
LogSqlCommand(sqlCommand);
int rowsAffected = await transaction.Connection!.ExecuteAsync(sqlCommand.Associate(transaction));
if (rowsAffected != rightResourceIdValues.Length)
{
throw new DataStoreUpdateException(new Exception("Row does not exist or multiple rows found."));
}
}, cancellationToken);
await _resourceDefinitionAccessor.OnWriteSucceededAsync(leftResource, WriteOperationKind.RemoveFromRelationship, cancellationToken);
}
}
private void LogSqlCommand(CommandDefinition command)
{
var parameters = (IDictionary<string, object?>?)command.Parameters;
_captureStore.Add(command.CommandText, parameters);
string message = GetLogText(command.CommandText, parameters);
_logger.LogInformation(message);
}
private string GetLogText(string statement, IDictionary<string, object?>? parameters)
{
if (parameters?.Any() == true)
{
string parametersText = string.Join(", ", parameters.Select(parameter => _parameterFormatter.Format(parameter.Key, parameter.Value)));
return $"Executing SQL with parameters: {parametersText}{Environment.NewLine}{statement}";
}
return $"Executing SQL: {Environment.NewLine}{statement}";
}
private async Task<TResult> ExecuteQueryAsync<TResult>(Func<DbConnection, Task<TResult>> asyncAction, CancellationToken cancellationToken)
{
if (_transactionFactory.AmbientTransaction != null)
{
DbConnection connection = _transactionFactory.AmbientTransaction.Current.Connection!;
return await asyncAction(connection);
}
await using DbConnection dbConnection = _dataModelService.CreateConnection();
await dbConnection.OpenAsync(cancellationToken);
return await asyncAction(dbConnection);
}
private async Task ExecuteInTransactionAsync(Func<DbTransaction, Task> asyncAction, CancellationToken cancellationToken)
{
try
{
if (_transactionFactory.AmbientTransaction != null)
{
await asyncAction(_transactionFactory.AmbientTransaction.Current);
}
else
{
await using AmbientTransaction transaction = await _transactionFactory.BeginTransactionAsync(cancellationToken);
await asyncAction(transaction.Current);
await transaction.CommitAsync(cancellationToken);
}
}
catch (DbException exception)
{
throw new DataStoreUpdateException(exception);
}
}
}