-
Notifications
You must be signed in to change notification settings - Fork 933
/
Copy pathLoader.cs
2177 lines (1900 loc) · 74.5 KB
/
Loader.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.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using NHibernate.AdoNet;
using NHibernate.Cache;
using NHibernate.Cache.Entry;
using NHibernate.Collection;
using NHibernate.Driver;
using NHibernate.Engine;
using NHibernate.Event;
using NHibernate.Exceptions;
using NHibernate.Hql.Util;
using NHibernate.Impl;
using NHibernate.Param;
using NHibernate.Persister;
using NHibernate.Persister.Collection;
using NHibernate.Persister.Entity;
using NHibernate.Proxy;
using NHibernate.SqlCommand;
using NHibernate.Transform;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Loader
{
/// <summary>
/// Abstract superclass of object loading (and querying) strategies.
/// </summary>
/// <remarks>
/// <para>
/// This class implements useful common functionality that concrete loaders would delegate to.
/// It is not intended that this functionality would be directly accessed by client code (Hence,
/// all methods of this class are declared <c>protected</c> or <c>private</c>.) This class relies heavily upon the
/// <see cref="ILoadable" /> interface, which is the contract between this class and
/// <see cref="IEntityPersister" />s that may be loaded by it.
/// </para>
/// <para>
/// The present implementation is able to load any number of columns of entities and at most
/// one collection role per query.
/// </para>
/// <para>
/// All this class members are thread safe. Entity and collection loaders are held in persisters shared among
/// sessions built from the same session factory. They must be thread safe.
/// </para>
/// </remarks>
/// <seealso cref="NHibernate.Persister.Entity.ILoadable"/>
public abstract partial class Loader : ILoader
{
/// <summary>
/// DTO for providing all query cache related details
/// </summary>
public sealed class QueryCacheInfo
{
public IType[] CacheTypes { get; set; }
/// <summary>
/// Loader.EntityPersister indexes to be cached.
/// </summary>
public IReadOnlyList<int> AdditionalEntities { get; set; }
}
private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(Loader));
private Lazy<QueryCacheInfo> _cacheInfo;
private readonly ISessionFactoryImplementor _factory;
private readonly SessionFactoryHelper _helper;
private ColumnNameCache _columnNameCache;
/// <summary>
/// Indicates whether the dialect is able to add limit and/or offset clauses to <see cref="SqlString"/>.
/// Even if a dialect generally supports the addition of limit and/or offset clauses to SQL statements,
/// there may (custom) SQL statements where this is not possible, for example in case of SQL Server
/// stored procedure invocations.
/// </summary>
private bool? _canUseLimits;
/// <summary>
/// Caches subclass entity aliases for given persister index in <see cref="EntityPersisters"/> and subclass entity name
/// </summary>
private readonly ConcurrentDictionary<Tuple<int, string>, string[][]> _subclassEntityAliasesMap = new ConcurrentDictionary<Tuple<int, string>, string[][]>();
protected Loader(ISessionFactoryImplementor factory)
{
_factory = factory;
_helper = new SessionFactoryHelper(factory);
}
protected SessionFactoryHelper Helper
{
get { return _helper; }
}
/// <summary>
/// An array indicating whether the entities have eager property fetching
/// enabled.
/// </summary>
/// <value> Eager property fetching indicators. </value>
protected virtual bool[] EntityEagerPropertyFetches
{
get { return null; }
}
/// <summary>
/// An array of hash sets indicating which lazy properties will be fetched for an entity persister.
/// </summary>
protected virtual ISet<string>[] EntityFetchLazyProperties
{
get { return null; }
}
/// <summary>
/// An array of indexes of the entity that owns an association
/// to the entity at the given index (-1 if there is no "owner")
/// </summary>
/// <remarks>
/// The indexes contained here are relative to the result of <see cref="EntityPersisters"/>.
/// </remarks>
protected virtual int[] Owners
{
get { return null; }
}
/// <summary>
/// An array of the owner types corresponding to the <see cref="Owners"/>
/// returns. Indices indicating no owner would be null here.
/// </summary>
protected virtual EntityType[] OwnerAssociationTypes
{
get { return null; }
}
/// <summary>
/// Get the index of the entity that owns the collection, or -1
/// if there is no owner in the query results (i.e. in the case of a
/// collection initializer) or no collection.
/// </summary>
protected virtual int[] CollectionOwners
{
get { return null; }
}
/// <summary>
/// Return false is this loader is a batch entity loader
/// </summary>
protected virtual bool IsSingleRowLoader
{
get { return false; }
}
public virtual bool IsSubselectLoadingEnabled
{
get { return false; }
}
/// <summary>
/// Get the result set descriptor
/// </summary>
protected abstract IEntityAliases[] EntityAliases { get; }
protected abstract ICollectionAliases[] CollectionAliases { get; }
/// <summary>
/// The result types of the result set, for query loaders.
/// </summary>
public IType[] ResultTypes { get; protected set; }
public IType[] CacheTypes => CacheInfo?.CacheTypes ?? ResultTypes;
public virtual QueryCacheInfo CacheInfo => _cacheInfo?.Value;
/// <summary>
/// Cache all additional persisters and collection persisters that were loaded by query (fetched entities and collections)
/// </summary>
/// <param name="resultTypePersisters">Persister indexes that are cached as part of query result (so present in ResultTypes)</param>
protected void CachePersistersWithCollections(IEnumerable<int> resultTypePersisters)
{
_cacheInfo = new Lazy<QueryCacheInfo>(() => GetQueryCacheInfo(resultTypePersisters));
}
public ISessionFactoryImplementor Factory
{
get { return _factory; }
}
/// <summary>
/// The SqlString to be called; implemented by all subclasses
/// </summary>
public abstract SqlString SqlString { get; }
/// <summary>
/// An array of persisters of entity classes contained in each row of results;
/// implemented by all subclasses
/// </summary>
/// <remarks>
/// The <c>setter</c> was added so that classes inheriting from Loader could write a
/// value using the Property instead of directly to the field.
/// </remarks>
public abstract ILoadable[] EntityPersisters { get; }
/// <summary>
/// An (optional) persister for a collection to be initialized; only collection loaders
/// return a non-null value
/// </summary>
protected internal virtual ICollectionPersister[] CollectionPersisters
{
get { return null; }
}
/// <summary>
/// What lock mode does this load entities with?
/// </summary>
/// <param name="lockModes">A Collection of lock modes specified dynamically via the Query Interface</param>
/// <returns></returns>
public abstract LockMode[] GetLockModes(IDictionary<string, LockMode> lockModes);
/// <summary>
/// Append <c>FOR UPDATE OF</c> clause, if necessary. This
/// empty superclass implementation merely returns its first
/// argument.
/// </summary>
protected virtual SqlString ApplyLocks(SqlString sql, IDictionary<string, LockMode> lockModes, Dialect.Dialect dialect)
{
return sql;
}
/// <summary>
/// Does this query return objects that might be already cached by
/// the session, whose lock mode may need upgrading.
/// </summary>
/// <returns></returns>
protected virtual bool UpgradeLocks()
{
return false;
}
/// <summary>
/// Get the SQL table aliases of entities whose
/// associations are subselect-loadable, returning
/// null if this loader does not support subselect
/// loading
/// </summary>
protected virtual string[] Aliases
{
get { return null; }
}
/// <summary>
/// Modify the SQL, adding lock hints and comments, if necessary
/// </summary>
protected virtual SqlString PreprocessSQL(SqlString sql, QueryParameters parameters, Dialect.Dialect dialect)
{
sql = ApplyLocks(sql, parameters.LockModes, dialect);
return Factory.Settings.IsCommentsEnabled ? PrependComment(sql, parameters) : sql;
}
private static SqlString PrependComment(SqlString sql, QueryParameters parameters)
{
string comment = parameters.Comment;
if (string.IsNullOrEmpty(comment))
{
return sql;
}
else
{
return sql.Insert(0, "/* " + comment + " */");
}
}
/// <summary>
/// Execute an SQL query and attempt to instantiate instances of the class mapped by the given
/// persister from each row of the <c>DataReader</c>. If an object is supplied, will attempt to
/// initialize that object. If a collection is supplied, attempt to initialize that collection.
/// </summary>
private IList DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters,
bool returnProxies)
{
return DoQueryAndInitializeNonLazyCollections(session, queryParameters, returnProxies, null, null);
}
private IList DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, bool returnProxies,
IResultTransformer forcedResultTransformer,
QueryCacheResultBuilder queryCacheResultBuilder)
{
IPersistenceContext persistenceContext = session.PersistenceContext;
bool defaultReadOnlyOrig = persistenceContext.DefaultReadOnly;
if (queryParameters.IsReadOnlyInitialized)
persistenceContext.DefaultReadOnly = queryParameters.ReadOnly;
else
queryParameters.ReadOnly = persistenceContext.DefaultReadOnly;
persistenceContext.BeforeLoad();
IList result;
try
{
try
{
result = DoQuery(session, queryParameters, returnProxies, forcedResultTransformer, queryCacheResultBuilder);
}
finally
{
persistenceContext.AfterLoad();
}
persistenceContext.InitializeNonLazyCollections();
}
finally
{
persistenceContext.DefaultReadOnly = defaultReadOnlyOrig;
}
return result;
}
/// <summary>
/// Loads a single row from the result set. This is the processing used from the
/// ScrollableResults where no collection fetches were encountered.
/// </summary>
/// <param name="resultSet">The result set from which to do the load.</param>
/// <param name="session">The session from which the request originated.</param>
/// <param name="queryParameters">The query parameters specified by the user.</param>
/// <param name="returnProxies">Should proxies be generated</param>
/// <returns>The loaded "row".</returns>
/// <exception cref="HibernateException" />
// Since v5.3
[Obsolete("This method has no more usages and will be removed in a future version")]
protected object LoadSingleRow(DbDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters,
bool returnProxies)
{
int entitySpan = EntityPersisters.Length;
IList hydratedObjects = entitySpan == 0 ? null : new List<object>(entitySpan);
var cacheBatcher = new CacheBatcher(session);
object result;
try
{
result =
GetRowFromResultSet(resultSet, session, queryParameters, GetLockModes(queryParameters.LockModes), null,
hydratedObjects, new EntityKey[entitySpan], returnProxies, null, null,
(persister, data) => cacheBatcher.AddToBatch(persister, data));
}
catch (HibernateException)
{
throw; // Don't call Convert on HibernateExceptions
}
catch (Exception sqle)
{
throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, sqle, "could not read next row of results",
SqlString, queryParameters.PositionalParameterValues,
queryParameters.NamedParameters);
}
InitializeEntitiesAndCollections(hydratedObjects, resultSet, session, queryParameters.IsReadOnly(session), cacheBatcher);
cacheBatcher.ExecuteBatch();
session.PersistenceContext.InitializeNonLazyCollections();
return result;
}
// Not ported: sequentialLoad, loadSequentialRowsForward, loadSequentialRowsReverse
internal static EntityKey GetOptionalObjectKey(QueryParameters queryParameters, ISessionImplementor session)
{
object optionalObject = queryParameters.OptionalObject;
object optionalId = queryParameters.OptionalId;
string optionalEntityName = queryParameters.OptionalEntityName;
if (optionalObject != null && !string.IsNullOrEmpty(optionalEntityName))
{
return session.GenerateEntityKey(optionalId, session.GetEntityPersister(optionalEntityName, optionalObject));
}
else
{
return null;
}
}
public object GetRowFromResultSet(
DbDataReader resultSet, ISessionImplementor session,
QueryParameters queryParameters, LockMode[] lockModeArray,
EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys,
bool returnProxies, IResultTransformer forcedResultTransformer,
QueryCacheResultBuilder queryCacheResultBuilder,
Action<IEntityPersister, CachePutData> cacheBatchingHandler)
{
ILoadable[] persisters = EntityPersisters;
int entitySpan = persisters.Length;
for (int i = 0; i < entitySpan; i++)
{
keys[i] =
GetKeyFromResultSet(i, persisters[i], i == entitySpan - 1 ? queryParameters.OptionalId : null, resultSet, session);
//TODO: the i==entitySpan-1 bit depends upon subclass implementation (very bad)
}
RegisterNonExists(keys, session);
// this call is side-effecty
object[] row =
GetRow(resultSet, persisters, keys, queryParameters.OptionalObject, optionalObjectKey, lockModeArray,
hydratedObjects, session, !returnProxies, cacheBatchingHandler);
var collections = ReadCollectionElements(row, resultSet, session);
if (returnProxies)
{
// now get an existing proxy for each row element (if there is one)
for (int i = 0; i < entitySpan; i++)
{
object entity = row[i];
var key = keys[i];
if (entity == null && key != null && IsChildFetchEntity(i))
{
// The entity was missing in the session, fallback on internal load (which will just yield a
// proxy if the persister supports it).
row[i] = session.InternalLoad(key.EntityName, key.Identifier, false, false);
}
else
{
object proxy = session.PersistenceContext.ProxyFor(persisters[i], keys[i], entity);
if (entity != proxy)
{
// Force the proxy to resolve itself
((INHibernateProxy) proxy).HibernateLazyInitializer.SetImplementation(entity);
row[i] = proxy;
}
}
}
}
var result = forcedResultTransformer == null
? GetResultColumnOrRow(row, queryParameters.ResultTransformer, resultSet, session)
: forcedResultTransformer.TransformTuple(GetResultRow(row, resultSet, session),
ResultRowAliases);
queryCacheResultBuilder?.AddRow(result, row, collections);
return result;
}
/// <summary>
/// Read any collection elements contained in a single row of the result set
/// </summary>
private IPersistentCollection[] ReadCollectionElements(object[] row, DbDataReader resultSet, ISessionImplementor session)
{
//TODO: make this handle multiple collection roles!
ICollectionPersister[] collectionPersisters = CollectionPersisters;
if (collectionPersisters != null)
{
var result = new IPersistentCollection[collectionPersisters.Length];
ICollectionAliases[] descriptors = CollectionAliases;
int[] collectionOwners = CollectionOwners;
for (int i = 0; i < collectionPersisters.Length; i++)
{
bool hasCollectionOwners = collectionOwners != null && collectionOwners[i] > -1;
//true if this is a query and we are loading multiple instances of the same collection role
//otherwise this is a CollectionInitializer and we are loading up a single collection or batch
object owner = hasCollectionOwners ? row[collectionOwners[i]] : null;
//if null, owner will be retrieved from session
ICollectionPersister collectionPersister = collectionPersisters[i];
object key;
if (owner == null)
{
key = null;
}
else
{
key = collectionPersister.CollectionType.GetKeyOfOwner(owner, session);
//TODO: old version did not require hashmap lookup:
//keys[collectionOwner].getIdentifier()
}
result[i] = ReadCollectionElement(owner, key, collectionPersister, descriptors[i], resultSet, session);
}
return result;
}
return null;
}
private IList DoQuery(ISessionImplementor session, QueryParameters queryParameters, bool returnProxies,
IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder)
{
using (session.BeginProcess())
{
RowSelection selection = queryParameters.RowSelection;
int maxRows = HasMaxRows(selection) ? selection.MaxRows : int.MaxValue;
int entitySpan = EntityPersisters.Length;
List<object> hydratedObjects = entitySpan == 0 ? null : new List<object>(entitySpan*10);
var st = PrepareQueryCommand(queryParameters, false, session);
var rs = GetResultSet(st, queryParameters, session, forcedResultTransformer);
// would be great to move all this below here into another method that could also be used
// from the new scrolling stuff.
//
// Would need to change the way the max-row stuff is handled (i.e. behind an interface) so
// that I could do the control breaking at the means to know when to stop
LockMode[] lockModeArray = GetLockModes(queryParameters.LockModes);
EntityKey optionalObjectKey = GetOptionalObjectKey(queryParameters, session);
bool createSubselects = IsSubselectLoadingEnabled;
List<EntityKey[]> subselectResultKeys = createSubselects ? new List<EntityKey[]>() : null;
IList results = new List<object>();
var cacheBatcher = new CacheBatcher(session);
try
{
HandleEmptyCollections(queryParameters.CollectionKeys, rs, session);
EntityKey[] keys = new EntityKey[entitySpan]; // we can reuse it each time
if (Log.IsDebugEnabled())
{
Log.Debug("processing result set");
}
int count;
for (count = 0; count < maxRows && rs.Read(); count++)
{
if (Log.IsDebugEnabled())
{
Log.Debug("result set row: {0}", count);
}
object result = GetRowFromResultSet(rs, session, queryParameters, lockModeArray, optionalObjectKey,
hydratedObjects,
keys, returnProxies, forcedResultTransformer, queryCacheResultBuilder,
(persister, data) => cacheBatcher.AddToBatch(persister, data));
results.Add(result);
if (createSubselects)
{
subselectResultKeys.Add(keys);
keys = new EntityKey[entitySpan]; //can't reuse in this case
}
}
if (Log.IsDebugEnabled())
{
Log.Debug("done processing result set ({0} rows)", count);
}
}
catch (Exception e)
{
e.Data["actual-sql-query"] = st.CommandText;
throw;
}
finally
{
session.Batcher.CloseCommand(st, rs);
}
InitializeEntitiesAndCollections(hydratedObjects, rs, session, queryParameters.IsReadOnly(session), cacheBatcher);
cacheBatcher.ExecuteBatch();
if (createSubselects)
{
CreateSubselects(subselectResultKeys, queryParameters, session);
}
return results;
}
}
protected bool HasSubselectLoadableCollections()
{
foreach (ILoadable loadable in EntityPersisters)
{
if (loadable.HasSubselectLoadableCollections)
{
return true;
}
}
return false;
}
private static ISet<EntityKey>[] Transpose(List<EntityKey[]> keys)
{
ISet<EntityKey>[] result = new ISet<EntityKey>[keys[0].Length];
for (int j = 0; j < result.Length; j++)
{
result[j] = new HashSet<EntityKey>();
for (int i = 0; i < keys.Count; i++)
{
EntityKey key = keys[i][j];
if (key != null)
{
result[j].Add(key);
}
}
}
return result;
}
public void CreateSubselects(List<EntityKey[]> keys, QueryParameters queryParameters, ISessionImplementor session)
{
if (keys.Count > 1)
{
//if we only returned one entity, query by key is more efficient
var subSelects = CreateSubselects(keys, queryParameters).ToArray();
foreach (EntityKey[] rowKeys in keys)
{
for (int i = 0; i < rowKeys.Length; i++)
{
if (rowKeys[i] != null && subSelects[i] != null)
{
session.PersistenceContext.BatchFetchQueue.AddSubselect(rowKeys[i], subSelects[i]);
}
}
}
}
}
private IEnumerable<SubselectFetch> CreateSubselects(List<EntityKey[]> keys, QueryParameters queryParameters)
{
// see NH-2123 NH-2125
ISet<EntityKey>[] keySets = Transpose(keys);
ILoadable[] loadables = EntityPersisters;
string[] aliases = Aliases;
for (int i = 0; i < loadables.Length; i++)
{
if (loadables[i].HasSubselectLoadableCollections)
{
yield return new SubselectFetch(aliases[i], loadables[i], queryParameters, keySets[i]);
}
else
{
yield return null;
}
}
}
public void InitializeEntitiesAndCollections(
IList hydratedObjects,
DbDataReader reader,
ISessionImplementor session,
bool readOnly,
CacheBatcher cacheBatcher)
{
ICollectionPersister[] collectionPersisters = CollectionPersisters;
var ownCacheBatcher = cacheBatcher == null;
if (ownCacheBatcher)
cacheBatcher = new CacheBatcher(session);
if (collectionPersisters != null)
{
foreach (var collectionPersister in collectionPersisters)
{
if (collectionPersister.IsArray)
{
//for arrays, we should end the collection load before resolving
//the entities, since the actual array instances are not instantiated
//during loading
//TODO: or we could do this polymorphically, and have two
// different operations implemented differently for arrays
EndCollectionLoad(reader, session, collectionPersister, cacheBatcher);
}
}
}
//important: reuse the same event instances for performance!
PreLoadEvent pre;
PostLoadEvent post;
if (session.IsEventSource)
{
var eventSourceSession = (IEventSource)session;
pre = new PreLoadEvent(eventSourceSession);
post = new PostLoadEvent(eventSourceSession);
}
else
{
pre = null;
post = null;
}
if (hydratedObjects != null)
{
int hydratedObjectsSize = hydratedObjects.Count;
if (Log.IsDebugEnabled())
{
Log.Debug("total objects hydrated: {0}", hydratedObjectsSize);
}
for (int i = 0; i < hydratedObjectsSize; i++)
{
TwoPhaseLoad.InitializeEntity(
hydratedObjects[i], readOnly, session, pre, post,
(persister, data) => cacheBatcher.AddToBatch(persister, data));
}
}
if (collectionPersisters != null)
{
foreach (var collectionPersister in collectionPersisters)
{
if (!collectionPersister.IsArray)
{
//for sets, we should end the collection load after resolving
//the entities, since we might call hashCode() on the elements
//TODO: or we could do this polymorphically, and have two
// different operations implemented differently for arrays
EndCollectionLoad(reader, session, collectionPersister, cacheBatcher);
}
}
}
if (ownCacheBatcher)
cacheBatcher.ExecuteBatch();
}
/// <summary>
/// Stops further collection population without actual collection initialization.
/// </summary>
public void StopLoadingCollections(ISessionImplementor session, DbDataReader reader)
{
var collectionPersisters = CollectionPersisters;
if (collectionPersisters == null || collectionPersisters.Length == 0)
return;
session.PersistenceContext.LoadContexts.GetCollectionLoadContext(reader).StopLoadingCollections(collectionPersisters);
}
private void EndCollectionLoad(DbDataReader reader, ISessionImplementor session, ICollectionPersister collectionPersister,
CacheBatcher cacheBatcher)
{
//this is a query and we are loading multiple instances of the same collection role
session.PersistenceContext.LoadContexts.GetCollectionLoadContext(reader).EndLoadingCollections(
collectionPersister, !IsCollectionPersisterCacheable(collectionPersister), cacheBatcher);
}
protected virtual bool IsCollectionPersisterCacheable(ICollectionPersister collectionPersister)
{
return true;
}
/// <summary>
/// Determine the actual ResultTransformer that will be used to transform query results.
/// </summary>
/// <param name="resultTransformer">The specified result transformer.</param>
/// <returns>The actual result transformer.</returns>
protected virtual IResultTransformer ResolveResultTransformer(IResultTransformer resultTransformer)
{
return resultTransformer;
}
/// <summary>
/// Are rows transformed immediately after being read from the ResultSet?
/// </summary>
/// <returns>True, if getResultColumnOrRow() transforms the results; false, otherwise</returns>
protected virtual bool AreResultSetRowsTransformedImmediately()
{
return false;
}
public virtual IList GetResultList(IList results, IResultTransformer resultTransformer)
{
return results;
}
/// <summary>
/// Returns the aliases that correspond to a result row.
/// </summary>
/// <returns>Returns the aliases that correspond to a result row.</returns>
protected virtual string[] ResultRowAliases
{
get { return null; }
}
/// <summary>
/// Get the actual object that is returned in the user-visible result list.
/// </summary>
/// <remarks>
/// This empty implementation merely returns its first argument. This is
/// overridden by some subclasses.
/// </remarks>
protected virtual object GetResultColumnOrRow(object[] row, IResultTransformer resultTransformer, DbDataReader rs, ISessionImplementor session)
{
return row;
}
protected virtual bool[] IncludeInResultRow
{
get { return null; }
}
protected virtual object[] GetResultRow(Object[] row, DbDataReader rs, ISessionImplementor session)
{
return row;
}
/// <summary>
/// For missing objects associated with another object in the
/// result set, register the fact that the the object is missing with the
/// session.
/// </summary>
private void RegisterNonExists(EntityKey[] keys, ISessionImplementor session)
{
var owners = Owners;
var ownerAssociationTypes = OwnerAssociationTypes;
if (owners != null && ownerAssociationTypes != null)
{
for (var i = 0; i < keys.Length; i++)
{
if (keys[i] == null)
{
var ownerAssociationType = ownerAssociationTypes[i];
if (ownerAssociationType?.PropertyName != null && ownerAssociationType.IsNullable)
{
var owner = owners[i];
if (owner > -1)
{
var ownerKey = keys[owner];
if (ownerKey != null)
{
session.PersistenceContext.AddNullProperty(ownerKey, ownerAssociationType.PropertyName);
}
}
}
}
}
}
}
/// <summary>
/// Read one collection element from the current row of the ADO.NET result set
/// </summary>
private static IPersistentCollection ReadCollectionElement(object optionalOwner, object optionalKey, ICollectionPersister persister,
ICollectionAliases descriptor, DbDataReader rs, ISessionImplementor session)
{
IPersistenceContext persistenceContext = session.PersistenceContext;
object collectionRowKey = persister.ReadKey(rs, descriptor.SuffixedKeyAliases, session);
if (collectionRowKey != null)
{
// we found a collection element in the result set
if (Log.IsDebugEnabled())
{
Log.Debug("found row of collection: {0}", MessageHelper.CollectionInfoString(persister, collectionRowKey));
}
object owner = optionalOwner;
if (owner == null)
{
owner = persistenceContext.GetCollectionOwner(collectionRowKey, persister);
if (owner == null)
{
//TODO: This is assertion is disabled because there is a bug that means the
// original owner of a transient, uninitialized collection is not known
// if the collection is re-referenced by a different object associated
// with the current Session
//throw new AssertionFailure("bug loading unowned collection");
}
}
IPersistentCollection rowCollection =
persistenceContext.LoadContexts.GetCollectionLoadContext(rs).GetLoadingCollection(persister, collectionRowKey);
if (rowCollection != null)
{
rowCollection.ReadFrom(rs, persister, descriptor, owner);
}
return rowCollection;
}
else if (optionalKey != null)
{
// we did not find a collection element in the result set, so we
// ensure that a collection is created with the owner's identifier,
// since what we have is an empty collection
if (Log.IsDebugEnabled())
{
Log.Debug("result set contains (possibly empty) collection: {0}", MessageHelper.CollectionInfoString(persister, optionalKey));
}
// handle empty collection
return persistenceContext.LoadContexts.GetCollectionLoadContext(rs).GetLoadingCollection(persister, optionalKey);
}
// else no collection element, but also no owner
return null;
}
/// <summary>
/// If this is a collection initializer, we need to tell the session that a collection
/// is being initialized, to account for the possibility of the collection having
/// no elements (hence no rows in the result set).
/// </summary>
public void HandleEmptyCollections(object[] keys, object resultSetId, ISessionImplementor session)
{
if (keys != null)
{
// this is a collection initializer, so we must create a collection
// for each of the passed-in keys, to account for the possibility
// that the collection is empty and has no rows in the result set
ICollectionPersister[] collectionPersisters = CollectionPersisters;
for (int j = 0; j < collectionPersisters.Length; j++)
{
for (int i = 0; i < keys.Length; i++)
{
// handle empty collections
if (Log.IsDebugEnabled())
{
Log.Debug("result set contains (possibly empty) collection: {0}",
MessageHelper.CollectionInfoString(collectionPersisters[j], keys[i]));
}
session.PersistenceContext.LoadContexts.GetCollectionLoadContext((DbDataReader)resultSetId).GetLoadingCollection(
collectionPersisters[j], keys[i]);
}
}
}
// else this is not a collection initializer (and empty collections will
// be detected by looking for the owner's identifier in the result set)
}
/// <summary>
/// Read a row of <c>EntityKey</c>s from the <c>DbDataReader</c> into the given array.
/// </summary>
/// <remarks>
/// Warning: this method is side-effecty. If an <c>id</c> is given, don't bother going
/// to the <c>DbDataReader</c>
/// </remarks>
private EntityKey GetKeyFromResultSet(int i, IEntityPersister persister, object id, DbDataReader rs, ISessionImplementor session)
{
object resultId;
// if we know there is exactly 1 row, we can skip.
// it would be great if we could _always_ skip this;
// it is a problem for <key-many-to-one>
if (IsSingleRowLoader && id != null)
{
resultId = id;
}
else
{
IType idType = persister.IdentifierType;
resultId = idType.NullSafeGet(rs, EntityAliases[i].SuffixedKeyAliases, session, null);
bool idIsResultId = id != null && resultId != null && idType.IsEqual(id, resultId, _factory);
if (idIsResultId)
{
resultId = id; //use the id passed in
}
}
return resultId == null ? null : session.GenerateEntityKey(resultId, persister);
}
/// <summary>
/// Check the version of the object in the <c>DbDataReader</c> against
/// the object version in the session cache, throwing an exception
/// if the version numbers are different.
/// </summary>
/// <exception cref="StaleObjectStateException"></exception>
private void CheckVersion(int i, IEntityPersister persister, object id, object entity, DbDataReader rs, ISessionImplementor session)
{
object version = session.PersistenceContext.GetEntry(entity).Version;
// null version means the object is in the process of being loaded somewhere else in the ResultSet
if (version != null)
{
IVersionType versionType = persister.VersionType;
object currentVersion = versionType.NullSafeGet(rs, EntityAliases[i].SuffixedVersionAliases, session, null);
if (!versionType.IsEqual(version, currentVersion))
{
if (session.Factory.Statistics.IsStatisticsEnabled)
{
session.Factory.StatisticsImplementor.OptimisticFailure(persister.EntityName);
}
throw new StaleObjectStateException(persister.EntityName, id);
}
}
}
/// <summary>
/// Resolve any ids for currently loaded objects, duplications within the <c>DbDataReader</c>,
/// etc. Instantiate empty objects to be initialized from the <c>DbDataReader</c>. Return an
/// array of objects (a row of results) and an array of booleans (by side-effect) that determine