-
-
Notifications
You must be signed in to change notification settings - Fork 198
/
Session.cs
1416 lines (1139 loc) · 47.9 KB
/
Session.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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Dapper;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using YesSql.Commands;
using YesSql.Data;
using YesSql.Indexes;
using YesSql.Services;
namespace YesSql
{
public class Session : ISession
{
private DbConnection _connection;
private DbTransaction _transaction;
internal List<IIndexCommand> _commands;
private readonly Dictionary<string, SessionState> _collectionStates;
private readonly SessionState _defaultState;
private Dictionary<string, IEnumerable<IndexDescriptor>> _descriptors;
internal readonly Store _store;
private volatile bool _disposed;
private bool _flushing;
protected bool _cancel;
protected bool _save;
protected List<IIndexProvider> _indexes;
protected string _tablePrefix;
private readonly ISqlDialect _dialect;
private readonly ILogger _logger;
private readonly bool _withTracking;
private readonly bool _enableThreadSafetyChecks;
private int _asyncOperations = 0;
private string _previousStackTrace = null;
public Session(Store store, bool withTracking = true)
{
_store = store;
_tablePrefix = _store.Configuration.TablePrefix;
_dialect = store.Dialect;
_logger = store.Configuration.Logger;
_withTracking = withTracking;
_defaultState = new SessionState();
_enableThreadSafetyChecks = _store.Configuration.EnableThreadSafetyChecks;
_collectionStates = new Dictionary<string, SessionState>()
{
[string.Empty] = _defaultState
};
}
public ISession RegisterIndexes(IIndexProvider[] indexProviders, string collection = null)
{
foreach (var indexProvider in indexProviders)
{
if (indexProvider.CollectionName == null)
{
indexProvider.CollectionName = collection ?? string.Empty;
}
}
_indexes ??= [];
_indexes.AddRange(indexProviders);
return this;
}
private SessionState GetState(string collection)
{
if (string.IsNullOrEmpty(collection))
{
return _defaultState;
}
if (!_collectionStates.TryGetValue(collection, out var state))
{
state = new SessionState();
_collectionStates[collection] = state;
}
return state;
}
public void Save(object entity, bool checkConcurrency = false, string collection = null)
=> SaveAsync(entity, checkConcurrency, collection).GetAwaiter().GetResult();
public async Task SaveAsync(object entity, bool checkConcurrency = false, string collection = null)
{
var state = GetState(collection);
CheckDisposed();
// already being saved or updated or tracked?
if (state.Saved.Contains(entity) || state.Updated.Contains(entity))
{
return;
}
// remove from tracked entities if explicitly saved
state.Tracked.Remove(entity);
// is it a new object?
if (state.IdentityMap.TryGetDocumentId(entity, out var id))
{
state.Updated.Add(entity);
// If this entity needs to be checked for concurrency, track its version
if (checkConcurrency || _store.Configuration.ConcurrentTypes.Contains(entity.GetType()))
{
state.Concurrent.Add(id);
}
return;
}
// Does it have a valid identifier?
var accessor = _store.GetIdAccessor(entity.GetType());
if (accessor != null)
{
id = accessor.Get(entity);
if (id > 0)
{
state.IdentityMap.AddEntity(id, entity);
state.Updated.Add(entity);
// If this entity needs to be checked for concurrency, track its version
if (checkConcurrency || _store.Configuration.ConcurrentTypes.Contains(entity.GetType()))
{
state.Concurrent.Add(id);
}
return;
}
}
// It's a new entity
id = await _store.GetNextIdAsync(collection);
state.IdentityMap.AddEntity(id, entity);
// Then assign a new identifier if it has one
accessor?.Set(entity, id);
state.Saved.Add(entity);
}
public bool Import(object entity, long id = 0, long version = 0, string collection = null)
{
CheckDisposed();
var state = GetState(collection);
// already known?
if (state.IdentityMap.HasEntity(entity))
{
return false;
}
var doc = new Document
{
Type = Store.TypeNames[entity.GetType()],
Content = Store.Configuration.ContentSerializer.Serialize(entity)
};
// Import version
if (version != 0)
{
doc.Version = version;
}
else
{
var versionAccessor = _store.GetVersionAccessor(entity.GetType());
if (versionAccessor != null)
{
doc.Version = versionAccessor.Get(entity);
}
}
if (id != 0)
{
state.IdentityMap.AddEntity(id, entity);
state.Updated.Add(entity);
doc.Id = id;
state.IdentityMap.AddDocument(doc);
return true;
}
else
{
// Does it have a valid identifier?
var accessor = _store.GetIdAccessor(entity.GetType());
if (accessor != null)
{
id = accessor.Get(entity);
if (id > 0)
{
state.IdentityMap.AddEntity(id, entity);
state.Updated.Add(entity);
doc.Id = id;
state.IdentityMap.AddDocument(doc);
return true;
}
throw new InvalidOperationException($"Invalid 'Id' value: {id}");
}
throw new InvalidOperationException("Objects without an 'Id' property can't be imported if no 'id' argument is provided.");
}
}
public void Detach(object entity, string collection)
{
CheckDisposed();
var state = GetState(collection);
DetachInternal(entity, state);
}
public void Detach(IEnumerable<object> entries, string collection)
{
CheckDisposed();
var state = GetState(collection);
foreach (var entry in entries)
{
DetachInternal(entry, state);
}
}
private static void DetachInternal(object entity, SessionState state)
{
state.Saved.Remove(entity);
state.Updated.Remove(entity);
state.Tracked.Remove(entity);
state.Deleted.Remove(entity);
if (state.IdentityMap.TryGetDocumentId(entity, out var id))
{
state.IdentityMap.Remove(id, entity);
}
}
private async Task SaveEntityAsync(object entity, string collection)
{
ArgumentNullException.ThrowIfNull(entity);
if (entity is Document)
{
throw new ArgumentException("A document should not be saved explicitly");
}
if (entity is IIndex)
{
throw new ArgumentException("An index should not be saved explicitly");
}
var state = GetState(collection);
var doc = new Document
{
Type = Store.TypeNames[entity.GetType()]
};
if (!state.IdentityMap.TryGetDocumentId(entity, out var id))
{
throw new InvalidOperationException("The object to save was not found in identity map.");
}
doc.Id = id;
await CreateConnectionAsync();
var versionAccessor = _store.GetVersionAccessor(entity.GetType());
if (versionAccessor != null)
{
doc.Version = versionAccessor.Get(entity);
}
if (doc.Version == 0)
{
doc.Version = 1;
}
versionAccessor?.Set(entity, doc.Version);
doc.Content = Store.Configuration.ContentSerializer.Serialize(entity);
_commands ??= [];
_commands.Add(new CreateDocumentCommand(doc, Store, collection));
state.IdentityMap.AddDocument(doc);
await MapNew(doc, entity, collection);
}
private async Task UpdateEntityAsync(object entity, bool tracked, string collection)
{
ArgumentNullException.ThrowIfNull(entity);
if (entity is Document)
{
throw new ArgumentException("A document should not be saved explicitly");
}
if (entity is IIndex)
{
throw new ArgumentException("An index should not be saved explicitly");
}
var state = GetState(collection);
// Reload to get the old map
if (!state.IdentityMap.TryGetDocumentId(entity, out var id))
{
throw new InvalidOperationException("The object to update was not found in identity map.");
}
if (!state.IdentityMap.TryGetDocument(id, out var oldDoc))
{
oldDoc = await GetDocumentByIdAsync(id, collection);
if (oldDoc == null)
{
throw new InvalidOperationException("Incorrect attempt to update an object that doesn't exist. Ensure a new object was not saved with an identifier value.");
}
}
var newContent = Store.Configuration.ContentSerializer.Serialize(entity);
// if the document has already been updated or saved with this session (auto or intentional flush), ensure it has
// been changed before doing another query
if (tracked && string.Equals(newContent, oldDoc.Content, StringComparison.Ordinal))
{
return;
}
long version = -1;
if (state.Concurrent.Contains(id))
{
version = oldDoc.Version;
var versionAccessor = _store.GetVersionAccessor(entity.GetType());
if (versionAccessor != null)
{
var localVersion = versionAccessor.Get(entity);
// if the version has been set, use it
if (localVersion != 0)
{
version = localVersion;
}
}
oldDoc.Version += 1;
// apply the new version to the object
if (versionAccessor != null)
{
versionAccessor.Set(entity, oldDoc.Version);
newContent = Store.Configuration.ContentSerializer.Serialize(entity);
}
}
var oldObj = Store.Configuration.ContentSerializer.Deserialize(oldDoc.Content, entity.GetType());
// Update map index
await MapDeleted(oldDoc, oldObj, collection);
await MapNew(oldDoc, entity, collection);
await CreateConnectionAsync();
oldDoc.Content = newContent;
_commands ??= [];
_commands.Add(new UpdateDocumentCommand(oldDoc, Store, version, collection));
}
private async Task<Document> GetDocumentByIdAsync(long id, string collection)
{
await CreateConnectionAsync();
var documentTable = Store.Configuration.TableNameConvention.GetDocumentTable(collection);
var command = "select * from " + _dialect.QuoteForTableName(_tablePrefix + documentTable, Store.Configuration.Schema) + " where " + _dialect.QuoteForColumnName("Id") + " = @Id";
var key = new WorkerQueryKey(nameof(GetDocumentByIdAsync), id);
try
{
var result = await _store.ProduceAsync(key, (key, state) =>
{
var logger = state.Store.Configuration.Logger;
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace(state.Command);
}
return state.Connection.QueryAsync<Document>(state.Command, state.Parameters, state.Transaction);
},
new { Store = _store, Connection = _connection, Transaction = _transaction, Command = command, Parameters = new { Id = id } });
// Clone documents returned from ProduceAsync as they might be shared across sessions
return result.FirstOrDefault()?.Clone();
}
catch
{
await CancelAsync();
throw;
}
}
public void Delete(object obj, string collection = null)
{
CheckDisposed();
var state = GetState(collection);
state.Deleted.Add(obj);
}
private async Task DeleteEntityAsync(object obj, string collection)
{
ArgumentNullException.ThrowIfNull(obj);
if (obj is IIndex)
{
throw new ArgumentException("Can't call DeleteEntity on an Index");
}
var state = GetState(collection);
if (!state.IdentityMap.TryGetDocumentId(obj, out var id))
{
var accessor = _store.GetIdAccessor(obj.GetType())
?? throw new InvalidOperationException("Could not delete object as it doesn't have an Id property");
id = accessor.Get(obj);
}
var doc = await GetDocumentByIdAsync(id, collection);
if (doc != null)
{
// Untrack the deleted object
state.IdentityMap.Remove(id, obj);
// Update impacted indexes
await MapDeleted(doc, obj, collection);
_commands ??= [];
// The command needs to come after any index deletion because of the database constraints
_commands.Add(new DeleteDocumentCommand(doc, Store, collection));
}
}
public async Task<IEnumerable<T>> GetAsync<T>(long[] ids, string collection = null) where T : class
{
if (ids?.Length == 0)
{
return Enumerable.Empty<T>();
}
CheckDisposed();
// Auto-flush
await FlushAsync();
await CreateConnectionAsync();
var documentTable = Store.Configuration.TableNameConvention.GetDocumentTable(collection);
var command = "select * from " + _dialect.QuoteForTableName(_tablePrefix + documentTable, _store.Configuration.Schema) + " where " + _dialect.QuoteForColumnName("Id") + " " + _dialect.InOperator("@Ids");
var key = new WorkerQueryKey(nameof(GetAsync), ids);
try
{
var documents = await _store.ProduceAsync(key, static (key, state) =>
{
var logger = state.Store.Configuration.Logger;
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace(state.Command);
}
return state.Connection.QueryAsync<Document>(state.Command, state.Parameters, state.Transaction);
},
new { Store = _store, Connection = _connection, Transaction = _transaction, Command = command, Parameters = new { Ids = ids } });
// Clone documents returned from ProduceAsync as they might be shared across sessions
var sortedDocuments = documents.Select(x => x.Clone())
.OrderBy(d => Array.IndexOf(ids, d.Id))
.ToList();
return Get<T>(sortedDocuments, collection);
}
catch
{
await CancelAsync();
throw;
}
}
public IEnumerable<T> Get<T>(IList<Document> documents, string collection) where T : class
{
if (documents?.Count == 0)
{
return Enumerable.Empty<T>();
}
var result = new List<T>();
var defaultAccessor = _store.GetIdAccessor(typeof(T));
var typeName = Store.TypeNames[typeof(T)];
var state = GetState(collection);
// Are all the objects already in cache?
foreach (var d in documents)
{
if (_withTracking && state.IdentityMap.TryGetEntityById(d.Id, out var entity))
{
result.Add((T)entity);
}
else
{
T item;
IAccessor<long> accessor;
// If the document type doesn't match the requested one, check it's a base type
if (!string.Equals(typeName, d.Type, StringComparison.Ordinal))
{
var itemType = Store.TypeNames[d.Type];
// Ignore the document if it can't be casted to the requested type
if (!typeof(T).IsAssignableFrom(itemType))
{
continue;
}
accessor = _store.GetIdAccessor(itemType);
item = (T)Store.Configuration.ContentSerializer.Deserialize(d.Content, itemType);
}
else
{
item = (T)Store.Configuration.ContentSerializer.Deserialize(d.Content, typeof(T));
accessor = defaultAccessor;
}
accessor?.Set(item, d.Id);
if (_withTracking)
{
// track the loaded object.
state.IdentityMap.AddEntity(d.Id, item);
state.IdentityMap.AddDocument(d);
}
result.Add(item);
}
}
return result;
}
public IQuery Query(string collection = null)
{
return new DefaultQuery(this, _tablePrefix, collection);
}
public IQuery<T> ExecuteQuery<T>(ICompiledQuery<T> compiledQuery, string collection = null) where T : class
{
ArgumentNullException.ThrowIfNull(compiledQuery);
var compiledQueryType = compiledQuery.GetType();
var discriminator = NullableThumbprintFactory.GetNullableThumbprint(compiledQuery);
var queryState = _store.CompiledQueries.GetOrAdd(discriminator, discriminator =>
{
var localQuery = ((IQuery)new DefaultQuery(this, _tablePrefix, collection)).For<T>(false);
var defaultQuery = (DefaultQuery.Query<T>)compiledQuery.Query().Compile().Invoke(localQuery);
return defaultQuery._query._queryState;
})
.Clone();
IQuery newQuery = new DefaultQuery(this, queryState, compiledQuery);
return newQuery.For<T>(false);
}
private void CheckDisposed()
{
#pragma warning disable CA1513 // Use ObjectDisposedException throw helper
if (_disposed)
{
throw new ObjectDisposedException(nameof(Session));
}
#pragma warning restore CA1513 // Use ObjectDisposedException throw helper
}
~Session()
{
// Ensure the session gets disposed if the user cannot wrap the session in a using block.
// For instance in OrchardCore the session is disposed from a middleware, so if an exception
// is thrown in a middleware, it might not get triggered.
Dispose(false);
}
public void Dispose(bool disposing)
{
// Do nothing if Dispose() was already called
if (!_disposed)
{
try
{
CommitOrRollbackTransactionAsync().GetAwaiter().GetResult();
}
catch
{
_connection = null;
_transaction = null;
}
}
_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public Task FlushAsync()
{
return FlushInternalAsync(false);
}
private async Task FlushInternalAsync(bool saving)
{
if (!HasWork())
{
return;
}
// prevent recursive calls in FlushAsync,
// when auto-flush is triggered from an IndexProvider
// for instance.
if (_flushing)
{
return;
}
_flushing = true;
// we only check if the session is disposed if
// there are no commands to commit.
CheckDisposed();
// Only check thread-safety if not called from SaveChangesAsync
if (!saving)
{
EnterAsyncExecution();
}
try
{
// saving all tracked entities
foreach (var collectionState in _collectionStates)
{
var state = collectionState.Value;
var collection = collectionState.Key;
foreach (var obj in state.Tracked)
{
if (!state.Deleted.Contains(obj))
{
await UpdateEntityAsync(obj, true, collection);
}
}
// saving all updated entities
foreach (var obj in state.Updated)
{
if (!state.Deleted.Contains(obj))
{
await UpdateEntityAsync(obj, false, collection);
}
}
// saving all pending entities
foreach (var obj in state.Saved)
{
await SaveEntityAsync(obj, collection);
}
// deleting all pending entities
foreach (var obj in state.Deleted)
{
await DeleteEntityAsync(obj, collection);
}
}
// compute all reduce indexes
await ReduceAsync();
await BeginTransactionAsync();
BatchCommands();
if (_commands != null)
{
foreach (var command in _commands)
{
await command.ExecuteAsync(_connection, _transaction, _dialect, _logger);
}
}
}
catch
{
await CancelAsync();
throw;
}
finally
{
foreach (var state in _collectionStates.Values)
{
// Track all saved and updated entities in case they are modified before
// CommitAsync is called
foreach (var saved in state.Saved)
{
state.Tracked.Add(saved);
}
foreach (var updated in state.Updated)
{
state.Tracked.Add(updated);
}
state.Saved.Clear();
state.Updated.Clear();
state.Deleted.Clear();
state.Maps.Clear();
}
_commands?.Clear();
_flushing = false;
// Only check thread-safety if not called from SaveChangesAsync
if (!saving)
{
ExitAsyncExecution();
}
}
}
private void BatchCommands()
{
if (_commands?.Count == 0)
{
return;
}
if (!_dialect.SupportsBatching || _store.Configuration.CommandsPageSize == 0)
{
return;
}
var batches = new List<IIndexCommand>();
// holds the queries, parameters and actions returned by an IIndexCommand, until we know we can
// add it to a batch if it fits the limits (page size and parameters boundaries)
var localDbCommand = _connection.CreateCommand();
var localQueries = new List<string>();
var localActions = new List<Action<DbDataReader>>();
var batch = new BatchCommand(_connection.CreateCommand());
var index = 0;
foreach (var command in _commands.OrderBy(x => x.ExecutionOrder))
{
index++;
// Can the command be batched
if (command.AddToBatch(_dialect, localQueries, localDbCommand, localActions, index))
{
// Does it go over the page or parameters limits
var tooManyQueries = batch.Queries.Count + localQueries.Count > _store.Configuration.CommandsPageSize;
var tooManyCommands = batch.Command.Parameters.Count + localDbCommand.Parameters.Count > _store.Configuration.SqlDialect.MaxParametersPerCommand;
if (tooManyQueries || tooManyCommands)
{
batches.Add(batch);
// Then start a new batch
batch = new BatchCommand(_connection.CreateCommand());
}
// We can add the queries to the current batch
batch.Queries.AddRange(localQueries);
batch.Actions.AddRange(localActions);
for (var i = localDbCommand.Parameters.Count - 1; i >= 0; i--)
{
// npgsql will prevent a parameter from being added to a collection
// if it's already in another one
var parameter = localDbCommand.Parameters[i];
localDbCommand.Parameters.RemoveAt(i);
batch.Command.Parameters.Add(parameter);
}
}
else
{
// The command can't be added to a batch, we leave it in the list of commands to execute individually
// Finalize the current batch
if (batch.Queries.Count > 0)
{
batches.Add(batch);
// Then start a new batch
batch = new BatchCommand(_connection.CreateCommand());
}
batches.Add(command);
}
localQueries.Clear();
localDbCommand.Parameters.Clear();
localActions.Clear();
}
// If the ongoing batch is not empty, add it
if (batch.Queries.Count > 0)
{
batches.Add(batch);
}
_commands.Clear();
_commands.AddRange(batches);
}
public void EnterAsyncExecution()
{
if (!_enableThreadSafetyChecks)
{
return;
}
if (Interlocked.Increment(ref _asyncOperations) > 1)
{
throw new InvalidOperationException($"Two concurrent threads have been detected accessing the same ISession instance from: \n{Environment.StackTrace}\nand:\n{_previousStackTrace}\n---");
}
_previousStackTrace = Environment.StackTrace;
}
public void ExitAsyncExecution()
{
if (!_enableThreadSafetyChecks)
{
return;
}
Interlocked.Decrement(ref _asyncOperations);
}
public async Task SaveChangesAsync()
{
EnterAsyncExecution();
try
{
if (!_cancel)
{
await FlushInternalAsync(true);
_save = true;
}
}
finally
{
await CommitOrRollbackTransactionAsync();
ExitAsyncExecution();
}
}
public async ValueTask DisposeAsync()
{
// Do nothing if Dispose() was already called
if (_disposed)
{
return;
}
_disposed = true;
try
{
await CommitOrRollbackTransactionAsync();
}
catch
{
_transaction = null;
_connection = null;
}
GC.SuppressFinalize(this);
}
private async Task CommitOrRollbackTransactionAsync()
{
try
{
if (_transaction != null)
{
if (_cancel || !_save)
{
await _transaction.RollbackAsync();
return;
}
await _transaction.CommitAsync();
}
}
finally
{
await ReleaseConnectionAsync();
}
}
/// <summary>
/// Clears all the resources associated to the transaction.
/// </summary>
private async Task ReleaseTransactionAsync()
{
foreach (var state in _collectionStates.Values)
{
// IdentityMap is cleared in ReleaseSession()
state._concurrent?.Clear();
state._saved?.Clear();
state._updated?.Clear();
state._tracked?.Clear();
state._deleted?.Clear();
state._maps?.Clear();
}
_commands?.Clear();
_commands = null;
if (_transaction != null)
{
await _transaction.DisposeAsync();
_transaction = null;
}
}
private async Task ReleaseConnectionAsync()
{
await ReleaseTransactionAsync();
if (_connection != null)
{
await _connection.CloseAsync();
await _connection.DisposeAsync();
_connection = null;
}
}
/// <summary>
/// Clears all the resources associated to the transaction.
/// </summary>
private void ReleaseTransaction()