This repository was archived by the owner on Jun 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathOptRange.cpp
More file actions
2503 lines (2316 loc) · 98.1 KB
/
OptRange.cpp
File metadata and controls
2503 lines (2316 loc) · 98.1 KB
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
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
#include <limits>
#include <float.h>
#include "nawstring.h"
#include "QRDescGenerator.h"
#include "NumericType.h"
#include "DatetimeType.h"
#include "QRLogger.h"
#include "OptRange.h"
#include "ItemLog.h"
#include "ComCextdecs.h"
double getDoubleValue(ConstValue* val, logLevel level);
/**
* Returns the Int64 value corresponding to the type of the ConstValue val.
* val can be of any numeric, datetime, or interval type. The returned value
* is used in the representation of a range of values implied by the predicates
* of a query for an exact numeric, datetime, or interval type.
*
* @param val ConstValue that wraps the value to be represented as an Int64.
* @param rangeColType The type of the column or expr the range is for.
* @param [out] truncated TRUE returned if the value returned was the result of
* truncating the input value. This can happen for floating
* point input, or exact numeric input that has greater
* scale than rangeColType.
* @param [out] valWasNegative TRUE returned if the input value was negative.
* Adjustment of truncated values is only done for
* positive values (because the truncation of a negative
* value adjusts it correctly). The caller can't just
* look at the returned value, because if it is 0, it
* may have been truncated from a small negative (-1 < n < 0)
* or a small positive (0 < n < 1) value.
* @param level Logging level to use in event of failure.
* @return The rangespec internal representation of the input constant value.
*/
static Int64 getInt64Value(ConstValue* val, const NAType* rangeColType,
NABoolean& truncated, NABoolean& valWasNegative,
logLevel level);
OptRangeSpec::OptRangeSpec(QRDescGenerator* descGenerator, CollHeap* heap, logLevel ll)
: RangeSpec(heap, ll),
descGenerator_(descGenerator),
rangeExpr_(NULL),
vid_(NULL_VALUE_ID),
isIntersection_(FALSE)
{
assertLogAndThrow(CAT_SQL_COMP_RANGE, logLevel_,
descGenerator, QRLogicException,
"OptRangeSpec constructed for null QRDescGenerator");
if (descGenerator->isDumpMvMode())
setDumpMvMode();
}
ValueId OptRangeSpec::getBaseCol(const ValueIdSet& vegMembers)
{
for (ValueId id=vegMembers.init(); vegMembers.next(id); vegMembers.advance(id))
{
if (id.getItemExpr()->getOperatorType() == ITM_BASECOLUMN)
return id;
}
return NULL_VALUE_ID;
}
ValueId OptRangeSpec::getBaseCol(const ValueId vegRefVid)
{
ItemExpr* itemExpr = vegRefVid.getItemExpr();
OperatorTypeEnum opType = itemExpr->getOperatorType();
// See if the vid is for a basecol instead of a vegref.
if (opType == ITM_BASECOLUMN)
return vegRefVid;
// Get the value id of the first member that is a base column.
assertLogAndThrow1(CAT_SQL_COMP_RANGE, logLevel_,
opType == ITM_VEG_REFERENCE, QRDescriptorException,
"OptRangeSpec::getBaseCol() expected value id of a "
"vegref, not of op type -- %d", opType);
ValueId baseColVid = getBaseCol(static_cast<VEGReference*>(itemExpr)
->getVEG()->getAllValues());
assertLogAndThrow(CAT_SQL_COMP_RANGE, logLevel_,
baseColVid != NULL_VALUE_ID, QRDescriptorException,
"Vegref contains no base columns");
return baseColVid;
}
OptRangeSpec* OptRangeSpec::createRangeSpec(QRDescGenerator* descGenerator,
ItemExpr* predExpr,
CollHeap* heap,
NABoolean createForNormalizer)
{
QRTRACER("createRangeSpec");
OptRangeSpec* range = NULL;
if (predExpr->getOperatorType() == ITM_RANGE_SPEC_FUNC)
{
assertLogAndThrow(CAT_SQL_COMP_RANGE, LL_ERROR,
!createForNormalizer, QRDescriptorException,
"RangeSpecRef should not be present if creating for Normalizer");
RangeSpecRef* rangeIE = static_cast<RangeSpecRef*>(predExpr);
range = new(heap) OptRangeSpec(*rangeIE->getRangeObject(), heap);
// RangeSpecRefs are produced by the Normalizer. The rangespec they contain
// may have a vegref vid as the rangecolvalueid instead of using the first
// basecol vid as we do when a range is created in mvqr. Also, the vid may
// be that of a joinpred, but will still be stored as the rangecolvalueid.
// Below, we sort out these issues for the new rangespec we have created
// using the copy ctor on the one in the RangeSpecRef.
ValueId rcvid = range->getRangeColValueId();
if (rcvid != NULL_VALUE_ID)
{
ItemExpr* ie = rcvid.getItemExpr();
if (ie->getOperatorType() == ITM_VEG_REFERENCE)
{
if (descGenerator->isJoinPredId(rcvid))
{
range->setRangeColValueId(NULL_VALUE_ID);
range->setRangeJoinPredId(rcvid);
}
else
{
rcvid = range->getBaseCol(((VEGReference*)ie)->getVEG()->getAllValues());
if (rcvid != NULL_VALUE_ID)
range->setRangeColValueId(rcvid);
}
}
}
}
else
{
if (createForNormalizer)
{
range = new (heap) OptNormRangeSpec(descGenerator, heap);
(static_cast<OptNormRangeSpec*>(range))
->setOriginalItemExpr(predExpr);
}
else
range = new (heap) OptRangeSpec(descGenerator, heap);
if (!range->buildRange(predExpr))
{
delete range;
return NULL;
}
}
range->setID(predExpr->getValueId());
range->log();
return range;
}
// Protected copy ctor, used by clone().
OptRangeSpec::OptRangeSpec(const OptRangeSpec& other, CollHeap* heap)
: RangeSpec(other, heap),
descGenerator_(other.descGenerator_),
rangeExpr_(NULL),
vid_(other.vid_),
isIntersection_(other.isIntersection_)
{
// At this point the inherited heap ptr mvqrHeap_ has been initialized
// by the superclass ctor.
if (other.rangeExpr_)
rangeExpr_ = other.rangeExpr_->copyTree(mvqrHeap_);
}
QRRangePredPtr OptRangeSpec::createRangeElem()
{
QRTRACER("createRangeElem");
QRRangePredPtr rangePredElem =
new (mvqrHeap_) QRRangePred(ADD_MEMCHECK_ARGS(mvqrHeap_));
rangePredElem->setRangeItem(genRangeItem());
NABoolean rangeIsOnCol = (rangeJoinPredId_ != NULL_VALUE_ID ||
rangeColValueId_ != NULL_VALUE_ID);
assertLogAndThrow(CAT_SQL_COMP_RANGE, logLevel_,
getID()>0, QRDescriptorException,
"No id for range element in OptRangeSpec::createRangeElem().");
// The id of this rangespec is the value id of the original predicate on the
// corresponding range column/expr. If other preds on the range col/expr were
// found and had to be intersected, we need to use the value id of the itemexpr
// that is the result of the intersection (so the right predicat will be used
// for the rewrite).
if (isIntersection_)
rangePredElem->setID(getRangeItemExpr()->getValueId());
else
rangePredElem->setID(getID());
const NAType* typePtr = getType();
assertLogAndThrow(CAT_SQL_COMP_RANGE, logLevel_,
typePtr, QRDescriptorException,
"Call to getType() returned NULL in OptRangeSpec::createRangeElem().");
const NAType& type = *typePtr;
rangePredElem->setSqlType(type.getTypeSQLname());
QROpInequalityPtr ineqOp;
QROpEQPtr eqOp = NULL;
QROpBTPtr betweenOp;
CollIndex numSubranges = subranges_.entries();
for (CollIndex i=0; i<numSubranges; i++)
{
SubrangeBase& subrange = *subranges_[i];
if (subrange.startIsMin() ||
(i==0 && rangeIsOnCol && subrange.isMinForType(type)))
{
assertLogAndThrow1(CAT_SQL_COMP_RANGE, logLevel_,
i==0, QRDescriptorException,
"Subrange other than 1st is unbounded on low side, "
"subrange index %d", i);
if (subrange.endIsMax() ||
(i==numSubranges-1 && rangeIsOnCol && subrange.isMaxForType(type)))
{
// Range spans all values of the type. If NULL is included as
// well, return NULL to indicate no range restriction. If NULL is
// not included in the range, an empty <RangePred> is used to
// indicate IS NOT NULL.
assertLogAndThrow(CAT_SQL_COMP_RANGE, logLevel_,
numSubranges==1, QRDescriptorException,
"Range of all values must have a single Subrange.");
if (nullIncluded_)
{
QRLogger::log(CAT_SQL_COMP_RANGE, LL_INFO,
"Range predicate ignored because it spans entire range + NULL.");
deletePtr(rangePredElem);
return NULL;
}
else
{
// An IS NOT NULL predicate on a NOT NULL column is removed in
// the early compilation stages. If we generate the usual empty
// range element to represent a predicate that spans all values,
// it will not match this missing predicate. So we detect and
// remove it.
QRElementPtr rangeItemElem = rangePredElem->getRangeItem()
->getReferencedElement();
if (rangeItemElem->getIDFirstChar() == 'C')
{
ValueId vid = rangeItemElem->getIDNum();
if ((static_cast<BaseColumn*>(vid.getItemExpr()))
->getNAColumn()->getNotNullNondroppable())
{
QRLogger::log(CAT_SQL_COMP_RANGE, LL_INFO,
"Range predicate ignored because it spans entire "
"range and has NOT NULL constraint.");
deletePtr(rangePredElem);
return NULL;
}
}
}
return rangePredElem; // leave it empty
}
if (subrange.endInclusive())
ineqOp = new (mvqrHeap_) QROpLE(ADD_MEMCHECK_ARGS(mvqrHeap_));
else
ineqOp = new (mvqrHeap_) QROpLS(ADD_MEMCHECK_ARGS(mvqrHeap_));
ineqOp->setValue(subrange.getEndScalarValElem(mvqrHeap_, type));
// If start is not min, we are here because lower bound for the type
// was start of first subrange.
ineqOp->setNormalized(!subrange.startIsMin());
rangePredElem->addOperator(ineqOp);
}
else if (subrange.endIsMax() ||
(i==numSubranges-1 && rangeIsOnCol
&& subrange.isMaxForType(type)))
{
assertLogAndThrow1(CAT_SQL_COMP_RANGE, logLevel_,
i==numSubranges-1, QRDescriptorException,
"Subrange other than last is unbounded on high side, "
"subrange index %d",
i);
if (eqOp) // wrap this up if one in progress
{
rangePredElem->addOperator(eqOp);
eqOp = NULL;
}
if (subrange.startInclusive())
ineqOp = new (mvqrHeap_) QROpGE(ADD_MEMCHECK_ARGS(mvqrHeap_));
else
ineqOp = new (mvqrHeap_) QROpGT(ADD_MEMCHECK_ARGS(mvqrHeap_));
ineqOp->setValue(subrange.getStartScalarValElem(mvqrHeap_, type));
// If end is not max, we are here because upper bound for the type
// was end of last subrange.
ineqOp->setNormalized(!subrange.endIsMax());
rangePredElem->addOperator(ineqOp);
}
else if (subrange.isSingleValue())
{
// Add the value to a new OpEQ or the one we are already working on,
// but don't finish it until we hit something besides a single-value
// subrange.
if (!eqOp)
eqOp = new (mvqrHeap_) QROpEQ(ADD_MEMCHECK_ARGS(mvqrHeap_));
eqOp->addValue(subrange.getStartScalarValElem(mvqrHeap_, type));
}
else
{
// If values have been accumulated in an OpEQ, add it before doing
// the between op.
if (eqOp)
{
rangePredElem->addOperator(eqOp);
eqOp = NULL;
}
betweenOp = new (mvqrHeap_) QROpBT(ADD_MEMCHECK_ARGS(mvqrHeap_));
betweenOp->setStartValue(subrange.getStartScalarValElem(mvqrHeap_,
type));
betweenOp->setStartIncluded(subrange.startInclusive());
betweenOp->setEndValue(subrange.getEndScalarValElem(mvqrHeap_,
type));
betweenOp->setEndIncluded(subrange.endInclusive());
rangePredElem->addOperator(betweenOp);
}
}
// If IS NULL is part of the range spec, it should come last. If an OpEQ
// element is in progress, add it there, else create one for it. In either
// of these cases, add it to the range pred element.
if (eqOp)
{
if (nullIncluded_)
eqOp->setNullVal(new(mvqrHeap_) QRNullVal(ADD_MEMCHECK_ARGS(mvqrHeap_)));
rangePredElem->addOperator(eqOp);
}
else if (nullIncluded_)
{
eqOp = new (mvqrHeap_) QROpEQ(ADD_MEMCHECK_ARGS(mvqrHeap_));
eqOp->setNullVal(new(mvqrHeap_) QRNullVal(ADD_MEMCHECK_ARGS(mvqrHeap_)));
rangePredElem->addOperator(eqOp);
}
return rangePredElem;
} // createRangeElem()
QRElementPtr OptRangeSpec::genRangeItem()
{
QRElementPtr elem;
if (rangeColValueId_ != NULL_VALUE_ID)
elem = descGenerator_->genQRColumn(rangeColValueId_,
rangeJoinPredId_);
else if (rangeExpr_)
elem = descGenerator_->genQRExpr(rangeExpr_, rangeJoinPredId_);
else
{
assertLogAndThrow(CAT_SQL_COMP_RANGE, logLevel_,
rangeJoinPredId_ != NULL_VALUE_ID, QRDescriptorException,
"All range value ids are null");
ValueId colVid = getBaseCol(rangeJoinPredId_);
elem = descGenerator_->genQRColumn(colVid,
rangeJoinPredId_);
}
return elem;
}
ItemExpr* OptRangeSpec::getRangeExpr() const
{
if (rangeExpr_)
return rangeExpr_;
else if (rangeJoinPredId_ != NULL_VALUE_ID)
return ((ValueId)rangeJoinPredId_).getItemExpr();
else
return ((ValueId)rangeColValueId_).getItemExpr();
}
// Exprs have been converted to a canonical form in which const is the 2nd operand.
// NULL is returned if there is not a constant operand, or if the other operand
// is not the one the range is being built for.
ConstValue* OptRangeSpec::getConstOperand(ItemExpr* predExpr, Lng32 constInx)
{
QRTRACER("getConstOperand");
ItemExpr* left = predExpr->child(0);
ItemExpr* right = predExpr->child(constInx);
// Bail out if we don't have a constant. If a vegref, see if the veg includes
// a constant, and substitute that if so.
if (right->getOperatorType() != ITM_CONSTANT)
{
if (right->getOperatorType() == ITM_VEG_REFERENCE)
{
ValueId constVid = (static_cast<VEGReference*>(right))->getVEG()->getAConstant(TRUE);
if (constVid == NULL_VALUE_ID)
return NULL;
else
right = constVid.getItemExpr();
}
else
return NULL;
}
ValueId colVid;
switch (left->getOperatorType())
{
case ITM_VEG_REFERENCE:
if (forNormalizer())
colVid = left->getValueId();
else
colVid = getBaseCol(((VEGReference*)left)->getVEG()->getAllValues());
break;
case ITM_BASECOLUMN: // Should only happen for a check constraint
colVid = left->getValueId();
break;
default: // must be an expression
colVid = NULL_VALUE_ID;
break;
}
if (colVid != NULL_VALUE_ID)
{
// If this range is for an expression, the pred is not on it.
if (rangeExpr_)
return NULL;
if (rangeColValueId_ == NULL_VALUE_ID)
{
rangeColValueId_ = colVid;
EqualitySet* eqSet =
descGenerator_->getEqualitySet(&rangeColValueId_);
if (eqSet)
{
rangeJoinPredId_ = (QRValueId)eqSet->getJoinPredId();
setType(eqSet->getType());
}
else
{
rangeJoinPredId_ = (QRValueId)NULL_VALUE_ID;
setType(&((ValueId)rangeColValueId_).getType());
}
}
else if (rangeColValueId_ != colVid)
return NULL;
}
else
{
// The left side of the pred is an expression. If this range is for a
// simple column, it doesn't match.
if (rangeColValueId_ != NULL_VALUE_ID)
return NULL;
if (!rangeExpr_)
{
// If more than one node is involved in an expression, it is a
// residual pred instead of a range pred.
if (descGenerator_->getExprNode(left) == NULL_CA_ID)
return NULL;
setRangeExpr(left); // sets rangeExpr_, rangeExprText_
EqualitySet* eqSet =
descGenerator_->getEqualitySet(&rangeExprText_);
if (eqSet)
{
rangeJoinPredId_ = (QRValueId)eqSet->getJoinPredId();
setType(eqSet->getType());
}
else
{
rangeJoinPredId_ = (QRValueId)NULL_VALUE_ID;
setType(&rangeExpr_->getValueId().getType());
}
}
else
{
// The ItemExpr ptrs will be different, so we compare the expression
// text to see if they are the same. At some point this text will be
// in a canonical form that ignores syntactic variances.
NAString exprText;
left->unparse(exprText, OPTIMIZER_PHASE, MVINFO_FORMAT);
if (rangeExprText_ != exprText)
return NULL;
}
}
if (!(QRDescGenerator::typeSupported(getType())))
return NULL;
// If we reach this point, the predicate has been confirmed to apply to the
// same col/expr of this range, and the right operand has been confirmed to
// be a constant. Before returning the ConstValue, make sure it is a type we
// currently support. Predicates involving types not yet supported will be
// treated as residual predicates.
if (QRDescGenerator::typeSupported(static_cast<ConstValue*>(right)->getType()))
{
/* add constvalue ‘not casespecific’ to type_*/
((CharType*)getType())->setCaseinsensitive(
((CharType *)(((ConstValue*)(right))->getType()))->isCaseinsensitive());
return static_cast<ConstValue*>(right);
}
else
return NULL;
} // getConstOperand()
void OptRangeSpec::addSubrange(ConstValue* start, ConstValue* end,
NABoolean startInclusive, NABoolean endInclusive)
{
QRTRACER("addSubrange");
const NAType* type = getType();
assertLogAndThrow(CAT_SQL_COMP_RANGE, logLevel_,
type, QRDescriptorException,
"Call to getType() returned NULL in OptRangeSpec::addSubrange().");
NAString unparsedStart(""), unparsedEnd("");
if (isDumpMvMode())
{
// Add the "official" unparsed text of the expression as a sub-element.
if (start)
start->unparse(unparsedStart, OPTIMIZER_PHASE, QUERY_FORMAT);
if (end)
end->unparse(unparsedEnd, OPTIMIZER_PHASE, QUERY_FORMAT);
}
NABuiltInTypeEnum typeQual = type->getTypeQualifier();
switch (typeQual)
{
case NA_NUMERIC_TYPE:
case NA_DATETIME_TYPE:
case NA_INTERVAL_TYPE:
case NA_BOOLEAN_TYPE:
//if (((const NumericType*)type)->isExact())
if (typeQual == NA_DATETIME_TYPE ||
typeQual == NA_INTERVAL_TYPE ||
(typeQual == NA_NUMERIC_TYPE &&
static_cast<const NumericType*>(type)->isExact()) ||
(typeQual == NA_BOOLEAN_TYPE))
{
// Fixed-point numeric subranges are normalized to be inclusive, to
// simplify equivalence and subsumption checks.
Subrange<Int64>* sub = new (mvqrHeap_) Subrange<Int64>(logLevel_);
sub->setUnparsedStart(unparsedStart);
sub->setUnparsedEnd(unparsedEnd);
NABoolean valTruncated;
NABoolean valNegative;
NABoolean startOverflowed = FALSE;
NABoolean endOverflowed = FALSE;
if (start)
{
// If the constant is truncated because it has higher scale than
// the type of the range col/expr, the truncated value is not the
// start of the range. 1 is added to the truncated value to get
// the next value that is possible for the type.
sub->start = getInt64Value(start, type, valTruncated, valNegative, logLevel_);
if ((!startInclusive || valTruncated) &&
(!valTruncated || !valNegative))
sub->makeStartInclusive(type, startOverflowed);
}
else
sub->setStartIsMin(TRUE);
if (end)
{
// If the constant is truncated because it has higher scale than
// the type of the range col/expr, the truncated value must be
// included in the range even if the end is not inclusive (<).
sub->end = getInt64Value(end, type, valTruncated, valNegative, logLevel_);
if ((!endInclusive && !valTruncated) ||
(valTruncated && valNegative))
sub->makeEndInclusive(type, endOverflowed);
}
else
sub->setEndIsMax(TRUE);
// If not originally inclusive, has been adjusted above.
// Need this in case makeXXXInclusive was not called, but leave as
// is if made noninclusive because of positive (for start) or
// negative (for end) overflow.
if (!startOverflowed)
sub->setStartInclusive(TRUE);
if (!endOverflowed)
sub->setEndInclusive(TRUE);
// Handling a constant with scale that exceeds that of the range
// column could result in an empty (i.e., start>end) range. For example,
// if n is a numeric(4,2), the predicate n = 12.341 will result in
// the range 12.35..12.34, which is appropriate since the predicate
// is guaranteed to be false by the type constraint of the column.
if (sub->startIsMin() || sub->endIsMax() || sub->start <= sub->end)
placeSubrange(sub);
else
delete sub;
}
else
{
Subrange<double>* sub = new (mvqrHeap_) Subrange<double>(logLevel_);
sub->setUnparsedStart(unparsedStart);
sub->setUnparsedEnd(unparsedEnd);
if (start)
sub->start = getDoubleValue(start, logLevel_);
else
sub->setStartIsMin(TRUE);
if (end)
sub->end = getDoubleValue(end, logLevel_);
else
sub->setEndIsMax(TRUE);
sub->setStartInclusive(startInclusive);
sub->setEndInclusive(endInclusive);
placeSubrange(sub);
}
break;
// In some cases, constant folding of char expressions produces a varchar
// constant, so we have to take a possible length field into account.
case NA_CHARACTER_TYPE:
{
Lng32 headerBytes;
const NAType* startType = (start ? start->getType() : NULL);
const NAType* endType = (end ? end->getType() : NULL);
// Alignment is 2 for UCS2, 1 for single-byte char set.
if (type->getDataAlignment() == 2)
{
// Unicode string.
Subrange<RangeWString>* sub = new (mvqrHeap_) Subrange<RangeWString>(logLevel_);
sub->setUnparsedStart(unparsedStart);
sub->setUnparsedEnd(unparsedEnd);
if (start)
{
headerBytes = startType->getVarLenHdrSize() +
startType->getSQLnullHdrSize();
sub->start.remove(0)
.append((const NAWchar*)start->getConstValue()
+ (headerBytes / sizeof(NAWchar)),
(start->getStorageSize() - headerBytes)
/ sizeof(NAWchar));
}
else
sub->setStartIsMin(TRUE);
if (end)
{
headerBytes = endType->getVarLenHdrSize() +
endType->getSQLnullHdrSize();
sub->end.remove(0)
.append((const NAWchar*)end->getConstValue()
+ (headerBytes / sizeof(NAWchar)),
(end->getStorageSize() - headerBytes)
/ sizeof(NAWchar));
}
else
sub->setEndIsMax(TRUE);
sub->setStartInclusive(startInclusive);
sub->setEndInclusive(endInclusive);
placeSubrange(sub);
}
else
{
// Latin1 string.
Subrange<RangeString>* sub = new (mvqrHeap_) Subrange<RangeString>(logLevel_);
sub->setUnparsedStart(unparsedStart);
sub->setUnparsedEnd(unparsedEnd);
if (start)
{
headerBytes = startType->getVarLenHdrSize() +
startType->getSQLnullHdrSize();
sub->start.remove(0)
.append((const char*)start->getConstValue() + headerBytes,
start->getStorageSize() - headerBytes);
}
else
sub->setStartIsMin(TRUE);
if (end)
{
headerBytes = endType->getVarLenHdrSize() +
endType->getSQLnullHdrSize();
sub->end.remove(0)
.append((const char*)end->getConstValue() + headerBytes,
end->getStorageSize() - headerBytes);
}
else
sub->setEndIsMax(TRUE);
sub->setStartInclusive(startInclusive);
sub->setEndInclusive(endInclusive);
placeSubrange(sub);
}
}
break;
default:
assertLogAndThrow1(CAT_SQL_COMP_RANGE, logLevel_,
FALSE, QRDescriptorException,
"Unhandled data type: %d", typeQual);
break;
}
} // addSubrange(ConstValue*...
ItemExpr* OptRangeSpec::getCheckConstraintPred(ItemExpr* checkConstraint)
{
if (checkConstraint->getOperatorType() != ITM_CASE)
{
QRLogger::log(CAT_SQL_COMP_RANGE, logLevel_,
"Expected ITM_CASE but found operator %d.",
checkConstraint->getOperatorType());
return NULL;
}
ItemExpr* itemExpr = checkConstraint->child(0);
if (itemExpr->getOperatorType() != ITM_IF_THEN_ELSE)
{
QRLogger::log(CAT_SQL_COMP_RANGE, logLevel_,
"Expected ITM_IF_THEN_ELSE but found operator %d.",
itemExpr->getOperatorType());
return NULL;
}
// Child of the if-then-else is either is_false, which is the parent of the
// predicate (for most check constraints), or the predicate itself (for
// isnotnull or the check option of a view).
itemExpr = itemExpr->child(0);
if (itemExpr->getOperatorType() == ITM_IS_FALSE)
return itemExpr->child(0);
else
return itemExpr;
}
void OptRangeSpec::intersectCheckConstraints(QRDescGenerator* descGen,
ValueId colValId)
{
QRTRACER("intersectCheckConstraints");
// Check and Not Null constraints.
//
ItemExpr* itemExpr = colValId.getItemExpr();
if (itemExpr->getOperatorType() == ITM_VEG_REFERENCE)
{
// For a vegref, intersect all constraints applied to any member.
const ValueIdSet& vidSet = static_cast<VEGReference*>(itemExpr)
->getVEG()->getAllValues();
for (ValueId vid=vidSet.init(); vidSet.next(vid); vidSet.advance(vid))
{
if (vid.getItemExpr()->getOperatorType() == ITM_BASECOLUMN)
intersectCheckConstraints(descGen, vid);
}
return;
}
else if (itemExpr->getOperatorType() != ITM_BASECOLUMN)
{
QRLogger::log(CAT_SQL_COMP_RANGE, logLevel_,
"Nonfatal unexpected result: range column operator type is "
"%d instead of ITM_BASECOLUMN.", itemExpr->getOperatorType());
return;
}
#ifdef _DEBUG
const NATable* tbl = colValId.getNAColumn()->getNATable();
const CheckConstraintList& checks = tbl->getCheckConstraints();
for (CollIndex c=0; c<checks.entries(); c++)
{
QRLogger::log(CAT_SQL_COMP_RANGE, LL_DEBUG,
"Check constraint on table %s: %s",
tbl->getTableName().getObjectName().data(),
checks[c]->getConstraintText().data());
}
#endif
OptRangeSpec* checkRange = NULL;
ItemExpr* checkPred;
const ValueIdList& checkConstraints =
(static_cast<BaseColumn*>(itemExpr))->getTableDesc()->getCheckConstraints();
for (CollIndex i=0; i<checkConstraints.entries(); i++)
{
checkPred = getCheckConstraintPred(checkConstraints[i].getItemExpr());
if (checkPred)
{
checkRange = new(mvqrHeap_) OptRangeSpec(descGen, mvqrHeap_);
checkRange->setRangeColValueId(colValId);
checkRange->setType(colValId.getType().newCopy(mvqrHeap_));
if (checkRange->buildRange(checkPred))
// Call the RangeSpec version of intersect; this avoids trying to
// modify the original ItemExpr with the check constraint pred.
RangeSpec::intersectRange(checkRange);
delete checkRange;
}
}
}
// Add type-implied constraint for numeric, datetime, and interval types.
void OptRangeSpec::intersectTypeConstraint(QRDescGenerator* descGen,
ValueId colValId)
{
QRTRACER("intersectTypeConstraint");
NABoolean isExact;
const NAType& colType = colValId.getType();
NABuiltInTypeEnum typeQual = colType.getTypeQualifier();
switch (typeQual)
{
case NA_NUMERIC_TYPE:
{
const NumericType& numType = static_cast<const NumericType&>(colType);
isExact = numType.isExact();
if (isExact && numType.getFSDatatype() == REC_BIN64_SIGNED)
return; // No type restriction for 64-bit integers
}
break;
case NA_DATETIME_TYPE:
case NA_INTERVAL_TYPE:
isExact = TRUE;
break;
default:
return; // No type constraint applied for other types
}
OptRangeSpec* typeRange = NULL;
if (isExact) // Exact numeric, datetime, interval
{
// Add the subrange implied by the type. If the type is largeint,
// nothing is needed here and no type range will be created. We don't
// need to set the type of the range specs created in this function,
// because addSubrange (which looks at the type) is bypassed and we call
// placeSubrange directly.
typeRange = new(mvqrHeap_) OptRangeSpec(descGen, mvqrHeap_);
Int64 start, end;
SubrangeBase::getExactNumericMinMax(colType, start, end, logLevel_);
Subrange<Int64>* numSubrange = new(mvqrHeap_) Subrange<Int64>(logLevel_);
numSubrange->setUnparsedStart("");
numSubrange->setUnparsedEnd("");
numSubrange->start = start;
numSubrange->end = end;
numSubrange->setStartIsMin(FALSE);
numSubrange->setEndIsMax(FALSE);
numSubrange->setStartInclusive(TRUE);
numSubrange->setEndInclusive(TRUE);
typeRange->placeSubrange(numSubrange);
}
else // approximate numeric
{
switch (colType.getFSDatatype())
{
case REC_IEEE_FLOAT32:
{
typeRange = new(mvqrHeap_) OptRangeSpec(descGen, mvqrHeap_);
Subrange<double>* dblSubrange = new(mvqrHeap_) Subrange<double>(logLevel_);
dblSubrange->end = static_cast<const NumericType&>(colType).getMaxValue();
dblSubrange->setUnparsedStart("");
dblSubrange->setUnparsedEnd("");
dblSubrange->start = -(dblSubrange->end);
dblSubrange->setStartIsMin(FALSE);
dblSubrange->setEndIsMax(FALSE);
dblSubrange->setStartInclusive(TRUE);
dblSubrange->setEndInclusive(TRUE);
typeRange->placeSubrange(dblSubrange);
}
break;
case REC_IEEE_FLOAT64:
// No range restriction needed.
break;
default:
QRLogger::log(CAT_SQL_COMP_RANGE, logLevel_,
"No case in intersectTypeConstraint() for "
"approximate numeric of type %d",
colType.getFSDatatype());
break;
}
}
if (typeRange)
{
typeRange->setNullIncluded(TRUE); // Null always part of a type range
// Call the RangeSpec version of intersect; this avoids trying to
// modify the original ItemExpr with the type constraint pred.
RangeSpec::intersectRange(typeRange);
delete typeRange;
}
} // intersectTypeConstraint()
void OptRangeSpec::addConstraints(QRDescGenerator* descGen)
{
QRTRACER("addConstraints");
ValueId colValId = getRangeColValueId();
if (colValId == NULL_VALUE_ID)
colValId = getRangeJoinPredId();
if (colValId == NULL_VALUE_ID)
return;
// Add constraint implied by the column's type.
intersectTypeConstraint(descGen, colValId);
// Check constraints can be added and dropped at will, and so can be in
// different states when the MV is created and when the query is matched.
// Therefore we utilize check constraints only for query descriptors. This
// may result in a NotProvided instead of a Provided match, but avoids the
// need to invalidate all the MV descriptors using a table when one of the
// table's check constraints is added/dropped.
if (descGen->getDescriptorType() == ET_QueryDescriptor)
intersectCheckConstraints(descGen, colValId);
// else
// assertLogAndThrow1(descGen->getDescriptorType() == ET_MVDescriptor,
// QRDescriptorException,
// "Invalid descriptor type -- %d",
// descGen->getDescriptorType());
}
void OptRangeSpec::addColumnsUsed(const QRDescGenerator* descGen)
{
if (descGen != descGenerator_)
descGenerator_->mergeDescGenerator(descGen);
}
#define AVR_STATE0 0
#define AVR_STATE1 1
#define AVR_STATE2 2
NABoolean OptRangeSpec::buildRange(ItemExpr* origPredExpr)
{
QRTRACER("buildRange");
ConstValue *startValue, *endValue;
OperatorTypeEnum leftOp, rightOp;
NABoolean isRange = TRUE;
NABoolean reprocessAND = FALSE;
//
// buildRange() can be called recursively for all the items in an IN-list
// at a point in time when we are already many levels deep in other
// recursion (e.g. Scan::applyAssociativityAndCommutativity() ). Consequently,
// we may not have much of our stack space available at the time, so
// we must eliminate the recursive calls to buildRange() by keeping the
// information needed by each "recursive" level in the heap and using
// a "while" loop to look at each node in the tree in the same order as
// the old recursive technique would have done.
// The information needed by each "recursive" level is basically just
// a pointer to what node (ItemExpr *) to look at next and a "state" value
// that tells us where we are in the buildRange() code for the ItemExpr
// node that we are currently working on.
//
ARRAY( ItemExpr * ) IEarray(mvqrHeap_, 10) ; //Initially 10 elements (no particular reason to choose 10)
ARRAY( Int16 ) state(mvqrHeap_, 10) ; //These ARRAYs will grow automatically as needed.)
Int32 currIdx = 0 ;
IEarray.insertAt( currIdx, origPredExpr ) ; //Initialize 1st element in the ARRAYs
state.insertAt( currIdx, AVR_STATE0 ) ;
while( currIdx >= 0 && isRange )
{
ItemExpr * predExpr = IEarray[currIdx] ; //Get ptr to the current IE
OperatorTypeEnum op = predExpr->getOperatorType();
switch (op)
{
case ITM_AND:
// Check for a bounded subrange, from BETWEEN predicate, etc. If not of
// this form, the predicate was presumably too complex to convert to
// conjunctive normal form without a combinatorial explosion of clauses,
// and we handle it by creating separate range objects for each operand
// of the AND, intersecting them, and then unioning the result with the
// primary range.
leftOp = predExpr->child(0)->getOperatorType();
rightOp = predExpr->child(1)->getOperatorType();
if (leftOp == ITM_LESS || leftOp == ITM_LESS_EQ)
{
if (rightOp == ITM_GREATER || rightOp == ITM_GREATER_EQ)
{
endValue = getConstOperand(predExpr->child(0));
if (endValue)
{
startValue = getConstOperand(predExpr->child(1));
if (startValue)
addSubrange(startValue, endValue,
rightOp == ITM_GREATER_EQ,
leftOp == ITM_LESS_EQ);
else
isRange = FALSE;
}
else
isRange = FALSE;
}
else
reprocessAND = TRUE;
}
else if (leftOp == ITM_GREATER || leftOp == ITM_GREATER_EQ)
{
if (rightOp == ITM_LESS || rightOp == ITM_LESS_EQ)
{
startValue = getConstOperand(predExpr->child(0));