-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HqlSqlWalker.cs
1186 lines (1011 loc) · 35.4 KB
/
HqlSqlWalker.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 Antlr.Runtime;
using Antlr.Runtime.Tree;
using Iesi.Collections.Generic;
using log4net;
using NHibernate.Engine;
using NHibernate.Hql.Ast.ANTLR.Tree;
using NHibernate.Hql.Ast.ANTLR.Util;
using NHibernate.Id;
using NHibernate.Param;
using NHibernate.Persister.Collection;
using NHibernate.Persister.Entity;
using NHibernate.SqlCommand;
using NHibernate.Type;
using NHibernate.UserTypes;
using NHibernate.Util;
namespace NHibernate.Hql.Ast.ANTLR
{
[CLSCompliant(false)]
public partial class HqlSqlWalker
{
private static readonly ILog log = LogManager.GetLogger(typeof(HqlSqlWalker));
// Fields
private readonly string _collectionFilterRole;
private readonly SessionFactoryHelperExtensions _sessionFactoryHelper;
private readonly QueryTranslatorImpl _qti;
private int _currentClauseType;
private int _level;
private bool _inSelect;
private bool _inFrom;
private bool _inFunctionCall;
private bool _inCase;
private int _statementType;
private int _currentStatementType;
private string _statementTypeName;
private int _positionalParameterCount;
private int _parameterCount;
private readonly NullableDictionary<string, object> _namedParameters = new NullableDictionary<string, object>();
private readonly List<IParameterSpecification> _parameters = new List<IParameterSpecification>();
private FromClause _currentFromClause;
private SelectClause _selectClause;
private readonly AliasGenerator _aliasGenerator = new AliasGenerator();
private readonly ASTPrinter _printer = new ASTPrinter();
private readonly Set<string> _querySpaces = new HashedSet<string>();
private readonly LiteralProcessor _literalProcessor;
private readonly IDictionary<string, string> _tokenReplacements;
private JoinType _impliedJoinType;
private IParseErrorHandler _parseErrorHandler = new ErrorCounter();
private IASTFactory _nodeFactory;
private readonly List<AssignmentSpecification> assignmentSpecifications = new List<AssignmentSpecification>();
private int numberOfParametersInSetClause;
public HqlSqlWalker(QueryTranslatorImpl qti,
ISessionFactoryImplementor sfi,
ITreeNodeStream input,
IDictionary<string, string> tokenReplacements,
string collectionRole)
: this(input)
{
_sessionFactoryHelper = new SessionFactoryHelperExtensions(sfi);
_qti = qti;
_literalProcessor = new LiteralProcessor(this);
_tokenReplacements = tokenReplacements;
_collectionFilterRole = collectionRole;
}
public override void ReportError(RecognitionException e)
{
_parseErrorHandler.ReportError(e);
}
/*
protected override void Mismatch(IIntStream input, int ttype, BitSet follow)
{
throw new MismatchedTokenException(ttype, input);
}
public override object RecoverFromMismatchedSet(IIntStream input, RecognitionException e, BitSet follow)
{
throw e;
}
*/
public IList<AssignmentSpecification> AssignmentSpecifications
{
get { return assignmentSpecifications; }
}
public int NumberOfParametersInSetClause
{
get { return numberOfParametersInSetClause; }
}
public IParseErrorHandler ParseErrorHandler
{
get { return _parseErrorHandler; }
set { _parseErrorHandler = value; }
}
public AliasGenerator AliasGenerator
{
get { return _aliasGenerator; }
}
public Set<string> QuerySpaces
{
get { return _querySpaces; }
}
public IDictionary<string, object> NamedParameters
{
get { return _namedParameters; }
}
internal SessionFactoryHelperExtensions SessionFactoryHelper
{
get { return _sessionFactoryHelper; }
}
public int CurrentStatementType
{
get { return _currentStatementType; }
}
public JoinType ImpliedJoinType
{
get { return _impliedJoinType; }
}
public String[] ReturnAliases
{
get { return _selectClause.QueryReturnAliases; }
}
public IType[] ReturnTypes
{
get { return _selectClause.QueryReturnTypes; }
}
public string CollectionFilterRole
{
get { return _collectionFilterRole; }
}
public SelectClause SelectClause
{
get { return _selectClause; }
}
public IList<IParameterSpecification> Parameters
{
get { return _parameters; }
}
void BeforeStatement(string statementName, int statementType)
{
_inFunctionCall = false;
_level++;
if (_level == 1)
{
_statementTypeName = statementName;
_statementType = statementType;
}
_currentStatementType = statementType;
if (log.IsDebugEnabled)
{
log.Debug(statementName + " << begin [level=" + _level + ", statement=" + _statementTypeName + "]");
}
}
void BeforeStatementCompletion(string statementName)
{
if (log.IsDebugEnabled)
{
log.Debug(statementName + " : finishing up [level=" + _level + ", statement=" + _statementTypeName + "]");
}
}
void PrepareVersioned(IASTNode updateNode, IASTNode versioned)
{
var updateStatement = (UpdateStatement)updateNode;
FromClause fromClause = updateStatement.FromClause;
if (versioned != null)
{
// Make sure that the persister is versioned
IQueryable persister = fromClause.GetFromElement().Queryable;
if (!persister.IsVersioned)
{
throw new SemanticException("increment option specified for update of non-versioned entity");
}
IVersionType versionType = persister.VersionType;
if (versionType is IUserVersionType)
{
throw new SemanticException("user-defined version types not supported for increment option");
}
IASTNode eq = ASTFactory.CreateNode(EQ, "=");
IASTNode versionPropertyNode = GenerateVersionPropertyNode(persister);
eq.SetFirstChild(versionPropertyNode);
IASTNode versionIncrementNode;
if (typeof(DateTime).IsAssignableFrom(versionType.ReturnedClass))
{
versionIncrementNode = ASTFactory.CreateNode(PARAM, "?");
IParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification(versionType);
((ParameterNode)versionIncrementNode).HqlParameterSpecification = paramSpec;
Parameters.Insert(0, paramSpec);
}
else
{
// Not possible to simply re-use the versionPropertyNode here as it causes
// OOM errors due to circularity :(
versionIncrementNode = ASTFactory.CreateNode(PLUS, "+");
versionIncrementNode.SetFirstChild(GenerateVersionPropertyNode(persister));
versionIncrementNode.AddChild(ASTFactory.CreateNode(IDENT, "1"));
}
eq.AddChild(versionIncrementNode);
EvaluateAssignment(eq, persister, 0);
IASTNode setClause = updateStatement.SetClause;
IASTNode currentFirstSetElement = setClause.GetFirstChild();
setClause.SetFirstChild(eq);
eq.NextSibling= currentFirstSetElement;
}
}
private IASTNode GenerateVersionPropertyNode(IQueryable persister)
{
string versionPropertyName = persister.PropertyNames[persister.VersionProperty];
var versionPropertyRef = ASTFactory.CreateNode(IDENT, versionPropertyName);
var versionPropertyNode = LookupNonQualifiedProperty(versionPropertyRef);
Resolve(versionPropertyNode);
return versionPropertyNode;
}
void PostProcessUpdate(IASTNode update)
{
var updateStatement = (UpdateStatement)update;
PostProcessDML(updateStatement);
}
void PostProcessDelete(IASTNode delete)
{
PostProcessDML((DeleteStatement)delete);
}
void PostProcessInsert(IASTNode insert)
{
var insertStatement = (InsertStatement)insert;
insertStatement.Validate();
SelectClause selectClause = insertStatement.SelectClause;
var persister = insertStatement.IntoClause.Queryable;
if (!insertStatement.IntoClause.IsExplicitIdInsertion)
{
// We need to generate ids as part of this bulk insert.
//
// Note that this is only supported for sequence-style generators and
// post-insert-style generators; basically, only in-db generators
IIdentifierGenerator generator = persister.IdentifierGenerator;
if (!SupportsIdGenWithBulkInsertion(generator))
{
throw new QueryException("can only generate ids as part of bulk insert with either sequence or post-insert style generators");
}
IASTNode idSelectExprNode = null;
var seqGenerator = generator as SequenceGenerator;
if (seqGenerator != null)
{
string seqName = seqGenerator.GeneratorKey();
string nextval = SessionFactoryHelper.Factory.Dialect.GetSelectSequenceNextValString(seqName);
idSelectExprNode = ASTFactory.CreateNode(SQL_TOKEN, nextval);
}
else
{
//Don't need this, because we should never ever be selecting no columns in an insert ... select...
//and because it causes a bug on DB2
/*String idInsertString = sessionFactoryHelper.getFactory().getDialect().getIdentityInsertString();
if ( idInsertString != null ) {
idSelectExprNode = getASTFactory().create( HqlSqlTokenTypes.SQL_TOKEN, idInsertString );
}*/
}
if (idSelectExprNode != null)
{
IASTNode currentFirstSelectExprNode = selectClause.GetFirstChild();
selectClause.SetFirstChild(idSelectExprNode);
idSelectExprNode.NextSibling= currentFirstSelectExprNode;
insertStatement.IntoClause.PrependIdColumnSpec();
}
}
bool includeVersionProperty = persister.IsVersioned && !insertStatement.IntoClause.IsExplicitVersionInsertion && persister.VersionPropertyInsertable;
if (includeVersionProperty)
{
// We need to seed the version value as part of this bulk insert
IVersionType versionType = persister.VersionType;
IASTNode versionValueNode;
if (SessionFactoryHelper.Factory.Dialect.SupportsParametersInInsertSelect)
{
versionValueNode = ASTFactory.CreateNode(PARAM, "?");
IParameterSpecification paramSpec = new VersionTypeSeedParameterSpecification(versionType);
((ParameterNode)versionValueNode).HqlParameterSpecification = paramSpec;
_parameters.Insert(0, paramSpec);
}
else
{
if (IsIntegral(versionType))
{
try
{
object seedValue = versionType.Seed(null);
versionValueNode = ASTFactory.CreateNode(SQL_TOKEN, seedValue.ToString());
}
catch (Exception t)
{
throw new QueryException("could not determine seed value for version on bulk insert [" + versionType + "]", t);
}
}
else if (IsDatabaseGeneratedTimestamp(versionType))
{
string functionName = SessionFactoryHelper.Factory.Dialect.CurrentTimestampSQLFunctionName;
versionValueNode = ASTFactory.CreateNode(SQL_TOKEN, functionName);
}
else
{
throw new QueryException("cannot handle version type [" + versionType + "] on bulk inserts with dialects not supporting parameters in insert-select statements");
}
}
IASTNode currentFirstSelectExprNode = selectClause.GetFirstChild();
selectClause.SetFirstChild(versionValueNode);
versionValueNode.NextSibling = currentFirstSelectExprNode;
insertStatement.IntoClause.PrependVersionColumnSpec();
}
if (insertStatement.IntoClause.IsDiscriminated)
{
string sqlValue = insertStatement.IntoClause.Queryable.DiscriminatorSQLValue;
IASTNode discrimValue = ASTFactory.CreateNode(SQL_TOKEN, sqlValue);
insertStatement.SelectClause.AddChild(discrimValue);
}
}
private static bool IsDatabaseGeneratedTimestamp(IType type)
{
// TODO NH: we should check the "generated" property
// currently only the Hibernate-supplied DbTimestampType is supported here
return typeof(TimestampType).IsAssignableFrom(type.GetType());
}
private static bool IsIntegral(IType type)
{
return
typeof(long).IsAssignableFrom(type.ReturnedClass) ||
typeof(int).IsAssignableFrom(type.ReturnedClass) ||
typeof(short).IsAssignableFrom(type.ReturnedClass);
}
public static bool SupportsIdGenWithBulkInsertion(IIdentifierGenerator generator)
{
return typeof(SequenceGenerator).IsAssignableFrom(generator.GetType())
|| typeof(IPostInsertIdentifierGenerator).IsAssignableFrom(generator.GetType());
}
private void PostProcessDML(IRestrictableStatement statement)
{
statement.FromClause.Resolve();
var fromElement = (FromElement)statement.FromClause.GetFromElements()[0];
IQueryable persister = fromElement.Queryable;
// Make #@%$^#^&# sure no alias is applied to the table name
fromElement.Text = persister.TableName;
// append any filter fragments; the EMPTY_MAP is used under the assumption that
// currently enabled filters should not affect this process
if (persister.DiscriminatorType != null)
{
new SyntheticAndFactory(this)
.AddDiscriminatorWhereFragment(statement, persister, new CollectionHelper.EmptyMapClass<string, IFilter>(), fromElement.TableAlias);
}
}
void AfterStatementCompletion(string statementName)
{
if (log.IsDebugEnabled)
{
log.Debug(statementName + " >> end [level=" + _level + ", statement=" + _statementTypeName + "]");
}
_level--;
}
void HandleClauseStart(int clauseType)
{
_currentClauseType = clauseType;
}
IASTNode CreateIntoClause(string path, IASTNode propertySpec)
{
var persister = (IQueryable) SessionFactoryHelper.RequireClassPersister(path);
var intoClause = (IntoClause) adaptor.Create(INTO, "into");
intoClause.SetFirstChild(propertySpec);
intoClause.Initialize(persister);
AddQuerySpaces(persister.QuerySpaces);
return intoClause;
}
IASTNode Resolve(IASTNode node)
{
if (node != null)
{
// This is called when it's time to fully resolve a path expression.
IResolvableNode r = (IResolvableNode)node;
if (_inFunctionCall)
{
r.ResolveInFunctionCall(false, true);
}
else
{
r.Resolve(false, true); // Generate implicit joins, only if necessary.
}
}
return node;
}
void ProcessQuery(IASTNode select, IASTNode query)
{
if ( log.IsDebugEnabled ) {
log.Debug( "processQuery() : " + query.ToStringTree() );
}
try {
QueryNode qn = ( QueryNode ) query;
// Was there an explicit select expression?
bool explicitSelect = select != null && select.ChildCount > 0;
if ( !explicitSelect ) {
// No explicit select expression; render the id and properties
// projection lists for every persister in the from clause into
// a single 'token node'.
//TODO: the only reason we need this stuff now is collection filters,
// we should get rid of derived select clause completely!
CreateSelectClauseFromFromClause( qn );
}
else {
// Use the explicitly declared select expression; determine the
// return types indicated by each select token
UseSelectClause( select );
}
// After that, process the JOINs.
// Invoke a delegate to do the work, as this is farily complex.
JoinProcessor joinProcessor = new JoinProcessor( this );
joinProcessor.ProcessJoins( qn );
// Attach any mapping-defined "ORDER BY" fragments
foreach (FromElement fromElement in qn.FromClause.GetProjectionList())
{
if ( fromElement.IsFetch && fromElement.QueryableCollection != null )
{
// Does the collection referenced by this FromElement
// specify an order-by attribute? If so, attach it to
// the query's order-by
if ( fromElement.QueryableCollection.HasOrdering)
{
string orderByFragment = fromElement
.QueryableCollection
.GetSQLOrderByString( fromElement.TableAlias );
qn.GetOrderByClause().AddOrderFragment( orderByFragment );
}
if ( fromElement.QueryableCollection.HasManyToManyOrdering )
{
string orderByFragment = fromElement.QueryableCollection
.GetManyToManyOrderByString( fromElement.TableAlias );
qn.GetOrderByClause().AddOrderFragment( orderByFragment );
}
}
}
}
finally
{
PopFromClause();
}
}
private void UseSelectClause(IASTNode select)
{
_selectClause = (SelectClause) select;
_selectClause.InitializeExplicitSelectClause(_currentFromClause);
}
private void CreateSelectClauseFromFromClause(IASTNode qn)
{
// TODO - check this. Not *exactly* the same logic as the Java original
qn.InsertChild(0, (IASTNode)adaptor.Create(SELECT_CLAUSE, "{derived select clause}"));
_selectClause = ( SelectClause ) qn.GetChild(0);
_selectClause.InitializeDerivedSelectClause( _currentFromClause );
if ( log.IsDebugEnabled )
{
log.Debug( "Derived SELECT clause created." );
}
}
/// <summary>
/// Returns to the previous 'FROM' context.
/// </summary>
private void PopFromClause()
{
_currentFromClause = _currentFromClause.ParentFromClause;
}
static void ProcessConstructor(IASTNode constructor)
{
ConstructorNode constructorNode = (ConstructorNode)constructor;
constructorNode.Prepare();
}
protected void EvaluateAssignment(IASTNode eq)
{
PrepareLogicOperator(eq);
IQueryable persister = CurrentFromClause.GetFromElement().Queryable;
EvaluateAssignment(eq, persister, -1);
}
private void EvaluateAssignment(IASTNode eq, IQueryable persister, int targetIndex)
{
if (persister.IsMultiTable)
{
// no need to even collect this information if the persister is considered multi-table
var specification = new AssignmentSpecification(eq, persister);
if (targetIndex >= 0)
{
assignmentSpecifications.Insert(targetIndex, specification);
}
else
{
assignmentSpecifications.Add(specification);
}
numberOfParametersInSetClause += specification.Parameters.Length;
}
}
void BeforeSelectClause()
{
// Turn off includeSubclasses on all FromElements.
FromClause from = CurrentFromClause;
foreach (FromElement fromElement in from.GetFromElements())
{
fromElement.IncludeSubclasses = false;
}
}
static void SetAlias(IASTNode selectExpr, IASTNode ident)
{
((ISelectExpression)selectExpr).Alias = ident.Text;
}
static void ResolveSelectExpression(IASTNode node)
{
// This is called when it's time to fully resolve a path expression.
int type = node.Type;
switch (type)
{
case DOT:
DotNode dot = (DotNode)node;
dot.ResolveSelectExpression();
break;
case ALIAS_REF:
// Notify the FROM element that it is being referenced by the select.
FromReferenceNode aliasRefNode = (FromReferenceNode)node;
aliasRefNode.Resolve(false, false); //TODO: is it kosher to do it here?
FromElement fromElement = aliasRefNode.FromElement;
if (fromElement != null)
{
fromElement.IncludeSubclasses = true;
}
break;
default:
break;
}
}
void PrepareFromClauseInputTree(IASTNode fromClauseInput, ITreeNodeStream input)
{
if (IsFilter())
{
// Handle collection-fiter compilation.
// IMPORTANT NOTE: This is modifying the INPUT (HQL) tree, not the output tree!
IQueryableCollection persister = _sessionFactoryHelper.GetCollectionPersister(_collectionFilterRole);
IType collectionElementType = persister.ElementType;
if (!collectionElementType.IsEntityType)
{
throw new QueryException("collection of values in filter: this");
}
string collectionElementEntityName = persister.ElementPersister.EntityName;
IASTNode fromElement = (IASTNode)adaptor.Create(FILTER_ENTITY, collectionElementEntityName);
IASTNode alias = (IASTNode)adaptor.Create(ALIAS, "this");
((HqlSqlWalkerTreeNodeStream)input).InsertChild(fromClauseInput, fromElement);
((HqlSqlWalkerTreeNodeStream)input).InsertChild(fromClauseInput, alias);
// fromClauseInput.AddChild(fromElement);
// fromClauseInput.AddChild(alias);
// Show the modified AST.
if (log.IsDebugEnabled)
{
log.Debug("prepareFromClauseInputTree() : Filter - Added 'this' as a from element...");
}
// Create a parameter specification for the collection filter...
IType collectionFilterKeyType = _sessionFactoryHelper.RequireQueryableCollection(_collectionFilterRole).KeyType;
ParameterNode collectionFilterKeyParameter = (ParameterNode)adaptor.Create(PARAM, "?");
CollectionFilterKeyParameterSpecification collectionFilterKeyParameterSpec = new CollectionFilterKeyParameterSpecification(
_collectionFilterRole, collectionFilterKeyType, _positionalParameterCount++
);
collectionFilterKeyParameter.HqlParameterSpecification = collectionFilterKeyParameterSpec;
_parameters.Add(collectionFilterKeyParameterSpec);
}
}
void CreateFromJoinElement(
IASTNode path,
IASTNode alias,
int joinType,
IASTNode fetchNode,
IASTNode propertyFetch,
IASTNode with)
{
bool fetch = fetchNode != null;
if ( fetch && IsSubQuery )
{
throw new QueryException( "fetch not allowed in subquery from-elements" );
}
// The path AST should be a DotNode, and it should have been evaluated already.
if ( path.Type != DOT )
{
throw new SemanticException( "Path expected for join!" );
}
DotNode dot = ( DotNode ) path;
//JoinType hibernateJoinType = JoinProcessor.ToHibernateJoinType( joinType );
JoinType hibernateJoinType = _impliedJoinType;
dot.JoinType = hibernateJoinType; // Tell the dot node about the join type.
dot.Fetch = fetch;
// Generate an explicit join for the root dot node. The implied joins will be collected and passed up
// to the root dot node.
dot.Resolve( true, false, alias == null ? null : alias.Text );
FromElement fromElement = dot.GetImpliedJoin();
if (fromElement == null)
{
throw new InvalidPathException("Invalid join: " + dot.Path);
}
fromElement.SetAllPropertyFetch(propertyFetch!=null);
if ( with != null )
{
if ( fetch )
{
throw new SemanticException( "with-clause not allowed on fetched associations; use filters" );
}
HandleWithFragment( fromElement, with );
}
if ( log.IsDebugEnabled )
{
log.Debug( "createFromJoinElement() : " + _printer.ShowAsString( fromElement, "-- join tree --" ) );
}
}
IASTNode CreateFromElement(string path, IASTNode pathNode, IASTNode alias, IASTNode propertyFetch)
{
FromElement fromElement = _currentFromClause.AddFromElement(path, alias);
fromElement.SetAllPropertyFetch(propertyFetch != null);
return fromElement;
}
IASTNode CreateFromFilterElement(IASTNode filterEntity, IASTNode alias)
{
FromElement fromElement = _currentFromClause.AddFromElement(filterEntity.Text, alias);
FromClause fromClause = fromElement.FromClause;
IQueryableCollection persister = _sessionFactoryHelper.GetCollectionPersister(_collectionFilterRole);
// Get the names of the columns used to link between the collection
// owner and the collection elements.
String[] keyColumnNames = persister.KeyColumnNames;
String fkTableAlias = persister.IsOneToMany
? fromElement.TableAlias
: fromClause.AliasGenerator.CreateName(_collectionFilterRole);
JoinSequence join = _sessionFactoryHelper.CreateJoinSequence();
join.SetRoot(persister, fkTableAlias);
if (!persister.IsOneToMany)
{
join.AddJoin((IAssociationType)persister.ElementType,
fromElement.TableAlias,
JoinType.InnerJoin,
persister.GetElementColumnNames(fkTableAlias));
}
join.AddCondition(fkTableAlias, keyColumnNames, " = ", true);
fromElement.JoinSequence = join;
fromElement.Filter = true;
if (log.IsDebugEnabled)
{
log.Debug("createFromFilterElement() : processed filter FROM element.");
}
return fromElement;
}
void SetImpliedJoinType(int joinType)
{
_impliedJoinType = JoinProcessor.ToHibernateJoinType(joinType);
}
void PushFromClause(IASTNode fromNode)
{
FromClause newFromClause = (FromClause)fromNode;
newFromClause.SetParentFromClause(_currentFromClause);
_currentFromClause = newFromClause;
}
static void PrepareArithmeticOperator(IASTNode op)
{
((IOperatorNode)op).Initialize();
}
static void ProcessFunction(IASTNode functionCall, bool inSelect)
{
MethodNode methodNode = (MethodNode)functionCall;
methodNode.Resolve(inSelect);
}
void ProcessBool(IASTNode constant)
{
_literalProcessor.ProcessBoolean(constant); // Use the delegate.
}
static void PrepareLogicOperator(IASTNode operatorNode)
{
( ( IOperatorNode ) operatorNode ).Initialize();
}
void ProcessNumericLiteral(IASTNode literal)
{
_literalProcessor.ProcessNumericLiteral((SqlNode) literal);
}
protected IASTNode LookupProperty(IASTNode dot, bool root, bool inSelect)
{
DotNode dotNode = (DotNode) dot;
FromReferenceNode lhs = dotNode.GetLhs();
IASTNode rhs = lhs.NextSibling;
switch (rhs.Type)
{
case ELEMENTS:
case INDICES:
if (log.IsDebugEnabled)
{
log.Debug("lookupProperty() " + dotNode.Path + " => " + rhs.Text + "(" + lhs.Path + ")");
}
CollectionFunction f = (CollectionFunction) rhs;
// Re-arrange the tree so that the collection function is the root and the lhs is the path.
f.SetFirstChild(lhs);
lhs.NextSibling = null;
dotNode.SetFirstChild(f);
Resolve(lhs); // Don't forget to resolve the argument!
f.Resolve(inSelect); // Resolve the collection function now.
return f;
default:
// Resolve everything up to this dot, but don't resolve the placeholders yet.
dotNode.ResolveFirstChild();
return dotNode;
}
}
static void ProcessIndex(IASTNode indexOp)
{
IndexNode indexNode = (IndexNode)indexOp;
indexNode.Resolve(true, true);
}
bool IsNonQualifiedPropertyRef(IASTNode ident)
{
string identText = ident.Text;
if ( _currentFromClause.IsFromElementAlias( identText ) )
{
return false;
}
IList<IASTNode> fromElements = _currentFromClause.GetExplicitFromElements();
if ( fromElements.Count == 1 )
{
FromElement fromElement = (FromElement) fromElements[0];
log.Info( "attempting to resolve property [" + identText + "] as a non-qualified ref" );
IType type;
return fromElement.GetPropertyMapping(identText).TryToType(identText, out type);
}
return false;
}
IASTNode LookupNonQualifiedProperty(IASTNode property)
{
FromElement fromElement = (FromElement) _currentFromClause.GetExplicitFromElements()[0];
IASTNode syntheticDotNode = GenerateSyntheticDotNodeForNonQualifiedPropertyRef( property, fromElement );
return LookupProperty( syntheticDotNode, false, _currentClauseType == SELECT );
}
IASTNode GenerateSyntheticDotNodeForNonQualifiedPropertyRef(IASTNode property, FromElement fromElement)
{
IASTNode dot = (IASTNode) adaptor.Create(DOT, "{non-qualified-property-ref}");
// TODO : better way?!?
((DotNode)dot).PropertyPath = ((FromReferenceNode)property).Path;
IdentNode syntheticAlias = (IdentNode)adaptor.Create(IDENT, "{synthetic-alias}");
syntheticAlias.FromElement = fromElement;
syntheticAlias.IsResolved = true;
dot.SetFirstChild(syntheticAlias);
dot.AddChild(property);
return dot;
}
void LookupAlias(IASTNode aliasRef)
{
FromElement alias = _currentFromClause.GetFromElement(aliasRef.Text);
FromReferenceNode aliasRefNode = (FromReferenceNode)aliasRef;
aliasRefNode.FromElement = alias;
}
IASTNode GenerateNamedParameter(IASTNode delimiterNode, IASTNode nameNode)
{
string name = nameNode.Text;
TrackNamedParameterPositions(name);
// create the node initially with the param name so that it shows
// appropriately in the "original text" attribute
ParameterNode parameter = (ParameterNode) adaptor.Create(NAMED_PARAM, name);
parameter.Text = "?";
NamedParameterSpecification paramSpec = new NamedParameterSpecification(
delimiterNode.Line,
delimiterNode.CharPositionInLine,
name
);
parameter.HqlParameterSpecification = paramSpec;
_parameters.Add(paramSpec);
return parameter;
}
IASTNode GeneratePositionalParameter(IASTNode inputNode)
{
if (_namedParameters.Count > 0)
{
throw new SemanticException("cannot define positional parameter after any named parameters have been defined");
}
ParameterNode parameter = (ParameterNode)adaptor.Create(PARAM, "?");
PositionalParameterSpecification paramSpec = new PositionalParameterSpecification(
inputNode.Line,
inputNode.CharPositionInLine,
_positionalParameterCount++
);
parameter.HqlParameterSpecification = paramSpec;
_parameters.Add(paramSpec);
return parameter;
}
public FromClause CurrentFromClause
{
get { return _currentFromClause; }
}
public int StatementType
{
get { return _statementType; }
}
public LiteralProcessor LiteralProcessor
{
get { return _literalProcessor; }
}
public int CurrentClauseType
{
get { return _currentClauseType; }
}
public IDictionary<string, IFilter> EnabledFilters
{
get { return _qti.EnabledFilters; }
}
public bool IsSubQuery
{
get { return _level > 1; }
}
public bool IsSelectStatement
{
get { return _statementType == SELECT; }
}
public bool IsInFrom
{
get { return _inFrom; }
}
public bool IsInSelect
{
get { return _inSelect; }
}
public IDictionary<string, string> TokenReplacements
{
get { return _tokenReplacements; }
}
public bool IsComparativeExpressionClause
{
get
{
// Note: once we add support for "JOIN ... ON ...",
// the ON clause needs to get included here
return CurrentClauseType == WHERE ||
CurrentClauseType == WITH ||
IsInCase;
}
}
public bool IsInCase
{
get { return _inCase; }
}
public bool IsShallowQuery
{
get
{
// select clauses for insert statements should alwasy be treated as shallow
return StatementType == INSERT || _qti.IsShallowQuery;
}
}
public FromClause GetFinalFromClause()
{
FromClause top = _currentFromClause;
while (top.ParentFromClause != null)
{
top = top.ParentFromClause;
}
return top;
}