-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathSmartQuery.java
1065 lines (957 loc) · 40.7 KB
/
SmartQuery.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
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.db.jdbc;
import sirius.db.jdbc.constraints.SQLConstraint;
import sirius.db.mixing.BaseEntity;
import sirius.db.mixing.BaseMapper;
import sirius.db.mixing.EntityDescriptor;
import sirius.db.mixing.Mapping;
import sirius.db.mixing.properties.BaseEntityRefProperty;
import sirius.db.mixing.properties.SQLEntityRefProperty;
import sirius.db.mixing.query.Query;
import sirius.db.mixing.query.constraints.FilterFactory;
import sirius.db.mixing.types.BaseEntityRef;
import sirius.kernel.async.TaskContext;
import sirius.kernel.commons.Explain;
import sirius.kernel.commons.Limit;
import sirius.kernel.commons.Monoflop;
import sirius.kernel.commons.PullBasedSpliterator;
import sirius.kernel.commons.Strings;
import sirius.kernel.commons.Tuple;
import sirius.kernel.commons.Value;
import sirius.kernel.commons.Watch;
import sirius.kernel.di.std.Part;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.HandledException;
import sirius.kernel.health.Microtiming;
import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* Provides a query DSL which is used to query {@link SQLEntity} instances from the database.
*
* @param <E> the generic type of entities being queried
*/
public class SmartQuery<E extends SQLEntity> extends Query<SmartQuery<E>, E, SQLConstraint> {
@Part
private static OMA oma;
@Part
private static Databases dbs;
protected List<Mapping> fields = Collections.emptyList();
protected List<String> aggregationFields = Collections.emptyList();
protected boolean distinct;
protected List<Tuple<Mapping, Boolean>> orderBys = new ArrayList<>();
protected List<String> groupBys = Collections.emptyList();
protected List<SQLConstraint> constraints = new ArrayList<>();
protected Database db;
protected Map<String, String> indexHints = new HashMap<>();
/**
* Indicates the "FOR" hint for the optimizer, when used with "USE INDEX" and "IGNORE INDEX".
*/
public enum IndexForHint {
/**
* Indicates to the optimizer that the index should be used, when the table is joined with another table.
*/
JOIN,
/**
* Indicates to the optimizer that the index should be used, when the table is ordered.
*/
ORDER_BY,
/**
* Indicates to the optimizer that the index should be used, when the results are grouped.
*/
GROUP_BY
}
/**
* Creates a new query instance.
* <p>
* Use {@link OMA#select(Class)} to create a new query.
*
* @param descriptor the descriptor of the type to query
* @param db the database to operate on
*/
protected SmartQuery(EntityDescriptor descriptor, Database db) {
super(descriptor);
this.db = db;
}
/**
* Returns the <tt>EntityDescriptor</tt> for the type of entities addressed by this query.
*
* @return the underlying entity descriptor of this query.
*/
public EntityDescriptor getEntityDescriptor() {
return descriptor;
}
@Override
public SmartQuery<E> where(SQLConstraint constraint) {
if (constraint != null) {
this.constraints.add(constraint);
}
return this;
}
/**
* Adds a "USE INDEX" hint for a table that recommends an index to the optimizer.
*
* @param table the table for which the index should be used.
* @param forHint the action for which the index should be used. Can be null.
* @param indexName the name of the index to use.
* @param <T> the type of the entities being queried.
* @return the query itself for fluent method calls.
*/
public <T extends SQLEntity> SmartQuery<E> useIndex(Class<T> table, IndexForHint forHint, String indexName) {
indexHint(table, "USE", forHint, indexName);
return this;
}
/**
* Adds a "FORCE INDEX" hint for a table that forces an index to the optimizer.
*
* @param table the table for wh index to use.
* @param indexName the name of the index to use.
* @param <T> the type of the entities the index should be used.
* @return the query itself for fluent method calls.
*/
public <T extends SQLEntity> SmartQuery<E> forceIndex(Class<T> table, String indexName) {
indexHint(table, "FORCE", null, indexName);
return this;
}
/**
* Adds a "IGNORE INDEX" hint for a table that makes the optimizer to not consider the given index.
*
* @param table the table for which the index should be used.
* @param forHint the {@link IndexForHint} for which the index should be used. Can be null.
* @param indexName the name of the index to use.
* @param <T> the type of the entities being queried.
* @return the query itself for fluent method calls
*/
public <T extends SQLEntity> SmartQuery<E> ignoreIndex(Class<T> table, IndexForHint forHint, String indexName) {
indexHint(table, "IGNORE", forHint, indexName);
return this;
}
/**
* Adds a hint for a table that is used by the optimizer.
*
* @param table the table for which the index should be used.
* @param type the type of the hint. Can be "USE", "FORCE" or "IGNORE".
* @param forHint the {@link IndexForHint} for which the index should be used. Can be null.
* @param indexName the name of the index to use.
* @param <T> the type of entities being queried.
*/
private <T extends SQLEntity> void indexHint(Class<T> table, String type, IndexForHint forHint, String indexName) {
StringBuilder indexHint = new StringBuilder();
indexHint.append(" ").append(type).append(" INDEX");
if (forHint != null) {
indexHint.append(" FOR ");
indexHint.append(forHint.name().replace("_", " "));
}
indexHint.append(" (").append(indexName).append(")");
indexHints.put(mixing.getDescriptor(table).getRelationName(), indexHint.toString());
}
@Override
public FilterFactory<SQLConstraint> filters() {
return oma.filters();
}
@Override
public SmartQuery<E> orderAsc(Mapping field) {
orderBys.add(Tuple.create(field, true));
return this;
}
@Override
public SmartQuery<E> orderDesc(Mapping field) {
orderBys.add(Tuple.create(field, false));
return this;
}
/**
* Specifies the fields to select, which also have to be <tt>DISTINCT</tt>.
*
* @param fields the fields to select and to apply a <tt>DISTINCT</tt> filter on.
* @return the query itself for fluent method calls
*/
public SmartQuery<E> distinctFields(Mapping... fields) {
this.fields = Arrays.asList(fields);
this.distinct = true;
return this;
}
/**
* Specifies which fields to select.
* <p>
* If no fields are given, <tt>*</tt> is selected
*
* @param fields the list of fields to select
* @return the query itself for fluent method calls
*/
public SmartQuery<E> fields(Mapping... fields) {
this.fields = Arrays.asList(fields);
return this;
}
/**
* Adds a complex expression like an aggregation function to the <tt>SELECT</tt> clause of the generated SQL.
* <p>
* In contrast to {@link #fields(Mapping...)}, this adds an expression but does not replace the previous ones
* (neither those added via {@link #fields(Mapping...)} nor other {@link #aggregationField(String)} calls).
* Therefore, this can be used to add fields or aggregations conditionally.
* <p>
* <b>NOTE:</b> This cannot be used in "normal" entity queries, as the O/R mapper cannot handle aggregations.
* Rather, the query has to be converted using {@link #asSQLQuery()} which then permits direct access to rows.
* <p>
* <b>ALSO NOTE:</b> The given expressions will directly end up on the SQL query and must therefore be constant
* and safe string which aren't subject to SQL injection attacks!
*
* @param expression the expression to group by
* @return the query itself for fluent method calls
* @see #groupBy(String)
* @see #asSQLQuery()
*/
public SmartQuery<E> aggregationField(String expression) {
if (this.aggregationFields.isEmpty()) {
this.aggregationFields = new ArrayList<>();
}
this.aggregationFields.add(expression);
return this;
}
/**
* Adds an expression to the <tt>GROUP BY</tt> clause of the generated SQL.
* <p>
* <b>NOTE:</b> This cannot be used in "normal" entity queries, as the O/R mapper cannot handle aggregations.
* Rather, the query has to be converted using {@link #asSQLQuery()} which then permits direct access to rows.
* <p>
* <b>ALSO NOTE:</b> The given expressions will directly end up on the SQL query and must therefore be constant
* and safe string which aren't subject to SQL injection attacks!
*
* @param expression the expression to group by
* @return the query itself for fluent method calls
* @see #aggregationField(String)
* @see #asSQLQuery()
*/
public SmartQuery<E> groupBy(String expression) {
if (this.groupBys.isEmpty()) {
this.groupBys = new ArrayList<>();
}
this.groupBys.add(expression);
return this;
}
@Override
public long count() {
if (forceFail) {
return 0;
}
Watch w = Watch.start();
Compiler compiler = compileCOUNT();
compiler.getIndexHints().putAll(indexHints);
try {
try (Connection c = db.getConnection()) {
return execCount(compiler, c);
} finally {
if (Microtiming.isEnabled()) {
w.submitMicroTiming("OMA", "COUNT: " + compiler.getQuery());
}
}
} catch (Exception e) {
throw queryError(compiler, e);
}
}
protected HandledException queryError(Compiler compiler, Exception e) {
return Exceptions.handle()
.to(OMA.LOG)
.error(e)
.withSystemErrorMessage("Error executing query '%s' for type '%s': %s (%s)",
compiler,
descriptor.getType().getName())
.handle();
}
protected long execCount(Compiler compiler, Connection c) throws SQLException {
try (PreparedStatement stmt = compiler.prepareStatement(c)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getLong(1);
} else {
return 0;
}
}
}
}
@Override
public boolean exists() {
if (forceFail) {
return false;
}
return copy().fields(SQLEntity.ID).first().isPresent();
}
@Override
public void delete(@Nullable Consumer<E> entityCallback) {
streamBlockwise().forEach(entity -> {
if (entityCallback != null) {
entityCallback.accept(entity);
}
oma.delete(entity);
});
}
@Override
public Stream<E> streamBlockwise() {
if (forceFail) {
return Stream.empty();
}
return StreamSupport.stream(new SmartQuerySpliterator(), false);
}
private class SmartQuerySpliterator extends PullBasedSpliterator<E> {
private E lastValue = null;
private List<Object> orderByValuesOfLastEntityDuringFetch = null;
private final TaskContext taskContext = TaskContext.get();
private final SmartQuery<E> adjustedQuery;
private SmartQuerySpliterator() {
adjustedQuery = adjustQuery(SmartQuery.this);
}
@Override
public int characteristics() {
return NONNULL | IMMUTABLE | ORDERED;
}
@Override
protected Iterator<E> pullNextBlock() {
if (!taskContext.isActive()) {
return null;
}
List<E> block = queryNextBlock();
if (!block.isEmpty()) {
lastValue = block.getLast();
orderByValuesOfLastEntityDuringFetch = extractOrderByValues(lastValue);
}
return block.iterator();
}
private SmartQuery<E> adjustQuery(SmartQuery<E> query) {
SmartQuery<E> adjusted = query.copy();
if (adjusted.limit > 0) {
throw new UnsupportedOperationException("SmartQuery doesn't allow 'limit' in streamBlockwise");
}
if (adjusted.skip > 0) {
throw new UnsupportedOperationException("SmartQuery doesn't allow 'skip' in streamBlockwise");
}
// we need to guarantee an absolute ordering
if (adjusted.distinct) {
// we have distinct fields, so we can easily create an absolute ordering, if it's not already there
adjusted.fields.stream()
.filter(Predicate.not(new HashSet<>(Tuple.firsts(orderBys))::contains))
.forEach(adjusted::orderAsc);
} else {
// we are not DISTINCT, so we can easily guarantee an absolute ordering using the ID
adjusted.orderAsc(BaseEntity.ID);
}
if (!adjusted.distinct && !fields.isEmpty()) {
// We SELECT a subset of the columns to optimize the network bandwidth.
// When pulling the next block, we need to continue exactly where we left of, so we need to SELECT
// at least all the fields from the ORDER BY clause.
Set<Mapping> allFields = new HashSet<>(adjusted.fields);
allFields.addAll(Tuple.firsts(adjusted.orderBys));
adjusted.fields(allFields.toArray(Mapping[]::new));
}
return adjusted;
}
private List<Object> extractOrderByValues(E entity) {
return Tuple.firsts(adjustedQuery.orderBys).stream().map(field -> getPropertyValue(field, entity)).toList();
}
private List<E> queryNextBlock() {
SmartQuery<E> effectiveQuery = adjustedQuery.copy().limit(MAX_LIST_SIZE);
if (lastValue == null) {
return effectiveQuery.queryList();
}
List<Object> orderByValuesOfLastEntity = extractOrderByValues(lastValue);
if (!orderByValuesOfLastEntityDuringFetch.equals(orderByValuesOfLastEntity)) {
throw new IllegalStateException(Strings.apply(
"Entity '%s' was changed while streaming over it. This is very likely to cause bad result sets, including infinity loops, and is not supported.\nPrevious values: %s\nCurrent values: %s",
lastValue,
orderByValuesOfLastEntityDuringFetch,
orderByValuesOfLastEntity));
}
SQLConstraint sortingFilterConstraint = null;
Map<Mapping, Object> previousSortingColumns = new HashMap<>();
for (Tuple<Mapping, Boolean> sorting : effectiveQuery.orderBys) {
Mapping sortColumn = sorting.getFirst();
boolean sortAscending = sorting.getSecond().booleanValue();
Object value = getPropertyValue(sortColumn, lastValue);
SQLConstraint currentColumConstraint =
createSqlConstraintForSortingColumn(sortAscending, sortColumn, value, previousSortingColumns);
sortingFilterConstraint = OMA.FILTERS.or(sortingFilterConstraint, currentColumConstraint);
previousSortingColumns.put(sortColumn, value);
}
return effectiveQuery.where(sortingFilterConstraint).queryList();
}
private Object getPropertyValue(Mapping mapping, BaseEntity<?> entity) {
BaseEntity<?> parent = findParent(mapping, entity);
return parent.getDescriptor().getProperty(mapping.getName()).getValue(parent);
}
private BaseEntity<?> findParent(Mapping mapping, BaseEntity<?> entity) {
if (mapping.getParent() != null) {
BaseEntity<?> parentEntity = findParent(mapping.getParent(), entity);
if (parentEntity.getDescriptor()
.getProperty(mapping.getParent()
.getName()) instanceof BaseEntityRefProperty<?, ?, ?> ref) {
BaseEntityRef<?, ?> entityRef = ref.getEntityRef(parentEntity);
return entityRef.getValueIfPresent().orElseThrow(() -> {
return new IllegalArgumentException(Strings.apply(
"The BaseEntityRef `%s` is not loaded, but is requested by the mapping `%s`.",
entityRef.getUniqueObjectName(),
mapping.getParent()));
});
} else {
throw new IllegalArgumentException(Strings.apply("You cannot join on the non-ref property `%s`",
mapping.getParent()));
}
}
return entity;
}
}
/**
* Creates a sql constraint for sorting purposes.
* </p>
* In MySQL/MariaDB, NULL is considered as a 'missing, unknown value'. Any arithmetic comparison with NULL
* returns false e.g. NULL != 'any' returns false.
* Therefore, comparisons with NULL values must be treated specially.
*
* @param sortAscending decides whether the sorting direction is descending or ascending
* @param column the column to be used for sorting
* @param value the value of the column
* @param previousSortingColumns all columns that should be sorted before the current one
* @return {@link SQLConstraint} which can be used to map a level of sorting.
*/
SQLConstraint createSqlConstraintForSortingColumn(boolean sortAscending,
Mapping column,
Object value,
Map<Mapping, Object> previousSortingColumns) {
SQLConstraint sortingStep = null;
for (Map.Entry<Mapping, Object> previousColumn : previousSortingColumns.entrySet()) {
sortingStep =
OMA.FILTERS.and(sortingStep, OMA.FILTERS.eq(previousColumn.getKey(), previousColumn.getValue()));
}
if (value == null) {
return createConstraintForSortingWithNull(sortAscending, sortingStep, column);
}
if (nullValuesFirst(sortAscending)) {
return OMA.FILTERS.and(sortingStep, OMA.FILTERS.gt(column, value));
} else {
return OMA.FILTERS.and(sortingStep,
OMA.FILTERS.or(OMA.FILTERS.lt(column, value), OMA.FILTERS.eq(column, null)));
}
}
private SQLConstraint createConstraintForSortingWithNull(boolean sortAscending,
SQLConstraint sortingStep,
Mapping column) {
if (nullValuesFirst(sortAscending)) {
return OMA.FILTERS.and(sortingStep, OMA.FILTERS.ne(column, null));
}
return null;
}
/**
* Indicates whether null values are listed before or after non-null values when executing this query.
* <p>
* Both the sort order and the implementation in the database tell us whether we will get a
* result where the null values are at the beginning or at the end.
*
* @param sortAscending decides whether the sorting direction is descending or ascending
* @return {@code true} if the sorted list starts with null values
*/
private boolean nullValuesFirst(boolean sortAscending) {
if (db == null) {
// should be only true in tests
return sortAscending;
}
if (sortAscending) {
return db.hasCapability(Capability.NULLS_FIRST);
} else {
return !db.hasCapability(Capability.NULLS_FIRST);
}
}
@Override
public void truncate() {
throw new UnsupportedOperationException(
"Truncate is not supported by OMA. Use as OMA.deleteStatement or SmartQuery.delete()");
}
/**
* Converts this query into a plain {@link SQLQuery} which will return rows instead of entities.
*
* @return the query converted into a plain SQL query.
*/
public SQLQuery asSQLQuery() {
if (forceFail) {
throw new IllegalStateException("A failed query can not be converted into a SQL query.");
}
Compiler compiler = compileSELECT();
return new SQLQuery(db, compiler.getQuery()) {
@Override
protected PreparedStatement createPreparedStatement(Connection c) throws SQLException {
return compiler.prepareStatement(c);
}
};
}
/**
* Creates a full copy of the query which can be modified without modifying this query.
*
* @return a copy of this query
*/
public SmartQuery<E> copy() {
SmartQuery<E> copy = new SmartQuery<>(descriptor, db);
copy.distinct = distinct;
copy.forceFail = forceFail;
copy.fields = new ArrayList<>(fields);
copy.orderBys.addAll(orderBys);
copy.constraints.addAll(constraints);
copy.limit = limit;
copy.skip = skip;
copy.indexHints = indexHints;
return copy;
}
@Override
protected void doIterate(Predicate<E> handler) {
if (forceFail) {
return;
}
Compiler compiler = compileSELECT();
try {
Watch w = Watch.start();
try (Connection c = db.getConnection(); PreparedStatement stmt = compiler.prepareStatement(c)) {
Limit limit = getLimit();
boolean nativeLimit = db.hasCapability(Capability.LIMIT);
tuneStatement(stmt, limit, nativeLimit);
try (ResultSet rs = stmt.executeQuery()) {
execIterate(handler, compiler, limit, nativeLimit, rs);
}
} finally {
if (Microtiming.isEnabled()) {
w.submitMicroTiming("OMA", "ITERATE: " + compiler.getQuery());
}
}
} catch (Exception e) {
throw queryError(compiler, e);
}
}
@SuppressWarnings("unchecked")
protected void execIterate(Predicate<E> handler,
Compiler compiler,
Limit limit,
boolean nativeLimit,
ResultSet resultSet) throws Exception {
Set<String> columns = dbs.readColumns(resultSet);
while (resultSet.next()) {
if (nativeLimit || limit.nextRow()) {
SQLEntity entity = makeEntity(descriptor, null, columns, resultSet);
compiler.executeJoinFetches(entity, columns, resultSet);
if (!handler.test((E) entity)) {
return;
}
}
if (!nativeLimit && !limit.shouldContinue()) {
return;
}
}
}
private static SQLEntity makeEntity(EntityDescriptor descriptor, String alias, Set<String> columns, ResultSet rs)
throws Exception {
SQLEntity result = (SQLEntity) descriptor.make(OMA.class, alias, key -> {
try {
return columns.contains(key.toUpperCase()) ? Value.of(rs.getObject(key)) : null;
} catch (SQLException e) {
throw Exceptions.handle(OMA.LOG, e);
}
});
if (descriptor.isVersioned() && columns.contains(BaseMapper.VERSION.toUpperCase())) {
result.setVersion(rs.getInt(BaseMapper.VERSION.toUpperCase()));
}
return result;
}
protected void tuneStatement(PreparedStatement stmt, Limit limit, boolean nativeLimit) throws SQLException {
if (!nativeLimit && limit.getTotalItems() > 0) {
stmt.setMaxRows(limit.getTotalItems());
}
if (limit.getTotalItems() > SQLQuery.DEFAULT_FETCH_SIZE || limit.getTotalItems() <= 0) {
if (db.hasCapability(Capability.STREAMING)) {
stmt.setFetchSize(1);
} else {
stmt.setFetchSize(SQLQuery.DEFAULT_FETCH_SIZE);
}
}
}
/**
* Represents the compiler which is used to generate SQL statements based on a {@link SmartQuery}.
*/
public static class Compiler {
private static class JoinFetch {
String tableAlias;
SQLEntityRefProperty property;
Map<String, JoinFetch> subFetches = new TreeMap<>();
}
protected EntityDescriptor ed;
protected StringBuilder preJoinQuery = new StringBuilder();
protected StringBuilder joins = new StringBuilder();
protected StringBuilder postJoinQuery = new StringBuilder();
protected List<Object> parameters = new ArrayList<>();
protected Map<String, Tuple<String, EntityDescriptor>> joinTable = new TreeMap<>();
protected AtomicInteger aliasCounter = new AtomicInteger(1);
protected String defaultAlias = "e";
protected JoinFetch rootFetch = new JoinFetch();
protected Map<String, String> indexHints = new HashMap<>();
/**
* Creates a new compiler for the given entity descriptor.
*
* @param ed the entity descriptor which is used to determine which table to select and how to JOIN other
* entities.
*/
public Compiler(@Nullable EntityDescriptor ed) {
this.ed = ed;
}
/**
* Provides access to the string builder which generates the SELECT part of the query.
*
* @return the string builder representing the SELECT part of the query
*/
public StringBuilder getSELECTBuilder() {
return preJoinQuery;
}
/**
* Provides access to the string builder which generates the WHERE part of the query.
*
* @return the string builder representing the WHERE part of the query.
*/
public StringBuilder getWHEREBuilder() {
return postJoinQuery;
}
public void setWHEREBuilder(StringBuilder newWHEREBuilder) {
this.postJoinQuery = newWHEREBuilder;
}
/**
* Generates an unique table alias.
*
* @return a table alias which is unique within this query
*/
public String generateTableAlias() {
return "t" + aliasCounter.getAndIncrement();
}
/**
* Returns the currently active translation state and replaces all settings for the new alias and base descriptor.
* <p>
* To restore the state, {@link #restoreTranslationState(TranslationState)} can be used.
*
* @param newDefaultAlias specifies the new default alias to use
* @param newDefaultDescriptor specifies the new main / default descriptor to use
* @return the currently active translation state
*/
public TranslationState captureAndReplaceTranslationState(String newDefaultAlias,
EntityDescriptor newDefaultDescriptor) {
TranslationState result = new TranslationState(ed, defaultAlias, joins, joinTable);
this.defaultAlias = newDefaultAlias;
this.ed = newDefaultDescriptor;
this.joins = new StringBuilder();
this.joinTable = new TreeMap<>();
return result;
}
/**
* Provides access to the currently generated JOINs.
*
* @return the currently generated JOINs
*/
public StringBuilder getJoins() {
return joins;
}
/**
* Restores a previously captured translation state.
*
* @param state the original state to restore
*/
public void restoreTranslationState(TranslationState state) {
this.defaultAlias = state.getDefaultAlias();
this.ed = state.getEd();
this.joins = state.getJoins();
this.joinTable = state.getJoinTable();
}
private Tuple<String, EntityDescriptor> determineAlias(Mapping parent) {
if (parent == null || ed == null) {
return Tuple.create(defaultAlias, ed);
}
String path = parent.toString();
Tuple<String, EntityDescriptor> result = joinTable.get(path);
if (result != null) {
return result;
}
Tuple<String, EntityDescriptor> parentAlias = determineAlias(parent.getParent());
SQLEntityRefProperty refProperty =
(SQLEntityRefProperty) parentAlias.getSecond().getProperty(parent.getName());
EntityDescriptor other = refProperty.getReferencedDescriptor();
String tableAlias = generateTableAlias();
joins.append(" LEFT JOIN ")
.append(other.getRelationName())
.append(" ")
.append(tableAlias)
.append(indexHints.getOrDefault(other.getRelationName(), ""))
.append(" ON ")
.append(tableAlias)
.append(".id = ")
.append(parentAlias.getFirst())
.append(".")
.append(parentAlias.getSecond().rewritePropertyName(parent.getName()));
result = Tuple.create(tableAlias, other);
joinTable.put(path, result);
return result;
}
/**
* Translates a column name into an effective name by applying aliases and rewrites.
*
* @param column the column to translate
* @return the translated name which is used in the database
*/
public String translateColumnName(Mapping column) {
Tuple<String, EntityDescriptor> aliasAndDescriptor = determineAlias(column.getParent());
EntityDescriptor effectiveDescriptor = aliasAndDescriptor.getSecond();
if (effectiveDescriptor != null) {
return aliasAndDescriptor.getFirst() + "." + effectiveDescriptor.rewritePropertyName(column.getName());
} else {
return aliasAndDescriptor.getFirst() + "." + column.getName();
}
}
private void createJoinFetch(Mapping field, List<Mapping> fields, List<Mapping> requiredColumns) {
List<Mapping> fetchPath = new ArrayList<>();
Mapping parent = field.getParent();
while (parent != null) {
fetchPath.addFirst(parent);
parent = parent.getParent();
}
JoinFetch jf = rootFetch;
EntityDescriptor currentDescriptor = ed;
for (Mapping col : fetchPath) {
if (!isContainedInFields(col, fields)) {
requiredColumns.add(col);
}
JoinFetch subFetch = jf.subFetches.get(col.getName());
if (subFetch == null) {
subFetch = new JoinFetch();
Tuple<String, EntityDescriptor> parentInfo = determineAlias(col);
subFetch.tableAlias = parentInfo.getFirst();
subFetch.property = (SQLEntityRefProperty) currentDescriptor.getProperty(col.getName());
jf.subFetches.put(col.getName(), subFetch);
}
jf = subFetch;
currentDescriptor = subFetch.property.getReferencedDescriptor();
}
}
private boolean isContainedInFields(Mapping col, List<Mapping> fields) {
return fields.stream().anyMatch(field -> field.toString().equals(col.toString()));
}
protected void executeJoinFetches(SQLEntity entity, Set<String> columns, ResultSet rs) {
executeJoinFetch(rootFetch, entity, columns, rs);
}
private void executeJoinFetch(JoinFetch jf, SQLEntity parent, Set<String> columns, ResultSet rs) {
try {
SQLEntity child = parent;
if (jf.property != null) {
child = makeEntity(jf.property.getReferencedDescriptor(), jf.tableAlias, columns, rs);
jf.property.setReferencedEntity(parent, child);
}
for (JoinFetch subFetch : jf.subFetches.values()) {
executeJoinFetch(subFetch, child, columns, rs);
}
} catch (Exception e) {
throw Exceptions.handle()
.to(OMA.LOG)
.error(e)
.withSystemErrorMessage(
"Error while trying to read join fetched values for %s (%s): %s (%s)",
jf.property,
columns)
.handle();
}
}
/**
* Adds a query parameter.
*
* @param parameter the parameter to add
*/
public void addParameter(Object parameter) {
parameters.add(parameter);
}
@SuppressWarnings("squid:S2095")
@Explain("The statement will be closed by the caller.")
private PreparedStatement prepareStatement(Connection c) throws SQLException {
PreparedStatement stmt =
c.prepareStatement(getQuery(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
for (int i = 0; i < parameters.size(); i++) {
Databases.convertAndSetParameter(stmt, i + 1, parameters.get(i));
}
return stmt;
}
protected String getQuery() {
return preJoinQuery.toString() + joins + postJoinQuery;
}
public Map<String, String> getIndexHints() {
return this.indexHints;
}
@Override
public String toString() {
if (parameters.isEmpty()) {
return getQuery();
} else {
return getQuery() + " " + parameters;
}
}
}
private Compiler compileSELECT() {
Compiler compiler = select();
from(compiler);
where(compiler);
groupBy(compiler);
orderBy(compiler);
limit(compiler);
return compiler;
}
private Compiler compileCOUNT() {
Compiler compiler = selectCount();
from(compiler);
where(compiler);
groupBy(compiler);
return compiler;
}
private Compiler select() {
Compiler c = new Compiler(descriptor);
c.getIndexHints().putAll(indexHints);
c.getSELECTBuilder().append("SELECT ");
if (fields.isEmpty() && aggregationFields.isEmpty()) {
c.getSELECTBuilder().append(" ").append(c.defaultAlias).append(".*");
} else {
if (distinct) {
c.getSELECTBuilder().append("DISTINCT ");
}
appendFieldList(c, true);
}
return c;
}
private void appendFieldList(Compiler c, boolean applyAliases) {
Monoflop mf = Monoflop.create();
List<Mapping> requiredFields = new ArrayList<>();
fields.forEach(field -> {
appendToSELECT(c, applyAliases, mf, field, true, requiredFields);
});
// make sure that the join fields are always fetched
requiredFields.forEach(requiredField -> appendToSELECT(c, applyAliases, mf, requiredField, false, null));
for (String aggregationField : aggregationFields) {
if (mf.successiveCall()) {
c.getSELECTBuilder().append(", ");
}
c.getSELECTBuilder().append(aggregationField);
}
}
private void appendToSELECT(Compiler c,
boolean applyAliases,
Monoflop mf,
Mapping field,
boolean createJoinFetch,
List<Mapping> requiredFieldsCollector) {
if (mf.successiveCall()) {
c.getSELECTBuilder().append(", ");
}
Tuple<String, EntityDescriptor> joinInfo = c.determineAlias(field.getParent());
c.getSELECTBuilder().append(joinInfo.getFirst());
c.getSELECTBuilder().append(".");
String columnName = joinInfo.getSecond().getProperty(field.getName()).getPropertyName();
c.getSELECTBuilder().append(columnName);
if (!c.defaultAlias.equals(joinInfo.getFirst())) {
if (applyAliases) {
c.getSELECTBuilder().append(" AS ");
c.getSELECTBuilder().append(joinInfo.getFirst());
c.getSELECTBuilder().append("_");
c.getSELECTBuilder().append(columnName);
}
if (createJoinFetch) {
c.createJoinFetch(field, fields, requiredFieldsCollector);
}
}
}
private Compiler selectCount() {
Compiler c = new Compiler(descriptor);
c.getSELECTBuilder().append("SELECT COUNT(");
if (fields.isEmpty() || (fields.size() == 1 && !distinct)) {
c.getSELECTBuilder().append("*");
} else if (distinct) {
c.getSELECTBuilder().append("DISTINCT ");
appendFieldList(c, false);
} else {
throw Exceptions.createHandled()
.to(OMA.LOG)
.withSystemErrorMessage("Only use multiple arguments in 'fields' and 'count' in "
+ "combination with the 'distinct' statement")
.handle();
}