forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSessionImpl.cs
2514 lines (2223 loc) · 66.6 KB
/
SessionImpl.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.Expressions;
using System.Runtime.Serialization;
using System.Security;
using NHibernate.AdoNet;
using NHibernate.Collection;
using NHibernate.Criterion;
using NHibernate.Engine;
using NHibernate.Engine.Query;
using NHibernate.Engine.Query.Sql;
using NHibernate.Event;
using NHibernate.Hql;
using NHibernate.Intercept;
using NHibernate.Loader.Criteria;
using NHibernate.Loader.Custom;
using NHibernate.MultiTenancy;
using NHibernate.Persister.Collection;
using NHibernate.Persister.Entity;
using NHibernate.Proxy;
using NHibernate.Stat;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Impl
{
/// <summary>
/// Concrete implementation of an <see cref="ISession" />, also the central, organizing component
/// of NHibernate's internal implementation.
/// </summary>
/// <remarks>
/// Exposes two interfaces: <see cref="ISession" /> itself, to the application and
/// <see cref="ISessionImplementor" /> to other components of NHibernate. This is where the
/// hard stuff is... This class is NOT THREADSAFE.
/// </remarks>
[Serializable]
public sealed partial class SessionImpl : AbstractSessionImpl, IEventSource, ISerializable, IDeserializationCallback
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(SessionImpl));
private CacheMode cacheMode = CacheMode.Normal;
//Since 5.2
[Obsolete()]
[NonSerialized]
private FutureCriteriaBatch futureCriteriaBatch;
//Since 5.2
[Obsolete()]
[NonSerialized]
private FutureQueryBatch futureQueryBatch;
[NonSerialized]
private readonly EventListeners listeners;
[NonSerialized]
private readonly ActionQueue actionQueue;
[NonSerialized]
private int _suspendAutoFlushCount;
[NonSerialized]
private readonly IDictionary<string, IFilter> enabledFilters = new Dictionary<string, IFilter>();
[NonSerialized]
private readonly List<string> enabledFilterNames = new List<string>();
[NonSerialized]
private readonly StatefulPersistenceContext persistenceContext;
[NonSerialized]
private readonly bool autoCloseSessionEnabled;
[NonSerialized]
private readonly ConnectionReleaseMode connectionReleaseMode;
#region System.Runtime.Serialization.ISerializable Members
/// <summary>
/// Constructor used to recreate the Session during the deserialization.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
/// <remarks>
/// This is needed because we have to do some checking before the serialization process
/// begins. I don't know how to add logic in ISerializable.GetObjectData and have .net
/// write all of the serializable fields out.
/// </remarks>
private SessionImpl(SerializationInfo info, StreamingContext context)
{
Timestamp = info.GetInt64("timestamp");
SessionFactoryImpl fact = (SessionFactoryImpl)info.GetValue("factory", typeof(SessionFactoryImpl));
Factory = fact;
listeners = fact.EventListeners;
persistenceContext = (StatefulPersistenceContext)info.GetValue("persistenceContext", typeof(StatefulPersistenceContext));
actionQueue = (ActionQueue)info.GetValue("actionQueue", typeof(ActionQueue));
FlushMode = (FlushMode)info.GetValue("flushMode", typeof(FlushMode));
cacheMode = (CacheMode)info.GetValue("cacheMode", typeof(CacheMode));
Interceptor = (IInterceptor)info.GetValue("interceptor", typeof(IInterceptor));
enabledFilters = (IDictionary<string, IFilter>)info.GetValue("enabledFilters", typeof(Dictionary<string, IFilter>));
enabledFilterNames = (List<string>)info.GetValue("enabledFilterNames", typeof(List<string>));
ConnectionManager = (ConnectionManager)info.GetValue("connectionManager", typeof(ConnectionManager));
TenantConfiguration = info.GetValue<TenantConfiguration>(nameof(TenantConfiguration));
}
/// <summary>
/// Verify the ISession can be serialized and write the fields to the Serializer.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
/// <remarks>
/// The fields are marked with [NonSerializable] as just a point of reference. This method
/// has complete control and what is serialized and those attributes are ignored. However,
/// this method should be in sync with the attributes for easy readability.
/// </remarks>
[SecurityCritical]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
log.Debug("writting session to serializer");
if (!ConnectionManager.IsReadyForSerialization)
{
throw new InvalidOperationException("Cannot serialize a Session while connected");
}
if (IsTransactionCoordinatorShared)
{
throw new InvalidOperationException("Cannot serialize a Session sharing its transaction coordinator");
}
info.AddValue("factory", Factory, typeof(SessionFactoryImpl));
info.AddValue("persistenceContext", persistenceContext, typeof(StatefulPersistenceContext));
info.AddValue("actionQueue", actionQueue, typeof(ActionQueue));
info.AddValue("timestamp", Timestamp);
info.AddValue("flushMode", FlushMode);
info.AddValue("cacheMode", cacheMode);
info.AddValue("interceptor", Interceptor, typeof(IInterceptor));
info.AddValue("enabledFilters", enabledFilters, typeof(IDictionary<string, IFilter>));
info.AddValue("enabledFilterNames", enabledFilterNames, typeof(List<string>));
info.AddValue("connectionManager", ConnectionManager, typeof(ConnectionManager));
info.AddValue(nameof(TenantConfiguration), TenantConfiguration);
}
#endregion
#region System.Runtime.Serialization.IDeserializationCallback Members
/// <summary>
/// Once the entire object graph has been deserialized then we can hook the
/// collections, proxies, and entities back up to the ISession.
/// </summary>
/// <param name="sender"></param>
void IDeserializationCallback.OnDeserialization(object sender)
{
log.Debug("OnDeserialization of the session.");
persistenceContext.SetSession(this);
// OnDeserialization() must be called manually on all Dictionaries and Hashtables,
// otherwise they are still empty at this point (the .NET deserialization code calls
// OnDeserialization() on them AFTER it calls the current method).
((IDeserializationCallback)enabledFilters).OnDeserialization(sender);
foreach (string filterName in enabledFilterNames)
{
FilterImpl filter = (FilterImpl)enabledFilters[filterName];
filter.AfterDeserialize(Factory.GetFilterDefinition(filterName));
}
}
#endregion
/// <summary>
/// Constructor used for OpenSession(...) processing, as well as construction
/// of sessions for GetCurrentSession().
/// </summary>
/// <param name="factory">The factory from which this session was obtained.</param>
/// <param name="options">The options of the session.</param>
internal SessionImpl(SessionFactoryImpl factory, ISessionCreationOptions options)
: base(factory, options)
{
// This context is disposed only on session own disposal. This greatly reduces the number of context switches
// for most usual session usages. It may cause an irrelevant session id to be set back on disposal, but since all
// session entry points are supposed to set it, it should not have any consequences.
_context = SessionIdLoggingContext.CreateOrNull(SessionId);
try
{
actionQueue = new ActionQueue(this);
persistenceContext = new StatefulPersistenceContext(this);
autoCloseSessionEnabled = options.ShouldAutoClose;
listeners = factory.EventListeners;
connectionReleaseMode = options.SessionConnectionReleaseMode;
if (factory.Statistics.IsStatisticsEnabled)
{
factory.StatisticsImplementor.OpenSession();
}
log.Debug("[session-id={0}] opened session at timestamp: {1}, for session factory: [{2}/{3}]",
SessionId, Timestamp, factory.Name, factory.Uuid);
CheckAndUpdateSessionStatus();
}
catch
{
_context?.Dispose();
throw;
}
}
//Since 5.2
[Obsolete("Replaced by QueryBatch")]
public override FutureCriteriaBatch FutureCriteriaBatch
{
get
{
if (futureCriteriaBatch == null)
futureCriteriaBatch = new FutureCriteriaBatch(this);
return futureCriteriaBatch;
}
protected internal set
{
futureCriteriaBatch = value;
}
}
//Since 5.2
[Obsolete("Replaced by QueryBatch")]
public override FutureQueryBatch FutureQueryBatch
{
get
{
if (futureQueryBatch == null)
futureQueryBatch = new FutureQueryBatch(this);
return futureQueryBatch;
}
protected internal set
{
futureQueryBatch = value;
}
}
public ConnectionReleaseMode ConnectionReleaseMode
{
get { return connectionReleaseMode; }
}
public bool IsAutoCloseSessionEnabled
{
get { return autoCloseSessionEnabled; }
}
public bool ShouldAutoClose
{
get { return IsAutoCloseSessionEnabled && !IsClosed; }
}
/// <summary>
/// Close the session and release all resources
/// <remarks>
/// Do not call this method inside a transaction scope, use <c>Dispose</c> instead, since
/// Close() is not aware of distributed transactions
/// </remarks>
/// </summary>
public DbConnection Close()
{
using (BeginContext())
{
log.Debug("closing session");
if (IsClosed)
{
throw new SessionException("Session was already closed");
}
if (Factory.Statistics.IsStatisticsEnabled)
{
Factory.StatisticsImplementor.CloseSession();
}
try
{
return CloseConnectionManager();
}
finally
{
SetClosed();
Cleanup();
}
}
}
/// <summary>
/// Ensure that the locks are downgraded to <see cref="LockMode.None"/>
/// and that all of the softlocks in the <see cref="Cache"/> have
/// been released.
/// </summary>
public override void AfterTransactionCompletion(bool success, ITransaction tx)
{
using (BeginContext())
{
log.Debug("transaction completion");
persistenceContext.AfterTransactionCompletion();
actionQueue.AfterTransactionCompletion(success);
if (Factory.Statistics.IsStatisticsEnabled)
{
Factory.StatisticsImplementor.EndTransaction(success);
}
try
{
Interceptor.AfterTransactionCompletion(tx);
}
catch (Exception t)
{
log.Error(t, "exception in interceptor afterTransactionCompletion()");
}
if (IsClosed)
{
// Cleanup was delayed to transaction completion, do it now.
persistenceContext.Clear();
}
//if (autoClear)
// Clear();
}
}
private void Cleanup()
{
// Let the after tran clear that if we are still in an active system transaction.
if (TransactionContext?.IsInActiveTransaction == true)
return;
persistenceContext.Clear();
}
public LockMode GetCurrentLockMode(object obj)
{
using (BeginProcess())
{
if (obj == null)
{
throw new ArgumentNullException("obj", "null object passed to GetCurrentLockMode");
}
if (obj.IsProxy())
{
var proxy = obj as INHibernateProxy;
obj = proxy.HibernateLazyInitializer.GetImplementation(this);
if (obj == null)
{
return LockMode.None;
}
}
EntityEntry e = persistenceContext.GetEntry(obj);
if (e == null)
{
throw new TransientObjectException("Given object not associated with the session");
}
if (e.Status != Status.Loaded)
{
throw new ObjectDeletedException("The given object was deleted", e.Id, e.EntityName);
}
return e.LockMode;
}
}
public override bool IsOpen
{
get { return !IsClosed; }
}
/// <summary>
/// Save a transient object. An id is generated, assigned to the object and returned
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public object Save(object obj)
{
using (BeginProcess())
{
return FireSave(new SaveOrUpdateEvent(null, obj, this));
}
}
public object Save(string entityName, object obj)
{
using (BeginProcess())
{
return FireSave(new SaveOrUpdateEvent(entityName, obj, this));
}
}
public void Save(string entityName, object obj, object id)
{
using (BeginProcess())
{
FireSave(new SaveOrUpdateEvent(entityName, obj, id, this));
}
}
/// <summary>
/// Save a transient object with a manually assigned ID
/// </summary>
/// <param name="obj"></param>
/// <param name="id"></param>
public void Save(object obj, object id)
{
using (BeginProcess())
{
FireSave(new SaveOrUpdateEvent(null, obj, id, this));
}
}
/// <summary>
/// Delete a persistent object
/// </summary>
/// <param name="obj"></param>
public void Delete(object obj)
{
using (BeginProcess())
{
FireDelete(new DeleteEvent(obj, this));
}
}
/// <summary> Delete a persistent object (by explicit entity name)</summary>
public void Delete(string entityName, object obj)
{
using (BeginProcess())
{
FireDelete(new DeleteEvent(entityName, obj, this));
}
}
public void Update(object obj)
{
using (BeginProcess())
{
FireUpdate(new SaveOrUpdateEvent(null, obj, this));
}
}
public void Update(string entityName, object obj)
{
using (BeginProcess())
{
FireUpdate(new SaveOrUpdateEvent(entityName, obj, this));
}
}
public void Update(string entityName, object obj, object id)
{
using (BeginProcess())
{
FireUpdate(new SaveOrUpdateEvent(entityName, obj, id, this));
}
}
public void SaveOrUpdate(object obj)
{
using (BeginProcess())
{
FireSaveOrUpdate(new SaveOrUpdateEvent(null, obj, this));
}
}
public void SaveOrUpdate(string entityName, object obj)
{
using (BeginProcess())
{
FireSaveOrUpdate(new SaveOrUpdateEvent(entityName, obj, this));
}
}
public void SaveOrUpdate(string entityName, object obj, object id)
{
using (BeginProcess())
{
FireSaveOrUpdate(new SaveOrUpdateEvent(entityName, obj, id, this));
}
}
public void Update(object obj, object id)
{
using (BeginProcess())
{
FireUpdate(new SaveOrUpdateEvent(null, obj, id, this));
}
}
private static readonly object[] NoArgs = Array.Empty<object>();
private static readonly IType[] NoTypes = Array.Empty<IType>();
IList Find(string query, object[] values, IType[] types)
{
using (BeginProcess())
{
return List(query.ToQueryExpression(), new QueryParameters(types, values));
}
}
public override void CloseSessionFromSystemTransaction()
{
Dispose(true);
}
public override void List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results)
{
List(queryExpression, queryParameters, results, null);
}
protected override void ListFilter(object collection, IQueryExpression queryExpression, QueryParameters queryParameters, IList results)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
List(queryExpression, queryParameters, results, collection);
}
private void List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results, object filterConnection)
{
using (BeginProcess())
{
queryParameters.ValidateParameters();
var isFilter = filterConnection != null;
var plan = isFilter
? GetFilterQueryPlan(filterConnection, queryExpression, queryParameters, false)
: GetHQLQueryPlan(queryExpression, false);
// GetFilterQueryPlan has already auto flushed or fully flush.
if (!isFilter)
AutoFlushIfRequired(plan.QuerySpaces);
bool success = false;
using (SuspendAutoFlush()) //stops flush being called multiple times if this method is recursively called
{
try
{
plan.PerformList(queryParameters, this, results);
success = true;
}
catch (HibernateException)
{
// Do not call Convert on HibernateExceptions
throw;
}
catch (Exception e)
{
throw Convert(e, "Could not execute query");
}
finally
{
AfterOperation(success);
}
}
}
}
// Since v5.2
[Obsolete("This method has no usages and will be removed in a future version")]
public override IQueryTranslator[] GetQueries(IQueryExpression query, bool scalar)
{
using (BeginProcess())
{
var plan = Factory.QueryPlanCache.GetHQLQueryPlan(query, scalar, enabledFilters);
AutoFlushIfRequired(plan.QuerySpaces);
return plan.Translators;
}
}
public override IEnumerable<T> Enumerable<T>(IQueryExpression queryExpression, QueryParameters queryParameters)
{
using (BeginProcess())
{
queryParameters.ValidateParameters();
var plan = GetHQLQueryPlan(queryExpression, true);
AutoFlushIfRequired(plan.QuerySpaces);
using (SuspendAutoFlush()) //stops flush being called multiple times if this method is recursively called
{
return plan.PerformIterate<T>(queryParameters, this);
}
}
}
public override IEnumerable Enumerable(IQueryExpression queryExpression, QueryParameters queryParameters)
{
using (BeginProcess())
{
queryParameters.ValidateParameters();
var plan = GetHQLQueryPlan(queryExpression, true);
AutoFlushIfRequired(plan.QuerySpaces);
using (SuspendAutoFlush()) //stops flush being called multiple times if this method is recursively called
{
return plan.PerformIterate(queryParameters, this);
}
}
}
// TODO: Scroll(string query, QueryParameters queryParameters)
public int Delete(string query)
{
return Delete(query, NoArgs, NoTypes);
}
public int Delete(string query, object value, IType type)
{
return Delete(query, new[] { value }, new[] { type });
}
public int Delete(string query, object[] values, IType[] types)
{
using (BeginProcess())
{
if (string.IsNullOrEmpty(query))
{
throw new ArgumentNullException("query", "attempt to perform delete-by-query with null query");
}
if (log.IsDebugEnabled())
{
log.Debug("delete: {0}", query);
if (values.Length != 0)
{
log.Debug("parameters: {0}", StringHelper.ToString(values));
}
}
IList list = Find(query, values, types);
int count = list.Count;
for (int i = 0; i < count; i++)
{
Delete(list[i]);
}
return count;
}
}
public void Lock(object obj, LockMode lockMode)
{
using (BeginProcess())
{
FireLock(new LockEvent(obj, lockMode, this));
}
}
public void Lock(string entityName, object obj, LockMode lockMode)
{
using (BeginProcess())
{
FireLock(new LockEvent(entityName, obj, lockMode, this));
}
}
public IQuery CreateFilter(object collection, string queryString)
{
using (BeginProcess())
{
var plan = GetFilterQueryPlan(collection, queryString, null, false);
var filter = new CollectionFilterImpl(queryString, collection, this, plan.ParameterMetadata);
//filter.SetComment(queryString);
return filter;
}
}
public override IQuery CreateFilter(object collection, IQueryExpression queryExpression)
{
using (BeginProcess())
{
var plan = GetFilterQueryPlan(collection, queryExpression, null, false);
var filter = new ExpressionFilterImpl(plan.QueryExpression, collection, this, plan.ParameterMetadata);
return filter;
}
}
private IQueryExpressionPlan GetFilterQueryPlan(object collection, IQueryExpression queryExpression, QueryParameters parameters, bool shallow)
{
return GetFilterQueryPlan(collection, parameters, shallow, null, queryExpression);
}
private IQueryExpressionPlan GetFilterQueryPlan(object collection, string filter, QueryParameters parameters, bool shallow)
{
return GetFilterQueryPlan(collection, parameters, shallow, filter, null);
}
private IQueryExpressionPlan GetFilterQueryPlan(object collection, QueryParameters parameters, bool shallow,
string filter, IQueryExpression queryExpression)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection), "null collection passed to filter");
if (filter != null && queryExpression != null)
throw new ArgumentException($"Either {nameof(filter)} or {nameof(queryExpression)} must be specified, not both.");
if (filter == null && queryExpression == null)
throw new ArgumentException($"{nameof(filter)} and {nameof(queryExpression)} were both null.");
var entry = persistenceContext.GetCollectionEntryOrNull(collection);
var roleBeforeFlush = entry?.LoadedPersister;
IQueryExpressionPlan plan;
if (roleBeforeFlush == null)
{
// if it was previously unreferenced, we need to flush in order to
// get its state into the database in order to execute query
Flush();
entry = persistenceContext.GetCollectionEntryOrNull(collection);
var roleAfterFlush = entry?.LoadedPersister;
if (roleAfterFlush == null)
{
throw new QueryException("The collection was unreferenced");
}
plan = GetFilterQueryPlan(roleAfterFlush.Role, shallow, filter, queryExpression);
}
else
{
// otherwise, we only need to flush if there are in-memory changes
// to the queried tables
plan = GetFilterQueryPlan(roleBeforeFlush.Role, shallow, filter, queryExpression);
if (AutoFlushIfRequired(plan.QuerySpaces))
{
// might need to run a different filter entirely after the flush
// because the collection role may have changed
entry = persistenceContext.GetCollectionEntryOrNull(collection);
var roleAfterFlush = entry?.LoadedPersister;
if (roleBeforeFlush != roleAfterFlush)
{
if (roleAfterFlush == null)
{
throw new QueryException("The collection was dereferenced");
}
plan = GetFilterQueryPlan(roleAfterFlush.Role, shallow, filter, queryExpression);
}
}
}
if (parameters != null)
{
parameters.PositionalParameterValues[0] = entry.LoadedKey;
parameters.PositionalParameterTypes[0] = entry.LoadedPersister.KeyType;
}
return plan;
}
private IQueryExpressionPlan GetFilterQueryPlan(string role, bool shallow, string filter, IQueryExpression queryExpression)
{
return filter == null
? Factory.QueryPlanCache.GetFilterQueryPlan(queryExpression, role, shallow, EnabledFilters)
: Factory.QueryPlanCache.GetFilterQueryPlan(filter, role, shallow, EnabledFilters);
}
//Since 5.3
[Obsolete("Use override with persister parameter")]
public override object Instantiate(string clazz, object id)
{
using (BeginProcess())
{
return Instantiate(Factory.GetEntityPersister(clazz), id);
}
}
/// <summary> Get the ActionQueue for this session</summary>
public ActionQueue ActionQueue
{
get
{
CheckAndUpdateSessionStatus();
return actionQueue;
}
}
/// <summary>
/// Give the interceptor an opportunity to override the default instantiation
/// </summary>
/// <param name="persister"></param>
/// <param name="id"></param>
/// <returns></returns>
public override object Instantiate(IEntityPersister persister, object id)
{
using (BeginProcess())
{
object result = Interceptor.Instantiate(persister.EntityName, id);
if (result == null)
{
result = persister.Instantiate(id);
}
return result;
}
}
#region IEventSource Members
/// <summary> Force an immediate flush</summary>
public void ForceFlush(EntityEntry entityEntry)
{
using (BeginProcess())
{
if (log.IsDebugEnabled())
{
log.Debug("flushing to force deletion of re-saved object: {0}",
MessageHelper.InfoString(entityEntry.Persister, entityEntry.Id, Factory));
}
if (persistenceContext.CascadeLevel > 0)
{
throw new ObjectDeletedException(
"deleted object would be re-saved by cascade (remove deleted object from associations)",
entityEntry.Id,
entityEntry.EntityName);
}
Flush();
}
}
/// <summary> Cascade merge an entity instance</summary>
public void Merge(string entityName, object obj, IDictionary copiedAlready)
{
using (BeginProcess())
{
FireMerge(copiedAlready, new MergeEvent(entityName, obj, this));
}
}
/// <summary> Cascade persist an entity instance</summary>
public void Persist(string entityName, object obj, IDictionary createdAlready)
{
using (BeginProcess())
{
FirePersist(createdAlready, new PersistEvent(entityName, obj, this));
}
}
/// <summary> Cascade persist an entity instance during the flush process</summary>
public void PersistOnFlush(string entityName, object obj, IDictionary copiedAlready)
{
using (BeginProcess())
{
FirePersistOnFlush(copiedAlready, new PersistEvent(entityName, obj, this));
}
}
/// <summary> Cascade refresh an entity instance</summary>
public void Refresh(object obj, IDictionary refreshedAlready)
{
using (BeginProcess())
{
FireRefresh(refreshedAlready, new RefreshEvent(obj, this));
}
}
/// <summary> Cascade delete an entity instance</summary>
public void Delete(string entityName, object child, bool isCascadeDeleteEnabled, ISet<object> transientEntities)
{
using (BeginProcess())
{
FireDelete(new DeleteEvent(entityName, child, isCascadeDeleteEnabled, this), transientEntities);
}
}
/// <inheritdoc/>
public bool AutoFlushSuspended => _suspendAutoFlushCount != 0;
/// <inheritdoc/>
public IDisposable SuspendAutoFlush()
{
return new SuspendAutoFlushHelper(this);
}
private sealed class SuspendAutoFlushHelper : IDisposable
{
private SessionImpl _session;
public SuspendAutoFlushHelper(SessionImpl session)
{
_session = session;
_session._suspendAutoFlushCount++;
}
public void Dispose()
{
if (_session == null)
throw new ObjectDisposedException("The auto-flush suspension helper has been disposed already");
_session._suspendAutoFlushCount--;
_session = null;
}
}
#endregion
public object Merge(string entityName, object obj)
{
using (BeginProcess())
{
return FireMerge(new MergeEvent(entityName, obj, this));
}
}
public T Merge<T>(T entity) where T : class
{
return (T)Merge((object)entity);
}
public T Merge<T>(string entityName, T entity) where T : class
{
return (T)Merge(entityName, (object)entity);
}
public object Merge(object obj)
{
return Merge(null, obj);
}
public void Persist(string entityName, object obj)
{
using (BeginProcess())
{
FirePersist(new PersistEvent(entityName, obj, this));
}
}
public void Persist(object obj)
{
Persist(null, obj);
}
public void PersistOnFlush(string entityName, object obj)
{
using (BeginProcess())
{
FirePersistOnFlush(new PersistEvent(entityName, obj, this));
}
}
public void PersistOnFlush(object obj)
{
Persist(null, obj);
}
// Obsolete in v5, and was already having no usages previously.
[Obsolete("Please use FlushMode instead.")]
public bool FlushBeforeCompletionEnabled => FlushMode >= FlushMode.Commit;
public override string BestGuessEntityName(object entity)
{
using (BeginContext())
{
if (entity.IsProxy())
{
INHibernateProxy proxy = entity as INHibernateProxy;
ILazyInitializer initializer = proxy.HibernateLazyInitializer;
// it is possible for this method to be called during flush processing,
// so make certain that we do not accidentally initialize an uninitialized proxy
if (initializer.IsUninitialized)
{
return initializer.PersistentClass.FullName;
}
entity = initializer.GetImplementation();
}
if (entity is IFieldInterceptorAccessor interceptorAccessor && interceptorAccessor.FieldInterceptor != null)
{
// NH: support of field-interceptor-proxy
return interceptorAccessor.FieldInterceptor.EntityName;
}
EntityEntry entry = persistenceContext.GetEntry(entity);
if (entry == null)
{
return GuessEntityName(entity);
}
else
{
return entry.Persister.EntityName;
}
}
}
public override string GuessEntityName(object entity)
{
using (BeginContext())
{
string entityName = Interceptor.GetEntityName(entity);
if (entityName == null)
{
System.Type t = entity.GetType();