forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPersistentGenericIdentifierBag.cs
540 lines (469 loc) · 12.5 KB
/
PersistentGenericIdentifierBag.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
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.DebugHelpers;
using NHibernate.Engine;
using NHibernate.Id;
using NHibernate.Linq;
using NHibernate.Loader;
using NHibernate.Persister.Collection;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Collection.Generic
{
/// <summary>
/// Implements "bag" semantics more efficiently than <see cref="PersistentGenericBag{T}" /> by adding
/// a synthetic identifier column to the table.
/// </summary>
/// <remarks>
/// <para>
/// The identifier is unique for all rows in the table, allowing very efficient
/// updates and deletes. The value of the identifier is never exposed to the
/// application.
/// </para>
/// <para>
/// Identifier bags may not be used for a many-to-one association. Furthermore,
/// there is no reason to use <c>inverse="true"</c>.
/// </para>
/// </remarks>
[Serializable]
[DebuggerTypeProxy(typeof (CollectionProxy<>))]
public partial class PersistentIdentifierBag<T> : AbstractPersistentCollection, IList<T>, IReadOnlyList<T>, IList, IQueryable<T>
{
/* 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
* many 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.
*/
private Dictionary<int, object> _identifiers; //index -> id
private IList<T> _values; //element
public PersistentIdentifierBag() {}
public PersistentIdentifierBag(ISessionImplementor session) : base(session) {}
public PersistentIdentifierBag(ISessionImplementor session, IEnumerable<T> coll) : base(session)
{
_values = coll as IList<T> ?? new List<T>(coll);
SetInitialized();
IsDirectlyAccessible = true;
_identifiers = new Dictionary<int, object>();
}
protected IList<T> InternalValues
{
get { return _values; }
set { _values = value; }
}
/// <summary>
/// Initializes this Bag from the cached values.
/// </summary>
/// <param name="persister">The CollectionPersister to use to reassemble the PersistentIdentifierBag.</param>
/// <param name="disassembled">The disassembled PersistentIdentifierBag.</param>
/// <param name="owner">The owner object.</param>
public override void InitializeFromCache(ICollectionPersister persister, object disassembled, object owner)
{
object[] array = (object[])disassembled;
int size = array.Length;
BeforeInitialize(persister, size);
for (int i = 0; i < size; i += 2)
{
_identifiers[i / 2] = persister.IdentifierType.Assemble(array[i], Session, owner);
_values.Add((T) persister.ElementType.Assemble(array[i + 1], Session, owner));
}
}
private object GetIdentifier(int index)
{
// NH specific : To emulate IDictionary behavior but using Dictionary<int, object> (without boxing/unboxing for index)
object result;
_identifiers.TryGetValue(index, out result);
return result;
}
public override object GetIdentifier(object entry, int i)
{
return GetIdentifier(i);
}
public override bool IsWrapper(object collection)
{
return _values == collection;
}
public override object Disassemble(ICollectionPersister persister)
{
object[] result = new object[_values.Count * 2];
int i = 0;
for (int j = 0; j < _values.Count; j++)
{
object val = _values[j];
result[i++] = persister.IdentifierType.Disassemble(_identifiers[j], Session, null);
result[i++] = persister.ElementType.Disassemble(val, Session, null);
}
return result;
}
public override bool Empty
{
get { return _values.Count == 0; }
}
public override IEnumerable Entries(ICollectionPersister persister)
{
return _values;
}
public override bool EntryExists(object entry, int i)
{
return entry != null;
}
public override bool EqualsSnapshot(ICollectionPersister persister)
{
IType elementType = persister.ElementType;
var snap = (ISet<SnapshotElement>)GetSnapshot();
if (snap.Count != _values.Count)
{
return false;
}
for (int i = 0; i < _values.Count; i++)
{
object val = _values[i];
object id = GetIdentifier(i);
object old = snap.Where(x => Equals(x.Id, id)).Select(x => x.Value).FirstOrDefault();
if (elementType.IsDirty(old, val, Session))
{
return false;
}
}
return true;
}
public override bool IsSnapshotEmpty(object snapshot)
{
return ((ISet<SnapshotElement>)snapshot).Count == 0;
}
public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula)
{
var snap = (ISet<SnapshotElement>)GetSnapshot();
var deletes = snap.ToList(x => x.Id);
for (int i = 0; i < _values.Count; i++)
{
if (_values[i] != null)
{
deletes.Remove(GetIdentifier(i));
}
}
return deletes;
}
public override object GetIndex(object entry, int i, ICollectionPersister persister)
{
throw new NotSupportedException("Bags don't have indexes");
}
public override object GetElement(object entry)
{
return entry;
}
public override object GetSnapshotElement(object entry, int i)
{
var snap = (ISet<SnapshotElement>)GetSnapshot();
object id = GetIdentifier(i);
return snap.Where(x => Equals(x.Id, id)).Select(x => x.Value).FirstOrDefault();
}
public override bool NeedsInserting(object entry, int i, IType elemType)
{
var snap = (ISet<SnapshotElement>)GetSnapshot();
object id = GetIdentifier(i);
object valueFound = snap.Where(x => Equals(x.Id, id)).Select(x => x.Value).FirstOrDefault();
return entry != null && (id == null || valueFound == null);
}
public override bool NeedsUpdating(object entry, int i, IType elemType)
{
if (entry == null)
{
return false;
}
var snap = (ISet<SnapshotElement>)GetSnapshot();
object id = GetIdentifier(i);
if (id == null)
{
return false;
}
object old = snap.Where(x => Equals(x.Id, id)).Select(x => x.Value).FirstOrDefault();
return old != null && elemType.IsDirty(old, entry, Session);
}
public override object ReadFrom(DbDataReader reader, ICollectionPersister persister, ICollectionAliases descriptor, object owner)
{
object element = persister.ReadElement(reader, owner, descriptor.SuffixedElementAliases, Session);
object id = persister.ReadIdentifier(reader, descriptor.SuffixedIdentifierAlias, Session);
// eliminate duplication if loaded in a cartesian product
if (!_identifiers.ContainsValue(id))
{
_identifiers[_values.Count] = id;
_values.Add((T) element);
}
return element;
}
public override object GetSnapshot(ICollectionPersister persister)
{
var map = new HashSet<SnapshotElement>();
int i = 0;
foreach (object value in _values)
{
object id;
_identifiers.TryGetValue(i++, out id);
var valueCopy = persister.ElementType.DeepCopy(value, persister.Factory);
map.Add(new SnapshotElement { Id = id, Value = valueCopy });
}
return map;
}
public override ICollection GetOrphans(object snapshot, string entityName)
{
var sn = (ISet<SnapshotElement>)GetSnapshot();
return GetOrphans(sn.ToArray(x => x.Value), (ICollection) _values, entityName, Session);
}
public override void PreInsert(ICollectionPersister persister)
{
if ((persister.IdentifierGenerator as IPostInsertIdentifierGenerator) != null)
{
// NH Different behavior (NH specific) : if we are using IdentityGenerator the PreInsert have no effect
return;
}
try
{
int i = 0;
foreach (object entry in _values)
{
int loc = i++;
if (!_identifiers.ContainsKey(loc)) // TODO: native ids
{
object id = persister.IdentifierGenerator.Generate(Session, entry);
_identifiers[loc] = id;
}
}
}
catch (Exception sqle)
{
throw new ADOException("Could not generate idbag row id.", sqle);
}
}
public override void AfterRowInsert(ICollectionPersister persister, object entry, int i, object id)
{
_identifiers[i] = id;
}
protected void BeforeRemove(int index)
{
int last = _values.Count - 1;
for (int i = index; i < last; i++)
{
object id = GetIdentifier(i + 1);
if (id == null)
{
_identifiers.Remove(i);
}
else
{
_identifiers[i] = id;
}
}
_identifiers.Remove(last);
}
protected void BeforeInsert(int index)
{
for (int i = _values.Count - 1; i >= index; i--)
{
object id = GetIdentifier(i);
if (id == null)
{
_identifiers.Remove(i + 1);
}
else
{
_identifiers[i + 1] = id;
}
}
_identifiers.Remove(index);
}
public override void BeforeInitialize(ICollectionPersister persister, int anticipatedSize)
{
_identifiers = anticipatedSize <= 0 ? new Dictionary<int, object>() : new Dictionary<int, object>(anticipatedSize + 1);
InternalValues = (IList<T>) persister.CollectionType.Instantiate(anticipatedSize);
}
int IList.Add(object value)
{
Add((T) value);
return _values.Count - 1;
}
public void Clear()
{
Initialize(true);
if (_values.Count > 0 || _identifiers.Count > 0)
{
_values.Clear();
_identifiers.Clear();
Dirty();
}
}
public bool IsReadOnly
{
get { return false; }
}
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (T) value; }
}
void IList.Insert(int index, object value)
{
Insert(index, (T) value);
}
public void RemoveAt(int index)
{
Write();
BeforeRemove(index);
_values.RemoveAt(index);
}
void IList.Remove(object value)
{
Remove((T) value);
}
bool IList.Contains(object value)
{
return Contains((T) value);
}
int IList.IndexOf(object value)
{
return IndexOf((T) value);
}
bool IList.IsFixedSize
{
get { return false; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
public int Count
{
get { return ReadSize() ? CachedSize : _values.Count; }
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
Read();
if (_values is ICollection collection)
{
collection.CopyTo(array, arrayIndex);
}
else
{
foreach (var item in _values)
array.SetValue(item, arrayIndex++);
}
}
object ICollection.SyncRoot
{
get { return this; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int IndexOf(T item)
{
Read();
return _values.IndexOf(item);
}
public void Insert(int index, T item)
{
Write();
BeforeInsert(index);
_values.Insert(index, item);
}
public T this[int index]
{
get
{
Read();
return _values[index];
}
set
{
Write();
_values[index] = value;
}
}
public void Add(T item)
{
Write();
_values.Add(item);
}
public bool Contains(T item)
{
Read();
return _values.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
Read();
_values.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
Initialize(true);
int index = _values.IndexOf(item);
if (index >= 0)
{
BeforeRemove(index);
_values.RemoveAt(index);
Dirty();
return true;
}
return false;
}
public IEnumerator<T> GetEnumerator()
{
Read();
return _values.GetEnumerator();
}
[Serializable]
private class SnapshotElement : IEquatable<SnapshotElement>
{
public object Id { get; set; }
public object Value { get; set; }
public bool Equals(SnapshotElement other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.Id, Id);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != typeof(SnapshotElement))
{
return false;
}
return Equals((SnapshotElement)obj);
}
public override int GetHashCode()
{
return (Id != null ? Id.GetHashCode() : 0);
}
}
#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
}
}