-
Notifications
You must be signed in to change notification settings - Fork 228
/
QueryRewriter.java
3582 lines (3283 loc) · 157 KB
/
QueryRewriter.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
/*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.query.rewriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.*;
import org.teiid.api.exception.query.ExpressionEvaluationException;
import org.teiid.api.exception.query.FunctionExecutionException;
import org.teiid.api.exception.query.QueryMetadataException;
import org.teiid.api.exception.query.QueryResolverException;
import org.teiid.api.exception.query.QueryValidatorException;
import org.teiid.common.buffer.BlockedException;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.core.TeiidRuntimeException;
import org.teiid.core.types.DataTypeManager;
import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
import org.teiid.core.types.Transform;
import org.teiid.core.util.Assertion;
import org.teiid.core.util.EquivalenceUtil;
import org.teiid.core.util.StringUtil;
import org.teiid.core.util.TimestampWithTimezone;
import org.teiid.language.Like.MatchMode;
import org.teiid.language.SQLConstants;
import org.teiid.query.QueryPlugin;
import org.teiid.query.eval.Evaluator;
import org.teiid.query.function.FunctionDescriptor;
import org.teiid.query.function.FunctionLibrary;
import org.teiid.query.function.FunctionMethods;
import org.teiid.query.metadata.MaterializationMetadataRepository;
import org.teiid.query.metadata.QueryMetadataInterface;
import org.teiid.query.metadata.TempMetadataAdapter;
import org.teiid.query.metadata.TempMetadataID;
import org.teiid.query.metadata.TempMetadataStore;
import org.teiid.query.optimizer.relational.AliasGenerator;
import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil;
import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria;
import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria.PlannedResult;
import org.teiid.query.optimizer.relational.rules.RulePlaceAccess;
import org.teiid.query.processor.relational.RelationalNodeUtil;
import org.teiid.query.resolver.ProcedureContainerResolver;
import org.teiid.query.resolver.QueryResolver;
import org.teiid.query.resolver.util.ResolverUtil;
import org.teiid.query.resolver.util.ResolverVisitor;
import org.teiid.query.sql.LanguageObject;
import org.teiid.query.sql.LanguageObject.Util;
import org.teiid.query.sql.LanguageVisitor;
import org.teiid.query.sql.ProcedureReservedWords;
import org.teiid.query.sql.lang.*;
import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
import org.teiid.query.sql.navigator.PostOrderNavigator;
import org.teiid.query.sql.navigator.PreOrPostOrderNavigator;
import org.teiid.query.sql.proc.*;
import org.teiid.query.sql.symbol.*;
import org.teiid.query.sql.symbol.AggregateSymbol.Type;
import org.teiid.query.sql.util.SymbolMap;
import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
import org.teiid.query.sql.visitor.ElementCollectorVisitor;
import org.teiid.query.sql.visitor.EvaluatableVisitor;
import org.teiid.query.sql.visitor.EvaluatableVisitor.EvaluationLevel;
import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
import org.teiid.query.sql.visitor.GroupCollectorVisitor;
import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
import org.teiid.query.util.CommandContext;
import org.teiid.query.validator.UpdateValidator.UpdateInfo;
import org.teiid.query.validator.UpdateValidator.UpdateMapping;
import org.teiid.query.validator.ValidationVisitor;
import org.teiid.translator.SourceSystemFunctions;
/**
* Rewrites commands and command fragments to a form that is better for planning and execution. There is a current limitation that
* command objects themselves cannot change type, since the same object is always used.
*/
public class QueryRewriter {
private static final String WRITE_THROUGH = "write-through"; //$NON-NLS-1$
private static final Constant ZERO_CONSTANT = new Constant(0, DataTypeManager.DefaultDataClasses.INTEGER);
public static final CompareCriteria TRUE_CRITERIA = new ImmutableCompareCriteria(new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER));
public static final CompareCriteria FALSE_CRITERIA = new ImmutableCompareCriteria(new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER), CompareCriteria.EQ, ZERO_CONSTANT);
public static final CompareCriteria UNKNOWN_CRITERIA = new ImmutableCompareCriteria(new Constant(null, DataTypeManager.DefaultDataClasses.STRING), CompareCriteria.NE, new Constant(null, DataTypeManager.DefaultDataClasses.STRING));
private static final Map<String, String> ALIASED_FUNCTIONS = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
private static final Set<String> PARSE_FORMAT_TYPES = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
static {
ALIASED_FUNCTIONS.put("lower", SourceSystemFunctions.LCASE); //$NON-NLS-1$
ALIASED_FUNCTIONS.put("upper", SourceSystemFunctions.UCASE); //$NON-NLS-1$
ALIASED_FUNCTIONS.put("cast", SourceSystemFunctions.CONVERT); //$NON-NLS-1$
ALIASED_FUNCTIONS.put("nvl", SourceSystemFunctions.IFNULL); //$NON-NLS-1$
ALIASED_FUNCTIONS.put("||", SourceSystemFunctions.CONCAT); //$NON-NLS-1$
ALIASED_FUNCTIONS.put("chr", SourceSystemFunctions.CHAR); //$NON-NLS-1$
ALIASED_FUNCTIONS.put("substr", SourceSystemFunctions.SUBSTRING); //$NON-NLS-1$
ALIASED_FUNCTIONS.put("st_geomfrombinary", SourceSystemFunctions.ST_GEOMFROMWKB); //$NON-NLS-1$
PARSE_FORMAT_TYPES.addAll( Arrays.asList(DataTypeManager.DefaultDataTypes.TIME,
DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.BIG_DECIMAL,
DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.LONG,
DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.DOUBLE));
}
// Constants used in simplifying mathematical criteria
private final static Integer INTEGER_ZERO = new Integer(0);
private final static Double DOUBLE_ZERO = new Double(0);
private final static Float FLOAT_ZERO = new Float(0);
private final static Long LONG_ZERO = new Long(0);
private final static BigInteger BIG_INTEGER_ZERO = new BigInteger("0"); //$NON-NLS-1$
private final static BigDecimal BIG_DECIMAL_ZERO = new BigDecimal("0"); //$NON-NLS-1$
private final static Short SHORT_ZERO = new Short((short)0);
private final static Byte BYTE_ZERO = new Byte((byte)0);
private boolean rewriteAggs = true;
private boolean preserveUnknown;
private QueryMetadataInterface metadata;
private CommandContext context;
private boolean rewriteSubcommands;
private boolean processing;
private Evaluator evaluator;
private Map<ElementSymbol, Expression> variables; //constant propagation
private QueryRewriter(QueryMetadataInterface metadata,
CommandContext context) {
this.metadata = metadata;
this.context = context;
this.evaluator = new Evaluator(Collections.emptyMap(), null, context);
}
public static Command evaluateAndRewrite(Command command, Evaluator eval, CommandContext context, QueryMetadataInterface metadata) throws TeiidProcessingException, TeiidComponentException {
QueryRewriter queryRewriter = new QueryRewriter(metadata, context);
queryRewriter.evaluator = eval;
queryRewriter.rewriteSubcommands = true;
queryRewriter.processing = true;
return queryRewriter.rewriteCommand(command, false);
}
public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context, Map<ElementSymbol, Expression> variableValues) throws TeiidComponentException, TeiidProcessingException{
QueryRewriter rewriter = new QueryRewriter(metadata, context);
rewriter.rewriteSubcommands = true;
rewriter.variables = variableValues;
return rewriter.rewriteCommand(command, false);
}
public static Command rewrite(Command command, QueryMetadataInterface metadata, CommandContext context) throws TeiidComponentException, TeiidProcessingException{
return rewrite(command, metadata, context, null);
}
/**
* Rewrites the command and all of its subcommands (both embedded and non-embedded)
*
* @param command
* @param removeOrderBy
* @return
* @throws QueryValidatorException
*/
private Command rewriteCommand(Command command, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
boolean oldRewriteAggs = rewriteAggs;
QueryMetadataInterface oldMetadata = metadata;
TempMetadataStore tempMetadata = command.getTemporaryMetadata();
if(tempMetadata != null) {
metadata = new TempMetadataAdapter(metadata, tempMetadata);
}
switch(command.getType()) {
case Command.TYPE_QUERY:
QueryCommand queryCommand = (QueryCommand)command;
if (removeOrderBy && queryCommand.getLimit() == null) {
queryCommand.setOrderBy(null);
}
List<WithQueryCommand> withList = queryCommand.getWith();
if (withList != null) {
queryCommand.setWith(null);
List<UnaryFromClause> clauses = getUnaryFromClauses(queryCommand);
queryCommand.setWith(withList);
outer: for (int i = withList.size() - 1; i >= 0; i--) {
WithQueryCommand withQueryCommand = withList.get(i);
if (withQueryCommand.getColumns() == null) {
List<ElementSymbol> columns = ResolverUtil.resolveElementsInGroup(withQueryCommand.getGroupSymbol(), metadata);
withQueryCommand.setColumns(LanguageObject.Util.deepClone(columns, ElementSymbol.class));
}
Collection<UnaryFromClause> all = new ArrayList<UnaryFromClause>(clauses);
List<UnaryFromClause> current = getUnaryFromClauses(withQueryCommand.getCommand());
clauses.addAll(current);
rewriteSubqueryContainer(withQueryCommand, true);
//can't inline with a hint or once it's planned
if (withQueryCommand.isNoInline() || withQueryCommand.getCommand().getProcessorPlan() != null || processing) {
//TODO: in the processing case we may want to remove unneeded cte declarations, rather than
//pushing them down
continue;
}
boolean removeOnly = false;
//check for scalar with clauses
boolean replaceScalar = replaceScalar(withQueryCommand);
if (!replaceScalar) {
int referenceCount = 0;
for (UnaryFromClause ufc : all) {
if (ufc.getGroup().getMetadataID() != withQueryCommand.getGroupSymbol().getMetadataID()) {
continue;
}
referenceCount++;
if (referenceCount > 1) {
continue outer; //referenced in more than 1 location
}
}
if (referenceCount == 0) {
removeOnly = true;
} else if (withQueryCommand.isRecursive()) {
continue; //can't inline if recursive
}
}
withList.remove(i);
if (withList.isEmpty()) {
queryCommand.setWith(null);
}
if (removeOnly) {
clauses = clauses.subList(0, clauses.size() - current.size());
continue;
}
for (UnaryFromClause clause : all) {
//we match on equality as the name can be redefined
if (clause.getGroup().getMetadataID() != withQueryCommand.getGroupSymbol().getMetadataID()) {
continue;
}
if (!replaceScalar) {
//use the original since we need to keep the references
//to nested unaryfromclause instances
clause.setExpandedCommand(withQueryCommand.getCommand());
break;
}
clause.setExpandedCommand((Command) withQueryCommand.getCommand().clone());
}
}
}
if(command instanceof Query) {
command = rewriteQuery((Query) command);
}else {
command = rewriteSetQuery((SetQuery) command);
}
break;
case Command.TYPE_STORED_PROCEDURE:
command = rewriteExec((StoredProcedure) command);
break;
case Command.TYPE_INSERT:
command = rewriteInsert((Insert) command);
break;
case Command.TYPE_UPDATE:
command = rewriteUpdate((Update) command);
break;
case Command.TYPE_DELETE:
command = rewriteDelete((Delete) command);
break;
case Command.TYPE_UPDATE_PROCEDURE:
command = rewriteUpdateProcedure((CreateProcedureCommand) command);
break;
case Command.TYPE_BATCHED_UPDATE:
List subCommands = ((BatchedUpdateCommand)command).getUpdateCommands();
for (int i = 0; i < subCommands.size(); i++) {
Command subCommand = (Command)subCommands.get(i);
subCommand = rewriteCommand(subCommand, false);
subCommands.set(i, subCommand);
}
break;
case Command.TYPE_TRIGGER_ACTION:
TriggerAction ta = (TriggerAction)command;
ta.setBlock(rewriteBlock(ta.getBlock()));
break;
}
this.rewriteAggs = oldRewriteAggs;
this.metadata = oldMetadata;
return command;
}
private boolean replaceScalar(WithQueryCommand withQueryCommand) {
if (!GroupCollectorVisitor.getGroups(withQueryCommand.getCommand(), false).isEmpty()) {
return false;
}
//if deterministic, just inline
return !FunctionCollectorVisitor.isNonDeterministic(withQueryCommand.getCommand());
}
private List<UnaryFromClause> getUnaryFromClauses(QueryCommand queryCommand) {
final List<UnaryFromClause> clauses = new ArrayList<UnaryFromClause>();
LanguageVisitor visitor = new LanguageVisitor() {
public void visit(UnaryFromClause obj) {
clauses.add(obj);
}
};
DeepPreOrderNavigator.doVisit(queryCommand, visitor);
return clauses;
}
private Command rewriteUpdateProcedure(CreateProcedureCommand command) throws TeiidComponentException {
Block block = rewriteBlock(command.getBlock());
command.setBlock(block);
return command;
}
private Block rewriteBlock(Block block) throws TeiidComponentException {
List<Statement> statements = block.getStatements();
List<Statement> newStmts = rewriteStatements(statements);
block.setStatements(newStmts);
if (block.getExceptionStatements() != null) {
block.setExceptionStatements(rewriteStatements(block.getExceptionStatements()));
}
return block;
}
private List<Statement> rewriteStatements(List<Statement> statements) throws TeiidComponentException {
Iterator<Statement> stmtIter = statements.iterator();
List<Statement> newStmts = new ArrayList<Statement>(statements.size());
// plan each statement in the block
while(stmtIter.hasNext()) {
Statement stmnt = stmtIter.next();
try {
rewriteStatement(stmnt, newStmts);
} catch (TeiidProcessingException e) {
/*
* defer the processing of the exception until runtime as there may be an exception handler
*/
RaiseStatement raise = new RaiseStatement(new Constant(e));
newStmts.add(raise);
break;
}
}
return newStmts;
}
private void rewriteStatement(Statement statement, List<Statement> newStmts)
throws TeiidComponentException, TeiidProcessingException{
// evaluate the HAS Criteria on the procedure and rewrite
int stmtType = statement.getType();
switch(stmtType) {
case Statement.TYPE_IF:
IfStatement ifStmt = (IfStatement) statement;
Criteria ifCrit = ifStmt.getCondition();
Criteria evalCrit = rewriteCriteria(ifCrit);
ifStmt.setCondition(evalCrit);
if(evalCrit.equals(TRUE_CRITERIA)) {
Block ifblock = rewriteBlock(ifStmt.getIfBlock());
if (ifblock.isAtomic()) {
newStmts.add(ifblock);
} else {
newStmts.addAll(ifblock.getStatements());
}
return;
} else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
if(ifStmt.hasElseBlock()) {
Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
if (elseBlock.isAtomic()) {
newStmts.add(elseBlock);
} else {
newStmts.addAll(elseBlock.getStatements());
}
return;
}
return;
} else {
Block ifblock = rewriteBlock(ifStmt.getIfBlock());
ifStmt.setIfBlock(ifblock);
if(ifStmt.hasElseBlock()) {
Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
ifStmt.setElseBlock(elseBlock);
}
}
break;
case Statement.TYPE_ERROR:
case Statement.TYPE_DECLARE:
case Statement.TYPE_ASSIGNMENT:
case Statement.TYPE_RETURN:
ExpressionStatement exprStmt = (ExpressionStatement) statement;
// replace variables to references, these references are later
// replaced in the processor with variable values
Expression expr = exprStmt.getExpression();
if (expr != null) {
boolean preserveUnknownOld = preserveUnknown;
preserveUnknown = true;
expr = rewriteExpressionDirect(expr);
preserveUnknown = preserveUnknownOld;
exprStmt.setExpression(expr);
}
break;
case Statement.TYPE_COMMAND:
CommandStatement cmdStmt = (CommandStatement) statement;
rewriteSubqueryContainer(cmdStmt, false);
if(cmdStmt.getCommand().getType() == Command.TYPE_UPDATE) {
Update update = (Update)cmdStmt.getCommand();
if (update.getChangeList().isEmpty()) {
return;
}
}
break;
case Statement.TYPE_LOOP:
LoopStatement loop = (LoopStatement)statement;
rewriteSubqueryContainer(loop, false);
rewriteBlock(loop.getBlock());
if (loop.getBlock().getStatements().isEmpty()) {
return;
}
break;
case Statement.TYPE_WHILE:
WhileStatement whileStatement = (WhileStatement) statement;
Criteria crit = whileStatement.getCondition();
crit = rewriteCriteria(crit);
whileStatement.setCondition(crit);
if(crit.equals(FALSE_CRITERIA) || crit.equals(UNKNOWN_CRITERIA)) {
return;
}
whileStatement.setBlock(rewriteBlock(whileStatement.getBlock()));
if (whileStatement.getBlock().getStatements().isEmpty()) {
return;
}
break;
case Statement.TYPE_COMPOUND:
statement = rewriteBlock((Block) statement);
break;
}
newStmts.add(statement);
}
/**
* @param removeOrderBy
* @param assStmt
* @throws QueryValidatorException
*/
private void rewriteSubqueryContainer(SubqueryContainer container, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
if (rewriteSubcommands && container.getCommand() != null && (container.getCommand().getProcessorPlan() == null || processing)) {
container.setCommand(rewriteCommand(container.getCommand(), removeOrderBy));
}
}
private Command rewriteQuery(Query query)
throws TeiidComponentException, TeiidProcessingException{
// Rewrite from clause
From from = query.getFrom();
if(from != null){
List<FromClause> clauses = new ArrayList<FromClause>(from.getClauses().size());
Iterator<FromClause> clauseIter = from.getClauses().iterator();
while(clauseIter.hasNext()) {
clauses.add( rewriteFromClause(query, clauseIter.next()) );
}
from.setClauses(clauses);
} else {
query.setOrderBy(null);
}
// Rewrite criteria
Criteria crit = query.getCriteria();
if(crit != null) {
if (query.getIsXML()) {
//only rewrite expressions, removing whole predicates could change the nature of the query,
//because we aren't considering the xml pseudo-functions context, row limit, etc.
rewriteExpressions(crit);
} else {
boolean preserveUnknownOld = preserveUnknown;
preserveUnknown = false;
crit = rewriteCriteria(crit);
preserveUnknown = preserveUnknownOld;
}
if(crit == TRUE_CRITERIA) {
query.setCriteria(null);
} else if (crit == UNKNOWN_CRITERIA) {
query.setCriteria(FALSE_CRITERIA);
} else {
query.setCriteria(crit);
}
}
if (from != null && !query.getIsXML()) {
rewriteSubqueriesAsJoins(query);
}
query = rewriteGroupBy(query);
// Rewrite having
Criteria having = query.getHaving();
if(having != null) {
boolean preserveUnknownOld = preserveUnknown;
preserveUnknown = false;
crit = rewriteCriteria(having);
preserveUnknown = preserveUnknownOld;
if(crit == TRUE_CRITERIA) {
query.setHaving(null);
} else {
query.setHaving(crit);
}
}
if (!query.getIsXML()) {
//remove multiple element symbols
boolean hasMes = false;
for (Expression ex : query.getSelect().getSymbols()) {
if (ex instanceof MultipleElementSymbol) {
hasMes = true;
}
}
if (hasMes) {
query.getSelect().setSymbols(query.getSelect().getProjectedSymbols());
}
}
boolean preserveUnknownOld = preserveUnknown;
preserveUnknown = true;
rewriteExpressions(query.getSelect());
if (from != null && !query.getIsXML()) {
List<Expression> symbols = query.getSelect().getSymbols();
RuleMergeCriteria rmc = new RuleMergeCriteria(null, null, null, this.context, this.metadata);
TreeSet<String> names = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
List<GroupSymbol> groups = query.getFrom().getGroups();
for (GroupSymbol gs : groups) {
names.add(gs.getName());
}
PlannedResult plannedResult = new PlannedResult();
for (int i = 0; i < symbols.size(); i++) {
Expression symbol = symbols.get(i);
plannedResult.reset();
rmc.findSubquery(SymbolMap.getExpression(symbol), context!=null?context.getOptions().isSubqueryUnnestDefault():false, plannedResult);
if (plannedResult.query == null || plannedResult.query.getProcessorPlan() != null
|| plannedResult.query.getFrom() == null) {
continue;
}
determineCorrelatedReferences(groups, plannedResult);
boolean requiresDistinct = requiresDistinctRows(query);
if (!rmc.planQuery(groups, requiresDistinct, plannedResult)) {
continue;
}
Query q = convertToJoin(plannedResult, names, query, true);
symbols.set(i, new AliasSymbol(ExpressionSymbol.getName(symbol), (Expression) q.getProjectedSymbols().get(0).clone()));
}
}
if (!query.getIsXML()) {
query = (Query)rewriteOrderBy(query);
}
preserveUnknown = preserveUnknownOld;
if (query.getLimit() != null) {
query.setLimit(rewriteLimitClause(query.getLimit()));
}
if (query.getInto() != null) {
return rewriteSelectInto(query);
}
return query;
}
private void rewriteSubqueriesAsJoins(Query query)
throws TeiidComponentException, QueryMetadataException,
QueryResolverException {
if (query.getCriteria() == null) {
return;
}
RuleMergeCriteria rmc = new RuleMergeCriteria(null, null, null, this.context, this.metadata);
List<Criteria> current = Criteria.separateCriteriaByAnd(query.getCriteria());
query.setCriteria(null);
List<GroupSymbol> groups = query.getFrom().getGroups();
TreeSet<String> names = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
for (GroupSymbol gs : groups) {
names.add(gs.getName());
}
for (Iterator<Criteria> crits = current.iterator(); crits.hasNext();) {
PlannedResult plannedResult = rmc.findSubquery(crits.next(), context!=null?context.getOptions().isSubqueryUnnestDefault():false);
if (plannedResult.not || plannedResult.query == null || plannedResult.query.getProcessorPlan() != null
|| plannedResult.query.getWith() != null) {
continue;
}
determineCorrelatedReferences(groups, plannedResult);
boolean requiresDistinct = requiresDistinctRows(query);
if (!rmc.planQuery(groups, requiresDistinct, plannedResult)) {
continue;
}
crits.remove();
convertToJoin(plannedResult, names, query, false);
//transform the query into an inner join
}
query.setCriteria(Criteria.combineCriteria(query.getCriteria(), Criteria.combineCriteria(current)));
}
private Query convertToJoin(PlannedResult plannedResult, Set<String> names, Query query, boolean leftOuter) throws QueryResolverException, QueryMetadataException, TeiidComponentException {
GroupSymbol viewName = RulePlaceAccess.recontextSymbol(new GroupSymbol("X"), names); //$NON-NLS-1$
viewName.setName(viewName.getName());
viewName.setDefinition(null);
Query q = createInlineViewQuery(viewName, plannedResult.query, metadata, plannedResult.query.getSelect().getProjectedSymbols());
Iterator<Expression> iter = q.getSelect().getProjectedSymbols().iterator();
HashMap<Expression, Expression> expressionMap = new HashMap<Expression, Expression>();
for (Expression symbol : plannedResult.query.getSelect().getProjectedSymbols()) {
expressionMap.put(SymbolMap.getExpression(symbol), SymbolMap.getExpression(iter.next()));
}
for (int i = 0; i < plannedResult.leftExpressions.size(); i++) {
plannedResult.nonEquiJoinCriteria.add(new CompareCriteria(SymbolMap.getExpression((Expression)plannedResult.leftExpressions.get(i)), CompareCriteria.EQ, (Expression)plannedResult.rightExpressions.get(i)));
}
Criteria mappedCriteria = Criteria.combineCriteria(plannedResult.nonEquiJoinCriteria);
ExpressionMappingVisitor.mapExpressions(mappedCriteria, expressionMap);
FromClause clause = q.getFrom().getClauses().get(0);
if (plannedResult.makeInd) {
clause.setMakeInd(new Option.MakeDep());
}
if (leftOuter) {
FromClause leftClause = query.getFrom().getClauses().get(0);
if (query.getFrom().getClauses().size() > 1) {
leftClause = null;
for (FromClause fc : query.getFrom().getClauses()) {
if (leftClause == null) {
leftClause = fc;
continue;
}
leftClause = new JoinPredicate(leftClause, fc, JoinType.JOIN_CROSS);
}
}
query.getFrom().getClauses().clear();
JoinPredicate jp = new JoinPredicate(leftClause, clause, JoinType.JOIN_LEFT_OUTER);
jp.setJoinCriteria(Criteria.separateCriteriaByAnd(mappedCriteria));
query.getFrom().getClauses().add(jp);
} else {
query.setCriteria(Criteria.combineCriteria(query.getCriteria(), mappedCriteria));
query.getFrom().addClause(clause);
}
query.getTemporaryMetadata().getData().putAll(q.getTemporaryMetadata().getData());
return q;
}
private void determineCorrelatedReferences(List<GroupSymbol> groups,
PlannedResult plannedResult) {
if (plannedResult.query.getCorrelatedReferences() == null) {
//create the correlated refs if they exist
//there is a little bit of a design problem here that null usually means no refs.
ArrayList<Reference> correlatedReferences = new ArrayList<Reference>();
CorrelatedReferenceCollectorVisitor.collectReferences(plannedResult.query, groups, correlatedReferences, metadata);
if (!correlatedReferences.isEmpty()) {
SymbolMap map = new SymbolMap();
for (Reference reference : correlatedReferences) {
map.addMapping(reference.getExpression(), reference.getExpression());
}
plannedResult.query.setCorrelatedReferences(map);
}
}
}
private boolean requiresDistinctRows(Query query) {
Set<AggregateSymbol> aggs = new HashSet<AggregateSymbol>();
aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(query.getSelect(), false));
aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(query.getHaving(), false));
if (!aggs.isEmpty() || query.getGroupBy() != null) {
if (!AggregateSymbol.areAggregatesCardinalityDependent(aggs)) {
return false;
}
} else if (query.getSelect().isDistinct()) {
for (Expression projectSymbol : query.getSelect().getProjectedSymbols()) {
Expression ex = SymbolMap.getExpression(projectSymbol);
if (FunctionCollectorVisitor.isNonDeterministic(ex)) {
return true;
}
if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(ex).isEmpty()) {
return true;
}
}
return false;
}
return true;
}
private Query rewriteGroupBy(Query query) throws TeiidComponentException, TeiidProcessingException {
if (query.getGroupBy() == null) {
rewriteAggs = false;
return query;
}
if (isDistinctWithGroupBy(query)) {
query.getSelect().setDistinct(false);
}
rewriteExpressions(query.getGroupBy());
List<Expression> expr = query.getGroupBy().getSymbols();
for (Iterator<Expression> iter = expr.iterator(); iter.hasNext();) {
if (EvaluatableVisitor.willBecomeConstant(iter.next())) {
iter.remove();
}
}
if (expr.isEmpty()) {
query.setGroupBy(null);
}
return query;
}
public static boolean isDistinctWithGroupBy(Query query) {
GroupBy groupBy = query.getGroupBy();
if (groupBy == null) {
return false;
}
HashSet<Expression> selectExpressions = new HashSet<Expression>();
for (Expression selectExpr : query.getSelect().getProjectedSymbols()) {
selectExpressions.add(SymbolMap.getExpression(selectExpr));
}
for (Expression groupByExpr : groupBy.getSymbols()) {
if (!selectExpressions.contains(groupByExpr)) {
return false;
}
}
return true;
}
private void rewriteExpressions(LanguageObject obj) throws TeiidComponentException, TeiidProcessingException{
if (obj == null) {
return;
}
ExpressionMappingVisitor visitor = new ExpressionMappingVisitor(null) {
/**
* @see org.teiid.query.sql.visitor.ExpressionMappingVisitor#replaceExpression(org.teiid.query.sql.symbol.Expression)
*/
@Override
public Expression replaceExpression(Expression element) {
try {
return rewriteExpressionDirect(element);
} catch (TeiidException err) {
throw new TeiidRuntimeException(err);
}
}
};
try {
PostOrderNavigator.doVisit(obj, visitor);
} catch (TeiidRuntimeException err) {
if (err.getCause() instanceof TeiidComponentException) {
throw (TeiidComponentException)err.getCause();
}
if (err.getCause() instanceof TeiidProcessingException) {
throw (TeiidProcessingException)err.getCause();
}
throw err;
}
}
/**
* Rewrite the order by clause.
* Unrelated order by expressions will cause the creation of nested inline views.
*
* @param query
* @throws TeiidComponentException, MetaMatrixProcessingException
* @throws TeiidProcessingException
*/
public QueryCommand rewriteOrderBy(QueryCommand queryCommand) throws TeiidComponentException, TeiidProcessingException {
final OrderBy orderBy = queryCommand.getOrderBy();
if (orderBy == null) {
return queryCommand;
}
Select select = queryCommand.getProjectedQuery().getSelect();
final List<Expression> projectedSymbols = select.getProjectedSymbols();
rewriteOrderBy(queryCommand, orderBy, projectedSymbols, context, metadata);
return queryCommand;
}
public static void rewriteOrderBy(QueryCommand queryCommand,
final OrderBy orderBy, final List projectedSymbols, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
HashSet<Expression> previousExpressions = new HashSet<Expression>();
for (int i = 0; i < orderBy.getVariableCount(); i++) {
Expression querySymbol = orderBy.getVariable(i);
int index = orderBy.getExpressionPosition(i);
if (index == -1) {
querySymbol = rewriteExpression(querySymbol, context, metadata);
} else {
querySymbol = (Expression)projectedSymbols.get(index);
}
Expression expr = SymbolMap.getExpression(querySymbol);
if (!previousExpressions.add(expr) || (queryCommand instanceof Query && EvaluatableVisitor.willBecomeConstant(expr))) {
orderBy.removeOrderByItem(i--);
} else {
orderBy.getOrderByItems().get(i).setSymbol((Expression)querySymbol.clone());
}
}
if (orderBy.getVariableCount() == 0) {
queryCommand.setOrderBy(null);
}
}
/**
* This method will alias each of the select into elements to the corresponding column name in the
* target table. This ensures that they will all be uniquely named.
*
* @param query
* @throws QueryValidatorException
*/
private Command rewriteSelectInto(Query query) throws TeiidProcessingException{
Into into = query.getInto();
try {
List<ElementSymbol> allIntoElements = Util.deepClone(ResolverUtil.resolveElementsInGroup(into.getGroup(), metadata), ElementSymbol.class);
Insert insert = new Insert(into.getGroup(), allIntoElements, Collections.emptyList());
insert.setSourceHint(query.getSourceHint());
query.setSourceHint(null);
query.setInto(null);
insert.setQueryExpression(query);
return rewriteInsert(correctDatatypes(insert));
} catch (QueryMetadataException e) {
throw new QueryValidatorException(e);
} catch (TeiidComponentException e) {
throw new QueryValidatorException(e);
}
}
private Insert correctDatatypes(Insert insert) {
boolean needsView = false;
for (int i = 0; !needsView && i < insert.getVariables().size(); i++) {
Expression ses = insert.getVariables().get(i);
if (ses.getType() != insert.getQueryExpression().getProjectedSymbols().get(i).getType()) {
needsView = true;
}
}
if (needsView) {
try {
insert.setQueryExpression(createInlineViewQuery(new GroupSymbol("X"), insert.getQueryExpression(), metadata, insert.getVariables())); //$NON-NLS-1$
} catch (TeiidException err) {
throw new TeiidRuntimeException(QueryPlugin.Event.TEIID30371, err);
}
}
return insert;
}
private void correctProjectedTypes(List actualSymbolTypes, Query query) {
List symbols = query.getSelect().getProjectedSymbols();
List newSymbols = SetQuery.getTypedProjectedSymbols(symbols, actualSymbolTypes, this.metadata);
query.getSelect().setSymbols(newSymbols);
}
private SetQuery rewriteSetQuery(SetQuery setQuery)
throws TeiidComponentException, TeiidProcessingException{
if (setQuery.getProjectedTypes() != null) {
for (QueryCommand command : setQuery.getQueryCommands()) {
if (!(command instanceof Query)) {
continue;
}
correctProjectedTypes(setQuery.getProjectedTypes(), (Query)command);
}
setQuery.setProjectedTypes(null, null);
}
setQuery.setLeftQuery((QueryCommand)rewriteCommand(setQuery.getLeftQuery(), true));
setQuery.setRightQuery((QueryCommand)rewriteCommand(setQuery.getRightQuery(), true));
rewriteOrderBy(setQuery);
if (setQuery.getLimit() != null) {
setQuery.setLimit(rewriteLimitClause(setQuery.getLimit()));
}
return setQuery;
}
private FromClause rewriteFromClause(Query parent, FromClause clause)
throws TeiidComponentException, TeiidProcessingException{
if(clause instanceof JoinPredicate) {
return rewriteJoinPredicate(parent, (JoinPredicate) clause);
} else if (clause instanceof SubqueryFromClause) {
rewriteSubqueryContainer((SubqueryFromClause)clause, true);
} else if (clause instanceof TextTable) {
TextTable tt = (TextTable)clause;
tt.setFile(rewriteExpressionDirect(tt.getFile()));
} else if (clause instanceof XMLTable) {
rewriteExpressions(clause);
} else if (clause instanceof ObjectTable) {
rewriteExpressions(clause);
} else if (clause instanceof ArrayTable) {
ArrayTable at = (ArrayTable)clause;
at.setArrayValue(rewriteExpressionDirect(at.getArrayValue()));
}
return clause;
}
private JoinPredicate rewriteJoinPredicate(Query parent, JoinPredicate predicate)
throws TeiidComponentException, TeiidProcessingException{
List joinCrits = predicate.getJoinCriteria();
if(joinCrits != null && joinCrits.size() > 0) {
//rewrite join crits by rewriting a compound criteria
Criteria criteria = new CompoundCriteria(new ArrayList(joinCrits));
criteria = rewriteCriteria(criteria);
joinCrits.clear();
if (criteria instanceof CompoundCriteria && ((CompoundCriteria)criteria).getOperator() == CompoundCriteria.AND) {
joinCrits.addAll(((CompoundCriteria)criteria).getCriteria());
} else {
joinCrits.add(criteria);
}
predicate.setJoinCriteria(joinCrits);
}
if (predicate.getJoinType() == JoinType.JOIN_UNION) {
predicate.setJoinType(JoinType.JOIN_FULL_OUTER);
predicate.setJoinCriteria(new ArrayList<Criteria>(Arrays.asList(FALSE_CRITERIA)));
} else if (predicate.getJoinType() == JoinType.JOIN_RIGHT_OUTER) {
predicate.setJoinType(JoinType.JOIN_LEFT_OUTER);
FromClause leftClause = predicate.getLeftClause();
predicate.setLeftClause(predicate.getRightClause());
predicate.setRightClause(leftClause);
}
predicate.setLeftClause( rewriteFromClause(parent, predicate.getLeftClause()));
predicate.setRightClause( rewriteFromClause(parent, predicate.getRightClause()));
return predicate;
}
/**
* Rewrite the criteria by evaluating some trivial cases.
* @param criteria The criteria to rewrite
* @param metadata
* @param userCriteria The criteria on user's command, used in rewriting HasCriteria
* in the procedural language.
* @return The re-written criteria
*/
public static Criteria rewriteCriteria(Criteria criteria, CommandContext context, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException{
return new QueryRewriter(metadata, context).rewriteCriteria(criteria);
}
/**
* Rewrite the criteria by evaluating some trivial cases.
* @param criteria The criteria to rewrite
* @param userCriteria The criteria on user's command, used in rewriting HasCriteria
* in the procedural language.
* @return The re-written criteria
*/
private Criteria rewriteCriteria(Criteria criteria) throws TeiidComponentException, TeiidProcessingException{
if(criteria instanceof CompoundCriteria) {
return rewriteCriteria((CompoundCriteria)criteria, true);
} else if(criteria instanceof NotCriteria) {
criteria = rewriteCriteria((NotCriteria)criteria);
} else if(criteria instanceof CompareCriteria) {
criteria = rewriteCriteria((CompareCriteria)criteria);
} else if(criteria instanceof SubqueryCompareCriteria) {
criteria = rewriteCriteria((SubqueryCompareCriteria)criteria);
} else if(criteria instanceof MatchCriteria) {
criteria = rewriteCriteria((MatchCriteria)criteria);
} else if(criteria instanceof SetCriteria) {
criteria = rewriteCriteria((SetCriteria)criteria);
} else if(criteria instanceof IsNullCriteria) {
criteria = rewriteCriteria((IsNullCriteria)criteria);
} else if(criteria instanceof BetweenCriteria) {
criteria = rewriteCriteria((BetweenCriteria)criteria);
} else if (criteria instanceof ExistsCriteria) {
ExistsCriteria exists = (ExistsCriteria)criteria;
if (exists.shouldEvaluate() && processing) {
return getCriteria(evaluator.evaluate(exists, null));
}
rewriteSubqueryContainer((SubqueryContainer)criteria, true);
if (!RelationalNodeUtil.shouldExecute(exists.getCommand(), false, true)) {
return exists.isNegated()?TRUE_CRITERIA:FALSE_CRITERIA;
}
if (exists.getCommand().getProcessorPlan() == null) {
if (exists.getCommand() instanceof Query) {
Query query = (Query)exists.getCommand();
if ((query.getLimit() == null || query.getOrderBy() == null) && query.getSelect().getProjectedSymbols().size() > 1) {