-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
AbstractSqlAstTranslator.java
9012 lines (8338 loc) · 304 KB
/
AbstractSqlAstTranslator.java
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
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later
* See the lgpl.txt file in the root directory or http://www.gnu.org/licenses/lgpl-2.1.html
*/
package org.hibernate.sql.ast.spi;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.hibernate.Internal;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.QueryException;
import org.hibernate.dialect.DmlTargetColumnQualifierSupport;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.RowLockStrategy;
import org.hibernate.dialect.SelectItemReferenceStrategy;
import org.hibernate.engine.jdbc.Size;
import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.engine.spi.AbstractDelegatingWrapperOptions;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.FilterJdbcParameter;
import org.hibernate.internal.util.MathHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.collections.Stack;
import org.hibernate.internal.util.collections.StandardStack;
import org.hibernate.metamodel.mapping.AttributeMapping;
import org.hibernate.metamodel.mapping.BasicValuedMapping;
import org.hibernate.metamodel.mapping.EmbeddableMappingType;
import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart;
import org.hibernate.metamodel.mapping.EntityAssociationMapping;
import org.hibernate.metamodel.mapping.EntityIdentifierMapping;
import org.hibernate.metamodel.mapping.JdbcMapping;
import org.hibernate.metamodel.mapping.JdbcMappingContainer;
import org.hibernate.metamodel.mapping.MappingModelExpressible;
import org.hibernate.metamodel.mapping.ModelPart;
import org.hibernate.metamodel.mapping.ModelPartContainer;
import org.hibernate.metamodel.mapping.PluralAttributeMapping;
import org.hibernate.metamodel.mapping.SqlTypedMapping;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.hibernate.persister.entity.Loadable;
import org.hibernate.persister.internal.SqlFragmentPredicate;
import org.hibernate.query.IllegalQueryOperationException;
import org.hibernate.query.ReturnableType;
import org.hibernate.query.SortDirection;
import org.hibernate.query.spi.Limit;
import org.hibernate.query.spi.QueryOptions;
import org.hibernate.query.sqm.BinaryArithmeticOperator;
import org.hibernate.query.sqm.ComparisonOperator;
import org.hibernate.query.sqm.FetchClauseType;
import org.hibernate.query.sqm.FrameExclusion;
import org.hibernate.query.sqm.FrameKind;
import org.hibernate.query.sqm.FrameMode;
import org.hibernate.query.NullPrecedence;
import org.hibernate.query.sqm.SetOperator;
import org.hibernate.query.sqm.UnaryArithmeticOperator;
import org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor;
import org.hibernate.query.sqm.function.MultipatternSqmFunctionDescriptor;
import org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression;
import org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression;
import org.hibernate.query.sqm.function.SqmFunctionDescriptor;
import org.hibernate.query.sqm.sql.internal.SqmParameterInterpretation;
import org.hibernate.query.sqm.sql.internal.SqmPathInterpretation;
import org.hibernate.query.sqm.tree.expression.Conversion;
import org.hibernate.spi.NavigablePath;
import org.hibernate.sql.ast.Clause;
import org.hibernate.sql.ast.SqlAstJoinType;
import org.hibernate.sql.ast.SqlAstNodeRenderingMode;
import org.hibernate.sql.ast.SqlAstTranslator;
import org.hibernate.sql.ast.SqlTreeCreationException;
import org.hibernate.sql.ast.internal.ParameterMarkerStrategyStandard;
import org.hibernate.sql.ast.tree.AbstractUpdateOrDeleteStatement;
import org.hibernate.sql.ast.tree.MutationStatement;
import org.hibernate.sql.ast.tree.SqlAstNode;
import org.hibernate.sql.ast.tree.Statement;
import org.hibernate.sql.ast.tree.cte.CteColumn;
import org.hibernate.sql.ast.tree.cte.CteContainer;
import org.hibernate.sql.ast.tree.cte.CteMaterialization;
import org.hibernate.sql.ast.tree.cte.CteObject;
import org.hibernate.sql.ast.tree.cte.CteSearchClauseKind;
import org.hibernate.sql.ast.tree.cte.CteStatement;
import org.hibernate.sql.ast.tree.cte.CteTableGroup;
import org.hibernate.sql.ast.tree.cte.SearchClauseSpecification;
import org.hibernate.sql.ast.tree.cte.SelfRenderingCteObject;
import org.hibernate.sql.ast.tree.delete.DeleteStatement;
import org.hibernate.sql.ast.tree.expression.AggregateColumnWriteExpression;
import org.hibernate.sql.ast.tree.expression.Any;
import org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression;
import org.hibernate.sql.ast.tree.expression.CaseSearchedExpression;
import org.hibernate.sql.ast.tree.expression.CaseSimpleExpression;
import org.hibernate.sql.ast.tree.expression.CastTarget;
import org.hibernate.sql.ast.tree.expression.Collation;
import org.hibernate.sql.ast.tree.expression.ColumnReference;
import org.hibernate.sql.ast.tree.expression.Distinct;
import org.hibernate.sql.ast.tree.expression.Duration;
import org.hibernate.sql.ast.tree.expression.DurationUnit;
import org.hibernate.sql.ast.tree.expression.EntityTypeLiteral;
import org.hibernate.sql.ast.tree.expression.Every;
import org.hibernate.sql.ast.tree.expression.Expression;
import org.hibernate.sql.ast.tree.expression.ExtractUnit;
import org.hibernate.sql.ast.tree.expression.Format;
import org.hibernate.sql.ast.tree.expression.JdbcLiteral;
import org.hibernate.sql.ast.tree.expression.JdbcParameter;
import org.hibernate.sql.ast.tree.expression.Literal;
import org.hibernate.sql.ast.tree.expression.LiteralAsParameter;
import org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression;
import org.hibernate.sql.ast.tree.expression.OrderedSetAggregateFunctionExpression;
import org.hibernate.sql.ast.tree.expression.Over;
import org.hibernate.sql.ast.tree.expression.Overflow;
import org.hibernate.sql.ast.tree.expression.QueryLiteral;
import org.hibernate.sql.ast.tree.expression.SelfRenderingExpression;
import org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression;
import org.hibernate.sql.ast.tree.expression.SqlSelectionExpression;
import org.hibernate.sql.ast.tree.expression.SqlTuple;
import org.hibernate.sql.ast.tree.expression.SqlTupleContainer;
import org.hibernate.sql.ast.tree.expression.Star;
import org.hibernate.sql.ast.tree.expression.Summarization;
import org.hibernate.sql.ast.tree.expression.TrimSpecification;
import org.hibernate.sql.ast.tree.expression.UnaryOperation;
import org.hibernate.sql.ast.tree.expression.UnparsedNumericLiteral;
import org.hibernate.sql.ast.tree.from.DerivedTableReference;
import org.hibernate.sql.ast.tree.from.FromClause;
import org.hibernate.sql.ast.tree.from.FunctionTableReference;
import org.hibernate.sql.ast.tree.from.LazyTableGroup;
import org.hibernate.sql.ast.tree.from.NamedTableReference;
import org.hibernate.sql.ast.tree.from.QueryPartTableGroup;
import org.hibernate.sql.ast.tree.from.QueryPartTableReference;
import org.hibernate.sql.ast.tree.from.StandardTableGroup;
import org.hibernate.sql.ast.tree.from.TableGroup;
import org.hibernate.sql.ast.tree.from.TableGroupJoin;
import org.hibernate.sql.ast.tree.from.TableGroupProducer;
import org.hibernate.sql.ast.tree.from.TableReference;
import org.hibernate.sql.ast.tree.from.TableReferenceJoin;
import org.hibernate.sql.ast.tree.from.ValuesTableReference;
import org.hibernate.sql.ast.tree.from.VirtualTableGroup;
import org.hibernate.sql.ast.tree.insert.ConflictClause;
import org.hibernate.sql.ast.tree.insert.InsertSelectStatement;
import org.hibernate.sql.ast.tree.insert.Values;
import org.hibernate.sql.ast.tree.predicate.BetweenPredicate;
import org.hibernate.sql.ast.tree.predicate.BooleanExpressionPredicate;
import org.hibernate.sql.ast.tree.predicate.ComparisonPredicate;
import org.hibernate.sql.ast.tree.predicate.ExistsPredicate;
import org.hibernate.sql.ast.tree.predicate.FilterPredicate;
import org.hibernate.sql.ast.tree.predicate.FilterPredicate.FilterFragmentParameter;
import org.hibernate.sql.ast.tree.predicate.FilterPredicate.FilterFragmentPredicate;
import org.hibernate.sql.ast.tree.predicate.GroupedPredicate;
import org.hibernate.sql.ast.tree.predicate.InArrayPredicate;
import org.hibernate.sql.ast.tree.predicate.InListPredicate;
import org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate;
import org.hibernate.sql.ast.tree.predicate.Junction;
import org.hibernate.sql.ast.tree.predicate.LikePredicate;
import org.hibernate.sql.ast.tree.predicate.NegatedPredicate;
import org.hibernate.sql.ast.tree.predicate.NullnessPredicate;
import org.hibernate.sql.ast.tree.predicate.Predicate;
import org.hibernate.sql.ast.tree.predicate.SelfRenderingPredicate;
import org.hibernate.sql.ast.tree.predicate.ThruthnessPredicate;
import org.hibernate.sql.ast.tree.select.QueryGroup;
import org.hibernate.sql.ast.tree.select.QueryPart;
import org.hibernate.sql.ast.tree.select.QuerySpec;
import org.hibernate.sql.ast.tree.select.SelectClause;
import org.hibernate.sql.ast.tree.select.SelectStatement;
import org.hibernate.sql.ast.tree.select.SortSpecification;
import org.hibernate.sql.ast.tree.update.Assignment;
import org.hibernate.sql.ast.tree.update.UpdateStatement;
import org.hibernate.sql.exec.ExecutionException;
import org.hibernate.sql.exec.internal.AbstractJdbcParameter;
import org.hibernate.sql.exec.internal.JdbcOperationQueryInsertImpl;
import org.hibernate.sql.exec.internal.JdbcParameterBindingImpl;
import org.hibernate.sql.exec.internal.JdbcParametersImpl;
import org.hibernate.sql.exec.internal.SqlTypedMappingJdbcParameter;
import org.hibernate.sql.exec.spi.ExecutionContext;
import org.hibernate.sql.exec.spi.JdbcLockStrategy;
import org.hibernate.sql.exec.spi.JdbcOperation;
import org.hibernate.sql.exec.spi.JdbcOperationQueryDelete;
import org.hibernate.sql.exec.spi.JdbcOperationQueryInsert;
import org.hibernate.sql.exec.spi.JdbcOperationQuerySelect;
import org.hibernate.sql.exec.spi.JdbcOperationQueryUpdate;
import org.hibernate.sql.exec.spi.JdbcParameterBinder;
import org.hibernate.sql.exec.spi.JdbcParameterBinding;
import org.hibernate.sql.exec.spi.JdbcParameterBindings;
import org.hibernate.sql.model.MutationOperation;
import org.hibernate.sql.model.ast.ColumnValueParameter;
import org.hibernate.sql.model.ast.ColumnWriteFragment;
import org.hibernate.sql.model.ast.RestrictedTableMutation;
import org.hibernate.sql.model.ast.TableMutation;
import org.hibernate.sql.model.internal.OptionalTableUpdate;
import org.hibernate.sql.model.internal.TableDeleteCustomSql;
import org.hibernate.sql.model.internal.TableDeleteStandard;
import org.hibernate.sql.model.internal.TableInsertCustomSql;
import org.hibernate.sql.model.internal.TableInsertStandard;
import org.hibernate.sql.model.internal.TableUpdateCustomSql;
import org.hibernate.sql.model.internal.TableUpdateStandard;
import org.hibernate.sql.results.internal.SqlSelectionImpl;
import org.hibernate.sql.results.jdbc.spi.JdbcValuesMappingProducer;
import org.hibernate.type.BasicType;
import org.hibernate.type.SqlTypes;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.jdbc.JdbcLiteralFormatter;
import org.hibernate.type.descriptor.jdbc.JdbcType;
import org.hibernate.type.descriptor.sql.DdlType;
import org.hibernate.type.descriptor.sql.spi.DdlTypeRegistry;
import org.hibernate.type.spi.TypeConfiguration;
import static org.hibernate.query.sqm.BinaryArithmeticOperator.DIVIDE_PORTABLE;
import static org.hibernate.query.sqm.TemporalUnit.NANOSECOND;
import static org.hibernate.sql.ast.SqlTreePrinter.logSqlAst;
import static org.hibernate.sql.results.graph.DomainResultGraphPrinter.logDomainResultGraph;
/**
* @author Steve Ebersole
*/
public abstract class AbstractSqlAstTranslator<T extends JdbcOperation> implements SqlAstTranslator<T>, SqlAppender {
/**
* When emulating the recursive WITH clause subclauses SEARCH and CYCLE,
* we need to build a string path and some database like MySQL require that
* we cast the expression to a char with certain size.
* To estimate the size, we need to assume a certain max recursion depth.
*/
private static final int MAX_RECURSION_DEPTH_ESTIMATE = 1000;
/* The following are size estimates for various temporal types */
private static final int DATE_CHAR_SIZE_ESTIMATE =
// year
4 +
// separator
1 +
// month
2 +
// separator
1 +
// day
2;
private static final int TIME_CHAR_SIZE_ESTIMATE =
// hour
2 +
// separator
1 +
// minute
2 +
// separator
1 +
// second
2;
private static final int TIMESTAMP_CHAR_SIZE_ESTIMATE =
DATE_CHAR_SIZE_ESTIMATE +
// separator
1 +
TIME_CHAR_SIZE_ESTIMATE +
// separator
1 +
// nanos
9;
private static final int OFFSET_TIMESTAMP_CHAR_SIZE_ESTIMATE =
TIMESTAMP_CHAR_SIZE_ESTIMATE +
// separator
1 +
// zone offset
6;
// pre-req state
private final SessionFactoryImplementor sessionFactory;
// In-flight state
private final StringBuilder sqlBuffer = new StringBuilder();
private final List<JdbcParameterBinder> parameterBinders = new ArrayList<>();
private final JdbcParametersImpl jdbcParameters = new JdbcParametersImpl();
private JdbcParameterBindings jdbcParameterBindings;
private Map<JdbcParameter, JdbcParameterBinding> appliedParameterBindings = Collections.emptyMap();
private SqlAstNodeRenderingMode parameterRenderingMode = SqlAstNodeRenderingMode.DEFAULT;
private final ParameterMarkerStrategy parameterMarkerStrategy;
private final Stack<Clause> clauseStack = new StandardStack<>( Clause.class );
private final Stack<QueryPart> queryPartStack = new StandardStack<>( QueryPart.class );
private final Stack<Statement> statementStack = new StandardStack<>( Statement.class );
private final Dialect dialect;
private final Set<String> affectedTableNames = new HashSet<>();
private CteStatement currentCteStatement;
private boolean needsSelectAliases;
// Column aliases that need to be injected
private List<String> columnAliases;
private Predicate additionalWherePredicate;
// We must reset the queryPartForRowNumbering fields to null if a query part is visited that does not
// contribute to the row numbering i.e. if the query part is a sub-query in the where clause.
// To determine whether a query part contributes to row numbering, we remember the clause depth
// and when visiting a query part, compare the current clause depth against the remembered one.
private QueryPart queryPartForRowNumbering;
private int queryPartForRowNumberingClauseDepth = -1;
private int queryPartForRowNumberingAliasCounter;
private int queryGroupAliasCounter;
// This field is used to remember the index of the most recently rendered top level with clause element in the sqlBuffer.
// See #visitCteContainer for details about the usage.
private int topLevelWithClauseIndex;
// This field holds the index of where the "recursive" keyword should appear in the sqlBuffer.
// See #visitCteContainer for details about the usage.
private int withClauseRecursiveIndex = -1;
private transient AbstractSqmSelfRenderingFunctionDescriptor castFunction;
private transient LazySessionWrapperOptions lazySessionWrapperOptions;
private transient BasicType<Integer> integerType;
private transient BasicType<String> stringType;
private transient BasicType<Boolean> booleanType;
private LockOptions lockOptions;
private Limit limit;
private JdbcParameter offsetParameter;
private JdbcParameter limitParameter;
private ForUpdateClause forUpdate;
protected AbstractSqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) {
this.sessionFactory = sessionFactory;
final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
this.dialect = jdbcServices.getDialect();
this.statementStack.push( statement );
this.parameterMarkerStrategy = jdbcServices.getParameterMarkerStrategy();
}
private static Clause matchWithClause(Clause clause) {
if ( clause == Clause.WITH ) {
return Clause.WITH;
}
return null;
}
public Dialect getDialect() {
return dialect;
}
@Override
public SessionFactoryImplementor getSessionFactory() {
return sessionFactory;
}
protected AbstractSqmSelfRenderingFunctionDescriptor castFunction() {
if ( castFunction == null ) {
castFunction = findSelfRenderingFunction( "cast", 2 );
}
return castFunction;
}
protected WrapperOptions getWrapperOptions() {
if ( lazySessionWrapperOptions == null ) {
lazySessionWrapperOptions = new LazySessionWrapperOptions( sessionFactory );
}
return lazySessionWrapperOptions;
}
public BasicType<Integer> getIntegerType() {
if ( integerType == null ) {
integerType = sessionFactory.getTypeConfiguration()
.getBasicTypeRegistry()
.resolve( StandardBasicTypes.INTEGER );
}
return integerType;
}
public BasicType<String> getStringType() {
if ( stringType == null ) {
stringType = sessionFactory.getTypeConfiguration()
.getBasicTypeRegistry()
.resolve( StandardBasicTypes.STRING );
}
return stringType;
}
public BasicType<Boolean> getBooleanType() {
if ( booleanType == null ) {
booleanType = sessionFactory.getTypeConfiguration()
.getBasicTypeRegistry()
.resolve( StandardBasicTypes.BOOLEAN );
}
return booleanType;
}
/**
* A lazy session implementation that is needed for rendering literals.
* Usually, only the {@link WrapperOptions} interface is needed,
* but for creating LOBs, it might be to have a full-blown session.
*/
private static class LazySessionWrapperOptions extends AbstractDelegatingWrapperOptions {
private final SessionFactoryImplementor sessionFactory;
private SessionImplementor session;
public LazySessionWrapperOptions(SessionFactoryImplementor sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void cleanup() {
if ( session != null ) {
session.close();
session = null;
}
}
@Override
protected SessionImplementor delegate() {
if ( session == null ) {
session = sessionFactory.openTemporarySession();
}
return session;
}
@Override
public SharedSessionContractImplementor getSession() {
return delegate();
}
@Override
public SessionFactoryImplementor getSessionFactory() {
return sessionFactory;
}
@Override
public boolean useStreamForLobBinding() {
return sessionFactory.getFastSessionServices().useStreamForLobBinding();
}
@Override
public int getPreferredSqlTypeCodeForBoolean() {
return sessionFactory.getFastSessionServices().getPreferredSqlTypeCodeForBoolean();
}
@Override
public TimeZone getJdbcTimeZone() {
return sessionFactory.getSessionFactoryOptions().getJdbcTimeZone();
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// for tests, for now
public String getSql() {
return sqlBuffer.toString();
}
// For Blaze-Persistence until its function rendering code doesn't depend on SQL fragments anymore
@Internal
public StringBuilder getSqlBuffer() {
return sqlBuffer;
}
protected void cleanup() {
if ( lazySessionWrapperOptions != null ) {
lazySessionWrapperOptions.cleanup();
lazySessionWrapperOptions = null;
}
this.jdbcParameterBindings = null;
this.lockOptions = null;
this.limit = null;
setOffsetParameter( null );
setLimitParameter( null );
}
public List<JdbcParameterBinder> getParameterBinders() {
return parameterBinders;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@SuppressWarnings("unused")
protected SqlAppender getSqlAppender() {
return this;
}
@Override
public Set<String> getAffectedTableNames() {
return affectedTableNames;
}
protected Statement getStatement() {
return statementStack.getRoot();
}
public MutationStatement getCurrentDmlStatement() {
return statementStack.findCurrentFirst( AbstractSqlAstTranslator::matchMutationStatement );
}
private static MutationStatement matchMutationStatement(Statement stmt) {
if ( stmt instanceof MutationStatement ) {
return (MutationStatement) stmt;
}
return null;
}
protected SqlAstNodeRenderingMode getParameterRenderingMode() {
return parameterRenderingMode;
}
protected void addAdditionalWherePredicate(Predicate predicate) {
additionalWherePredicate = Predicate.combinePredicates( additionalWherePredicate, predicate );
}
@Override
public boolean supportsFilterClause() {
// By default, we report false because not many dialects support this
return false;
}
@Override
public void appendSql(String fragment) {
sqlBuffer.append( fragment );
}
@Override
public void appendSql(char fragment) {
sqlBuffer.append( fragment );
}
@Override
public void appendSql(int value) {
sqlBuffer.append( value );
}
@Override
public void appendSql(long value) {
sqlBuffer.append( value );
}
@Override
public void appendSql(boolean value) {
sqlBuffer.append( value );
}
@Override
public Appendable append(CharSequence csq) {
sqlBuffer.append( csq );
return this;
}
@Override
public Appendable append(CharSequence csq, int start, int end) {
sqlBuffer.append( csq, start, end );
return this;
}
@Override
public Appendable append(char c) {
sqlBuffer.append( c );
return this;
}
protected JdbcServices getJdbcServices() {
return getSessionFactory().getJdbcServices();
}
protected void addAppliedParameterBinding(JdbcParameter parameter, JdbcParameterBinding binding) {
if ( appliedParameterBindings.isEmpty() ) {
appliedParameterBindings = new IdentityHashMap<>();
}
if ( binding == null ) {
appliedParameterBindings.put( parameter, null );
}
else {
final JdbcMapping bindType = binding.getBindType();
//noinspection unchecked
final Object value = ( (JavaType<Object>) bindType.getJdbcJavaType() )
.getMutabilityPlan()
.deepCopy( binding.getBindValue() );
appliedParameterBindings.put( parameter, new JdbcParameterBindingImpl( bindType, value ) );
}
}
protected Map<JdbcParameter, JdbcParameterBinding> getAppliedParameterBindings() {
return appliedParameterBindings;
}
protected JdbcLockStrategy getJdbcLockStrategy() {
return lockOptions == null ? JdbcLockStrategy.FOLLOW_ON : JdbcLockStrategy.NONE;
}
protected JdbcParameterBindings getJdbcParameterBindings() {
return jdbcParameterBindings;
}
protected LockOptions getLockOptions() {
return lockOptions;
}
protected Limit getLimit() {
return limit;
}
protected boolean hasLimit() {
return limit != null && !limit.isEmpty();
}
protected boolean hasLimit(QueryPart queryPart) {
if ( queryPart.isRoot() && hasLimit() && limit.getMaxRows() != null ) {
return true;
}
else {
return queryPart.getFetchClauseExpression() != null;
}
}
protected boolean hasOffset(QueryPart queryPart) {
if ( queryPart.isRoot() && hasLimit() && limit.getFirstRow() != null ) {
return true;
}
else {
return queryPart.getOffsetClauseExpression() != null;
}
}
protected boolean useOffsetFetchClause(QueryPart queryPart) {
return !queryPart.isRoot() || limit == null || limit.isEmpty();
}
protected boolean isRowsOnlyFetchClauseType(QueryPart queryPart) {
if ( queryPart.isRoot() && hasLimit() || queryPart.getFetchClauseType() == null ) {
return true;
}
else {
return queryPart.getFetchClauseType() == FetchClauseType.ROWS_ONLY;
}
}
protected JdbcParameter getOffsetParameter() {
return offsetParameter;
}
protected void setOffsetParameter(JdbcParameter offsetParameter) {
this.offsetParameter = offsetParameter;
}
protected JdbcParameter getLimitParameter() {
return limitParameter;
}
protected void setLimitParameter(JdbcParameter limitParameter) {
this.limitParameter = limitParameter;
}
@SuppressWarnings("unchecked")
protected <R> R interpretExpression(Expression expression, JdbcParameterBindings jdbcParameterBindings) {
if ( expression instanceof Literal ) {
return (R) ( (Literal) expression ).getLiteralValue();
}
else if ( expression instanceof JdbcParameter ) {
if ( jdbcParameterBindings == null ) {
throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" );
}
return (R) getParameterBindValue( (JdbcParameter) expression );
}
else if ( expression instanceof SqmParameterInterpretation ) {
if ( jdbcParameterBindings == null ) {
throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" );
}
return (R) getParameterBindValue( (JdbcParameter) ( (SqmParameterInterpretation) expression).getResolvedExpression() );
}
throw new UnsupportedOperationException( "Can't interpret expression: " + expression );
}
protected void renderExpressionAsLiteral(Expression expression, JdbcParameterBindings jdbcParameterBindings) {
if ( expression instanceof Literal ) {
expression.accept( this );
return;
}
else if ( expression instanceof JdbcParameter ) {
if ( jdbcParameterBindings == null ) {
throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" );
}
final JdbcParameter parameter = (JdbcParameter) expression;
renderAsLiteral( parameter, getParameterBindValue( parameter ) );
return;
}
else if ( expression instanceof SqmParameterInterpretation ) {
if ( jdbcParameterBindings == null ) {
throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" );
}
final JdbcParameter parameter = (JdbcParameter) ( (SqmParameterInterpretation) expression).getResolvedExpression();
renderAsLiteral( parameter, getParameterBindValue( parameter ) );
return;
}
throw new UnsupportedOperationException( "Can't render expression as literal: " + expression );
}
protected Object getParameterBindValue(JdbcParameter parameter) {
final JdbcParameterBinding binding;
if ( parameter == getOffsetParameter() ) {
binding = new JdbcParameterBindingImpl( getIntegerType(), getLimit().getFirstRow() );
}
else if ( parameter == getLimitParameter() ) {
binding = new JdbcParameterBindingImpl( getIntegerType(), getLimit().getMaxRows() );
}
else {
binding = jdbcParameterBindings.getBinding( parameter );
}
addAppliedParameterBinding( parameter, binding );
return binding.getBindValue();
}
protected Expression getLeftHandExpression(Predicate predicate) {
if ( predicate instanceof NullnessPredicate ) {
return ( (NullnessPredicate) predicate ).getExpression();
}
assert predicate instanceof ComparisonPredicate;
return ( (ComparisonPredicate) predicate ).getLeftHandExpression();
}
protected boolean inOverOrWithinGroupClause() {
return clauseStack.findCurrentFirst( AbstractSqlAstTranslator::matchOverOrWithinGroupClauses ) != null;
}
private static Boolean matchOverOrWithinGroupClauses(final Clause clause) {
switch ( clause ) {
case OVER:
case WITHIN_GROUP:
return Boolean.TRUE;
default:
return null;
}
}
protected Stack<Clause> getClauseStack() {
return clauseStack;
}
protected Stack<Statement> getStatementStack() {
return statementStack;
}
protected Stack<QueryPart> getQueryPartStack() {
return queryPartStack;
}
@Override
public QueryPart getCurrentQueryPart() {
return queryPartStack.getCurrent();
}
@Override
public Stack<Clause> getCurrentClauseStack() {
return clauseStack;
}
protected CteStatement getCurrentCteStatement() {
return currentCteStatement;
}
protected CteStatement getCteStatement(final String cteName) {
return statementStack.findCurrentFirstWithParameter( cteName, AbstractSqlAstTranslator::matchCteStatement );
}
private static CteStatement matchCteStatement(final Statement stmt, final String cteName) {
if ( stmt instanceof CteContainer ) {
final CteContainer cteContainer = (CteContainer) stmt;
return cteContainer.getCteStatement( cteName );
}
return null;
}
private static CteContainer matchCteContainerByStatement(final Statement stmt, final String cteName) {
if ( stmt instanceof CteContainer ) {
final CteContainer cteContainer = (CteContainer) stmt;
if ( cteContainer.getCteStatement( cteName ) != null ) {
return cteContainer;
}
}
return null;
}
@Override
public T translate(JdbcParameterBindings jdbcParameterBindings, QueryOptions queryOptions) {
try {
this.jdbcParameterBindings = jdbcParameterBindings;
final Statement statement = statementStack.pop();
if ( statement instanceof TableMutation ) {
return translateTableMutation( (TableMutation<?>) statement );
}
this.lockOptions = queryOptions.getLockOptions().makeCopy();
this.limit = queryOptions.getLimit() == null ? null : queryOptions.getLimit().makeCopy();
final JdbcOperation jdbcOperation;
if ( statement instanceof DeleteStatement ) {
jdbcOperation = translateDelete( (DeleteStatement) statement );
}
else if ( statement instanceof UpdateStatement ) {
jdbcOperation = translateUpdate( (UpdateStatement) statement );
}
else if ( statement instanceof InsertSelectStatement ) {
jdbcOperation = translateInsert( (InsertSelectStatement) statement );
}
else if ( statement instanceof SelectStatement ) {
jdbcOperation = translateSelect( (SelectStatement) statement );
}
else {
throw new IllegalArgumentException( "Unexpected statement - " + statement );
}
//noinspection unchecked
return (T) jdbcOperation;
}
finally {
cleanup();
}
}
protected JdbcOperationQueryDelete translateDelete(DeleteStatement sqlAst) {
visitDeleteStatement( sqlAst );
return new JdbcOperationQueryDelete(
getSql(),
getParameterBinders(),
getAffectedTableNames(),
getAppliedParameterBindings()
);
}
protected JdbcOperationQueryUpdate translateUpdate(UpdateStatement sqlAst) {
visitUpdateStatement( sqlAst );
return new JdbcOperationQueryUpdate(
getSql(),
getParameterBinders(),
getAffectedTableNames(),
getAppliedParameterBindings()
);
}
protected JdbcOperationQueryInsert translateInsert(InsertSelectStatement sqlAst) {
visitInsertStatement( sqlAst );
return new JdbcOperationQueryInsertImpl(
getSql(),
getParameterBinders(),
getAffectedTableNames(),
getUniqueConstraintNameThatMayFail(sqlAst)
);
}
protected String getUniqueConstraintNameThatMayFail(InsertSelectStatement sqlAst) {
final ConflictClause conflictClause = sqlAst.getConflictClause();
if ( conflictClause == null || !conflictClause.getConstraintColumnNames().isEmpty() ) {
return null;
}
else {
if ( sqlAst.getSourceSelectStatement() != null && !isFetchFirstRowOnly( sqlAst.getSourceSelectStatement() )
|| sqlAst.getValuesList().size() > 1 ) {
throw new IllegalQueryOperationException( "Can't emulate conflict clause with constraint name for more than one row to insert" );
}
return conflictClause.getConstraintName() == null ? "" : conflictClause.getConstraintName();
}
}
protected JdbcOperationQuerySelect translateSelect(SelectStatement selectStatement) {
logDomainResultGraph( selectStatement.getDomainResultDescriptors() );
logSqlAst( selectStatement );
visitSelectStatement( selectStatement );
final int rowsToSkip;
return new JdbcOperationQuerySelect(
getSql(),
getParameterBinders(),
buildJdbcValuesMappingProducer( selectStatement ),
getAffectedTableNames(),
rowsToSkip = getRowsToSkip( selectStatement, getJdbcParameterBindings() ),
getMaxRows( selectStatement, getJdbcParameterBindings(), rowsToSkip ),
getAppliedParameterBindings(),
getJdbcLockStrategy(),
getOffsetParameter(),
getLimitParameter()
);
}
private JdbcValuesMappingProducer buildJdbcValuesMappingProducer(SelectStatement selectStatement) {
return getSessionFactory()
.getFastSessionServices()
.getJdbcValuesMappingProducerProvider()
.buildMappingProducer( selectStatement, getSessionFactory() );
}
protected int getRowsToSkip(SelectStatement sqlAstSelect, JdbcParameterBindings jdbcParameterBindings) {
if ( hasLimit() ) {
if ( offsetParameter != null && needsRowsToSkip() ) {
return interpretExpression( offsetParameter, jdbcParameterBindings );
}
}
else {
final Expression offsetClauseExpression = sqlAstSelect.getQueryPart().getOffsetClauseExpression();
if ( offsetClauseExpression != null && needsRowsToSkip() ) {
return interpretExpression( offsetClauseExpression, jdbcParameterBindings );
}
}
return 0;
}
protected int getMaxRows(SelectStatement sqlAstSelect, JdbcParameterBindings jdbcParameterBindings, int rowsToSkip) {
if ( hasLimit() ) {
if ( limitParameter != null && needsMaxRows() ) {
final Number fetchCount = interpretExpression( limitParameter, jdbcParameterBindings );
return rowsToSkip + fetchCount.intValue();
}
}
else {
final Expression fetchClauseExpression = sqlAstSelect.getQueryPart().getFetchClauseExpression();
if ( fetchClauseExpression != null && needsMaxRows() ) {
final Number fetchCount = interpretExpression( fetchClauseExpression, jdbcParameterBindings );
return rowsToSkip + fetchCount.intValue();
}
}
return Integer.MAX_VALUE;
}
protected boolean needsRowsToSkip() {
return false;
}
protected boolean needsMaxRows() {
return false;
}
protected void prepareLimitOffsetParameters() {
final Limit limit = getLimit();
if ( limit.getFirstRow() != null ) {
setOffsetParameter(
new OffsetJdbcParameter(
sessionFactory.getTypeConfiguration().getBasicTypeForJavaType( Integer.class )
)
);
}
if ( limit.getMaxRows() != null ) {
setLimitParameter(
new LimitJdbcParameter(
sessionFactory.getTypeConfiguration().getBasicTypeForJavaType( Integer.class )
)
);
}
}
private static class OffsetJdbcParameter extends AbstractJdbcParameter {
public OffsetJdbcParameter(BasicType<Integer> type) {
super( type );
}
@Override
public void bindParameterValue(
PreparedStatement statement,
int startPosition,
JdbcParameterBindings jdbcParamBindings,
ExecutionContext executionContext) throws SQLException {
//noinspection unchecked
getJdbcMapping().getJdbcValueBinder().bind(
statement,
executionContext.getQueryOptions().getLimit().getFirstRow(),
startPosition,
executionContext.getSession()
);
}
}
private static class LimitJdbcParameter extends AbstractJdbcParameter {
public LimitJdbcParameter(BasicType<Integer> type) {
super( type );
}
@Override
public void bindParameterValue(
PreparedStatement statement,
int startPosition,
JdbcParameterBindings jdbcParamBindings,
ExecutionContext executionContext) throws SQLException {
//noinspection unchecked
getJdbcMapping().getJdbcValueBinder().bind(
statement,
executionContext.getQueryOptions().getLimit().getMaxRows(),
startPosition,
executionContext.getSession()
);
}
}
@Override