forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFromElement.cs
738 lines (654 loc) · 18.8 KB
/
FromElement.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
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Antlr.Runtime;
using NHibernate.Hql.Ast.ANTLR.Util;
using NHibernate.Param;
using NHibernate.Persister.Collection;
using NHibernate.Persister.Entity;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.Util;
using IQueryable = NHibernate.Persister.Entity.IQueryable;
namespace NHibernate.Hql.Ast.ANTLR.Tree
{
[CLSCompliant(false)]
public class FromElement : HqlSqlWalkerNode, IDisplayableNode, IParameterContainer
{
private static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(FromElement));
private bool _isAllPropertyFetch;
private FromElementType _elementType;
private string _tableAlias;
private string _classAlias;
private string _className;
private string _collectionTableAlias;
private FromClause _fromClause;
private string[] _columns;
private string[] _fetchLazyProperties;
private FromElement _origin;
private bool _useFromFragment;
private bool _useWhereFragment = true;
private bool _includeSubclasses = true;
private readonly List<FromElement> _destinations = new List<FromElement>();
private bool _dereferencedBySubclassProperty;
private bool _dereferencedBySuperclassProperty;
private bool _collectionJoin;
private string _role;
private bool _initialized;
private SqlString _withClauseFragment;
private string _withClauseJoinAlias;
private bool _filter;
private IToken _token;
public FromElement(IToken token) : base(token)
{
_token= token;
}
/// <summary>
/// Constructor form used to initialize <see cref="ComponentJoin"/>.
/// </summary>
/// <param name="fromClause">The FROM clause to which this element belongs.</param>
/// <param name="origin">The origin (LHS) of this element.</param>
/// <param name="alias">The alias applied to this element.</param>
protected FromElement(FromClause fromClause,FromElement origin,string alias):this(origin._token)
{
_fromClause = fromClause;
_origin = origin;
_classAlias = alias;
_tableAlias = origin.TableAlias;
base.Initialize(fromClause.Walker);
}
protected void InitializeComponentJoin(FromElementType elementType)
{
_elementType = elementType;
_fromClause.RegisterFromElement(this);
_initialized = true;
}
public void SetAllPropertyFetch(bool fetch)
{
_isAllPropertyFetch = fetch;
}
public void SetWithClauseFragment(String withClauseJoinAlias, SqlString withClauseFragment)
{
_withClauseJoinAlias = withClauseJoinAlias;
_withClauseFragment = withClauseFragment;
}
public Engine.JoinSequence JoinSequence
{
get { return _elementType.JoinSequence; }
set { _elementType.JoinSequence = value; }
}
public string[] Columns
{
get { return _columns; }
set { _columns = value; }
}
public bool IsEntity
{
get { return _elementType.IsEntity; }
}
public bool IsFromOrJoinFragment
{
get { return Type == HqlSqlWalker.FROM_FRAGMENT || Type == HqlSqlWalker.JOIN_FRAGMENT || Type == HqlSqlWalker.ENTITY_JOIN; }
}
public bool IsAllPropertyFetch
{
get { return _isAllPropertyFetch; }
set { _isAllPropertyFetch = value; }
}
/// <summary>
/// Names of lazy properties to be fetched.
/// </summary>
public string[] FetchLazyProperties
{
get { return _fetchLazyProperties; }
set { _fetchLazyProperties = value; }
}
public virtual bool IsImpliedInFromClause
{
get { return false; } // Since this is an explicit FROM element, it can't be implied in the FROM clause.
}
public bool IsFetch
{
get { return _fetch; }
}
public bool Filter
{
set { _filter = value; }
}
public bool IsFilter
{
get { return _filter; }
}
public IParameterSpecification[] GetEmbeddedParameters()
{
return _embeddedParameters.ToArray();
}
public bool HasEmbeddedParameters
{
get { return _embeddedParameters != null && _embeddedParameters.Count > 0; }
}
public IParameterSpecification IndexCollectionSelectorParamSpec
{
get { return _elementType.IndexCollectionSelectorParamSpec; }
set
{
if (value == null)
{
if (_elementType.IndexCollectionSelectorParamSpec != null)
{
_embeddedParameters.Remove(_elementType.IndexCollectionSelectorParamSpec);
_elementType.IndexCollectionSelectorParamSpec = null;
}
}
else
{
_elementType.IndexCollectionSelectorParamSpec = value;
AddEmbeddedParameter(value);
}
}
}
/// <summary>
/// Returns true if this FromElement was implied by a path, or false if this FROM element is explicitly declared in
/// the FROM clause.
/// </summary>
public virtual bool IsImplied
{
get { return false; } // This is an explicit FROM element.
}
public bool IsDereferencedBySuperclassOrSubclassProperty
{
get
{
return _dereferencedBySubclassProperty || _dereferencedBySuperclassProperty;
}
}
public bool IsDereferencedBySubclassProperty
{
get { return _dereferencedBySubclassProperty; }
}
public IEntityPersister EntityPersister
{
get { return _elementType.EntityPersister; }
}
public override IType DataType
{
get
{
return _elementType.DataType;
}
set
{
base.DataType = value;
}
}
public string TableAlias
{
get { return _tableAlias; }
}
private string TableName
{
get
{
IQueryable queryable = Queryable;
return (queryable != null) ? queryable.TableName : "{none}";
}
}
public string ClassAlias
{
get { return _classAlias; }
}
public string ClassName
{
get { return _className; }
}
public FromClause FromClause
{
get { return _fromClause; }
}
public IQueryable Queryable
{
get { return _elementType.Queryable; }
}
public IQueryableCollection QueryableCollection
{
get { return _elementType.QueryableCollection; }
set { _elementType.QueryableCollection = value; }
}
public string CollectionTableAlias
{
get { return _collectionTableAlias; }
set { _collectionTableAlias = value; }
}
public bool CollectionJoin
{
get { return _collectionJoin; }
set { _collectionJoin = value; }
}
public string CollectionSuffix
{
get { return _elementType.CollectionSuffix; }
set { _elementType.CollectionSuffix = value; }
}
public IType SelectType
{
get { return _elementType.SelectType; }
}
public bool IsCollectionOfValuesOrComponents
{
get { return _elementType.IsCollectionOfValuesOrComponents; }
}
public bool IsCollectionJoin
{
get { return _collectionJoin; }
}
public void SetRole(string role)
{
_role = role;
}
public FromElement Origin
{
get { return _origin; }
}
public FromElement RealOrigin
{
get
{
if (_origin == null)
{
return null;
}
if (String.IsNullOrEmpty(_origin.Text))
{
return _origin.RealOrigin;
}
return _origin;
}
}
public SqlString WithClauseFragment
{
get { return _withClauseFragment; }
}
public string WithClauseJoinAlias
{
get { return _withClauseJoinAlias; }
}
/// <summary>
/// Returns the identifier select SQL fragment.
/// </summary>
/// <param name="size">The total number of returned types.</param>
/// <param name="k">The sequence of the current returned type.</param>
/// <returns>the identifier select SQL fragment.</returns>
public string RenderIdentifierSelect(int size, int k)
{
return _elementType.RenderIdentifierSelect(size, k);
}
/// <summary>
/// Returns the property select SQL fragment.
/// </summary>
/// <param name="size">The total number of returned types.</param>
/// <param name="k">The sequence of the current returned type.</param>
/// <returns>the property select SQL fragment.</returns>
public string RenderPropertySelect(int size, int k)
{
return _elementType.RenderPropertySelect(
size,
k,
IsAllPropertyFetch || _fetchLazyProperties?.Contains(TableAlias) == true);
}
public override SqlString RenderText(Engine.ISessionFactoryImplementor sessionFactory)
{
var result = SqlString.Parse(Text);
// query-parameter = the parameter specified in the NHibernate query
// sql-parameter = real parameter/s inside the final SQL
// here is where we suppose the SqlString has all sql-parameters in sequence for a given query-parameter.
// This happen when the query-parameter spans multiple columns (components,custom-types and so on).
if (HasEmbeddedParameters)
{
var parameters = result.GetParameters().ToArray();
var sqlParameterPos = 0;
var paramTrackers = _embeddedParameters.SelectMany(specification => specification.GetIdsForBackTrack(sessionFactory));
foreach (var paramTracker in paramTrackers)
{
parameters[sqlParameterPos++].BackTrack = paramTracker;
}
}
return result;
}
public string RenderCollectionSelectFragment(int size, int k)
{
return _elementType.RenderCollectionSelectFragment(size, k);
}
public string RenderValueCollectionSelectFragment(int size, int k)
{
return _elementType.RenderValueCollectionSelectFragment(size, k);
}
public void SetIndexCollectionSelectorParamSpec(IParameterSpecification indexCollectionSelectorParamSpec)
{
if (indexCollectionSelectorParamSpec == null)
{
if (_elementType.IndexCollectionSelectorParamSpec != null)
{
_embeddedParameters.Remove(_elementType.IndexCollectionSelectorParamSpec);
_elementType.IndexCollectionSelectorParamSpec = null;
}
}
else
{
_elementType.IndexCollectionSelectorParamSpec = indexCollectionSelectorParamSpec;
AddEmbeddedParameter(indexCollectionSelectorParamSpec);
}
}
public virtual void SetImpliedInFromClause(bool flag)
{
throw new InvalidOperationException("Explicit FROM elements can't be implied in the FROM clause!");
}
public virtual bool IncludeSubclasses
{
get { return _includeSubclasses; }
set
{
if (IsDereferencedBySuperclassOrSubclassProperty)
{
if (!_includeSubclasses && Log.IsInfoEnabled())
{
Log.Info(new Exception("stack-trace source"), "attempt to disable subclass-inclusions");
}
}
_includeSubclasses = value;
}
}
public virtual bool InProjectionList
{
get { return !IsImplied && IsFromOrJoinFragment; }
set
{
// Do nothing, eplicit from elements are *always* in the projection list.
}
}
private bool _fetch;
public bool Fetch
{
get { return _fetch; }
set
{
_fetch = value;
// Fetch can't be used with scroll() or iterate().
if (_fetch && Walker.IsShallowQuery)
{
throw new QueryException(LiteralProcessor.ErrorCannotFetchWithIterate);
}
}
}
/// <summary>
/// Render the identifier select, but in a 'scalar' context (i.e. generate the column alias).
/// </summary>
/// <param name="i">the sequence of the returned type</param>
/// <returns>the identifier select with the column alias.</returns>
public string RenderScalarIdentifierSelect(int i)
{
return _elementType.RenderScalarIdentifierSelect(i);
}
public bool UseFromFragment
{
get
{
CheckInitialized();
// If it's not implied or it is implied and it's a many to many join where the target wasn't found.
return !IsImplied || _useFromFragment;
}
set { _useFromFragment = value; }
}
public bool UseWhereFragment
{
get { return _useWhereFragment;}
set { _useWhereFragment = value; }
}
public string[] ToColumns(string tableAlias, string path, bool inSelect)
{
return _elementType.ToColumns(tableAlias, path, inSelect);
}
public string[] ToColumns(string tableAlias, string path, bool inSelect, bool forceAlias)
{
return _elementType.ToColumns(tableAlias, path, inSelect, forceAlias);
}
public IPropertyMapping GetPropertyMapping(string propertyName)
{
return _elementType.GetPropertyMapping(propertyName);
}
public IType GetPropertyType(string propertyName, string propertyPath)
{
return _elementType.GetPropertyType(propertyName, propertyPath);
}
public virtual string GetIdentityColumn()
{
CheckInitialized();
string table = TableAlias;
if (table == null)
{
throw new InvalidOperationException("No table alias for node " + this);
}
string[] cols;
string propertyName;
if (EntityPersister != null && EntityPersister.EntityMetamodel != null
&& EntityPersister.EntityMetamodel.HasNonIdentifierPropertyNamedId)
{
propertyName = EntityPersister.IdentifierPropertyName;
}
else if (IsCollectionOfValuesOrComponents)
{
propertyName = CollectionPropertyNames.Elements;
}
else
{
propertyName = NHibernate.Persister.Entity.EntityPersister.EntityID;
}
if (Walker.StatementType == HqlSqlWalker.SELECT || Walker.IsSubQuery)
{
cols = GetPropertyMapping(propertyName).ToColumns(table, propertyName);
}
else
{
cols = GetPropertyMapping(propertyName).ToColumns(propertyName);
}
string result = string.Join(", ", cols);
if (cols.Length > 1 && Walker.IsComparativeExpressionClause)
{
return "(" + result + ")";
}
return result;
}
public void HandlePropertyBeingDereferenced(IType propertySource, string propertyName)
{
if (QueryableCollection != null && CollectionProperties.IsCollectionProperty(propertyName))
{
// propertyName refers to something like collection.size...
return;
}
if (propertySource.IsComponentType)
{
// property name is a sub-path of a component...
return;
}
IQueryable persister = Queryable;
if (persister != null)
{
try
{
Declarer propertyDeclarer = persister.GetSubclassPropertyDeclarer(propertyName);
if (Log.IsInfoEnabled())
{
Log.Info("handling property dereference [{0} ({1}) -> {2} ({3})]", persister.EntityName, ClassAlias, propertyName, propertyDeclarer);
}
if (propertyDeclarer == Declarer.SubClass)
{
_dereferencedBySubclassProperty = true;
_includeSubclasses = true;
}
else if (propertyDeclarer == Declarer.SuperClass)
{
_dereferencedBySuperclassProperty = true;
}
}
catch (QueryException ex)
{
// ignore it; the incoming property could not be found so we
// cannot be sure what to do here. At the very least, the
// safest is to simply not apply any dereference toggling...
Log.Debug(ex, "Unable to find property {0}, no dereference will be handled for it.", propertyName);
}
}
}
public void SetOrigin(FromElement origin, bool manyToMany)
{
_origin = origin;
origin.AddDestination(this);
if (origin.FromClause == FromClause)
{
// TODO: Figure out a better way to get the FROM elements in a proper tree structure.
// If this is not the destination of a many-to-many, add it as a child of the origin.
if (manyToMany)
{
origin.AddSibling(this);
}
else
{
if (!Walker.IsInFrom && !Walker.IsInSelect)
{
FromClause.AddChild(this);
}
else
{
origin.AddChild(this);
}
}
}
else if (!Walker.IsInFrom)
{
// HHH-276 : implied joins in a subselect where clause - The destination needs to be added
// to the destination's from clause.
FromClause.AddChild(this); // Not sure if this is will fix everything, but it works.
}
else
{
// Otherwise, the destination node was implied by the FROM clause and the FROM clause processor
// will automatically add it in the right place.
}
}
public void SetIncludeSubclasses(bool includeSubclasses)
{
if (IsDereferencedBySuperclassOrSubclassProperty)
{
if (!includeSubclasses && Log.IsInfoEnabled())
{
Log.Info(new Exception("stack-trace source"), "attempt to disable subclass-inclusions");
}
}
_includeSubclasses = includeSubclasses;
}
public virtual string GetDisplayText()
{
StringBuilder buf = new StringBuilder();
buf.Append("FromElement{");
AppendDisplayText(buf);
buf.Append("}");
return buf.ToString();
}
public void InitializeCollection(FromClause fromClause, string classAlias, string tableAlias)
{
DoInitialize(fromClause, tableAlias, null, classAlias, null, null);
_initialized = true;
}
public void InitializeEntity(FromClause fromClause,
string className,
IEntityPersister persister,
EntityType type,
string classAlias,
string tableAlias)
{
DoInitialize(fromClause, tableAlias, className, classAlias, persister, type);
_initialized = true;
}
public void CheckInitialized()
{
if (!_initialized)
{
throw new InvalidOperationException("FromElement has not been initialized!");
}
}
protected void AppendDisplayText(StringBuilder buf)
{
buf.Append(IsImplied ? (
IsImpliedInFromClause ? "implied in FROM clause" : "implied")
: "explicit");
buf.Append(",").Append(IsCollectionJoin ? "collection join" : "not a collection join");
buf.Append(",").Append(_fetch ? "fetch join" : "not a fetch join");
buf.Append(",").Append(IsAllPropertyFetch ? "fetch all properties" : "fetch non-lazy properties");
buf.Append(",classAlias=").Append(ClassAlias);
buf.Append(",role=").Append(_role);
buf.Append(",tableName=").Append(TableName);
buf.Append(",tableAlias=").Append(TableAlias);
FromElement origin = RealOrigin;
buf.Append(",origin=").Append(origin == null ? "null" : origin.Text);
buf.Append(",colums={");
if (_columns != null)
{
for (int i = 0; i < _columns.Length; i++)
{
buf.Append(_columns[i]);
if (i < _columns.Length)
{
buf.Append(" ");
}
}
}
buf.Append(",className=").Append(_className);
buf.Append("}");
}
private void AddDestination(FromElement fromElement)
{
_destinations.Add(fromElement);
}
private void DoInitialize(FromClause fromClause, string tableAlias, string className, string classAlias,
IEntityPersister persister, EntityType type)
{
if (_initialized)
{
throw new InvalidOperationException("Already initialized!!");
}
_fromClause = fromClause;
_tableAlias = tableAlias;
_className = className;
_classAlias = classAlias;
_elementType = new FromElementType(this, persister, type);
if (Walker == null)
{
Walker = _fromClause.Walker;
}
// Register the FromElement with the FROM clause, now that we have the names and aliases.
fromClause.RegisterFromElement(this);
if (Log.IsDebugEnabled())
{
Log.Debug("{0} : {1} ({2}) -> {3}",
fromClause,
className,
(classAlias ?? "no alias"),
tableAlias);
}
}
// ParameterContainer impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private List<IParameterSpecification> _embeddedParameters;
public void AddEmbeddedParameter(IParameterSpecification specification)
{
if (_embeddedParameters == null)
{
_embeddedParameters = new List<IParameterSpecification>();
}
_embeddedParameters.Add(specification);
}
internal bool IsEntityJoin()
{
return Type == HqlSqlWalker.ENTITY_JOIN;
}
}
}