-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathitem_cmpfunc.cc
8233 lines (7220 loc) · 279 KB
/
item_cmpfunc.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) 2000, 2024, 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 sql/item_cmpfunc.cc
@brief
This file defines all Items that compare values (e.g. >=, ==, LIKE, etc.)
*/
#include "sql/item_cmpfunc.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <type_traits>
#include <utility>
#include "decimal.h"
#include "field_types.h"
#include "mf_wcomp.h" // wild_one, wild_many
#include "my_alloc.h"
#include "my_bitmap.h"
#include "my_dbug.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "mysql/strings/dtoa.h"
#include "mysql/strings/m_ctype.h"
#include "mysql/udf_registration_types.h"
#include "mysql_com.h"
#include "mysql_time.h"
#include "mysqld_error.h"
#include "sql-common/json_dom.h" // Json_scalar_holder
#include "sql/aggregate_check.h" // Distinct_check
#include "sql/check_stack.h"
#include "sql/current_thd.h" // current_thd
#include "sql/derror.h" // ER_THD
#include "sql/error_handler.h"
#include "sql/field.h"
#include "sql/histograms/histogram.h"
#include "sql/item.h"
#include "sql/item_func.h"
#include "sql/item_json_func.h" // json_value, get_json_atom_wrapper
#include "sql/item_subselect.h" // Item_subselect
#include "sql/item_sum.h" // Item_sum_hybrid
#include "sql/item_timefunc.h" // Item_typecast_date
#include "sql/join_optimizer/bit_utils.h"
#include "sql/join_optimizer/secondary_statistics.h"
#include "sql/key.h"
#include "sql/mysqld.h" // log_10
#include "sql/nested_join.h"
#include "sql/opt_trace.h" // Opt_trace_object
#include "sql/opt_trace_context.h"
#include "sql/parse_tree_helpers.h" // PT_item_list
#include "sql/parse_tree_node_base.h" // Parse_context
#include "sql/query_options.h"
#include "sql/sql_array.h"
#include "sql/sql_base.h"
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h" // THD
#include "sql/sql_const.h"
#include "sql/sql_error.h"
#include "sql/sql_executor.h"
#include "sql/sql_lex.h"
#include "sql/sql_opt_exec_shared.h"
#include "sql/sql_optimizer.h" // JOIN
#include "sql/sql_select.h"
#include "sql/sql_time.h" // str_to_datetime
#include "sql/system_variables.h"
#include "sql/thd_raii.h"
#include "string_with_len.h"
using std::max;
using std::min;
static const enum_walk walk_options =
enum_walk::PREFIX | enum_walk::POSTFIX | enum_walk::SUBQUERY;
static bool convert_constant_item(THD *, Item_field *, Item **, bool *);
static longlong get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
const Item *warn_item, bool *is_null);
static Item **cache_converted_constant(THD *thd, Item **value,
Item **cache_item, Item_result type);
/**
Compare row signature of two expressions
@param item1 first expression
@param item2 second expression
@returns true if row types are compatible, false otherwise.
The function checks that two expressions have compatible row signatures
i.e. that the number of columns they return are the same and that if they
are both row expressions then each component from the first expression has
a row signature compatible with the signature of the corresponding component
of the second expression.
*/
static bool row_types_are_compatible(Item *item1, Item *item2) {
const uint n = item1->cols();
if (item2->check_cols(n)) return false;
for (uint i = 0; i < n; i++) {
if (item2->element_index(i)->check_cols(item1->element_index(i)->cols()) ||
(item1->element_index(i)->result_type() == ROW_RESULT &&
!row_types_are_compatible(item1->element_index(i),
item2->element_index(i))))
return false;
}
return true;
}
/**
Aggregates result types from the array of items.
This function aggregates result types from the array of items. Found type
supposed to be used later for comparison of values of these items.
Aggregation itself is performed by the item_cmp_type() function.
@param items array of items to aggregate the type from
@param nitems number of items in the array
@returns the aggregated type
*/
static Item_result agg_cmp_type(Item **items, uint nitems) {
Item_result type = items[0]->result_type();
for (uint i = 1; i < nitems; i++) {
type = item_cmp_type(type, items[i]->result_type());
}
return type;
}
static void write_histogram_to_trace(THD *thd, const Item_func *item,
const double selectivity) {
Opt_trace_object obj(&thd->opt_trace, "histogram_selectivity");
obj.add("condition", item).add("histogram_selectivity", selectivity);
}
/**
@brief Aggregates field types from the array of items.
@param[in] items array of items to aggregate the type from
@param[in] nitems number of items in the array
@details This function aggregates field types from the array of items.
Found type is supposed to be used later as the result field type
of a multi-argument function.
Aggregation itself is performed by the Field::field_type_merge()
function.
@note The term "aggregation" is used here in the sense of inferring the
result type of a function from its argument types.
@return aggregated field type.
*/
enum_field_types agg_field_type(Item **items, uint nitems) {
assert(nitems > 0 && items[0]->result_type() != ROW_RESULT);
enum_field_types res = items[0]->data_type();
for (uint i = 1; i < nitems; i++)
res = Field::field_type_merge(res, items[i]->data_type());
return real_type_to_type(res);
}
/**
Collects different types for comparison of first item with each other items
@param items Array of items to collect types from
@param nitems Number of items in the array
@param skip_nulls Don't collect types of NULL items if true
@note
This function collects different result types for comparison of the first
item in the list with each of the remaining items in the 'items' array.
@retval 0 Error, row type incompatibility has been detected
@retval <> 0 Bitmap of collected types - otherwise
*/
static uint collect_cmp_types(Item **items, uint nitems,
bool skip_nulls = false) {
const Item_result left_result = items[0]->result_type();
assert(nitems > 1);
uint found_types = 0;
for (uint i = 1; i < nitems; i++) {
if (skip_nulls && items[i]->type() == Item::NULL_ITEM)
continue; // Skip NULL constant items
if ((left_result == ROW_RESULT || items[i]->result_type() == ROW_RESULT) &&
!row_types_are_compatible(items[0], items[i]))
return 0;
found_types |=
1U << (uint)item_cmp_type(left_result, items[i]->result_type());
}
/*
Even if all right-hand items are NULLs and we are skipping them all, we need
at least one type bit in the found_type bitmask.
*/
if (skip_nulls && !found_types) found_types = 1U << (uint)left_result;
return found_types;
}
static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
const char *fname) {
my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0), c1.collation->m_coll_name,
c1.derivation_name(), c2.collation->m_coll_name,
c2.derivation_name(), fname);
}
/// This is used to indicate that the selectivity of a predicate has
/// not been determined.
static constexpr double kUndefinedSelectivity{-1.0};
/**
Try to find the selectivity of an Item_func (predicate) using a
histogram.
@param thd The current thread.
@param field The field for which we will look for a histogram.
@param op The comparison operator of item_func.
@param item_func The predicate.
@return The selectivity if a histogram was found and the arguments
of item_func allowed use of a histogram. Otherwise, kUndefinedSelectivity.
*/
static double get_histogram_selectivity(THD *thd, const Field &field,
histograms::enum_operator op,
const Item_func &item_func) {
const histograms::Histogram *histogram =
field.table->find_histogram(field.field_index());
if (histogram != nullptr) {
double selectivity;
if (!histogram->get_selectivity(item_func.arguments(),
item_func.argument_count(), op,
&selectivity)) {
if (unlikely(thd->opt_trace.is_started()))
write_histogram_to_trace(thd, &item_func, selectivity);
return selectivity;
}
}
return kUndefinedSelectivity;
}
/**
Estimate the selectivity of a predicate of type field=expression,
using an index containing 'field'. ('expression' is assumed to be
independent of the table that 'field' belongs to, meaning that this
function should not be called for e.g. "t1.f1=t1.f2+1").
@param field The field for which we estimate the selectivity.
@returns The selectivity estimate, or kUndefinedSelectivity if no
suitable index was found.
*/
static double IndexSelectivityOfUnknownValue(const Field &field) {
const ha_rows row_count{field.table->file->stats.records};
int contributing_keys{0};
double selectivity_product{-1.0};
if (row_count == 0) {
return kUndefinedSelectivity;
}
uint shortest_prefix{UINT_MAX};
// Loop over the keys containing 'field'.
for (uint key_no = field.part_of_key.get_first_set(); key_no != MY_BIT_NONE;
key_no = field.part_of_key.get_next_set(key_no)) {
const KEY &key{field.table->key_info[key_no]};
// Loop over the fields of 'key'.
for (uint part_no = 0; part_no < key.user_defined_key_parts; part_no++) {
if (!key.has_records_per_key(part_no)) {
break;
}
const Field &key_field{*key.key_part[part_no].field};
// Find (the square of) a selectivity estimate for a field that is part of
// an index, but not the first field of that index.
const auto subsequent_field_selectivity_squared = [&]() {
assert(part_no > 0);
/*
For a field that is the first part (zero-indexed) of a key we
can obtain the number of distinct values directly from the
records_per_key statistic, but if the field is the k'th > 0
part we have to make an estimate. Let d_k denote the number of
distinct values in the k-part prefix of the key. Given that we
only have information about d_k and d_(k-1) the number of
distinct values in the field can be anywhere between d_k and
d_k / d_(k-1), so we use the geometric mean of these two
values as our estimate.
*/
// Case 1: key field 'part_no' and the preceding fields are
// uncorrelated.
const double uncorrelated_estimate{
double{key.records_per_key(part_no)} /
key.records_per_key(part_no - 1)};
// Case 2: The preceding fields are functionally dependent on
// key field 'part_no'.
const double correlated_estimate{
std::min(1.0, double{key.records_per_key(part_no)} / row_count)};
// Use the geometric mean of case 1 and 2.
return uncorrelated_estimate * correlated_estimate;
};
if (&field == &key_field) {
if (part_no == 0) {
// We need std::min() since records_per_key() and stats.records
// may be updated at different points in time.
return std::min(1.0, double{key.records_per_key(0)} / row_count);
} else if (part_no < shortest_prefix) {
shortest_prefix = part_no;
selectivity_product = subsequent_field_selectivity_squared();
contributing_keys = 1;
break;
} else if (part_no == shortest_prefix) {
// If 'field' is the n'th part of several indexes, we calculate the
// geometric mean of the estimate from each of them.
selectivity_product *= subsequent_field_selectivity_squared();
contributing_keys++;
break;
}
}
}
}
switch (contributing_keys) {
case 0:
return kUndefinedSelectivity;
case 1:
return std::sqrt(
selectivity_product); // Minor optimization for the most common case.
default:
return std::pow(selectivity_product, 0.5 / contributing_keys);
}
}
/**
This implementation of the factory method also implements flattening of
row constructors. Examples of flattening are:
- ROW(a, b) op ROW(x, y) => a op x P b op y.
- ROW(a, ROW(b, c) op ROW(x, ROW(y, z))) => a op x P b op y P c op z.
P is either AND or OR, depending on the comparison operation, and this
detail is left for combine().
The actual operator @c op is created by the concrete subclass in
create_scalar_predicate().
*/
Item_bool_func *Linear_comp_creator::create(Item *a, Item *b) const {
/*
Test if the arguments are row constructors and thus can be flattened into
a list of ANDs or ORs.
*/
if (a->type() == Item::ROW_ITEM && b->type() == Item::ROW_ITEM) {
if (a->cols() != b->cols()) {
my_error(ER_OPERAND_COLUMNS, MYF(0), a->cols());
return nullptr;
}
assert(a->cols() > 1);
List<Item> list;
for (uint i = 0; i < a->cols(); ++i)
list.push_back(create(a->element_index(i), b->element_index(i)));
return combine(list);
}
return create_scalar_predicate(a, b);
}
Item_bool_func *Eq_creator::create_scalar_predicate(Item *a, Item *b) const {
assert(a->type() != Item::ROW_ITEM || b->type() != Item::ROW_ITEM);
return new Item_func_eq(a, b);
}
Item_bool_func *Eq_creator::combine(List<Item> list) const {
return new Item_cond_and(list);
}
Item_bool_func *Equal_creator::create_scalar_predicate(Item *a, Item *b) const {
assert(a->type() != Item::ROW_ITEM || b->type() != Item::ROW_ITEM);
return new Item_func_equal(a, b);
}
Item_bool_func *Equal_creator::combine(List<Item> list) const {
return new Item_cond_and(list);
}
Item_bool_func *Ne_creator::create_scalar_predicate(Item *a, Item *b) const {
assert(a->type() != Item::ROW_ITEM || b->type() != Item::ROW_ITEM);
return new Item_func_ne(a, b);
}
Item_bool_func *Ne_creator::combine(List<Item> list) const {
return new Item_cond_or(list);
}
Item_bool_func *Gt_creator::create(Item *a, Item *b) const {
return new Item_func_gt(a, b);
}
Item_bool_func *Lt_creator::create(Item *a, Item *b) const {
return new Item_func_lt(a, b);
}
Item_bool_func *Ge_creator::create(Item *a, Item *b) const {
return new Item_func_ge(a, b);
}
Item_bool_func *Le_creator::create(Item *a, Item *b) const {
return new Item_func_le(a, b);
}
float Item_func_not::get_filtering_effect(THD *thd, table_map filter_for_table,
table_map read_tables,
const MY_BITMAP *fields_to_ignore,
double rows_in_table) {
const float filter = args[0]->get_filtering_effect(
thd, filter_for_table, read_tables, fields_to_ignore, rows_in_table);
/*
If the predicate that will be negated has COND_FILTER_ALLPASS
filtering it means that some dependent tables have not been
read, that the predicate is of a type that filtering effect is
not calculated for or something similar. In any case, the
filtering effect of the inverted predicate should also be
COND_FILTER_ALLPASS.
*/
if (filter == COND_FILTER_ALLPASS) return COND_FILTER_ALLPASS;
return 1.0f - filter;
}
/*
Test functions
Most of these returns 0LL if false and 1LL if true and
NULL if some arg is NULL.
*/
longlong Item_func_not::val_int() {
assert(fixed);
const bool value = args[0]->val_bool();
null_value = args[0]->null_value;
/*
If NULL, return 0 because some higher layers like
evaluate_join_record() just test for !=0 to implement IS TRUE.
If not NULL, return inverted value.
*/
return ((!null_value && value == 0) ? 1 : 0);
}
/*
We put any NOT expression into parenthesis to avoid
possible problems with internal view representations where
any '!' is converted to NOT. It may cause a problem if
'!' is used in an expression together with other operators
whose precedence is lower than the precedence of '!' yet
higher than the precedence of NOT.
*/
void Item_func_not::print(const THD *thd, String *str,
enum_query_type query_type) const {
str->append('(');
Item_func::print(thd, str, query_type);
str->append(')');
}
/**
special NOT for ALL subquery.
*/
longlong Item_func_not_all::val_int() {
assert(fixed);
const bool value = args[0]->val_bool();
/*
return TRUE if there was no record in underlying select in max/min
optimization (ALL subquery)
*/
if (empty_underlying_subquery()) return 1;
null_value = args[0]->null_value;
return ((!null_value && value == 0) ? 1 : 0);
}
bool Item_func_not_all::empty_underlying_subquery() {
assert(subselect != nullptr ||
!(test_sum_item != nullptr || test_sub_item != nullptr));
/*
When outer argument is NULL the subquery has not yet been evaluated, we
need to evaluate it to get to know whether it returns any rows to return
the correct result. 'ANY' subqueries are an exception because the
result would be false or null which for a top level item always mean false.
The subselect->unit->item->... chain should be used instead of
subselect->... to workaround subquery transformation which could make
subselect->engine unusable.
*/
if (subselect != nullptr &&
subselect->subquery_type() != Item_subselect::ANY_SUBQUERY &&
subselect->query_expr()->item != nullptr &&
!subselect->query_expr()->item->is_evaluated())
subselect->query_expr()->item->exec(current_thd);
return (test_sum_item != nullptr && !test_sum_item->has_values()) ||
(test_sub_item != nullptr && !test_sub_item->has_values());
}
void Item_func_not_all::print(const THD *thd, String *str,
enum_query_type query_type) const {
if (show)
Item_func::print(thd, str, query_type);
else
args[0]->print(thd, str, query_type);
}
/**
Special NOP (No OPeration) for ALL subquery. It is like
Item_func_not_all.
@return
(return TRUE if underlying subquery do not return rows) but if subquery
returns some rows it return same value as argument (TRUE/FALSE).
*/
longlong Item_func_nop_all::val_int() {
assert(fixed);
const longlong value = args[0]->val_int();
/*
return FALSE if there was records in underlying select in max/min
optimization (SAME/ANY subquery)
*/
if (empty_underlying_subquery()) return 0;
null_value = args[0]->null_value;
return (null_value || value == 0) ? 0 : 1;
}
/**
Return an an unsigned Item_int containing the value of the year as stored in
field. The item is typed as a YEAR.
@param field the field containign the year value
@return the year wrapped in an Item in as described above, or nullptr on
error.
*/
static Item *make_year_constant(Field *field) {
Item_int *year = new Item_int(field->val_int());
if (year == nullptr) return nullptr;
year->unsigned_flag = field->is_flag_set(UNSIGNED_FLAG);
year->set_data_type(MYSQL_TYPE_YEAR);
return year;
}
/**
Convert a constant item to an int and replace the original item.
The function converts a constant expression or string to an integer.
On successful conversion the original item is substituted for the
result of the item evaluation.
This is done when comparing DATE/TIME of different formats and
also when comparing bigint to strings (in which case strings
are converted to bigints).
@param thd thread handle
@param field_item item will be converted using the type of this field
@param[in,out] item reference to the item to convert
@param[out] converted True if a replacement was done.
@note
This function may be called both at prepare and optimize stages.
When called at optimize stage, ensure that we record transient changes.
@returns false if success, true if error
*/
static bool convert_constant_item(THD *thd, Item_field *field_item, Item **item,
bool *converted) {
Field *field = field_item->field;
*converted = false;
if ((*item)->may_evaluate_const(thd) &&
/*
In case of GC it's possible that this func will be called on an
already converted constant. Don't convert it again.
*/
!((*item)->data_type() == field_item->data_type() &&
(*item)->basic_const_item())) {
TABLE *table = field->table;
const sql_mode_t orig_sql_mode = thd->variables.sql_mode;
const enum_check_fields orig_check_for_truncated_fields =
thd->check_for_truncated_fields;
my_bitmap_map *old_maps[2];
ulonglong orig_field_val = 0; /* original field value if valid */
old_maps[0] = nullptr;
old_maps[1] = nullptr;
if (table)
dbug_tmp_use_all_columns(table, old_maps, table->read_set,
table->write_set);
/* For comparison purposes allow invalid dates like 2000-01-32 */
thd->variables.sql_mode =
(orig_sql_mode & ~MODE_NO_ZERO_DATE) | MODE_INVALID_DATES;
thd->check_for_truncated_fields = CHECK_FIELD_IGNORE;
/*
Store the value of the field/constant if it references an outer field
because the call to save_in_field below overrides that value.
Don't save field value if no data has been read yet.
Outer constant values are always saved.
*/
bool save_field_value =
field_item->depended_from &&
(field_item->const_item() || field->table->has_row());
if (save_field_value) orig_field_val = field->val_int();
int rc;
if (!(*item)->is_null() &&
(((rc = (*item)->save_in_field(field, true)) == TYPE_OK) ||
rc == TYPE_NOTE_TIME_TRUNCATED)) // TS-TODO
{
int field_cmp = 0;
/*
If item is a decimal value, we must reject it if it was truncated.
TODO: consider doing the same for MYSQL_TYPE_YEAR,.
However: we have tests which assume that things '1999' and
'1991-01-01 01:01:01' can be converted to year.
Testing for MYSQL_TYPE_YEAR here, would treat such literals
as 'incorrect DOUBLE value'.
See Bug#13580652 YEAR COLUMN CAN BE EQUAL TO 1999.1
*/
if (field->type() == MYSQL_TYPE_LONGLONG) {
field_cmp = stored_field_cmp_to_item(thd, field, *item);
DBUG_PRINT("info", ("convert_constant_item %d", field_cmp));
}
// @todo it is not correct, in time_col = datetime_const_function,
// to convert the latter to Item_time_with_ref below. Time_col should
// rather be cast to datetime. WL#6570 check if the "fix temporals"
// patch fixes this.
if (0 == field_cmp) {
Item *tmp =
field->type() == MYSQL_TYPE_TIME
?
#define OLD_CMP
#ifdef OLD_CMP
new Item_time_with_ref(field->decimals(),
field->val_time_temporal(), *item)
:
#else
new Item_time_with_ref(
max((*item)->time_precision(), field->decimals()),
(*item)->val_time_temporal(), *item)
:
#endif
is_temporal_type_with_date(field->type())
?
#ifdef OLD_CMP
new Item_datetime_with_ref(field->type(), field->decimals(),
field->val_date_temporal(),
*item)
:
#else
new Item_datetime_with_ref(
field->type(),
max((*item)->datetime_precision(), field->decimals()),
(*item)->val_date_temporal(), *item)
:
#endif
field->type() == MYSQL_TYPE_YEAR
? make_year_constant(field)
: new Item_int_with_ref(
field->type(), field->val_int(), *item,
field->is_flag_set(UNSIGNED_FLAG));
if (tmp == nullptr) return true;
if (thd->lex->is_exec_started())
thd->change_item_tree(item, tmp);
else
*item = tmp;
*converted = true; // Item was replaced
}
}
/* Restore the original field value. */
if (save_field_value) {
*converted = field->store(orig_field_val, true);
/* orig_field_val must be a valid value that can be restored back. */
assert(!*converted);
}
thd->variables.sql_mode = orig_sql_mode;
thd->check_for_truncated_fields = orig_check_for_truncated_fields;
if (table)
dbug_tmp_restore_column_maps(table->read_set, table->write_set, old_maps);
}
return false;
}
bool Item_bool_func2::convert_constant_arg(THD *thd, Item *field, Item **item,
bool *converted) {
*converted = false;
if (field->real_item()->type() != FIELD_ITEM) return false;
Item_field *field_item = (Item_field *)(field->real_item());
if (field_item->field->can_be_compared_as_longlong() &&
!(field_item->is_temporal_with_date() &&
(*item)->result_type() == STRING_RESULT)) {
if (convert_constant_item(thd, field_item, item, converted)) return true;
if (*converted) {
if (cmp.set_cmp_func(this, args, args + 1, INT_RESULT)) return true;
field->cmp_context = (*item)->cmp_context = INT_RESULT;
}
}
return false;
}
bool Item_bool_func2::resolve_type(THD *thd) {
DBUG_TRACE;
// Both arguments are needed for type resolving
assert(args[0] && args[1]);
if (Item_bool_func::resolve_type(thd)) {
return true;
}
/*
See agg_item_charsets() in item.cc for comments
on character set and collation aggregation.
Charset comparison is skipped for SHOW CREATE VIEW
statements since the join fields are not resolved
during SHOW CREATE VIEW.
*/
if (thd->lex->sql_command != SQLCOM_SHOW_CREATE &&
args[0]->result_type() == STRING_RESULT &&
args[1]->result_type() == STRING_RESULT &&
agg_arg_charsets_for_comparison(cmp.cmp_collation, args, 2))
return true;
args[0]->cmp_context = args[1]->cmp_context =
item_cmp_type(args[0]->result_type(), args[1]->result_type());
/*
Geometry item cannot participate in an arithmetic or string comparison or
a full text search, except in equal/not equal comparison.
We allow geometry arguments in equal/not equal, since such
comparisons are used now and are meaningful, although it simply compares
the GEOMETRY byte string rather than doing a geometric equality comparison.
*/
const Functype func_type = functype();
uint nvector_args = num_vector_args();
if (func_type == EQ_FUNC && nvector_args != 0 && nvector_args != arg_count) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), func_name());
return true;
}
if ((func_type == LT_FUNC || func_type == LE_FUNC || func_type == GE_FUNC ||
func_type == GT_FUNC || func_type == FT_FUNC) &&
(reject_geometry_args() || reject_vector_args()))
return true;
// Make a special case of compare with fields to get nicer DATE comparisons
if (!(thd->lex->is_view_context_analysis())) {
bool cvt1, cvt2;
if (convert_constant_arg(thd, args[0], &args[1], &cvt1) ||
convert_constant_arg(thd, args[1], &args[0], &cvt2))
return true;
if (cvt1 || cvt2) return false;
}
if (marker == MARKER_IMPLICIT_NE_ZERO) { // Results may surprise
if (args[1]->result_type() == STRING_RESULT &&
args[1]->data_type() == MYSQL_TYPE_JSON)
push_warning(thd, Sql_condition::SL_WARNING,
ER_IMPLICIT_COMPARISON_FOR_JSON,
ER_THD(thd, ER_IMPLICIT_COMPARISON_FOR_JSON));
}
return (thd->lex->sql_command != SQLCOM_SHOW_CREATE) ? set_cmp_func() : false;
}
bool Item_func_like::resolve_type(THD *thd) {
// Function returns 0 or 1
max_length = 1;
// Determine the common character set for all arguments
if (agg_arg_charsets_for_comparison(cmp.cmp_collation, args, arg_count))
return true;
for (uint i = 0; i < arg_count; i++) {
if (args[i]->data_type() == MYSQL_TYPE_INVALID &&
args[i]->propagate_type(
thd,
Type_properties(MYSQL_TYPE_VARCHAR, cmp.cmp_collation.collation))) {
return true;
}
}
if (reject_geometry_args()) return true;
if (reject_vector_args()) return true;
// LIKE is always carried out as a string operation
args[0]->cmp_context = STRING_RESULT;
args[1]->cmp_context = STRING_RESULT;
if (arg_count > 2) {
args[2]->cmp_context = STRING_RESULT;
// ESCAPE clauses that vary per row are not valid:
if (!args[2]->const_for_execution()) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "ESCAPE");
return true;
}
}
/*
If the escape item is const, evaluate it now, so that the range optimizer
can try to optimize LIKE 'foo%' into a range query.
TODO: If we move this into escape_is_evaluated(), which is called later,
we might be able to optimize more cases.
*/
if (!escape_was_used_in_parsing() || args[2]->const_item()) {
escape_is_const = true;
if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)) {
if (eval_escape_clause(thd)) return true;
if (check_covering_prefix_keys(thd)) return true;
}
}
return false;
}
Item *Item_func_like::replace_scalar_subquery(uchar *) {
// Replacing a scalar subquery with a reference to a column in a derived table
// could change the constness. Check that the ESCAPE clause is still
// const_for_execution().
if (escape_was_used_in_parsing() && !args[2]->const_for_execution()) {
my_error(ER_WRONG_ARGUMENTS, MYF(0), "ESCAPE");
return nullptr;
}
return this;
}
Item *Item_bool_func2::replace_scalar_subquery(uchar *) {
if (set_cmp_func()) {
return nullptr;
}
return this;
}
void Arg_comparator::cleanup() {
if (comparators != nullptr) {
/*
We cannot rely on (*left)->cols(), since *left may be deallocated
at this point, so use comparator_count to loop.
*/
for (size_t i = 0; i < comparator_count; i++) {
comparators[i].cleanup();
}
}
if (json_scalar != nullptr) {
::destroy_at(json_scalar);
json_scalar = nullptr;
}
value1.mem_free();
value2.mem_free();
}
bool Arg_comparator::set_compare_func(Item_func *item, Item_result type) {
m_compare_type = type;
owner = item;
func = comparator_matrix[type];
switch (type) {
case ROW_RESULT: {
const uint n = (*left)->cols();
if (n != (*right)->cols()) {
my_error(ER_OPERAND_COLUMNS, MYF(0), n);
comparators = nullptr;
return true;
}
if (!(comparators = new (*THR_MALLOC) Arg_comparator[n])) return true;
comparator_count = n;
for (uint i = 0; i < n; i++) {
if ((*left)->element_index(i)->cols() !=
(*right)->element_index(i)->cols()) {
my_error(ER_OPERAND_COLUMNS, MYF(0),
(*left)->element_index(i)->cols());
return true;
}
if (comparators[i].set_cmp_func(owner, (*left)->addr(i),
(*right)->addr(i), set_null))
return true;
}
break;
}
case STRING_RESULT: {
/*
We must set cmp_charset here as we may be called from for an automatic
generated item, like in natural join
*/
if (cmp_collation.set((*left)->collation, (*right)->collation,
MY_COLL_CMP_CONV) ||
cmp_collation.derivation == DERIVATION_NONE) {
const char *func_name = owner != nullptr ? owner->func_name() : "";
my_coll_agg_error((*left)->collation, (*right)->collation, func_name);
return true;
}
if (cmp_collation.collation == &my_charset_bin) {
/*
We are using BLOB/BINARY/VARBINARY, change to compare byte by byte,
without removing end space
*/
if (func == &Arg_comparator::compare_string)
func = &Arg_comparator::compare_binary_string;
}
/*
If the comparison's and arguments' collations differ, prevent column
substitution. Otherwise we would get into trouble with comparisons
like:
WHERE col = 'j' AND col = BINARY 'j'
which would be transformed to:
WHERE col = 'j' AND 'j' = BINARY 'j', then to:
WHERE col = 'j'. That would be wrong, if col contains 'J'.
*/
if ((*left)->collation.collation != cmp_collation.collation)
(*left)->walk(&Item::disable_constant_propagation, enum_walk::POSTFIX,
nullptr);
if ((*right)->collation.collation != cmp_collation.collation)
(*right)->walk(&Item::disable_constant_propagation, enum_walk::POSTFIX,
nullptr);
break;
}
case INT_RESULT: {
if ((*left)->is_temporal() && (*right)->is_temporal()) {
func = &Arg_comparator::compare_time_packed;
} else if (func == &Arg_comparator::compare_int_signed) {
if ((*left)->unsigned_flag)
func = (((*right)->unsigned_flag)
? &Arg_comparator::compare_int_unsigned
: &Arg_comparator::compare_int_unsigned_signed);
else if ((*right)->unsigned_flag)
func = &Arg_comparator::compare_int_signed_unsigned;
}
break;
}
case DECIMAL_RESULT:
break;
case REAL_RESULT: {
if ((*left)->decimals < DECIMAL_NOT_SPECIFIED &&
(*right)->decimals < DECIMAL_NOT_SPECIFIED) {
precision = 5 / log_10[max((*left)->decimals, (*right)->decimals) + 1];
if (func == &Arg_comparator::compare_real)
func = &Arg_comparator::compare_real_fixed;
}
break;
}
default:
assert(0);
}
return false;
}
/**
A minion of get_mysql_time_from_str, see its description.
This version doesn't issue any warnings, leaving that to its parent.
This method has one extra argument which return warnings.
@param[in] thd Thread handle
@param[in] str A string to convert