-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathsql_const_folding.cc
1587 lines (1465 loc) · 57.7 KB
/
sql_const_folding.cc
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
/* Copyright (c) 2018, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program 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 General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@brief Fold constant query expressions. Currently, this is only done at
optimize time, but should eventually be done as much as possible at prepare
time. For dynamic parameters, we'd still need to do it at optimize time.
@defgroup Constant_Folding Query Optimizer
@{
*/
#include "sql/sql_const_folding.h"
#include <assert.h>
#include <float.h> // DBL_MAX, FLT_MAX
#include <stdint.h> // UINT64_MAX
#include <sys/types.h> // uint
#include <utility> // swap
#include "decimal.h" // E_DEC_FATAL_ERROR
#include "field_types.h" // MYSQL_TYPE_DATE
// assert
#include "my_inttypes.h" // longlong, ulonglong
#include "my_time.h" // TIME_to_longlong_datetime_packed
#include "mysql/strings/dtoa.h" // DECIMAL_NOT_SPECIFIED
#include "mysql/udf_registration_types.h" // INT_RESULT, STRING_RESULT
#include "mysql_time.h" // MYSQL_TIME
#include "sql-common/my_decimal.h" // my_decimal, my_decimal_cmp
#include "sql/field.h" // Field_real, Field
#include "sql/item.h" // Item, Item_field, Item_int
#include "sql/item_cmpfunc.h" // Item_bool_func2, Item_cond
#include "sql/item_func.h" // Item_func, Item_func::LE_FUNC
#include "sql/item_timefunc.h" // Item_date_literal
#include "sql/sql_class.h" // THD
#include "sql/sql_list.h" // List_iterator
#include "sql/sql_time.h" // my_time_set, actual_decimals
#include "sql/tztime.h" // Time_zone, my_tz_UTC
#include "sql_string.h" // String
#include "template_utils.h" // down_cast
/**
fold_condition uses analyze_field_constant to analyze constants in
comparisons expressions with a view to fold the expression. The analysis
will determine the range characteristic of the constant, as represented by
one value of this set. In the simple case, if the constant is within the range
of the field to which it is being compared, the value used is RP_INSIDE.
*/
enum Range_placement {
/**
The constant is larger than the highest value in the range
*/
RP_OUTSIDE_HIGH,
/**
The constant is lower than the lowest value in the range
*/
RP_OUTSIDE_LOW,
/**
The constant has the value of the lowest value in the range. Only used
for integer types and the YEAR type.
*/
RP_ON_MIN,
/**
The constant has the value of the highest value in the range. Only used
for integer types and the YEAR type.
*/
RP_ON_MAX,
/**
The constant has a value within the range, but that is *not* on one of the
borders if applicable for the type, cf. RP_ON_MIN and RP_ON_MAX.
*/
RP_INSIDE,
/**
The constant has a value within the range, but was truncated. Used
for DECIMAL if the constant has more precision in the fraction than the
field and for floating point underflow.
*/
RP_INSIDE_TRUNCATED,
/**
The YEAR type has a discontinuous range {0} U [1901, 2155]. If the constant
is larger than 0, but less than 1901, we represent that with this value.
*/
RP_INSIDE_YEAR_HOLE,
/**
The constant has been rounded down, i.e.\ to the left on the number line,
due to restriction on field length (FLOAT or DOUBLE) or because we have a
FLOAT type and the constant given has a mantissa with more significant
digits than allowed for FLOAT.
*/
RP_ROUNDED_DOWN,
/**
The constant has been rounded up, i.e.\ to the right on the number line, due
to restriction on field length (FLOAT or DOUBLE) or because we have a FLOAT
type and the constant given has a mantissa with more significant digits
than allowed for FLOAT.
*/
RP_ROUNDED_UP
};
/**
Minion of analyze_int_field_constant.
Round up or down decimal d, then convert constant to int if possible.
If d has a fraction part, set discount_equal. If it can't be converted to
int, it is out of range, and we fold by setting place accordingly.
@param[in] thd the session context
@param[in, out] const_val the constant we are folding
@param[in, out] place the range placement of the constant as analyzed
@param[in] f the field the constant is being compared to
@param[in] d the decimal value of the constant
@param[in] up true if we are to round up, else we round down
@param[out] discount_equal
set to true of d has a non-zero fraction part
@return true on error
*/
static bool round_fold_or_convert_dec(THD *thd, Item **const_val,
Range_placement *place, Item_field *f,
my_decimal *d, bool up,
bool *discount_equal) {
/*
Round the decimal to next integral value, then try to convert
that to a longlong
*/
my_decimal a, b;
if (my_decimal_floor(E_DEC_FATAL_ERROR, d, &a)) return true;
if (my_decimal_ceiling(E_DEC_FATAL_ERROR, d, &b)) return true;
*discount_equal = my_decimal_cmp(&a, &b) != 0;
longlong ni;
if (!my_decimal2int(0, /* mask: do not generate error in diagnostic area */
up ? &b : &a, f->unsigned_flag, &ni)) {
Item *ni_item = (f->unsigned_flag ? new (thd->mem_root) Item_uint(ni)
: new (thd->mem_root) Item_int(ni));
if (ni_item == nullptr) return true;
thd->change_item_tree(const_val, ni_item);
} else {
*place = d->sign() ? RP_OUTSIDE_LOW : RP_OUTSIDE_HIGH;
}
return false;
}
/**
Minion of analyze_int_field_constant.
Analyze decimal d. Convert decimal constant d to int if d has a zero fraction
part and is within integer range. If it can't be converted to
int, it is out of range, and we set place accordingly. If it has a non-zero
fraction part, we fold. Used for = and <>.
@param[in] thd the session context
@param[in, out] const_val the constant we are folding
@param[in, out] place the range placement of the constant as analyzed
@param[in] f the field the constant is being compared to
@param[in] d the decimal value of the constant
@return true on error
*/
static bool fold_or_convert_dec(THD *thd, Item **const_val,
Range_placement *place, Item_field *f,
my_decimal *d) {
my_decimal a, b;
if (my_decimal_ceiling(E_DEC_FATAL_ERROR, d, &a)) return true;
if (my_decimal_floor(E_DEC_FATAL_ERROR, d, &b)) return true;
if (my_decimal_cmp(&a, &b) == 0) {
// no fraction part, so try to convert to int
longlong ni;
if (!my_decimal2int(0 /* mask: want no diagnostics generated */, &a,
f->unsigned_flag, &ni)) {
const auto ni_item =
(f->unsigned_flag ? new (thd->mem_root) Item_uint(ni)
: new (thd->mem_root) Item_int(ni));
if (ni_item == nullptr) return true;
thd->change_item_tree(const_val, ni_item);
return false;
}
}
/*
Either decimal constant has a fraction, or it's out of all integer
range, so cannot be true
*/
*place = RP_OUTSIDE_HIGH; // well, or low, it doesn't matter for =, <>
return false;
}
/**
Minion of analyze_field_constant for integer type fields.
Analyze a constant's placement within (or without) the type range of the
field f. Also normalize the given constant to the type of the field if
applicable.
@param thd the session context
@param f the integer typed field
@param[out] const_val a pointer to an item tree pointer containing the
constant (at execution time). May be modified if
we replace or fold the constant.
@param ft the function type of the comparison
@param left_has_field
the field is the left operand
@param[out] place the placement of the const_val relative to
the range of f
@param[out] discount_equal
set to true: caller should replace GE with GT or LE
with LT.
@returns true on error
*/
static bool analyze_int_field_constant(THD *thd, Item_field *f,
Item **const_val, Item_func::Functype ft,
bool left_has_field,
Range_placement *place,
bool *discount_equal) {
const bool field_unsigned = f->unsigned_flag;
my_decimal *d = nullptr;
my_decimal dec;
switch ((*const_val)->result_type()) {
case INT_RESULT:
break;
case STRING_RESULT: {
if ((*const_val)->type() == Item::HEX_BIN_ITEM) {
/*
0x digits have STRING_RESULT but are ints in int
context.
*/
break;
}
}
[[fallthrough]];
case REAL_RESULT: {
/*
Try to convert to decimal. If that fails, we know the constant is out of
range for integer too. If it can be converted, continue with the decimal
logic.
*/
const double v = (*const_val)->val_real();
int err = double2decimal(v, &dec);
if (err & E_DEC_OVERFLOW) {
if (v < 0)
*place = RP_OUTSIDE_LOW;
else
*place = RP_OUTSIDE_HIGH;
return false;
}
if (err & E_DEC_TRUNCATED) {
/*
Check for underflow, e.g. 1.7976931348623157E-308 would end up as
decimal 0.0, which means that the floating point values was
marginally greater than 0.0, so we "simulate" this by adding 0.1.
Correspondingly for negative underflow, we subtract 0.1. This is OK,
because we round later. The value can also be truncated even if it
isn't quite as small as zero, but in such a case its absolute value
would always be smaller than 0.1, but not representable as a decimal,
so we use 0.1 for those as well.
*/
if (v > 0) {
// underflow on the positive side
const String s("0.1", thd->charset());
err = str2my_decimal(E_DEC_FATAL_ERROR, s.ptr(), s.length(),
s.charset(), &dec);
assert(err == 0);
} else {
const String s("-0.1", thd->charset());
err = str2my_decimal(E_DEC_FATAL_ERROR, s.ptr(), s.length(),
s.charset(), &dec);
assert(err == 0);
}
}
d = &dec;
}
[[fallthrough]];
case DECIMAL_RESULT: {
/*
If out of bounds of longlong, return RP_OUTSIDE_LOW or RP_OUTSIDE_HIGH
as the case may be. If not, if the decimal has a non-zero fraction,
equality cannot be true, so just return an RP_OUTSIDE_*.
For >, >=, < and <=, if we have a non-zero fraction, round up or down
to closest integer, then proceed with the integer constant logic.
For equality and a zero fraction convert to integer and proceed with
the integer constant logic.
*/
my_decimal d_buff;
if (d == nullptr) d = (*const_val)->val_decimal(&d_buff);
if (ft == Item_func::LT_FUNC || ft == Item_func::LE_FUNC) {
/*
Round up (or down if field is the right operand) the decimal to next
integral value, then try to convert that to a longlong, or short
circuit
*/
if (round_fold_or_convert_dec(thd, const_val, place, f, d,
left_has_field, discount_equal))
return true;
if (*place != RP_INSIDE) return false;
} else if (ft == Item_func::GT_FUNC || ft == Item_func::GE_FUNC) {
/*
Round down (or up) the decimal to next integral value, then try to
convert that to a longlong
*/
if (round_fold_or_convert_dec(thd, const_val, place, f, d,
!left_has_field, discount_equal))
return true;
if (*place != RP_INSIDE) return false;
} else { // for =, <>
if (fold_or_convert_dec(thd, const_val, place, f, d)) return true;
if (*place != RP_INSIDE) return false;
}
} break;
default:
return false;
}
longlong s_max = 0;
longlong s_min = 0;
longlong u_max = 0;
switch (f->field->type()) {
case MYSQL_TYPE_TINY:
s_max = INT_MAX8;
s_min = INT_MIN8;
u_max = UINT_MAX8;
break;
case MYSQL_TYPE_SHORT:
s_max = INT_MAX16;
s_min = INT_MIN16;
u_max = UINT_MAX16;
break;
case MYSQL_TYPE_INT24:
s_max = INT_MAX24;
s_min = INT_MIN24;
u_max = UINT_MAX24;
break;
case MYSQL_TYPE_LONG:
s_max = INT_MAX32;
s_min = INT_MIN32;
u_max = UINT_MAX32;
break;
case MYSQL_TYPE_LONGLONG:
// special treatment below
break;
default:
assert(false); /* purecov: inspected */
}
switch (f->field->type()) {
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_LONG: {
const longlong v = (*const_val)->val_int();
const bool value_unsigned = (*const_val)->unsigned_flag;
if (field_unsigned) {
/* unsigned field: e.g. for TINYINT, accept [0, 255] */
if (v < 0 && !value_unsigned) {
*place = RP_OUTSIDE_LOW;
} else if (static_cast<ulonglong>(v) > static_cast<ulonglong>(u_max)) {
*place = RP_OUTSIDE_HIGH;
} else if (v == u_max) {
*place = RP_ON_MAX;
} else if (v == 0) {
*place = RP_ON_MIN;
}
} else {
/* signed field: e.g. for TINYINT, accept [-128, 127] */
if (value_unsigned &&
(static_cast<ulonglong>(v) > static_cast<ulonglong>(s_max))) {
*place = RP_OUTSIDE_HIGH;
} else if (v < s_min) {
*place = RP_OUTSIDE_LOW;
} else if (v > s_max) {
*place = RP_OUTSIDE_HIGH;
} else if (v == s_min) {
*place = RP_ON_MIN;
} else if (v == s_max) {
*place = RP_ON_MAX;
}
}
} break;
case MYSQL_TYPE_LONGLONG: {
/*
Since for 64 bits int we don't have the "luxury" of doing the analysis
math in a wider int type, the structure is slightly different than the
checks above.
*/
const longlong v = (*const_val)->val_int();
const bool value_unsigned = (*const_val)->unsigned_flag;
if (field_unsigned) {
/* unsigned field: accept [0, 18446744073709551615] */
if (v < 0 && !value_unsigned) {
*place = RP_OUTSIDE_LOW;
// No need to check (ulonglong)v > (ulonglong)UINT64_MAX): impossible
} else if (static_cast<ulonglong>(v) == UINT64_MAX) {
*place = RP_ON_MAX;
} else if (v == 0) {
*place = RP_ON_MIN;
}
} else {
/* signed field: accept [-9223372036854775808 9223372036854775807] */
if (value_unsigned &&
(static_cast<ulonglong>(v) > static_cast<ulonglong>(INT_MAX64))) {
*place = RP_OUTSIDE_HIGH;
// No need to check v < static_cast<ulonglong>(INT_MIN64): impossible
} else if (!value_unsigned && v == INT_MIN64) {
*place = RP_ON_MIN;
} else if (!value_unsigned && v == INT_MAX64) {
*place = RP_ON_MAX;
}
}
} break;
default:
assert(false); /* purecov: inspected */
}
return false;
}
/**
Minion of analyze_field_constant for decimal type fields
Analyze a constant's placement inside (or outside) the type range of the
field f. Also normalize the given constant to the type of the field if
applicable.
@param thd the session context
@param f the decimal typed field
@param[out] const_val a pointer to an item tree pointer containing the
constant (at execution time). May be modified if
we replace or fold the constant.
@param ft the function type of the comparison
@param[out] place the placement of the const_val relative to
the range of f
@param[out] negative true if the constant has a (minus) sign
@returns true on error
*/
static bool analyze_decimal_field_constant(THD *thd, const Item_field *f,
Item **const_val,
Item_func::Functype ft,
Range_placement *place,
bool *negative) {
const auto fd = down_cast<const Field_new_decimal *>(f->field);
const int f_frac = fd->dec;
const int f_intg = fd->precision - f_frac;
bool was_string_or_real = false;
int err;
Item_result ir = (*const_val)->result_type();
/*
If we have a string, it may be anything inside, so assume decimal,
which also recognizes real constants, btw. The exception is the
0xnnn numbers, which also have STRING result type, but should be treated
the same as ints.
*/
if (ir == STRING_RESULT && (*const_val)->type() != Item::HEX_BIN_ITEM) {
was_string_or_real = true;
ir = DECIMAL_RESULT;
}
switch (ir) {
case STRING_RESULT:
case INT_RESULT: {
my_decimal tmp;
const auto *const d = (*const_val)->val_decimal(&tmp);
if (thd->is_error()) return true;
assert(d != nullptr);
assert(decimal_actual_fraction(d) == 0);
const int actual_intg = decimal_intg(d);
if (actual_intg > f_intg) { // overflow
*place = d->sign() ? RP_OUTSIDE_LOW : RP_OUTSIDE_HIGH;
break;
}
// inside, but convert const to decimal, similar precision as field
my_decimal tmp_ext;
if (decimal_round(d, &tmp_ext, f_frac, FLOOR)) return true;
const auto new_dec = new (thd->mem_root) Item_decimal(&tmp_ext);
if (new_dec == nullptr) return true;
thd->change_item_tree(const_val, new_dec);
} break;
case REAL_RESULT: {
my_decimal val_dec;
const double v = (*const_val)->val_real();
err = double2decimal(v, &val_dec);
if (err & E_DEC_OVERFLOW) {
if (v < 0)
*place = RP_OUTSIDE_LOW;
else
*place = RP_OUTSIDE_HIGH;
return false;
}
if (err & E_DEC_TRUNCATED) {
/*
Check for underflow, e.g. 1.7976931348623157E-308 would end up
as decimal 0.0, which means that the floating point values was
marginally greater that 0.0. So, we convert to 0 and compensate
in logic for RP_INSIDE_TRUNCATED in fold_condition.
Similar logic for negative underflow.
*/
*place = RP_INSIDE_TRUNCATED;
*negative = v < 0;
my_decimal tmp;
err = longlong2decimal(0, &tmp);
assert(err == 0);
widen_fraction(f_frac, &tmp);
const auto new_dec = new (thd->mem_root) Item_decimal(&tmp);
if (new_dec == nullptr) return true;
thd->change_item_tree(const_val, new_dec);
return false;
}
was_string_or_real = true;
}
[[fallthrough]];
case DECIMAL_RESULT: {
/*
Decimal constant can have different range and precision
*/
// Dictionary info about decimal field:
// Compute actual (minimal) decimal type of the constant
my_decimal buff, *d;
d = (*const_val)->val_decimal(&buff);
if ((*const_val)->null_value) return false;
assert(d != nullptr);
const int actual_frac = decimal_actual_fraction(d);
const int actual_intg = decimal_intg(d);
const bool overflow = actual_intg > f_intg;
const bool truncation = actual_frac > f_frac;
if (overflow) {
*place = d->sign() ? RP_OUTSIDE_LOW : RP_OUTSIDE_HIGH;
} else if (truncation) {
my_decimal cpy;
my_decimal2decimal(d, &cpy);
if (ft == Item_func::GT_FUNC || ft == Item_func::GE_FUNC ||
ft == Item_func::LT_FUNC || ft == Item_func::LE_FUNC) {
// adjust precision to same as field
*negative = cpy.sign();
if (decimal_round(&cpy, &cpy, f_frac, cpy.sign() ? CEILING : FLOOR))
return true;
const auto new_dec = new (thd->mem_root) Item_decimal(&cpy);
if (new_dec == nullptr) return true;
thd->change_item_tree(const_val, new_dec);
*place = RP_INSIDE_TRUNCATED;
} else {
*place = RP_OUTSIDE_HIGH; // =, <>, so outside: convention use high
}
} else if (d->frac > f_frac) {
// truncate zeros
my_decimal cpy;
my_decimal2decimal(d, &cpy);
if (decimal_round(&cpy, &cpy, f_frac, TRUNCATE)) return true;
const auto new_dec = new (thd->mem_root) Item_decimal(&cpy);
if (new_dec == nullptr) return true;
thd->change_item_tree(const_val, new_dec);
} else if (actual_frac < f_frac) {
my_decimal cpy;
my_decimal2decimal(d, &cpy);
widen_fraction(f_frac, &cpy);
const auto new_dec = new (thd->mem_root) Item_decimal(&cpy);
if (new_dec == nullptr) return true;
thd->change_item_tree(const_val, new_dec);
} else if (was_string_or_real) {
// Make a decimal constant instead
const auto new_dec = new (thd->mem_root) Item_decimal(d);
if (new_dec == nullptr) return true;
thd->change_item_tree(const_val, new_dec);
}
} break;
default:
break;
}
return false;
}
/**
Minion of analyze_field_constant for real type fields
Analyze a constant's placement within (or without) the type range of the
field f. Also normalize the given constant to the type of the field if
applicable.
@param thd the session context
@param f the real (FLOAT, DOUBLE) typed field
@param[out] const_val a pointer to an item tree pointer containing the
constant (at execution time). May be modified if
we replace or fold the constant.
@param[out] place the placement of the const_val relative to
@returns true on error
*/
static bool analyze_real_field_constant(THD *thd, Item_field *f,
Item **const_val,
Range_placement *place) {
switch ((*const_val)->result_type()) {
case REAL_RESULT:
case STRING_RESULT:
case INT_RESULT:
case DECIMAL_RESULT:
/*
Can all be safely converted to a double value. Although we may lose
precision, we won't overflow. Any constants too large for double will
have been caught at parsing time.
*/
break;
default:
assert(false); /* purecov: inspected */
break;
}
double v = (*const_val)->val_real();
const double orig = v;
const bool is_float = f->field->type() == MYSQL_TYPE_FLOAT;
/*
This check/truncation also handles fixed # decimals digits real types, a
MySQL extension, e.g. FLOAT(5,2).
*/
const auto fd = down_cast<Field_real *>(f->field);
Field_real::Truncate_result err =
fd->truncate(&v, (is_float ? FLT_MAX : DBL_MAX));
if (err != Field_real::TR_OK) {
*place = (err == Field_real::TR_NEGATIVE_OVERFLOW ? RP_OUTSIDE_LOW
: RP_OUTSIDE_HIGH);
return false;
}
if (!fd->not_fixed) {
if (is_float) {
v = (float)v;
/*
The number can now have been rounded up or down due to restriction on
field length or a float orig_v in presence of longer mantissa than
allowed for float.
*/
if (v > (float)orig || v < (float)orig) {
*place = v > orig ? RP_ROUNDED_UP : RP_ROUNDED_DOWN;
}
} else {
if (v > orig || v < orig) {
*place = v > orig ? RP_ROUNDED_UP : RP_ROUNDED_DOWN;
}
}
}
/*
Lastly, convert to double representation.
*/
if (v != orig || (*const_val)->type() != Item::REAL_ITEM) {
const auto new_const =
new (thd->mem_root) Item_float(v, DECIMAL_NOT_SPECIFIED);
if (new_const == nullptr) return true;
thd->change_item_tree(const_val, new_const);
}
return false;
}
/**
Minion of analyze_field_constant for YEAR type fields
Analyze a constant's placement within (or without) the type range of the
field f. Also normalize the given constant to the type of the field if
applicable.
@param thd the session context
@param[out] const_val a pointer to an item tree pointer containing the
constant (at execution time). May be modified if
we replace or fold the constant.
@param[out] place the placement of the const_val relative to
@returns true on error
*/
static bool analyze_year_field_constant(THD *thd, Item **const_val,
Range_placement *place) {
if ((*const_val)->data_type() == MYSQL_TYPE_YEAR) {
/*
Decimal, real and string constants have already been converted to int if
they allowed year values, and these as well as integer constants that are
allowed year values have been typed as MYSQL_TYPE_YEAR, cf.
convert_constant_item called during type resolution.
*/
assert((*const_val)->result_type() == INT_RESULT);
const longlong year = (*const_val)->val_int();
if (year == 0)
*place = RP_ON_MIN;
else if (year == Field_year::MAX_YEAR)
*place = RP_ON_MAX;
else
*place = RP_INSIDE;
return false;
}
// The constant is outside allowed year values, so fold.
const Item_result ir = (*const_val)->result_type();
switch (ir) {
case STRING_RESULT:
case DECIMAL_RESULT:
case REAL_RESULT:
case INT_RESULT: {
const double year = (*const_val)->val_real();
if (year > static_cast<double>(Field_year::MAX_YEAR)) {
*place = RP_OUTSIDE_HIGH;
} else if (year < 0.0) {
*place = RP_OUTSIDE_LOW;
} else if (year > 0.0 &&
year < static_cast<double>(Field_year::MIN_YEAR)) {
/*
These values can be given as constants, but are not allowed to be
stored in the field, so an = or <> comparison can be folded. For
other operations, we treat the constants as if it is inside range,
since a year field may contain 0.
*/
*place = RP_INSIDE_YEAR_HOLE;
// Make sure we have an int constant
if (ir != INT_RESULT) {
const auto i = new (thd->mem_root) Item_int(static_cast<int>(year));
if (i == nullptr) return true;
thd->change_item_tree(const_val, i);
}
} else {
if (ir != INT_RESULT) {
const auto i = new (thd->mem_root) Item_int(static_cast<int>(year));
if (i == nullptr) return true;
thd->change_item_tree(const_val, i);
}
}
} break;
default:
assert(false); /* purecov: inspected */
break;
}
return false;
}
/**
Minion of analyze_field_constant for TIMESTAMP, DATETIME, DATE fields
Analyze a constant's placement within (or without) the type range of the
field f. Also normalize the given constant to the type of the field if
applicable.
@param thd the session context
@param f the field
@param[out] const_val a pointer to an item tree pointer containing the
constant (at execution time). May be modified if
we replace or fold the constant.
@param[out] place the placement of the const_val relative to
@returns true on error
*/
static bool analyze_timestamp_field_constant(THD *thd, const Item_field *f,
Item **const_val,
Range_placement *place) {
const auto rtype = (*const_val)->result_type();
switch (rtype) {
case STRING_RESULT: // This covers both string and TIMESTAMP literals
case INT_RESULT: {
MYSQL_TIME ltime =
my_time_set(0, 0, 0, 0, 0, 0, 0, false, MYSQL_TIMESTAMP_DATETIME);
MYSQL_TIME_STATUS status;
if (rtype == STRING_RESULT) {
String buf;
String *res = (*const_val)->val_str(&buf);
if (res == nullptr) {
assert((*const_val)->null_value);
return false;
}
/*
Some wrong values are still compared as DATETIME, e.g. '2018-02-31
06:14:07' (illegal day in February), while worse values lead to
comparison as strings (e.g. '2018'). Cf. comment on Bug#27692509. Any
warnings have already been given earlier, so ignore.
*/
if (get_mysql_time_from_str_no_warn(thd, res, <ime, &status)) {
// Could not fold, so leave untouched.
return false;
}
/*
A date constant being compared to a timestamp or datetime field is ok,
convert it to a datetime literal, using 00:00:00 as the time.
If the field type is DATE, we also use a MYSQL_TIMESTAMP_DATETIME
constant with zero time part.
*/
if (ltime.time_type == MYSQL_TIMESTAMP_DATE)
ltime.time_type = MYSQL_TIMESTAMP_DATETIME;
} else if (rtype == INT_RESULT) {
if ((*const_val)->data_type() == MYSQL_TYPE_TIMESTAMP ||
(*const_val)->data_type() == MYSQL_TYPE_DATETIME ||
(*const_val)->data_type() == MYSQL_TYPE_DATE) {
TIME_from_longlong_datetime_packed(<ime, (*const_val)->val_int());
} else {
/*
The integral constant could not be interpreted as a datetime value,
the operands will be compared using double.
*/
return false;
}
}
MYSQL_TIME ltime_utc = ltime;
const enum_field_types ft = f->field->type();
if (ft == MYSQL_TYPE_TIMESTAMP) {
/*
Convert constant to timeval, if it fits. If not, we are out of
range for a TIMESTAMP. The timeval is UTC since epoch, using 32
bits range.
*/
int warnings = 0;
my_timeval tm = {0, 0};
int zeros = 0;
zeros += ltime.year == 0;
zeros += ltime.month == 0;
zeros += ltime.day == 0;
if (zeros == 0 || zeros == 3) { // Cf. NO_ZERO_DATE, NO_ZERO_IN_DATE
datetime_with_no_zero_in_date_to_timeval(<ime, *thd->time_zone(),
&tm, &warnings);
if ((warnings & MYSQL_TIME_WARN_OUT_OF_RANGE) != 0) {
/*
For RP_OUTSIDE_HIGH, this check may not catch case where field
type has no/fewer fraction digits than the constant. This will
be caught below.
*/
*place = ltime.year < 1971 ? RP_OUTSIDE_LOW : RP_OUTSIDE_HIGH;
return false;
}
} // else zero in date => 0 timeval too
/*
Convert timestamp's timeval to UTC ltime and pack it so we can
compare with min/max, unless it is 0 or has a zero date part (year,
month or day)
*/
if (tm.m_tv_sec != 0) {
/* '2038-01-19 03:14:07.[999999]' */
MYSQL_TIME max_timestamp = my_time_set(
TIMESTAMP_MAX_YEAR, 1, 19, 3, 14, 7,
max_fraction(
down_cast<const Field_temporal *>(f->field)->decimals()),
false, MYSQL_TIMESTAMP_DATETIME);
/* '1970-01-01 00:00:01.[000000]' */
const MYSQL_TIME min_timestamp = my_time_set(
1970, 1, 1, 0, 0, 1, 0, false, MYSQL_TIMESTAMP_DATETIME);
// We store in UTC, so use as is
const longlong max_t =
TIME_to_longlong_datetime_packed(max_timestamp);
const longlong min_t =
TIME_to_longlong_datetime_packed(min_timestamp);
my_tz_UTC->gmt_sec_to_TIME(<ime_utc, tm);
const longlong cnst = TIME_to_longlong_datetime_packed(ltime_utc);
if (cnst > max_t) {
*place = RP_OUTSIDE_HIGH;
return false;
}
if (cnst < min_t) {
/*
A zero ltime (if error in str_to_datetime) before GMT conversion
ends up as 1970-01-01 00:00:00 which get us here.
*/
*place = RP_OUTSIDE_LOW;
return false;
}
} // else: 0 timevalue
} // else: not TIMESTAMP field
/*
We do not try to truncate the number of decimal digits in the
constant if it exceeds the number of allowed decimals in the
type of the field. This could be improved. If we want to try that,
we could use RP_INSIDE_TRUNCATED. This could lead to folding away of
=, <>.
*/
if ((*const_val)->type() == Item::FUNC_ITEM &&
down_cast<Item_func *>(*const_val)->functype() ==
Item_func::DATETIME_LITERAL) {
/* User supplied an ok literal */
} else {
Item *i = nullptr;
/*
Make a DATETIME literal, unless the field is a DATE and the constant
has zero time, in which case we make a DATE literal
*/
if (ft == MYSQL_TYPE_DATE) {
ltime.time_type = MYSQL_TIMESTAMP_DATE;
if (ltime.hour == 0 && ltime.minute == 0 && ltime.second == 0 &&
ltime.second_part == 0) {
/* OK, time part is zero, so trivial type change */
} else {
/* truncate time part: must adjust operators */
ltime.hour = 0;
ltime.minute = 0;
ltime.second = 0;
ltime.second_part = 0;
*place = RP_INSIDE_TRUNCATED;
}
i = new (thd->mem_root) Item_date_literal(<ime);
} else if (!check_time_zone_convertibility(ltime)) {
i = new (thd->mem_root) Item_datetime_literal(
<ime, actual_decimals(<ime), thd->time_zone());
}
if (i == nullptr) return true;
thd->change_item_tree(const_val, i);
}
} break;
case REAL_RESULT:
case DECIMAL_RESULT:
/*
The number could not be interpreted as datetime, so
compares as double.
*/
break;
default:
break;
}
return false;
}
/*
Minion of analyze_field_constant for TIME fields. Creates a TIME literal
of a valid TIME constant.
*/
static bool analyze_time_field_constant(THD *thd, Item **const_val) {
if (!((*const_val)->result_type() == INT_RESULT &&
(*const_val)->data_type() == MYSQL_TYPE_TIME)) {
// Not a TIME constant. Compare as string or double.
return false;
}
/*
An OK TIME constant, represented as Item_time_with_ref.
Note that excessive decimals have already been rounded, so there is no
opportunity for folding. This is in contrast to DATETIME/TIMESTAMP
btw, which retains any excessive decimals digits when comparing.
Cf. Bug#28320529
*/
MYSQL_TIME ltime;
TIME_from_longlong_time_packed(<ime, (*const_val)->val_time_temporal());
auto i =
new (thd->mem_root) Item_time_literal(<ime, actual_decimals(<ime));
if (i == nullptr) return true;
thd->change_item_tree(const_val, i);
return false;
}
/**
Analyze a constant's placement within (or without) the type range of the
field f. Also normalize the given constant to the type of the field if
applicable.
@param thd the session context
@param f the field
@param[out] const_val a pointer to an item tree pointer containing the
constant (at execution time). May be modified if
we replace or fold the constant.
@param func the function of the comparison
@param left_has_field
the field is the left operand
@param[out] place the placement of the const_val relative to
the range of f
@param[out] discount_equal
set to true: caller should replace GE with GT or LE
with LT.
@param[out] negative true if the constant (decimal) is has a (minus) sign
@returns true on error
*/