forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJoinWalker.cs
1308 lines (1138 loc) · 37.9 KB
/
JoinWalker.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.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NHibernate.Collection;
using NHibernate.Engine;
using NHibernate.Persister.Collection;
using NHibernate.Persister.Entity;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.Util;
namespace NHibernate.Loader
{
public class JoinWalker
{
private readonly ISessionFactoryImplementor factory;
protected readonly IList<OuterJoinableAssociation> associations = new List<OuterJoinableAssociation>();
private readonly HashSet<AssociationKey> visitedAssociationKeys = new HashSet<AssociationKey>();
private readonly IDictionary<string, IFilter> enabledFilters;
private readonly IDictionary<string, IFilter> enabledFiltersForManyToOne;
private static readonly Regex aliasRegex = new Regex(@"[\w]+(?=\.)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private string[] suffixes;
private string[] collectionSuffixes;
private ILoadable[] persisters;
private int[] owners;
private EntityType[] ownerAssociationTypes;
private ICollectionPersister[] collectionPersisters;
private int[] collectionOwners;
private string[] aliases;
private LockMode[] lockModeArray;
private SqlString sql;
private readonly Queue<IJoinQueueEntry> _joinQueue = new();
private int _depth;
public string[] CollectionSuffixes
{
get { return collectionSuffixes; }
set { collectionSuffixes = value; }
}
public LockMode[] LockModeArray
{
get { return lockModeArray; }
set { lockModeArray = value; }
}
public string[] Suffixes
{
get { return suffixes; }
set { suffixes = value; }
}
public string[] Aliases
{
get { return aliases; }
set { aliases = value; }
}
public bool[] EagerPropertyFetches { get; set; }
public bool[] ChildFetchEntities { get; set; }
public ISet<string>[] EntityFetchLazyProperties { get; set; }
public int[] CollectionOwners
{
get { return collectionOwners; }
set { collectionOwners = value; }
}
public ICollectionPersister[] CollectionPersisters
{
get { return collectionPersisters; }
set { collectionPersisters = value; }
}
public EntityType[] OwnerAssociationTypes
{
get { return ownerAssociationTypes; }
set { ownerAssociationTypes = value; }
}
public int[] Owners
{
get { return owners; }
set { owners = value; }
}
public ILoadable[] Persisters
{
get { return persisters; }
set { persisters = value; }
}
public SqlString SqlString
{
get { return sql; }
set { sql = value; }
}
protected ISessionFactoryImplementor Factory
{
get { return factory; }
}
protected Dialect.Dialect Dialect
{
get { return factory.Dialect; }
}
protected IDictionary<string, IFilter> EnabledFilters
{
get { return enabledFilters; }
}
protected virtual bool IsTooManyCollections
{
get { return false; }
}
//Since v5.3
[Obsolete("This class is not used and will be removed in a future version.")]
public class DependentAlias
{
public string Alias { get; set; }
public string[] DependsOn { get; set; }
}
protected JoinWalker(ISessionFactoryImplementor factory, IDictionary<string, IFilter> enabledFilters)
{
this.factory = factory;
this.enabledFilters = enabledFilters;
enabledFiltersForManyToOne = FilterHelper.GetEnabledForManyToOne(enabledFilters);
}
/// <summary>
/// Add on association (one-to-one, many-to-one, or a collection) to a list
/// of associations to be fetched by outerjoin (if necessary)
/// </summary>
private void AddAssociationToJoinTreeIfNecessary(IAssociationType type, string[] aliasedLhsColumns,
string alias, string path, string pathAlias, JoinType joinType)
{
if (joinType >= JoinType.InnerJoin)
{
AddAssociationToJoinTree(type, aliasedLhsColumns, alias, path, pathAlias, joinType);
}
}
// Since v5.2
[Obsolete("Use or override the overload taking a pathAlias additional parameter")]
protected virtual SqlString GetWithClause(string path)
{
return SqlString.Empty;
}
protected virtual SqlString GetWithClause(string path, string pathAlias)
{
// 6.0 TODO: inline the call
#pragma warning disable 618
return GetWithClause(path);
#pragma warning restore 618
}
/// <summary>
/// Add on association (one-to-one, many-to-one, or a collection) to a list
/// of associations to be fetched by outerjoin
/// </summary>
private void AddAssociationToJoinTree(IAssociationType type, string[] aliasedLhsColumns, string alias,
string path, string pathAlias, JoinType joinType)
{
IJoinable joinable = type.GetAssociatedJoinable(Factory);
string subalias = GenerateTableAlias(associations.Count + 1, path, pathAlias, joinable);
var qc = joinable.IsCollection ? (IQueryableCollection) joinable : null;
var assoc =
InitAssociation(
new OuterJoinableAssociation(
type,
alias,
aliasedLhsColumns,
subalias,
joinType,
//for many-to-many with clause is applied with OuterJoinableAssociation created for entity persister so simply skip it here
qc?.IsManyToMany == true ? null :GetWithClause(path, pathAlias),
Factory,
enabledFilters,
GetSelectMode(path)),
path);
assoc.ValidateJoin(path);
AddAssociation(assoc);
if (qc != null)
{
var collection = new CollectionJoinQueueEntry(qc, subalias, path, pathAlias);
// Many-to-Many element entity join needs to be added right after collection bridge table
// (see IsManyToManyWith, ManyToManySelectFragment, IsManyToManyRoot usages)
if (qc.IsManyToMany)
{
collection.Walk(this);
return;
}
_joinQueue.Enqueue(collection);
}
else if (joinable is IOuterJoinLoadable jl)
{
_joinQueue.Enqueue(new EntityJoinQueueEntry(jl, subalias, path));
}
}
protected virtual SelectMode GetSelectMode(string path)
{
return SelectMode.Undefined;
}
protected virtual ISet<string> GetEntityFetchLazyProperties(string path)
{
return null;
}
private struct DependentAlias2
{
public DependentAlias2(string alias, ICollection<string> dependsOn)
{
Alias = alias;
DependsOn = dependsOn;
}
public string Alias { get; }
public ICollection<string> DependsOn { get; }
}
/// <summary>
/// Returns list of indexes in sorted order
/// </summary>
private static int[] GetTopologicalSortOrder(IList<DependentAlias2> fields)
{
TopologicalSorter g = new TopologicalSorter(fields.Count);
Dictionary<string, int> indexes = new Dictionary<string, int>(fields.Count, StringComparer.OrdinalIgnoreCase);
// add vertices
for (int i = 0; i < fields.Count; i++)
{
indexes[fields[i].Alias] = g.AddVertex(i);
}
// add edges
for (int i = 0; i < fields.Count; i++)
{
var dependentFields = fields[i].DependsOn;
if (dependentFields != null)
{
foreach (var dependentField in dependentFields)
{
if (indexes.TryGetValue(dependentField, out var end))
{
g.AddEdge(i, end);
}
}
}
}
return g.Sort();
}
private static List<DependentAlias2> GetDependentAliases(IList<OuterJoinableAssociation> associations)
{
var dependentAliases = new List<DependentAlias2>(associations.Count);
foreach (var association in associations)
{
dependentAliases.Add(new DependentAlias2(association.RHSAlias, GetDependsOn(association)));
}
return dependentAliases;
}
private static HashSet<string> GetDependsOn(OuterJoinableAssociation association)
{
if (SqlStringHelper.IsEmpty(association.On))
return null;
var dependencies = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (Match match in aliasRegex.Matches(association.On.ToString()))
{
string alias = match.Value;
if (string.Equals(alias, association.RHSAlias, StringComparison.OrdinalIgnoreCase))
continue;
dependencies.Add(alias);
}
return dependencies;
}
/// <summary>
/// Adds an association
/// </summary>
private void AddAssociation(OuterJoinableAssociation association)
{
associations.Add(association);
}
/// <summary>
/// For an entity class, return a list of associations to be fetched by outerjoin
/// </summary>
protected void WalkEntityTree(IOuterJoinLoadable persister, string alias)
{
WalkEntityTree(persister, alias, String.Empty);
ProcessJoins();
}
/// <summary>
/// For a collection role, return a list of associations to be fetched by outerjoin
/// </summary>
protected void WalkCollectionTree(IQueryableCollection persister, string alias)
{
WalkCollectionTree(persister, alias, String.Empty, String.Empty);
ProcessJoins();
}
protected void ProcessJoins()
{
while (_joinQueue.Count > 0)
{
var entry = _joinQueue.Dequeue();
entry.Walk(this);
}
}
/// <summary>
/// For a collection role, return a list of associations to be fetched by outerjoin
/// </summary>
private void WalkCollectionTree(IQueryableCollection persister, string alias, string path, string pathAlias)
{
if (persister.IsOneToMany)
{
WalkEntityTree((IOuterJoinLoadable) persister.ElementPersister, alias, path);
}
else
{
IType type = persister.ElementType;
if (type.IsAssociationType)
{
// a many-to-many
// decrement currentDepth here to allow join across the association table
// without exceeding MAX_FETCH_DEPTH (i.e. the "currentDepth - 1" bit)
IAssociationType associationType = (IAssociationType) type;
string[] aliasedLhsColumns = persister.GetElementColumnNames(alias);
string[] lhsColumns = persister.ElementColumnNames;
// if the current depth is 0, the root thing being loaded is the
// many-to-many collection itself. Here, it is alright to use
// an inner join...
bool useInnerJoin = _depth == 0;
var joinType =
GetJoinType(
associationType,
persister.FetchMode,
path,
pathAlias,
persister.TableName,
lhsColumns,
!useInnerJoin,
_depth - 1,
null);
AddAssociationToJoinTreeIfNecessary(
associationType,
aliasedLhsColumns,
alias,
path,
pathAlias,
joinType);
}
else if (type.IsComponentType)
{
_joinQueue.Enqueue(NextLevelJoinQueueEntry.Instance);
WalkCompositeElementTree(
(IAbstractComponentType) type,
persister.ElementColumnNames,
persister,
alias,
path);
}
}
}
internal void AddExplicitEntityJoinAssociation(
IOuterJoinLoadable persister,
string tableAlias,
JoinType joinType,
string path,
string pathAlias)
{
_depth = 0;
visitedAssociationKeys.Clear();
OuterJoinableAssociation assoc =
InitAssociation(new OuterJoinableAssociation(
persister.EntityType,
string.Empty,
Array.Empty<string>(),
tableAlias,
joinType,
GetWithClause(path, pathAlias),
Factory,
enabledFilters,
GetSelectMode(path)) {ForceFilter = true},
path);
AddAssociation(assoc);
}
internal OuterJoinableAssociation InitAssociation(OuterJoinableAssociation association, string path)
{
association.EntityFetchLazyProperties = GetEntityFetchLazyProperties(path);
return association;
}
private void WalkEntityAssociationTree(IAssociationType associationType, IOuterJoinLoadable persister,
int propertyNumber, string alias, string path, bool nullable,
ILhsAssociationTypeSqlInfo associationTypeSQLInfo)
{
string[] aliasedLhsColumns = associationTypeSQLInfo.GetAliasedColumnNames(associationType, 0);
string[] lhsColumns = associationTypeSQLInfo.GetColumnNames(associationType, 0);
string lhsTable = associationTypeSQLInfo.GetTableName(associationType);
string subpath = SubPath(path, persister.GetSubclassPropertyName(propertyNumber));
// Obtain children aliases for the current path and alias
var subPathAliases = GetChildAliases(alias, subpath);
foreach (var subPathAlias in subPathAliases)
{
var joinType = GetJoinType(
associationType,
persister.GetFetchMode(propertyNumber),
subpath,
subPathAlias,
lhsTable,
lhsColumns,
nullable,
_depth,
persister.GetCascadeStyle(propertyNumber));
AddAssociationToJoinTreeIfNecessary(
associationType,
aliasedLhsColumns,
alias,
subpath,
subPathAlias,
joinType);
}
}
/// <summary>
/// For an entity class, add to a list of associations to be fetched
/// by outerjoin
/// </summary>
protected virtual void WalkEntityTree(IOuterJoinLoadable persister, string alias, string path)
{
int n = persister.CountSubclassProperties();
_joinQueue.Enqueue(NextLevelJoinQueueEntry.Instance);
for (int i = 0; i < n; i++)
{
IType type = persister.GetSubclassPropertyType(i);
ILhsAssociationTypeSqlInfo associationTypeSQLInfo = JoinHelper.GetLhsSqlInfo(alias, i, persister, Factory);
if (type.IsAssociationType)
{
WalkEntityAssociationTree((IAssociationType) type, persister, i, alias, path,
persister.IsSubclassPropertyNullable(i), associationTypeSQLInfo);
}
else if (type.IsComponentType)
{
WalkComponentTree((IAbstractComponentType) type, 0, alias, SubPath(path, persister.GetSubclassPropertyName(i)),
associationTypeSQLInfo);
}
}
}
/// <summary>
/// For an entity class, add to a list of associations to be fetched
/// by outerjoin
/// </summary>
// Since 5.4
[Obsolete("Use or override the overload without the currentDepth parameter")]
protected virtual void WalkEntityTree(IOuterJoinLoadable persister, string alias, string path, int currentDepth)
{
WalkEntityTree(persister, alias, path);
}
/// <summary>
/// For a component, add to a list of associations to be fetched by outerjoin
/// </summary>
protected void WalkComponentTree(IAbstractComponentType componentType, int begin, string alias, string path,
ILhsAssociationTypeSqlInfo associationTypeSQLInfo)
{
IType[] types = componentType.Subtypes;
string[] propertyNames = componentType.PropertyNames;
for (int i = 0; i < types.Length; i++)
{
if (types[i].IsAssociationType)
{
var associationType = (IAssociationType) types[i];
string[] aliasedLhsColumns = associationTypeSQLInfo.GetAliasedColumnNames(associationType, begin);
string[] lhsColumns = associationTypeSQLInfo.GetColumnNames(associationType, begin);
string lhsTable = associationTypeSQLInfo.GetTableName(associationType);
string subpath = SubPath(path, propertyNames[i]);
bool[] propertyNullability = componentType.PropertyNullability;
// Obtain related aliases to the current path
var subPathAliases = GetChildAliases(alias, subpath);
foreach (var subPathAlias in subPathAliases)
{
var joinType = GetJoinType(
associationType,
componentType.GetFetchMode(i),
subpath,
subPathAlias,
lhsTable,
lhsColumns,
propertyNullability == null || propertyNullability[i],
_depth,
componentType.GetCascadeStyle(i));
AddAssociationToJoinTreeIfNecessary(
associationType,
aliasedLhsColumns,
alias,
subpath,
subPathAlias,
joinType);
}
}
else if (types[i].IsComponentType)
{
string subpath = SubPath(path, propertyNames[i]);
WalkComponentTree((IAbstractComponentType) types[i], begin, alias, subpath, associationTypeSQLInfo);
}
begin += types[i].GetColumnSpan(Factory);
}
}
/// <summary>
/// For a component, add to a list of associations to be fetched by outerjoin
/// </summary>
// Since 5.4
[Obsolete("Use or override the overload without the currentDepth parameter")]
protected void WalkComponentTree(IAbstractComponentType componentType, int begin, string alias, string path,
int currentDepth, ILhsAssociationTypeSqlInfo associationTypeSQLInfo)
{
WalkComponentTree(componentType, begin, alias, path, associationTypeSQLInfo);
}
/// <summary>
/// For a composite element, add to a list of associations to be fetched by outerjoin
/// </summary>
private void WalkCompositeElementTree(IAbstractComponentType compositeType, string[] cols,
IQueryableCollection persister, string alias, string path)
{
IType[] types = compositeType.Subtypes;
string[] propertyNames = compositeType.PropertyNames;
int begin = 0;
for (int i = 0; i < types.Length; i++)
{
int length = types[i].GetColumnSpan(factory);
string[] lhsColumns = ArrayHelper.Slice(cols, begin, length);
if (types[i].IsAssociationType)
{
IAssociationType associationType = types[i] as IAssociationType;
// simple, because we can't have a one-to-one or collection
// (or even a property-ref) in a composite element:
string[] aliasedLhsColumns = StringHelper.Qualify(alias, lhsColumns);
string subpath = SubPath(path, propertyNames[i]);
bool[] propertyNullability = compositeType.PropertyNullability;
var subPathAliases = GetChildAliases(alias, subpath);
foreach (var subPathAlias in subPathAliases)
{
var joinType =
GetJoinType(
associationType,
compositeType.GetFetchMode(i),
subpath,
subPathAlias,
persister.TableName,
lhsColumns,
propertyNullability == null || propertyNullability[i],
_depth,
compositeType.GetCascadeStyle(i));
AddAssociationToJoinTreeIfNecessary(
associationType,
aliasedLhsColumns,
alias,
subpath,
subPathAlias,
joinType);
}
}
else if (types[i].IsComponentType)
{
string subpath = SubPath(path, propertyNames[i]);
WalkCompositeElementTree(
(IAbstractComponentType) types[i],
lhsColumns,
persister,
alias,
subpath);
}
begin += length;
}
}
/// <summary>
/// Extend the path by the given property name
/// </summary>
protected static string SubPath(string path, string property)
{
if (string.IsNullOrEmpty(property))
return path;
return string.IsNullOrEmpty(path) ? property : StringHelper.Qualify(path, property);
}
/// <summary>
/// Get the join type (inner, outer, etc) or -1 if the
/// association should not be joined. Override on
/// subclasses.
/// </summary>
// Since v5.2
[Obsolete("Use or override the overload taking a pathAlias additional parameter")]
protected virtual JoinType GetJoinType(IAssociationType type, FetchMode config, string path, string lhsTable,
string[] lhsColumns, bool nullable, int currentDepth, CascadeStyle cascadeStyle)
{
if (!IsJoinedFetchEnabled(type, config, cascadeStyle))
return JoinType.None;
if (IsTooDeep(currentDepth) || (type.IsCollectionType && IsTooManyCollections))
return JoinType.None;
bool dupe = IsDuplicateAssociation(lhsTable, lhsColumns, type);
if (dupe)
return JoinType.None;
return GetJoinType(nullable, currentDepth);
}
/// <summary>
/// Get the join type (inner, outer, etc) or -1 if the
/// association should not be joined. Override on
/// subclasses.
/// </summary>
protected virtual JoinType GetJoinType(IAssociationType type, FetchMode config, string path, string pathAlias,
string lhsTable, string[] lhsColumns, bool nullable, int currentDepth, CascadeStyle cascadeStyle)
{
// 6.0 TODO: inline the call
#pragma warning disable 618
return GetJoinType(type, config, path, lhsTable, lhsColumns, nullable, currentDepth, cascadeStyle);
#pragma warning restore 618
}
// By default, multiple aliases for a child are not supported. There is only one and its value
// does not matter for default implementation.
private static readonly IReadOnlyCollection<string> DefaultChildAliases = new[] { string.Empty };
/// <summary>
/// Returns the child criteria aliases for a parent SQL alias and a child path.
/// </summary>
protected virtual IReadOnlyCollection<string> GetChildAliases(string parentSqlAlias, string childPath)
{
return DefaultChildAliases;
}
/// <summary>
/// Use an inner join if it is a non-null association and this
/// is the "first" join in a series
/// </summary>
protected JoinType GetJoinType(bool nullable, int currentDepth)
{
//TODO: this is too conservative; if all preceding joins were
// also inner joins, we could use an inner join here
return !nullable && currentDepth == 0 ? JoinType.InnerJoin : JoinType.LeftOuterJoin;
}
protected virtual bool IsTooDeep(int currentDepth)
{
int maxFetchDepth = Factory.Settings.MaximumFetchDepth;
return maxFetchDepth >= 0 && currentDepth >= maxFetchDepth;
}
/// <summary>
/// Does the mapping, and Hibernate default semantics, specify that
/// this association should be fetched by outer joining
/// </summary>
protected bool IsJoinedFetchEnabledInMapping(FetchMode config, IAssociationType type)
{
if (!type.IsEntityType && !type.IsCollectionType)
{
return false;
}
else
{
switch (config)
{
case FetchMode.Join:
return true;
case FetchMode.Select:
return false;
case FetchMode.Default:
if (type.IsEntityType)
{
//TODO: look at the owning property and check that it
// isn't lazy (by instrumentation)
EntityType entityType = (EntityType)type;
IEntityPersister persister = factory.GetEntityPersister(entityType.GetAssociatedEntityName());
return !persister.HasProxy;
}
else
{
return false;
}
default:
throw new ArgumentOutOfRangeException("config", config, "Unknown OJ strategy " + config);
}
}
}
/// <summary>
/// Override on subclasses to enable or suppress joining
/// of certain association types
/// </summary>
protected virtual bool IsJoinedFetchEnabled(IAssociationType type, FetchMode config,
CascadeStyle cascadeStyle)
{
return type.IsEntityType && IsJoinedFetchEnabledInMapping(config, type);
}
// Since v5.2
[Obsolete("Use or override the overload taking a pathAlias additional parameter")]
protected virtual string GenerateTableAlias(int n, string path, IJoinable joinable)
{
return StringHelper.GenerateAlias(joinable.Name, n);
}
protected virtual string GenerateTableAlias(int n, string path, string pathAlias, IJoinable joinable)
{
// 6.0 TODO: inline the call
#pragma warning disable 618
return GenerateTableAlias(n, path, joinable);
#pragma warning restore 618
}
protected virtual string GenerateRootAlias(string description)
{
return StringHelper.GenerateAlias(description, 0);
}
/// <summary>
/// Used to detect circularities in the joined graph, note that
/// this method is side-effecty
/// </summary>
protected virtual bool IsDuplicateAssociation(string foreignKeyTable, string[] foreignKeyColumns)
{
if (!Factory.Settings.DetectFetchLoops)
{
return false;
}
AssociationKey associationKey = new AssociationKey(foreignKeyColumns, foreignKeyTable);
return !visitedAssociationKeys.Add(associationKey);
}
/// <summary>
/// Used to detect circularities in the joined graph, note that
/// this method is side-effecty
/// </summary>
protected virtual bool IsDuplicateAssociation(string lhsTable, string[] lhsColumnNames, IAssociationType type)
{
string foreignKeyTable;
string[] foreignKeyColumns;
if (type.ForeignKeyDirection.Equals(ForeignKeyDirection.ForeignKeyFromParent))
{
foreignKeyTable = lhsTable;
foreignKeyColumns = lhsColumnNames;
}
else
{
var joinable = type.GetAssociatedJoinable(Factory);
foreignKeyTable = joinable.TableName;
foreignKeyColumns = JoinHelper.GetRHSColumnNames(joinable, type);
}
return IsDuplicateAssociation(foreignKeyTable, foreignKeyColumns);
}
/// <summary>
/// Uniquely identifier a foreign key, so that we don't
/// join it more than once, and create circularities
/// </summary>
protected sealed class AssociationKey
{
private readonly string[] columns;
private readonly string table;
private readonly int hashCode;
public AssociationKey(string[] columns, string table)
{
this.columns = columns;
this.table = table;
hashCode = table.GetHashCode();
}
public override bool Equals(object other)
{
AssociationKey that = other as AssociationKey;
if (that == null)
return false;
return that.table.Equals(table) && CollectionHelper.SequenceEquals<string>(columns, that.columns);
}
public override int GetHashCode()
{
return hashCode;
}
}
/// <summary>
/// Should we join this association?
/// </summary>
protected bool IsJoinable(JoinType joinType, ISet<AssociationKey> visitedAssociationKeys, string lhsTable,
string[] lhsColumnNames, IAssociationType type, int depth)
{
if (joinType < JoinType.InnerJoin) return false;
if (joinType == JoinType.InnerJoin) return true;
int maxFetchDepth = Factory.Settings.MaximumFetchDepth;
bool tooDeep = maxFetchDepth >= 0 && depth >= maxFetchDepth;
return !tooDeep && !IsDuplicateAssociation(lhsTable, lhsColumnNames, type);
}
protected SqlString OrderBy(IList<OuterJoinableAssociation> associations, SqlString orderBy)
{
return MergeOrderings(OrderBy(associations), orderBy);
}
protected SqlString OrderBy(IList<OuterJoinableAssociation> associations, string orderBy)
{
return MergeOrderings(OrderBy(associations), new SqlString(orderBy));
}
protected SqlString MergeOrderings(SqlString ass, SqlString orderBy)
{
if (ass.Length == 0)
return orderBy;
if (orderBy.Length == 0)
return ass;
return orderBy.Append(StringHelper.CommaSpace, ass);
}
protected SqlString MergeOrderings(string ass, SqlString orderBy) {
return this.MergeOrderings(new SqlString(ass), orderBy);
}
protected SqlString MergeOrderings(string ass, string orderBy) {
return this.MergeOrderings(new SqlString(ass), new SqlString(orderBy));
}
/// <summary>
/// Generate a sequence of <c>LEFT OUTER JOIN</c> clauses for the given associations.
/// </summary>
protected JoinFragment MergeOuterJoins(IList<OuterJoinableAssociation> associations)
{
JoinFragment outerjoin = Dialect.CreateOuterJoinFragment();
var sortedAssociations = GetSortedAssociations(associations);
OuterJoinableAssociation last = null;
foreach (OuterJoinableAssociation oj in sortedAssociations)
{
if (last != null && last.IsManyToManyWith(oj))
{
oj.AddManyToManyJoin(outerjoin, (IQueryableCollection) last.Joinable);
}
else
{
// NH Different behavior : NH1179 and NH1293
// Apply filters for entity joins and Many-To-One associations
SqlString filter = null;
var enabledFiltersForJoin = oj.ForceFilter ? enabledFilters : enabledFiltersForManyToOne;
if (oj.ForceFilter || enabledFiltersForJoin.Count > 0)
{
string manyToOneFilterFragment = oj.Joinable.FilterFragment(oj.RHSAlias, enabledFiltersForJoin);
bool joinClauseDoesNotContainsFilterAlready =
oj.On?.IndexOfCaseInsensitive(manyToOneFilterFragment) == -1;
if (joinClauseDoesNotContainsFilterAlready)
{
filter = new SqlString(manyToOneFilterFragment);
}
}
if (TableGroupJoinHelper.ProcessAsTableGroupJoin(new[] {oj}, new[] {oj.On, filter}, true, outerjoin, alias => true, factory))
continue;
oj.AddJoins(outerjoin);
// Ensure that the join condition is added to the join, not the where clause.
// Adding the condition to the where clause causes left joins to become inner joins.
if (SqlStringHelper.IsNotEmpty(filter))
outerjoin.AddFromFragmentString(filter);
}
last = oj;
}
return outerjoin;
}
private static IList<OuterJoinableAssociation> GetSortedAssociations(IList<OuterJoinableAssociation> associations)
{
if (associations.Count < 2)
return associations;
var fields = GetDependentAliases(associations);
if (!fields.Exists(a => a.DependsOn?.Count > 0))
return associations;
var indexes = GetTopologicalSortOrder(fields);
var sortedAssociations = new List<OuterJoinableAssociation>(associations.Count);
for (int index = indexes.Length - 1; index >= 0; index--)
{
sortedAssociations.Add(associations[indexes[index]]);
}
return sortedAssociations;
}
/// <summary>
/// Count the number of instances of IJoinable which are actually
/// also instances of ILoadable, or are one-to-many associations
/// </summary>
protected static int CountEntityPersisters(IList<OuterJoinableAssociation> associations)
{
int result = 0;
foreach (OuterJoinableAssociation oj in associations)
{
if (oj.Joinable.ConsumesEntityAlias() && oj.SelectMode != SelectMode.JoinOnly)
result++;
}
return result;
}
/// <summary>
/// Count the number of instances of <see cref="IJoinable" /> which
/// are actually also instances of <see cref="IPersistentCollection" />
/// which are being fetched by outer join
/// </summary>
protected static int CountCollectionPersisters(IList<OuterJoinableAssociation> associations)
{
int result = 0;
foreach (OuterJoinableAssociation oj in associations)
{
if (oj.ShouldFetchCollectionPersister())
result++;
}
return result;
}
/// <summary>
/// Get the order by string required for collection fetching
/// </summary>
protected SqlString OrderBy(IList<OuterJoinableAssociation> associations)
{
SqlStringBuilder buf = new SqlStringBuilder();
OuterJoinableAssociation last = null;
foreach (OuterJoinableAssociation oj in associations)
{
if (oj.ShouldFetchCollectionPersister())
{
IQueryableCollection queryableCollection = (IQueryableCollection) oj.Joinable;
if (queryableCollection.HasOrdering)
{
string orderByString = queryableCollection.GetSQLOrderByString(oj.RHSAlias);
buf.Add(orderByString).Add(StringHelper.CommaSpace);
}
}
else if (!oj.IsCollection && last?.ShouldFetchCollectionPersister() == true)
{
// it might still need to apply a collection ordering based on a