forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPersistentGenericBag.cs
520 lines (448 loc) · 11.9 KB
/
PersistentGenericBag.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using NHibernate.Collection.Trackers;
using NHibernate.DebugHelpers;
using NHibernate.Engine;
using NHibernate.Linq;
using NHibernate.Loader;
using NHibernate.Persister.Collection;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Collection.Generic
{
/// <summary>
/// An unordered, unkeyed collection that can contain the same element
/// multiple times. The .NET collections API, has no <c>Bag</c>.
/// Most developers seem to use <see cref="IList{T}"/> to represent bag semantics,
/// so NHibernate follows this practice.
/// </summary>
/// <typeparam name="T">The type of the element the bag should hold.</typeparam>
/// <remarks>The underlying collection used is an <see cref="List{T}"/></remarks>
[Serializable]
[DebuggerTypeProxy(typeof (CollectionProxy<>))]
public partial class PersistentGenericBag<T> : AbstractPersistentCollection, IList<T>, IReadOnlyList<T>, IList, IQueryable<T>
{
// TODO NH: find a way to writeonce (no duplicated code from PersistentBag)
/* NH considerations:
* For various reason we know that the underlining type will be a List<T> or a
* PersistentGenericBag<T>; in both cases the class implement all we need to don't duplicate
* all code from PersistentBag.
* In the explicit implementation of IList<T> we need to duplicate
* code to take advantage from the better performance the use of generic implementation have
* (mean .NET implementation of the underlining list).
* In other cases, where PersistentBag use for example bag.Add, a cast, probably, is more
* expensive than .NET original implementation.
*/
/* For a one-to-many, a <bag> is not really a bag;
* it is *really* a set, since it can't contain the
* same element twice. It could be considered a bug
* in the mapping dtd that <bag> allows <one-to-many>.
* Anyway, here we implement <set> semantics for a
* <one-to-many> <bag>!
*/
private IList<T> _gbag;
private bool _isOneToMany; // 6.0 TODO: Remove
public PersistentGenericBag()
{
}
public PersistentGenericBag(ISessionImplementor session)
: base(session)
{
}
public PersistentGenericBag(ISessionImplementor session, IEnumerable<T> coll)
: base(session)
{
_gbag = coll as IList<T> ?? new List<T>(coll);
SetInitialized();
IsDirectlyAccessible = true;
}
internal override AbstractQueueOperationTracker CreateQueueOperationTracker()
{
var entry = Session.PersistenceContext.GetCollectionEntry(this);
return new BagQueueOperationTracker<T>(entry.LoadedPersister);
}
public override void ApplyQueuedOperations()
{
var queueOperation = (BagQueueOperationTracker<T>) QueueOperationTracker;
queueOperation?.ApplyChanges(_gbag);
QueueOperationTracker = null;
}
protected IList<T> InternalBag
{
get { return _gbag; }
set { _gbag = value; }
}
public override bool Empty
{
get { return _gbag.Count == 0; }
}
public override bool RowUpdatePossible
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return this; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
Read();
if (_gbag is ICollection collection)
{
collection.CopyTo(array, arrayIndex);
}
else
{
foreach (var item in _gbag)
array.SetValue(item, arrayIndex++);
}
}
bool IList.IsFixedSize
{
get { return false; }
}
int IList.IndexOf(object value)
{
return IndexOf((T) value);
}
int IList.Add(object value)
{
if (!IsOperationQueueEnabled || !ReadSize())
{
Write();
return ((IList) _gbag).Add((T) value);
}
var val = (T) value;
QueueAddElement(val);
return CachedSize;
}
void IList.Insert(int index, object value)
{
Insert(index, (T) value);
}
void IList.Remove(object value)
{
Remove((T) value);
}
bool IList.Contains(object value)
{
return Contains((T) value);
}
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (T) value; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
Read();
return _gbag.GetEnumerator();
}
public int Count
{
get { return ReadSize() ? CachedSize : _gbag.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public void Add(T item)
{
if (!IsOperationQueueEnabled)
{
Write();
_gbag.Add(item);
}
else
{
QueueAddElement(item);
}
}
public void Clear()
{
if (ClearQueueEnabled)
{
QueueClearCollection();
}
else
{
Initialize(true);
if (_gbag.Count != 0)
{
_gbag.Clear();
Dirty();
}
}
}
public bool Contains(T item)
{
return ReadElementExistence(item, out _) ?? _gbag.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
Read();
_gbag.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
Initialize(true);
var result = _gbag.Remove(item);
if (result)
{
Dirty();
}
return result;
}
public T this[int index]
{
get
{
Read();
return _gbag[index];
}
set
{
Write();
_gbag[index] = value;
}
}
public int IndexOf(T item)
{
Read();
return _gbag.IndexOf(item);
}
public void Insert(int index, T item)
{
Write();
_gbag.Insert(index, item);
}
public void RemoveAt(int index)
{
Write();
_gbag.RemoveAt(index);
}
public override void BeforeInitialize(ICollectionPersister persister, int anticipatedSize)
{
_gbag = (IList<T>) persister.CollectionType.Instantiate(anticipatedSize);
_isOneToMany = persister.IsOneToMany;
}
public override object Disassemble(ICollectionPersister persister)
{
var length = _gbag.Count;
var result = new object[length];
for (var i = 0; i < length; i++)
{
result[i] = persister.ElementType.Disassemble(_gbag[i], Session, null);
}
return result;
}
public override IEnumerable Entries(ICollectionPersister persister)
{
return _gbag;
}
public override bool EntryExists(object entry, int i)
{
return entry != null;
}
public override bool EqualsSnapshot(ICollectionPersister persister)
{
var elementType = persister.ElementType;
var sn = (IList) GetSnapshot();
if (sn.Count != _gbag.Count)
{
return false;
}
for (var i = 0; i < _gbag.Count; i++)
{
if (elementType.IsSame(_gbag[i], sn[i]))
continue;
var elt = _gbag[i];
var countInSnapshot = CountOccurrences(elt, sn, elementType);
if (countInSnapshot == 0 || CountOccurrences(elt, _gbag, elementType) != countInSnapshot)
return false;
}
return true;
}
public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula)
{
var elementType = persister.ElementType;
var deletes = new List<object>();
var sn = (IList) GetSnapshot();
var i = 0;
foreach (var old in sn)
{
var found = false;
if (_gbag.Count > i && elementType.IsSame(old, _gbag[i++]))
{
//a shortcut if its location didn't change!
found = true;
}
else
{
foreach (object newObject in _gbag)
{
if (elementType.IsSame(old, newObject))
{
found = true;
break;
}
}
}
if (!found)
{
deletes.Add(old);
}
}
return deletes;
}
public override object GetElement(object entry)
{
return entry;
}
public override object GetIndex(object entry, int i, ICollectionPersister persister)
{
throw new NotSupportedException("Bags don't have indexes");
}
public override ICollection GetOrphans(object snapshot, string entityName)
{
var sn = (ICollection) snapshot;
return GetOrphans(sn, (ICollection) _gbag, entityName, Session);
}
public override object GetSnapshot(ICollectionPersister persister)
{
var clonedList = new List<object>(_gbag.Count);
foreach (object current in _gbag)
{
clonedList.Add(persister.ElementType.DeepCopy(current, persister.Factory));
}
return clonedList;
}
public override object GetSnapshotElement(object entry, int i)
{
var sn = (IList) GetSnapshot();
return sn[i];
}
/// <summary>
/// Initializes this PersistentBag from the cached values.
/// </summary>
/// <param name="persister">The CollectionPersister to use to reassemble the PersistentBag.</param>
/// <param name="disassembled">The disassembled PersistentBag.</param>
/// <param name="owner">The owner object.</param>
public override void InitializeFromCache(ICollectionPersister persister, object disassembled, object owner)
{
var array = (object[]) disassembled;
var size = array.Length;
BeforeInitialize(persister, size);
for (var i = 0; i < size; i++)
{
var element = persister.ElementType.Assemble(array[i], Session, owner);
if (element != null)
{
_gbag.Add((T) element);
}
}
}
public override bool IsSnapshotEmpty(object snapshot)
{
return ((ICollection) snapshot).Count == 0;
}
public override bool IsWrapper(object collection)
{
return _gbag == collection;
}
public override bool NeedsInserting(object entry, int i, IType elemType)
{
var sn = (IList) GetSnapshot();
if (sn.Count > i && elemType.IsSame(sn[i], entry))
{
// a shortcut if its location didn't change
return false;
}
//search for it
foreach (var old in sn)
{
if (elemType.IsEqual(old, entry))
{
return false;
}
}
return true;
}
/// <summary>
/// Gets a <see cref="bool"/> indicating if this PersistentBag needs to be recreated
/// in the database.
/// </summary>
/// <param name="persister"></param>
/// <returns>
/// <see langword="false" /> if this is a <c>one-to-many</c> Bag, <see langword="true" /> if this is not
/// a <c>one-to-many</c> Bag. Since a Bag is an unordered, unindexed collection
/// that permits duplicates it is not possible to determine what has changed in a
/// <c>many-to-many</c> so it is just recreated.
/// </returns>
public override bool NeedsRecreate(ICollectionPersister persister)
{
return !persister.IsOneToMany;
}
public override bool NeedsUpdating(object entry, int i, IType elemType)
{
return false;
}
public override object ReadFrom(DbDataReader reader, ICollectionPersister role, ICollectionAliases descriptor, object owner)
{
// note that if we load this collection from a cartesian product
// the multiplicity would be broken ... so use an idbag instead
var element = role.ReadElement(reader, owner, descriptor.SuffixedElementAliases, Session);
if (element != null)
_gbag.Add((T) element);
return element;
}
public override string ToString()
{
Read();
return StringHelper.CollectionToString(_gbag);
}
#region IQueryable<T> Members
[NonSerialized]
IQueryable<T> _queryable;
Expression IQueryable.Expression => InnerQueryable.Expression;
System.Type IQueryable.ElementType => InnerQueryable.ElementType;
IQueryProvider IQueryable.Provider => InnerQueryable.Provider;
IQueryable<T> InnerQueryable => _queryable ?? (_queryable = new NhQueryable<T>(Session, this));
#endregion
/// <summary>
/// Counts the number of times that the <paramref name="element"/> occurs
/// in the <paramref name="list"/>.
/// </summary>
/// <param name="element">The element to find in the list.</param>
/// <param name="list">The <see cref="IList"/> to search.</param>
/// <param name="elementType">The <see cref="IType"/> that can determine equality.</param>
/// <returns>
/// The number of occurrences of the element in the list.
/// </returns>
private static int CountOccurrences(object element, IEnumerable list, IType elementType)
{
var result = 0;
foreach (var obj in list)
{
if (elementType.IsSame(element, obj))
{
result++;
}
}
return result;
}
}
}