forked from mysql/mysql-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitem_cmpfunc.cc
7984 lines (6892 loc) · 217 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, 2023, 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 also distributed 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 included with MySQL.
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
This file defines all compare functions
*/
#include <m_ctype.h>
#include "sql_select.h"
#include "sql_optimizer.h" // JOIN_TAB
#include "sql_parse.h" // check_stack_overrun
#include "sql_time.h" // make_truncated_value_warning
#include "opt_trace.h"
#include "parse_tree_helpers.h"
#include "template_utils.h"
#include "item_json_func.h" // json_value, get_json_atom_wrapper
#include <algorithm>
using std::min;
using std::max;
#include "aggregate_check.h"
static bool convert_constant_item(THD *, Item_field *, Item **);
static longlong
get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
const Item *warn_item, bool *is_null);
static Item_result item_store_type(Item_result a, Item *item,
my_bool unsigned_flag)
{
Item_result b= item->result_type();
if (a == STRING_RESULT || b == STRING_RESULT)
return STRING_RESULT;
else if (a == REAL_RESULT || b == REAL_RESULT)
return REAL_RESULT;
else if (a == DECIMAL_RESULT || b == DECIMAL_RESULT ||
unsigned_flag != item->unsigned_flag)
return DECIMAL_RESULT;
else
return INT_RESULT;
}
static void agg_result_type(Item_result *type, my_bool *unsigned_flag,
Item **items, uint nitems)
{
Item **item, **item_end;
*type= STRING_RESULT;
*unsigned_flag= FALSE;
/* Skip beginning NULL items */
for (item= items, item_end= item + nitems; item < item_end; item++)
{
if ((*item)->type() != Item::NULL_ITEM)
{
*type= (*item)->result_type();
*unsigned_flag= (*item)->unsigned_flag;
item++;
break;
}
}
/* Combine result types. Note: NULL items don't affect the result */
for (; item < item_end; item++)
{
if ((*item)->type() != Item::NULL_ITEM)
{
*type= item_store_type(*type, *item, *unsigned_flag);
*unsigned_flag= *unsigned_flag && (*item)->unsigned_flag;
}
}
}
/*
Compare row signature of two expressions
SYNOPSIS:
cmp_row_type()
item1 the first expression
item2 the second expression
DESCRIPTION
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.
RETURN VALUES
1 type incompatibility has been detected
0 otherwise
*/
static int cmp_row_type(Item* item1, Item* item2)
{
uint n= item1->cols();
if (item2->check_cols(n))
return 1;
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 &&
cmp_row_type(item1->element_index(i), item2->element_index(i))))
return 1;
}
return 0;
}
/**
Aggregates result types from the array of items.
SYNOPSIS:
agg_cmp_type()
type [out] the aggregated type
items array of items to aggregate the type from
nitems number of items in the array
DESCRIPTION
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[out] type the aggregated type
@param items array of items to aggregate the type from
@param nitems number of items in the array
@retval
1 type incompatibility has been detected
@retval
0 otherwise
*/
static int agg_cmp_type(Item_result *type, Item **items, uint nitems)
{
uint i;
type[0]= items[0]->result_type();
for (i= 1 ; i < nitems ; i++)
{
type[0]= item_cmp_type(type[0], items[i]->result_type());
/*
When aggregating types of two row expressions we have to check
that they have the same cardinality and that each component
of the first row expression has a compatible row signature with
the signature of the corresponding component of the second row
expression.
*/
if (type[0] == ROW_RESULT && cmp_row_type(items[0], items[i]))
return 1; // error found: invalid usage of rows
}
return 0;
}
/**
@brief Aggregates field types from the array of items.
@param[in] items array of items to aggregate the type from
@paran[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)
{
uint i;
if (!nitems || items[0]->result_type() == ROW_RESULT )
return (enum_field_types)-1;
enum_field_types res= items[0]->field_type();
for (i= 1 ; i < nitems ; i++)
res= Field::field_type_merge(res, items[i]->field_type());
return real_type_to_type(res);
}
/*
Collects different types for comparison of first item with each other items
SYNOPSIS
collect_cmp_types()
items Array of items to collect types from
nitems Number of items in the array
skip_nulls Don't collect types of NULL items if TRUE
DESCRIPTION
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.
RETURN
0 - if row type incompatibility has been detected (see cmp_row_type)
Bitmap of collected types - otherwise
*/
static uint collect_cmp_types(Item **items, uint nitems, bool skip_nulls= FALSE)
{
uint i;
uint found_types;
Item_result left_result= items[0]->result_type();
assert(nitems > 1);
found_types= 0;
for (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) &&
cmp_row_type(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->name,c1.derivation_name(),
c2.collation->name,c2.derivation_name(),
fname);
}
/**
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 @i 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 NULL;
}
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(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(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 == 1);
bool value= args[0]->val_bool();
null_value=args[0]->null_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(String *str, enum_query_type query_type)
{
str->append('(');
Item_func::print(str, query_type);
str->append(')');
}
/**
special NOT for ALL subquery.
*/
longlong Item_func_not_all::val_int()
{
assert(fixed == 1);
bool value= args[0]->val_bool();
/*
return TRUE if there was records 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 || !(test_sum_item || test_sub_item));
/*
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 &&
subselect->substype() != Item_subselect::ANY_SUBS &&
!subselect->unit->item->is_evaluated())
subselect->unit->item->exec();
return ((test_sum_item && !test_sum_item->any_value()) ||
(test_sub_item && !test_sub_item->any_value()));
}
void Item_func_not_all::print(String *str, enum_query_type query_type)
{
if (show)
Item_func::print(str, query_type);
else
args[0]->print(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 == 1);
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;
}
/**
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 will be converted using the type of this field
@param[in,out] item reference to the item to convert
@note
This function is called only at prepare stage.
As all derived tables are filled only after all derived tables
are prepared we do not evaluate items with subselects here because
they can contain derived tables and thus we may attempt to use a
table that has not been populated yet.
@retval
0 Can't convert item
@retval
1 Item was replaced with an integer version of the item
*/
static bool convert_constant_item(THD *thd, Item_field *field_item,
Item **item)
{
Field *field= field_item->field;
int result= 0;
if ((*item)->const_item() &&
/*
In case of GC it's possible that this func will be called on an
already converted constant. Don't convert it again.
*/
!((*item)->field_type() == field_item->field_type() &&
(*item)->basic_const_item()))
{
TABLE *table= field->table;
sql_mode_t orig_sql_mode= thd->variables.sql_mode;
enum_check_fields orig_count_cuted_fields= thd->count_cuted_fields;
my_bitmap_map *old_maps[2];
ulonglong orig_field_val= 0; /* original field value if valid */
old_maps[0]= NULL;
old_maps[1]= NULL;
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->count_cuted_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->status &
(STATUS_GARBAGE | STATUS_NOT_FOUND))));
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));
}
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
field->is_temporal_with_date() ?
#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
new Item_int_with_ref(field->type(), field->val_int(), *item,
MY_TEST(field->flags & UNSIGNED_FLAG));
if (tmp)
thd->change_item_tree(item, tmp);
result= 1; // Item was replaced
}
}
/* Restore the original field value. */
if (save_field_value)
{
result= field->store(orig_field_val, TRUE);
/* orig_field_val must be a valid value that can be restored back. */
assert(!result);
}
thd->variables.sql_mode= orig_sql_mode;
thd->count_cuted_fields= orig_count_cuted_fields;
if (table)
dbug_tmp_restore_column_maps(table->read_set, table->write_set, old_maps);
}
return result;
}
bool Item_bool_func2::convert_constant_arg(THD *thd, Item *field, Item **item)
{
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))
{
cmp.set_cmp_func(this, tmp_arg, tmp_arg + 1, INT_RESULT);
field->cmp_context= (*item)->cmp_context= INT_RESULT;
return true;
}
}
return false;
}
void Item_bool_func2::fix_length_and_dec()
{
max_length= 1; // Function returns 0 or 1
THD *thd;
/*
As some compare functions are generated after sql_yacc,
we have to check for out of memory conditions here
*/
if (!args[0] || !args[1])
return;
DBUG_ENTER("Item_bool_func2::fix_length_and_dec");
/*
See agg_item_charsets() in item.cc for comments
on character set and collation aggregation.
*/
if (args[0]->result_type() == STRING_RESULT &&
args[1]->result_type() == STRING_RESULT &&
agg_arg_charsets_for_comparison(cmp.cmp_collation, args, 2))
DBUG_VOID_RETURN;
args[0]->cmp_context= args[1]->cmp_context=
item_cmp_type(args[0]->result_type(), args[1]->result_type());
// Make a special case of compare with fields to get nicer DATE comparisons
if (functype() == LIKE_FUNC) // Disable conversion in case of LIKE function.
{
set_cmp_func();
DBUG_VOID_RETURN;
}
/*
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();
if (func_type == LT_FUNC || func_type == LE_FUNC || func_type == GE_FUNC ||
func_type == GT_FUNC || func_type == FT_FUNC)
reject_geometry_args(arg_count, args, this);
thd= current_thd;
if (!thd->lex->is_ps_or_view_context_analysis())
{
if (convert_constant_arg(thd, args[0], &args[1]) ||
convert_constant_arg(thd, args[1], &args[0]))
DBUG_VOID_RETURN;
}
set_cmp_func();
DBUG_VOID_RETURN;
}
void Arg_comparator::cleanup()
{
if (comparators != NULL)
{
/*
We cannot rely on (*a)->cols(), since *a may be deallocated
at this point, so use comparator_count to loop.
*/
for (size_t i= 0; i < comparator_count; i++)
{
comparators[i].cleanup();
}
}
delete[] comparators;
comparators= 0;
delete_json_scalar_holder(json_scalar);
json_scalar= 0;
}
int Arg_comparator::set_compare_func(Item_result_field *item, Item_result type)
{
owner= item;
func= comparator_matrix[type]
[is_owner_equal_func()];
switch (type) {
case ROW_RESULT:
{
uint n= (*a)->cols();
if (n != (*b)->cols())
{
my_error(ER_OPERAND_COLUMNS, MYF(0), n);
comparators= 0;
return 1;
}
if (!(comparators= new Arg_comparator[n]))
return 1;
comparator_count= n;
for (uint i=0; i < n; i++)
{
if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols())
{
my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
return 1;
}
if (comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i),
set_null))
return 1;
}
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((*a)->collation, (*b)->collation, MY_COLL_CMP_CONV) ||
cmp_collation.derivation == DERIVATION_NONE)
{
my_coll_agg_error((*a)->collation, (*b)->collation,
owner->func_name());
return 1;
}
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;
else if (func == &Arg_comparator::compare_e_string)
func= &Arg_comparator::compare_e_binary_string;
/*
As this is binary compassion, mark all fields that they can't be
transformed. Otherwise we would get into trouble with comparisons
like:
WHERE col= 'j' AND col LIKE BINARY 'j'
which would be transformed to:
WHERE col= 'j'
*/
(*a)->walk(&Item::set_no_const_sub, Item::WALK_POSTFIX, NULL);
(*b)->walk(&Item::set_no_const_sub, Item::WALK_POSTFIX, NULL);
}
break;
}
case INT_RESULT:
{
if ((*a)->is_temporal() && (*b)->is_temporal())
{
func= is_owner_equal_func() ?
&Arg_comparator::compare_e_time_packed :
&Arg_comparator::compare_time_packed;
}
else if (func == &Arg_comparator::compare_int_signed)
{
if ((*a)->unsigned_flag)
func= (((*b)->unsigned_flag)?
&Arg_comparator::compare_int_unsigned :
&Arg_comparator::compare_int_unsigned_signed);
else if ((*b)->unsigned_flag)
func= &Arg_comparator::compare_int_signed_unsigned;
}
else if (func== &Arg_comparator::compare_e_int)
{
if ((*a)->unsigned_flag ^ (*b)->unsigned_flag)
func= &Arg_comparator::compare_e_int_diff_signedness;
}
break;
}
case DECIMAL_RESULT:
break;
case REAL_RESULT:
{
if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC)
{
precision= 5 / log_10[max((*a)->decimals, (*b)->decimals) + 1];
if (func == &Arg_comparator::compare_real)
func= &Arg_comparator::compare_real_fixed;
else if (func == &Arg_comparator::compare_e_real)
func= &Arg_comparator::compare_e_real_fixed;
}
break;
}
default:
assert(0);
}
return 0;
}
/**
Parse date provided in a string to a MYSQL_TIME.
@param[in] thd Thread handle
@param[in] str A string to convert
@param[in] warn_type Type of the timestamp for issuing the warning
@param[in] warn_name Field name for issuing the warning
@param[out] l_time The MYSQL_TIME objects is initialized.
Parses a date provided in the string str into a MYSQL_TIME object. If the
string contains an incorrect date or doesn't correspond to a date at all
then a warning is issued. The warn_type and the warn_name arguments are used
as the name and the type of the field when issuing the warning. If any input
was discarded (trailing or non-timestamp-y characters), return value will be
TRUE.
@return Status flag
@retval FALSE Success.
@retval True Indicates failure.
*/
bool get_mysql_time_from_str(THD *thd, String *str, timestamp_type warn_type,
const char *warn_name, MYSQL_TIME *l_time)
{
bool value;
MYSQL_TIME_STATUS status;
my_time_flags_t flags= TIME_FUZZY_DATE | TIME_INVALID_DATES;
if (thd->variables.sql_mode & MODE_NO_ZERO_IN_DATE)
flags|= TIME_NO_ZERO_IN_DATE;
if (thd->variables.sql_mode & MODE_NO_ZERO_DATE)
flags|= TIME_NO_ZERO_DATE;
if (!str_to_datetime(str, l_time, flags, &status) &&
(l_time->time_type == MYSQL_TIMESTAMP_DATETIME ||
l_time->time_type == MYSQL_TIMESTAMP_DATE))
/*
Do not return yet, we may still want to throw a "trailing garbage"
warning.
*/
value= FALSE;
else
{
value= TRUE;
status.warnings= MYSQL_TIME_WARN_TRUNCATED; /* force warning */
}
if (status.warnings > 0)
make_truncated_value_warning(thd, Sql_condition::SL_WARNING,
ErrConvString(str), warn_type, warn_name);
return value;
}
/**
@brief Convert date provided in a string
to its packed temporal int representation.
@param[in] thd thread handle
@param[in] str a string to convert
@param[in] warn_type type of the timestamp for issuing the warning
@param[in] warn_name field name for issuing the warning
@param[out] error_arg could not extract a DATE or DATETIME
@details Convert date provided in the string str to the int
representation. If the string contains wrong date or doesn't
contain it at all then a warning is issued. The warn_type and
the warn_name arguments are used as the name and the type of the
field when issuing the warning.
@return
converted value. 0 on error and on zero-dates -- check 'failure'
*/
static ulonglong get_date_from_str(THD *thd, String *str,
timestamp_type warn_type,
const char *warn_name, bool *error_arg)
{
MYSQL_TIME l_time;
*error_arg= get_mysql_time_from_str(thd, str, warn_type, warn_name, &l_time);
if (*error_arg)
return 0;
return TIME_to_longlong_datetime_packed(&l_time);
}
/**
Check if str_arg is a constant and convert it to datetime packed value.
Note, const_value may stay untouched, so the caller is responsible to
initialize it.
@param date_arg date argument, it's name is used for error reporting.
@param str_arg string argument to get datetime value from.
@param[out] const_value the converted value is stored here, if not NULL.
@return true on error, false on success, false if str_arg is not a const.
*/
bool Arg_comparator::get_date_from_const(Item *date_arg,
Item *str_arg,
ulonglong *const_value)
{
THD *thd= current_thd;
/*
Do not cache GET_USER_VAR() function as its const_item() may return TRUE
for the current thread but it still may change during the execution.
Don't use cache while in the context analysis mode only (i.e. for
EXPLAIN/CREATE VIEW and similar queries). Cache is useless in such
cases and can cause problems. For example evaluating subqueries can
confuse storage engines since in context analysis mode tables
aren't locked.
*/
if (!thd->lex->is_ps_or_view_context_analysis() &&
str_arg->const_item() &&
(str_arg->type() != Item::FUNC_ITEM ||
((Item_func*) str_arg)->functype() != Item_func::GUSERVAR_FUNC))
{
ulonglong value;
if (str_arg->field_type() == MYSQL_TYPE_TIME)
{
// Convert from TIME to DATETIME
value= str_arg->val_date_temporal();
if (str_arg->null_value)
return true;
}
else
{
// Convert from string to DATETIME
assert(str_arg->result_type() == STRING_RESULT);
bool error;
String tmp, *str_val= 0;
timestamp_type t_type= (date_arg->field_type() == MYSQL_TYPE_DATE ?
MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME);
str_val= str_arg->val_str(&tmp);
if (str_arg->null_value)
return true;
value= get_date_from_str(thd, str_val, t_type,
date_arg->item_name.ptr(), &error);
if (error)
return true;
}
if (const_value)
*const_value= value;
}
return false;
}
/*
Check whether compare_datetime() can be used to compare items.
SYNOPSIS
Arg_comparator::can_compare_as_dates()
a, b [in] items to be compared
const_value [out] converted value of the string constant, if any
DESCRIPTION
Check several cases when the DATE/DATETIME comparator should be used.