forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractPersistentCollection.cs
1358 lines (1196 loc) · 39.9 KB
/
AbstractPersistentCollection.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 System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NHibernate.Collection.Generic;
using NHibernate.Collection.Trackers;
using NHibernate.Engine;
using NHibernate.Impl;
using NHibernate.Loader;
using NHibernate.Persister.Collection;
using NHibernate.Proxy;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Collection
{
/// <summary>
/// Base class for implementing <see cref="IPersistentCollection"/>.
/// </summary>
// 6.0 TODO: remove ILazyInitializedCollection once IPersistentCollection derives from it
[Serializable]
public abstract partial class AbstractPersistentCollection : IPersistentCollection, ILazyInitializedCollection
{
// Since v5.3
[Obsolete("This field has no more usages in NHibernate and will be removed in a future version.")]
protected internal static readonly object Unknown = new object(); //place holder
// Since v5.3
[Obsolete("This field has no more usages in NHibernate and will be removed in a future version.")]
protected internal static readonly object NotFound = new object(); //place holder
// Since v5.3
[Obsolete("This class has no more usages in NHibernate and will be removed in a future version.")]
protected interface IDelayedOperation
{
object AddedInstance { get; }
object Orphan { get; }
void Operate();
}
class TypeComparer : IEqualityComparer<object>
{
private readonly IType _type;
private readonly ISessionFactoryImplementor _sessionFactory;
public TypeComparer(IType type, ISessionFactoryImplementor sessionFactory)
{
_type = type;
_sessionFactory = sessionFactory;
}
public new bool Equals(object x, object y)
{
return _type.IsEqual(x, y, _sessionFactory);
}
public int GetHashCode(object obj)
{
return _type.GetHashCode(obj, _sessionFactory);
}
}
// 6.0 TODO: Remove
private class AdditionEnumerable : IEnumerable
{
private readonly AbstractPersistentCollection enclosingInstance;
public AdditionEnumerable(AbstractPersistentCollection enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
public IEnumerator GetEnumerator()
{
return new AdditionEnumerator(enclosingInstance);
}
private class AdditionEnumerator : IEnumerator
{
private readonly AbstractPersistentCollection enclosingInstance;
private int position = -1;
public AdditionEnumerator(AbstractPersistentCollection enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
public object Current
{
get
{
try
{
return enclosingInstance.operationQueue[position].AddedInstance;
}
catch (IndexOutOfRangeException ex)
{
throw new InvalidOperationException(
"MoveNext as not been called or its last call has yielded false (meaning the enumerator is beyond the end of the enumeration).",
ex);
}
}
}
public bool MoveNext()
{
position++;
return (position < enclosingInstance.operationQueue.Count);
}
public void Reset()
{
position = -1;
}
}
}
[NonSerialized] private ISessionImplementor session;
private bool initialized;
#pragma warning disable 618
[NonSerialized] private List<IDelayedOperation> operationQueue; // 6.0 TODO: Remove
#pragma warning restore 618
[NonSerialized] private bool directlyAccessible;
[NonSerialized] private bool initializing;
[NonSerialized] private AbstractQueueOperationTracker _queueOperationTracker;
private object owner;
private int cachedSize = -1;
private string role;
private object key;
// collections detect changes made via their public interface and mark
// themselves as dirty as a performance optimization
private bool dirty;
private object storedSnapshot;
/// <summary>
/// Not called by Hibernate, but used by non-NET serialization, eg. SOAP libraries.
/// </summary>
protected AbstractPersistentCollection() {}
protected AbstractPersistentCollection(ISessionImplementor session)
{
this.session = session;
}
public string Role
{
get { return role; }
}
public object Key
{
get { return key; }
}
public bool IsUnreferenced
{
get { return role == null; }
}
public bool IsDirty
{
get { return dirty; }
}
public object StoredSnapshot
{
get { return storedSnapshot; }
}
protected int CachedSize
{
get { return cachedSize; }
set { cachedSize = value; }
}
/// <summary>
/// Is the collection currently connected to an open session?
/// </summary>
protected bool IsConnectedToSession
{
get { return session != null && session.IsOpen && session.PersistenceContext.ContainsCollection(this); }
}
/// <summary>
/// Is this collection in a state that would allow us to "queue" additions?
/// </summary>
protected bool IsOperationQueueEnabled
{
get { return !initialized && IsConnectedToSession && IsInverseCollection; }
}
/// <summary> Is this collection in a state that would allow us to
/// "queue" puts? This is a special case, because of orphan
/// delete.
/// </summary>
protected bool PutQueueEnabled
{
get { return !initialized && IsConnectedToSession && InverseOneToManyOrNoOrphanDelete; }
}
/// <summary> Is this collection in a state that would allow us to
/// "queue" clear? This is a special case, because of orphan
/// delete.
/// </summary>
protected bool ClearQueueEnabled
{
get { return !initialized && IsConnectedToSession && InverseCollectionNoOrphanDelete; }
}
/// <summary> Is this the "inverse" end of a bidirectional association?</summary>
protected bool IsInverseCollection
{
get
{
CollectionEntry ce = session.PersistenceContext.GetCollectionEntry(this);
return ce != null && ce.LoadedPersister.IsInverse;
}
}
/// <summary>
/// Is this the "inverse" end of a bidirectional association with
/// no orphan delete enabled?
/// </summary>
protected bool InverseCollectionNoOrphanDelete
{
get
{
CollectionEntry ce = session.PersistenceContext.GetCollectionEntry(this);
return ce != null && ce.LoadedPersister.IsInverse && !ce.LoadedPersister.HasOrphanDelete;
}
}
/// <summary>
/// Is this the "inverse" end of a bidirectional one-to-many, or
/// of a collection with no orphan delete?
/// </summary>
protected bool InverseOneToManyOrNoOrphanDelete
{
get
{
CollectionEntry ce = session.PersistenceContext.GetCollectionEntry(this);
return
ce != null && ce.LoadedPersister.IsInverse
&& (ce.LoadedPersister.IsOneToMany || !ce.LoadedPersister.HasOrphanDelete);
}
}
/// <summary>
/// Return the user-visible collection (or array) instance
/// </summary>
/// <returns>
/// By default, the NHibernate wrapper is an acceptable collection for
/// the end user code to work with because it is interface compatible.
/// An NHibernate PersistentList is an IList, an NHibernate PersistentMap is an IDictionary
/// and those are the types user code is expecting.
/// </returns>
public virtual object GetValue()
{
return this;
}
public virtual bool RowUpdatePossible
{
get { return true; }
}
/// <summary></summary>
protected virtual ISessionImplementor Session
{
get { return session; }
}
public virtual object Owner
{
get { return owner; }
set { owner = value; }
}
public void ClearDirty()
{
dirty = false;
}
public void Dirty()
{
dirty = true;
}
/// <summary>
/// Is the initialized collection empty?
/// </summary>
public abstract bool Empty { get; } //Careful: these methods do not initialize the collection.
/// <summary>
/// Called by any read-only method of the collection interface
/// </summary>
public virtual void Read()
{
Initialize(false);
}
/// <summary> Called by the <tt>Count</tt> property</summary>
protected virtual bool ReadSize()
{
if (!initialized)
{
if (cachedSize != -1 && !HasQueuedOperations)
{
return true;
}
ThrowLazyInitializationExceptionIfNotConnected();
var entry = session.PersistenceContext.GetCollectionEntry(this);
var persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
var queueOperationTracker = GetOrCreateQueueOperationTracker();
if (queueOperationTracker == null)
{
if (HasQueuedOperations)
{
session.Flush();
}
cachedSize = persister.GetSize(entry.LoadedKey, session);
return true;
}
if (!queueOperationTracker.Cleared && !queueOperationTracker.DatabaseCollectionSize.HasValue)
{
queueOperationTracker.DatabaseCollectionSize = persister.GetSize(entry.LoadedKey, session);
}
cachedSize = queueOperationTracker.Cleared
? queueOperationTracker.GetQueueSize()
: queueOperationTracker.GetCollectionSize();
return true;
}
Read();
}
return false;
}
// Since v5.3
[Obsolete("This method has no more usages in NHibernate and will be removed in a future version.")]
protected virtual bool? ReadIndexExistence(object index)
{
if (!initialized)
{
ThrowLazyInitializationExceptionIfNotConnected();
CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(this);
ICollectionPersister persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
if (HasQueuedOperations)
{
session.Flush();
}
return persister.IndexExists(entry.LoadedKey, index, session);
}
}
Read();
return null;
}
// Since v5.3
[Obsolete("This method has no more usages in NHibernate and will be removed in a future version.")]
protected virtual bool? ReadElementExistence(object element)
{
if (!initialized)
{
ThrowLazyInitializationExceptionIfNotConnected();
CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(this);
ICollectionPersister persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
if (HasQueuedOperations)
{
session.Flush();
}
return persister.ElementExists(entry.LoadedKey, element, session);
}
}
Read();
return null;
}
// Since v5.3
[Obsolete("This method has no more usages in NHibernate and will be removed in a future version.")]
protected virtual object ReadElementByIndex(object index)
{
if (!initialized)
{
ThrowLazyInitializationExceptionIfNotConnected();
CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(this);
ICollectionPersister persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
if (HasQueuedOperations)
{
session.Flush();
}
var elementByIndex = persister.GetElementByIndex(entry.LoadedKey, index, session, owner);
return persister.NotFoundObject == elementByIndex ? NotFound : elementByIndex;
}
}
Read();
return Unknown;
}
protected virtual bool? ReadKeyExistence<TKey, TValue>(TKey elementKey)
{
if (!initialized)
{
ThrowLazyInitializationExceptionIfNotConnected();
CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(this);
ICollectionPersister persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
var queueOperationTracker = (AbstractMapQueueOperationTracker<TKey, TValue>) GetOrCreateQueueOperationTracker();
if (queueOperationTracker == null)
{
if (HasQueuedOperations)
{
session.Flush();
}
return persister.IndexExists(entry.LoadedKey, elementKey, session);
}
if (queueOperationTracker.ContainsKey(elementKey))
{
return true;
}
if (queueOperationTracker.Cleared)
{
return false;
}
if (queueOperationTracker.IsElementKeyQueuedForDelete(elementKey))
{
return false;
}
// As keys are unordered we don't have to calculate the current order of the key
return persister.IndexExists(entry.LoadedKey, elementKey, session);
}
Read();
}
return null;
}
protected virtual bool? ReadElementExistence<T>(T element, out bool? existsInDb)
{
if (!initialized)
{
ThrowLazyInitializationExceptionIfNotConnected();
CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(this);
ICollectionPersister persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
var queueOperationTracker = (AbstractCollectionQueueOperationTracker<T>) GetOrCreateQueueOperationTracker();
if (queueOperationTracker == null)
{
if (HasQueuedOperations)
{
session.Flush();
}
existsInDb = persister.ElementExists(entry.LoadedKey, element, session);
return existsInDb;
}
if (queueOperationTracker.ContainsElement(element))
{
existsInDb = null;
return true;
}
if (queueOperationTracker.Cleared)
{
existsInDb = null;
return false;
}
if (queueOperationTracker.IsElementQueuedForDelete(element))
{
existsInDb = null;
return false;
}
existsInDb = persister.ElementExists(entry.LoadedKey, element, session);
return existsInDb;
}
Read();
}
existsInDb = null;
return null;
}
protected virtual bool? TryReadElementByKey<TKey, TValue>(TKey elementKey, out TValue element, out bool? existsInDb)
{
if (!initialized)
{
ThrowLazyInitializationExceptionIfNotConnected();
CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(this);
ICollectionPersister persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
var queueOperationTracker = (AbstractMapQueueOperationTracker<TKey, TValue>) GetOrCreateQueueOperationTracker();
if (queueOperationTracker == null)
{
if (HasQueuedOperations)
{
session.Flush();
}
}
else
{
if (queueOperationTracker.TryGetElementByKey(elementKey, out element))
{
existsInDb = null;
return true;
}
if (queueOperationTracker.Cleared)
{
existsInDb = null;
return false;
}
if (queueOperationTracker.IsElementKeyQueuedForDelete(elementKey))
{
existsInDb = null;
return false;
}
}
var elementByKey = persister.GetElementByIndex(entry.LoadedKey, elementKey, session, owner);
if (persister.NotFoundObject == elementByKey)
{
element = default(TValue);
existsInDb = false;
return false;
}
element = (TValue) elementByKey;
existsInDb = true;
return true;
}
Read();
}
element = default(TValue);
existsInDb = null;
return null;
}
protected virtual bool? TryReadElementAtIndex<T>(int index, out T element)
{
if (!initialized)
{
ThrowLazyInitializationExceptionIfNotConnected();
CollectionEntry entry = session.PersistenceContext.GetCollectionEntry(this);
ICollectionPersister persister = entry.LoadedPersister;
if (persister.IsExtraLazy)
{
var queueOperationTracker = (AbstractCollectionQueueOperationTracker<T>) GetOrCreateQueueOperationTracker();
if (queueOperationTracker == null)
{
if (HasQueuedOperations)
{
session.Flush();
}
}
else if (HasQueuedOperations)
{
if (queueOperationTracker.RequiresFlushing(nameof(queueOperationTracker.TryGetElementAtIndex)))
{
session.Flush();
}
else
{
if (!queueOperationTracker.DatabaseCollectionSize.HasValue &&
queueOperationTracker.RequiresDatabaseCollectionSize(nameof(queueOperationTracker.TryGetElementAtIndex)) &&
!ReadSize())
{
element = default(T);
return null; // The collection was loaded
}
if (queueOperationTracker.TryGetElementAtIndex(index, out element))
{
return true;
}
if (queueOperationTracker.Cleared)
{
return false;
}
// We have to calculate the database index based on the changes in the queue
var dbIndex = queueOperationTracker.GetDatabaseElementIndex(index);
if (!dbIndex.HasValue)
{
element = default(T);
return false;
}
index = dbIndex.Value;
}
}
var elementByIndex = persister.GetElementByIndex(entry.LoadedKey, index, session, owner);
if (persister.NotFoundObject == elementByIndex)
{
element = default(T);
return false;
}
element = (T) elementByIndex;
return true;
}
Read();
}
element = default(T);
return null;
}
/// <summary>
/// Called by any writer method of the collection interface
/// </summary>
protected virtual void Write()
{
Initialize(true);
Dirty();
}
internal virtual AbstractQueueOperationTracker CreateQueueOperationTracker() => null;
internal AbstractQueueOperationTracker QueueOperationTracker
{
get => _queueOperationTracker;
set => _queueOperationTracker = value;
}
internal AbstractQueueOperationTracker GetOrCreateQueueOperationTracker()
{
if (_queueOperationTracker != null)
{
return _queueOperationTracker;
}
_queueOperationTracker = CreateQueueOperationTracker();
return _queueOperationTracker;
}
/// <summary>
/// Queue an addition, delete etc. if the persistent collection supports it
/// </summary>
// Since v5.3
[Obsolete("This method has no more usages in NHibernate and will be removed in a future version.")]
protected virtual void QueueOperation(IDelayedOperation element)
{
if (operationQueue == null)
{
operationQueue = new List<IDelayedOperation>(10);
}
operationQueue.Add(element);
dirty = true; //needed so that we remove this collection from the second-level cache
}
protected bool QueueAddElement<T>(T element)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<T>(nameof(AbstractCollectionQueueOperationTracker<T>.AddElement));
return queueOperationTracker.AddElement(element);
}
protected void QueueRemoveExistingElement<T>(T element, bool? existsInDb)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<T>(nameof(AbstractCollectionQueueOperationTracker<T>.RemoveExistingElement), out var wasFlushed);
queueOperationTracker.RemoveExistingElement(element, wasFlushed ? true : existsInDb);
}
protected void QueueRemoveElementAtIndex<T>(int index, T element)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<T>(nameof(AbstractCollectionQueueOperationTracker<T>.RemoveElementAtIndex));
queueOperationTracker.RemoveElementAtIndex(index, element);
}
protected void QueueAddElementAtIndex<T>(int index, T element)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<T>(nameof(AbstractCollectionQueueOperationTracker<T>.AddElementAtIndex));
queueOperationTracker.AddElementAtIndex(index, element);
}
protected void QueueSetElementAtIndex<T>(int index, T element, T oldElement)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<T>(nameof(AbstractCollectionQueueOperationTracker<T>.SetElementAtIndex));
queueOperationTracker.SetElementAtIndex(index, element, oldElement);
}
protected void QueueClearCollection()
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker(nameof(AbstractQueueOperationTracker.ClearCollection), out _);
queueOperationTracker.ClearCollection();
}
protected void QueueAddElementByKey<TKey, TValue>(TKey elementKey, TValue element)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<TKey, TValue>(nameof(AbstractMapQueueOperationTracker<TKey, TValue>.AddElementByKey));
queueOperationTracker.AddElementByKey(elementKey, element);
}
protected void QueueSetElementByKey<TKey, TValue>(TKey elementKey, TValue element, TValue oldElement, bool? existsInDb)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<TKey, TValue>(nameof(AbstractMapQueueOperationTracker<TKey, TValue>.SetElementByKey));
queueOperationTracker.SetElementByKey(elementKey, element, oldElement, existsInDb);
}
protected bool QueueRemoveElementByKey<TKey, TValue>(TKey elementKey, TValue oldElement, bool? existsInDb)
{
var queueOperationTracker = TryFlushAndGetQueueOperationTracker<TKey, TValue>(nameof(AbstractMapQueueOperationTracker<TKey, TValue>.RemoveElementByKey));
return queueOperationTracker.RemoveElementByKey(elementKey, oldElement, existsInDb);
}
private AbstractMapQueueOperationTracker<TKey, TValue> TryFlushAndGetQueueOperationTracker<TKey, TValue>(string operationName)
{
return (AbstractMapQueueOperationTracker<TKey, TValue>) TryFlushAndGetQueueOperationTracker(operationName, out _);
}
private AbstractCollectionQueueOperationTracker<T> TryFlushAndGetQueueOperationTracker<T>(string operationName)
{
return (AbstractCollectionQueueOperationTracker<T>) TryFlushAndGetQueueOperationTracker(operationName, out _);
}
private AbstractCollectionQueueOperationTracker<T> TryFlushAndGetQueueOperationTracker<T>(string operationName, out bool wasFlushed)
{
return (AbstractCollectionQueueOperationTracker<T>) TryFlushAndGetQueueOperationTracker(operationName, out wasFlushed);
}
private AbstractQueueOperationTracker TryFlushAndGetQueueOperationTracker(string operationName, out bool wasFlushed)
{
var queueOperationTracker = GetOrCreateQueueOperationTracker();
if (queueOperationTracker == null)
{
throw new InvalidOperationException($"{nameof(CreateQueueOperationTracker)} must return a not null value.");
}
if (queueOperationTracker.RequiresFlushing(operationName))
{
session.Flush();
wasFlushed = true;
}
else
{
wasFlushed = false;
}
queueOperationTracker.BeforeOperation(operationName);
if (!queueOperationTracker.DatabaseCollectionSize.HasValue && queueOperationTracker.RequiresDatabaseCollectionSize(operationName) && !ReadSize())
{
throw new InvalidOperationException($"The collection role {Role} must be mapped as extra lazy.");
}
dirty = true; // Needed so that we remove this collection from the second-level cache
return queueOperationTracker;
}
internal bool CanSkipElementExistenceCheck(object element)
{
var queryableCollection = (IQueryableCollection) Session.Factory.GetCollectionPersister(Role);
return
queryableCollection != null &&
queryableCollection.ElementType.IsEntityType &&
!queryableCollection.ElementPersister.EntityMetamodel.OverridesEquals &&
!element.IsProxy() &&
!Session.PersistenceContext.IsEntryFor(element) &&
ForeignKeys.IsTransientFast(queryableCollection.ElementPersister.EntityName, element, Session) == true;
}
// Obsolete since v5.2
/// <summary>
/// After reading all existing elements from the database,
/// add the queued elements to the underlying collection.
/// </summary>
[Obsolete("Use or override ApplyQueuedOperations instead")]
protected virtual void PerformQueuedOperations()
{
for (int i = 0; i < operationQueue.Count; i++)
{
operationQueue[i].Operate();
}
}
/// <summary>
/// After reading all existing elements from the database, do the queued operations
/// (adds or removes) on the underlying collection.
/// </summary>
public virtual void ApplyQueuedOperations()
{
if (operationQueue == null)
throw new InvalidOperationException("There are no operation queue.");
#pragma warning disable 618
PerformQueuedOperations();
#pragma warning restore 618
operationQueue = null;
}
public void SetSnapshot(object key, string role, object snapshot)
{
this.key = key;
this.role = role;
storedSnapshot = snapshot;
}
/// <summary>
/// Clears out any Queued operation.
/// </summary>
/// <remarks>
/// After flushing, clear any "queued" additions, since the
/// database state is now synchronized with the memory state.
/// </remarks>
public virtual void PostAction()
{
operationQueue = null;
_queueOperationTracker?.AfterFlushing();
cachedSize = -1;
ClearDirty();
}
/// <summary>
/// Called just before reading any rows from the <see cref="DbDataReader" />
/// </summary>
public virtual void BeginRead()
{
// override on some subclasses
initializing = true;
}
/// <summary>
/// Called after reading all rows from the <see cref="DbDataReader" />
/// </summary>
/// <remarks>
/// This should be overridden by sub collections that use temporary collections
/// to store values read from the db.
/// </remarks>
public virtual bool EndRead(ICollectionPersister persister)
{
// override on some subclasses
return AfterInitialize(persister);
}
public virtual bool AfterInitialize(ICollectionPersister persister)
{
SetInitialized();
cachedSize = -1;
return operationQueue == null && _queueOperationTracker == null;
}
/// <summary>
/// Initialize the collection, if possible, wrapping any exceptions
/// in a runtime exception
/// </summary>
/// <param name="writing">currently obsolete</param>
/// <exception cref="LazyInitializationException">if we cannot initialize</exception>
protected virtual void Initialize(bool writing)
{
if (!initialized)
{
if (initializing)
{
throw new LazyInitializationException("illegal access to loading collection");
}
ThrowLazyInitializationExceptionIfNotConnected();
session.InitializeCollection(this, writing);
}
}
protected void ThrowLazyInitializationExceptionIfNotConnected()
{
if (!IsConnectedToSession)
{
ThrowLazyInitializationException("no session or session was closed");
}
if (!session.IsConnected)
{
ThrowLazyInitializationException("session is disconnected");
}
}
protected void ThrowLazyInitializationException(string message)
{
var ownerEntityName = role == null ? "Unavailable" : StringHelper.Qualifier(role);
throw new LazyInitializationException(ownerEntityName, key, "failed to lazily initialize a collection"
+ (role == null ? "" : " of role: " + role) + ", " + message);
}
/// <summary>
/// Mark the collection as initialized.
/// </summary>
protected virtual void SetInitialized()
{
initializing = false;
initialized = true;
}
/// <summary>
/// Gets a <see cref="Boolean"/> indicating if the underlying collection is directly
/// accessible through code.
/// </summary>
/// <value>
/// <see langword="true" /> if we are not guaranteed that the NHibernate collection wrapper
/// is being used.
/// </value>
/// <remarks>
/// This is typically <see langword="false" /> whenever a transient object that contains a collection is being
/// associated with an <see cref="ISession" /> through <see cref="ISession.Save(object)" /> or <see cref="ISession.SaveOrUpdate(object)" />.
/// NHibernate can't guarantee that it will know about all operations that would cause NHibernate's collections
/// to call <see cref="Read()" /> or <see cref="Write" />.
/// </remarks>
public virtual bool IsDirectlyAccessible
{
get { return directlyAccessible; }
protected set { directlyAccessible = value; }
}
/// <summary>
/// Disassociate this collection from the given session.
/// </summary>
/// <param name="currentSession"></param>
/// <returns>true if this was currently associated with the given session</returns>
public bool UnsetSession(ISessionImplementor currentSession)
{
if (currentSession == session)
{
session = null;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Associate the collection with the given session.
/// </summary>
/// <param name="session"></param>
/// <returns>false if the collection was already associated with the session</returns>
public virtual bool SetCurrentSession(ISessionImplementor session)
{
if (session == this.session // NH: added to fix NH-704
&& session.PersistenceContext.ContainsCollection(this))
{
return false;
}
else
{
if (IsConnectedToSession)
{
CollectionEntry ce = session.PersistenceContext.GetCollectionEntry(this);
if (ce == null)
{
throw new HibernateException("Illegal attempt to associate a collection with two open sessions");
}
else
{
throw new HibernateException("Illegal attempt to associate a collection with two open sessions: "
+ MessageHelper.CollectionInfoString(ce.LoadedPersister, this, ce.LoadedKey, session));
}
}
else
{
this.session = session;
return true;
}
}
}
/// <summary>
/// Gets a <see cref="Boolean"/> indicating if the rows for this collection
/// need to be recreated in the table.
/// </summary>
/// <param name="persister">The <see cref="ICollectionPersister"/> for this Collection.</param>
/// <returns>
/// <see langword="false" /> by default since most collections can determine which rows need to be
/// individually updated/inserted/deleted. Currently only <see cref="PersistentGenericBag{T}"/>'s for <c>many-to-many</c>
/// need to be recreated.
/// </returns>