forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathActionQueue.cs
789 lines (690 loc) · 22.3 KB
/
ActionQueue.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NHibernate.Action;
using NHibernate.Cache;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Engine
{
/// <summary>
/// Responsible for maintaining the queue of actions related to events.
/// <para>
/// The ActionQueue holds the DML operations queued as part of a session's
/// transactional-write-behind semantics. DML operations are queued here
/// until a flush forces them to be executed against the database.
/// </para>
/// </summary>
[Serializable]
public partial class ActionQueue
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(ActionQueue));
private const int InitQueueListSize = 5;
private ISessionImplementor session;
// Object insertions, updates, and deletions have list semantics because
// they must happen in the right order so as to respect referential
// integrity
private readonly List<AbstractEntityInsertAction> insertions;
private readonly List<EntityDeleteAction> deletions;
private readonly List<EntityUpdateAction> updates;
// Actually the semantics of the next three are really "Bag"
// Note that, unlike objects, collection insertions, updates,
// deletions are not really remembered between flushes. We
// just re-use the same Lists for convenience.
private readonly List<CollectionRecreateAction> collectionCreations;
private readonly List<CollectionUpdateAction> collectionUpdates;
private readonly List<CollectionRemoveAction> collectionRemovals;
private readonly AfterTransactionCompletionProcessQueue afterTransactionProcesses;
private readonly BeforeTransactionCompletionProcessQueue beforeTransactionProcesses;
private readonly HashSet<string> executedSpaces;
public ActionQueue(ISessionImplementor session)
{
this.session = session;
insertions = new List<AbstractEntityInsertAction>(InitQueueListSize);
deletions = new List<EntityDeleteAction>(InitQueueListSize);
updates = new List<EntityUpdateAction>(InitQueueListSize);
collectionCreations = new List<CollectionRecreateAction>(InitQueueListSize);
collectionUpdates = new List<CollectionUpdateAction>(InitQueueListSize);
collectionRemovals = new List<CollectionRemoveAction>(InitQueueListSize);
afterTransactionProcesses = new AfterTransactionCompletionProcessQueue();
beforeTransactionProcesses = new BeforeTransactionCompletionProcessQueue();
executedSpaces = new HashSet<string>();
}
public virtual void Clear()
{
updates.Clear();
insertions.Clear();
deletions.Clear();
collectionCreations.Clear();
collectionRemovals.Clear();
collectionUpdates.Clear();
}
public void AddAction(EntityInsertAction action)
{
insertions.Add(action);
}
public void AddAction(EntityDeleteAction action)
{
deletions.Add(action);
}
public void AddAction(EntityUpdateAction action)
{
updates.Add(action);
}
public void AddAction(CollectionRecreateAction action)
{
collectionCreations.Add(action);
}
public void AddAction(CollectionRemoveAction action)
{
collectionRemovals.Add(action);
}
public void AddAction(CollectionUpdateAction action)
{
collectionUpdates.Add(action);
}
public void AddAction(EntityIdentityInsertAction insert)
{
insertions.Add(insert);
}
public void AddAction(BulkOperationCleanupAction cleanupAction)
{
RegisterCleanupActions(cleanupAction);
}
//Since v5.1
[Obsolete("This method is no longer executed asynchronously and will be removed in a next major version.")]
public Task AddActionAsync(BulkOperationCleanupAction cleanupAction, CancellationToken cancellationToken=default(CancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
try
{
AddAction(cleanupAction);
return Task.CompletedTask;
}
catch (Exception e)
{
return Task.FromException(e);
}
}
public void RegisterProcess(IBeforeTransactionCompletionProcess process)
{
beforeTransactionProcesses.Register(process);
}
public void RegisterProcess(IAfterTransactionCompletionProcess process)
{
afterTransactionProcesses.Register(process);
}
//Since v5.2
[Obsolete("This method is not used and will be removed in a future version.")]
public void RegisterProcess(BeforeTransactionCompletionProcessDelegate process)
{
RegisterProcess(new BeforeTransactionCompletionDelegatedProcess(process));
}
//Since v5.2
[Obsolete("This method is not used and will be removed in a future version.")]
public void RegisterProcess(AfterTransactionCompletionProcessDelegate process)
{
RegisterProcess(new AfterTransactionCompletionDelegatedProcess(process));
}
private void ExecuteActions<T>(List<T> list) where T: IExecutable
{
// Actions may raise events to which user code can react and cause changes to action list.
// It will then fail here due to list being modified. (Some previous code was dodging the
// trouble with a for loop which was not failing provided the list was not getting smaller.
// But then it was clearing it without having executed added actions (if any), ...)
foreach (var executable in list)
{
InnerExecute(executable);
}
list.Clear();
session.Batcher.ExecuteBatch();
}
private void PreInvalidateCaches()
{
if (session.Factory.Settings.IsQueryCacheEnabled && executedSpaces.Count > 0)
{
session.Factory.UpdateTimestampsCache.PreInvalidate(executedSpaces);
}
}
public void Execute(IExecutable executable)
{
try
{
InnerExecute(executable);
}
finally
{
PreInvalidateCaches();
}
}
private void InnerExecute(IExecutable executable)
{
try
{
executable.Execute();
}
finally
{
RegisterCleanupActions(executable);
}
}
private void RegisterCleanupActions(IExecutable executable)
{
if (executable is IAsyncExecutable asyncExecutable)
{
RegisterProcess(asyncExecutable.BeforeTransactionCompletionProcess);
RegisterProcess(asyncExecutable.AfterTransactionCompletionProcess);
}
else
{
#pragma warning disable 618,619
RegisterProcess(executable.BeforeTransactionCompletionProcess);
RegisterProcess(executable.AfterTransactionCompletionProcess);
#pragma warning restore 618,619
}
if (executable.PropertySpaces != null)
{
executedSpaces.UnionWith(executable.PropertySpaces);
}
}
/// <summary>
/// Perform all currently queued entity-insertion actions.
/// </summary>
public void ExecuteInserts()
{
try
{
ExecuteActions(insertions);
}
finally
{
PreInvalidateCaches();
}
}
/// <summary>
/// Perform all currently queued actions.
/// </summary>
public void ExecuteActions()
{
try
{
ExecuteActions(insertions);
ExecuteActions(updates);
ExecuteActions(collectionRemovals);
ExecuteActions(collectionUpdates);
ExecuteActions(collectionCreations);
ExecuteActions(deletions);
}
finally
{
PreInvalidateCaches();
}
}
private static void PrepareActions<T>(List<T> queue) where T: IExecutable
{
foreach (var executable in queue)
executable.BeforeExecutions();
}
/// <summary>
/// Prepares the internal action queues for execution.
/// </summary>
public void PrepareActions()
{
PrepareActions(collectionRemovals);
PrepareActions(collectionUpdates);
PrepareActions(collectionCreations);
}
/// <summary>
/// Execute any registered <see cref="IBeforeTransactionCompletionProcess" />
/// </summary>
public void BeforeTransactionCompletion()
{
beforeTransactionProcesses.BeforeTransactionCompletion();
}
/// <summary>
/// Performs cleanup of any held cache softlocks.
/// </summary>
/// <param name="success">Was the transaction successful.</param>
public void AfterTransactionCompletion(bool success)
{
afterTransactionProcesses.AfterTransactionCompletion(success);
InvalidateCaches();
}
private void InvalidateCaches()
{
if (session.Factory.Settings.IsQueryCacheEnabled && executedSpaces.Count > 0)
{
session.Factory.UpdateTimestampsCache.Invalidate(executedSpaces);
}
executedSpaces.Clear();
}
/// <summary>
/// Check whether the given tables/query-spaces are to be executed against
/// given the currently queued actions.
/// </summary>
/// <param name="tables">The table/query-spaces to check. </param>
/// <returns> True if we contain pending actions against any of the given tables; false otherwise.</returns>
public virtual bool AreTablesToBeUpdated(ISet<string> tables)
{
return
AreTablesToUpdated(updates, tables)
|| AreTablesToUpdated(insertions, tables)
|| AreTablesToUpdated(deletions, tables)
|| AreTablesToUpdated(collectionUpdates, tables)
|| AreTablesToUpdated(collectionCreations, tables)
|| AreTablesToUpdated(collectionRemovals, tables);
}
/// <summary>
/// Check whether any insertion or deletion actions are currently queued.
/// </summary>
/// <returns> True if insertions or deletions are currently queued; false otherwise.</returns>
public bool AreInsertionsOrDeletionsQueued
{
get { return (insertions.Count > 0 || deletions.Count > 0); }
}
private static bool AreTablesToUpdated<T>(List<T> executables, ISet<string> tablespaces) where T: IExecutable
{
foreach (var exec in executables)
{
var spaces = exec.PropertySpaces;
foreach (string o in spaces)
{
if(tablespaces.Contains(o))
{
if(log.IsDebugEnabled())
log.Debug("changes must be flushed to space: {0}", o);
return true;
}
}
}
return false;
}
public int CollectionRemovalsCount
{
get { return collectionRemovals.Count; }
}
public int CollectionUpdatesCount
{
get { return collectionUpdates.Count; }
}
public int CollectionCreationsCount
{
get { return collectionCreations.Count; }
}
public int DeletionsCount
{
get { return deletions.Count; }
}
public int UpdatesCount
{
get { return updates.Count; }
}
public int InsertionsCount
{
get { return insertions.Count; }
}
public void SortCollectionActions()
{
if (session.Factory.Settings.IsOrderUpdatesEnabled)
{
//sort the updates by fk
collectionCreations.Sort();
collectionUpdates.Sort();
collectionRemovals.Sort();
}
}
public void SortActions()
{
if (session.Factory.Settings.IsOrderUpdatesEnabled)
{
//sort the updates by pk
updates.Sort();
}
if (session.Factory.Settings.IsOrderInsertsEnabled)
{
SortInsertActions();
}
}
//Order the {@link #insertions} queue such that we group inserts
//against the same entity together (without violating constraints). The
//original order is generated by cascade order, which in turn is based on
//the directionality of foreign-keys. So even though we will be changing
//the ordering here, we need to make absolutely certain that we do not
//circumvent this FK ordering to the extent of causing constraint
//violations
private void SortInsertActions()
{
new InsertActionSorter(this).Sort();
}
public IList<EntityDeleteAction> CloneDeletions()
{
return new List<EntityDeleteAction>(deletions);
}
public void ClearFromFlushNeededCheck(int previousCollectionRemovalSize)
{
collectionCreations.Clear();
collectionUpdates.Clear();
updates.Clear();
// collection deletions are a special case since update() can add
// deletions of collections not loaded by the session.
for (int i = collectionRemovals.Count - 1; i >= previousCollectionRemovalSize; i--)
{
collectionRemovals.RemoveAt(i);
}
}
public bool HasBeforeTransactionActions()
{
return beforeTransactionProcesses.HasActions;
}
public bool HasAfterTransactionActions()
{
return afterTransactionProcesses.HasActions;
}
public bool HasAnyQueuedActions
{
get
{
return
updates.Count > 0
|| insertions.Count > 0
|| deletions.Count > 0
|| collectionUpdates.Count > 0
|| collectionRemovals.Count > 0
|| collectionCreations.Count > 0;
}
}
public override string ToString()
{
// todo-events : use the helper for the collections
return new StringBuilder()
.Append("ActionQueue[insertions=")
.Append(insertions)
.Append(" updates=")
.Append(updates)
.Append(" deletions=")
.Append(deletions)
.Append(" collectionCreations=")
.Append(collectionCreations)
.Append(" collectionRemovals=")
.Append(collectionRemovals)
.Append(" collectionUpdates=")
.Append(collectionUpdates)
.Append("]").ToString();
}
[Serializable]
private partial class BeforeTransactionCompletionProcessQueue
{
private List<IBeforeTransactionCompletionProcess> processes = new List<IBeforeTransactionCompletionProcess>();
public bool HasActions
{
get { return processes.Count > 0; }
}
public void Register(IBeforeTransactionCompletionProcess process)
{
if (process == null)
{
return;
}
processes.Add(process);
}
public void BeforeTransactionCompletion()
{
int size = processes.Count;
for (int i = 0; i < size; i++)
{
try
{
var process = processes[i];
process.ExecuteBeforeTransactionCompletion();
}
catch (HibernateException)
{
throw;
}
catch (Exception e)
{
throw new AssertionFailure("Unable to perform BeforeTransactionCompletion callback", e);
}
}
processes.Clear();
}
}
[Serializable]
private partial class AfterTransactionCompletionProcessQueue
{
private List<IAfterTransactionCompletionProcess> processes = new List<IAfterTransactionCompletionProcess>(InitQueueListSize * 3);
public bool HasActions
{
get { return processes.Count > 0; }
}
public void Register(IAfterTransactionCompletionProcess process)
{
if (process == null)
{
return;
}
processes.Add(process);
}
public void AfterTransactionCompletion(bool success)
{
int size = processes.Count;
for (int i = 0; i < size; i++)
{
try
{
var process = processes[i];
process.ExecuteAfterTransactionCompletion(success);
}
catch (CacheException e)
{
log.Error(e, "could not release a cache lock");
// continue loop
}
catch (Exception e)
{
throw new AssertionFailure("Unable to perform AfterTransactionCompletion callback", e);
}
}
processes.Clear();
}
}
//6.0 TODO: Remove
[Obsolete]
private partial class BeforeTransactionCompletionDelegatedProcess : IBeforeTransactionCompletionProcess
{
private readonly BeforeTransactionCompletionProcessDelegate _delegate;
public BeforeTransactionCompletionDelegatedProcess(BeforeTransactionCompletionProcessDelegate @delegate)
{
_delegate = @delegate;
}
public void ExecuteBeforeTransactionCompletion()
{
_delegate?.Invoke();
}
}
//6.0 TODO: Remove
[Obsolete]
private partial class AfterTransactionCompletionDelegatedProcess : IAfterTransactionCompletionProcess
{
private readonly AfterTransactionCompletionProcessDelegate _delegate;
public AfterTransactionCompletionDelegatedProcess(AfterTransactionCompletionProcessDelegate @delegate)
{
_delegate = @delegate;
}
public void ExecuteAfterTransactionCompletion(bool success)
{
_delegate?.Invoke(success);
}
}
[Serializable]
private class InsertActionSorter
{
private readonly ActionQueue _actionQueue;
// The map of entity names to their latest batch.
private readonly Dictionary<string, int> _latestBatches = new Dictionary<string, int>();
// The map of entities to their batch.
private readonly Dictionary<object, int> _entityBatchNumber;
// The map of entities to the latest batch (of another entities) they depend on.
private readonly Dictionary<object, int> _entityBatchDependency = new Dictionary<object, int>(ReferenceComparer<object>.Instance);
// the map of batch numbers to EntityInsertAction lists
private readonly Dictionary<int, List<AbstractEntityInsertAction>> _actionBatches = new Dictionary<int, List<AbstractEntityInsertAction>>();
/// <summary>
/// A sorter aiming to group inserts as much as possible for optimizing batching.
/// </summary>
/// <param name="actionQueue">The list of inserts to optimize, already sorted in order to avoid constraint violations.</param>
public InsertActionSorter(ActionQueue actionQueue)
{
_actionQueue = actionQueue;
//optimize the hash size to eliminate a rehash.
_entityBatchNumber = new Dictionary<object, int>(actionQueue.insertions.Count + 1, ReferenceComparer<object>.Instance);
}
// This sorting does not actually optimize some features like mapped inheritance or joined-table,
// which causes additional inserts per action, causing the batcher to flush on each. Moreover,
// inheritance may causes children entities batches to get split per concrete parent classes.
// (See InsertOrderingFixture.WithJoinedTableInheritance by example.)
// Trying to merge those children batches cases would probably require to much computing.
public void Sort()
{
// build the map of entity names that indicate the batch number
foreach (var action in _actionQueue.insertions)
{
var entityName = action.EntityName;
// the entity associated with the current action.
var currentEntity = action.Instance;
var batchNumber = GetBatchNumber(action, entityName);
_entityBatchNumber[currentEntity] = batchNumber;
AddToBatch(batchNumber, action);
UpdateChildrenDependencies(batchNumber, action);
}
_actionQueue.insertions.Clear();
// now rebuild the insertions list. There is a batch for each entry in the name list.
for (var i = 0; i < _actionBatches.Count; i++)
{
var batch = _actionBatches[i];
foreach (var action in batch)
{
_actionQueue.insertions.Add(action);
}
}
}
private int GetBatchNumber(AbstractEntityInsertAction action, string entityName)
{
int batchNumber;
if (_latestBatches.TryGetValue(entityName, out batchNumber))
{
// There is already an existing batch for this type of entity.
// Check to see if the latest batch is acceptable.
if (!RequireNewBatch(action, batchNumber))
return batchNumber;
}
// add an entry for this type of entity.
// we can be assured that all referenced entities have already
// been processed,
// so specify that this entity is with the latest batch.
// doing the batch number before adding the name to the list is
// a faster way to get an accurate number.
batchNumber = _actionBatches.Count;
_latestBatches[entityName] = batchNumber;
return batchNumber;
}
private bool RequireNewBatch(AbstractEntityInsertAction action, int latestBatchNumberForType)
{
// This method assumes the original action list is already sorted in order to respect dependencies.
var propertyValues = action.State;
var propertyTypes = action.Persister.EntityMetamodel?.PropertyTypes;
if (propertyTypes == null)
{
log.Info(
"Entity {0} persister does not provide meta-data, giving up batching grouping optimization for this entity.",
action.EntityName);
// Cancel grouping optimization for this entity.
return true;
}
int latestDependency;
if (_entityBatchDependency.TryGetValue(action.Instance, out latestDependency) && latestDependency > latestBatchNumberForType)
return true;
for (var i = 0; i < propertyValues.Length; i++)
{
var value = propertyValues[i];
var type = propertyTypes[i];
if (type.IsEntityType && value != null &&
// If the value is not initialized, it is a proxy with pending load from database,
// so it can only be an already persisted entity. It can not have its own pending
// insertion batch. So there is no need to seek for it, and it avoids initializing
// it by searching it in a dictionary. Fixes #1338.
NHibernateUtil.IsInitialized(value))
{
// find the batch number associated with the current association, if any.
int associationBatchNumber;
if (_entityBatchNumber.TryGetValue(value, out associationBatchNumber) &&
associationBatchNumber > latestBatchNumberForType)
{
return true;
}
}
}
return false;
}
private void AddToBatch(int batchNumber, AbstractEntityInsertAction action)
{
List<AbstractEntityInsertAction> actions;
if (!_actionBatches.TryGetValue(batchNumber, out actions))
{
actions = new List<AbstractEntityInsertAction>();
_actionBatches[batchNumber] = actions;
}
actions.Add(action);
}
private void UpdateChildrenDependencies(int batchNumber, AbstractEntityInsertAction action)
{
var propertyValues = action.State;
var propertyTypes = action.Persister.EntityMetamodel?.PropertyTypes;
if (propertyTypes == null)
{
log.Warn(
"Entity {0} persister does not provide meta-data: if there is dependent entities providing " +
"meta-data, they may get batched before this one and cause a failure.",
action.EntityName);
return;
}
var sessionFactory = action.Session.Factory;
for (var i = 0; i < propertyValues.Length; i++)
{
var type = propertyTypes[i];
if (!type.IsCollectionType)
continue;
var collectionType = (CollectionType)type;
var collectionPersister = sessionFactory.GetCollectionPersister(collectionType.Role);
if (collectionPersister.IsManyToMany || !collectionPersister.ElementType.IsEntityType)
continue;
var children = propertyValues[i] as IEnumerable;
if (children == null)
continue;
foreach(var child in children)
{
if (child == null ||
// If the child is not initialized, it is a proxy with pending load from database,
// so it can only be an already persisted entity. It can not have its own pending
// insertion batch. So we do not need to keep track of the highest other batch on
// which it depends. And this avoids initializing the proxy by searching it into
// a dictionary.
!NHibernateUtil.IsInitialized(child))
{
continue;
}
int latestDependency;
if (_entityBatchDependency.TryGetValue(child, out latestDependency) && latestDependency > batchNumber)
continue;
_entityBatchDependency[child] = batchNumber;
}
}
}
}
}
}