/
item_cmpfunc.cc
6705 lines (5753 loc) · 175 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, 2013, Oracle and/or its affiliates.
Copyright (c) 2009, 2013, Monty Program Ab.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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 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 Street, Fifth Floor, Boston, MA 02110-1301, USA */
/**
@file
@brief
This file defines all compare functions
*/
#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation // gcc: Class implementation
#endif
#include <my_global.h>
#include "sql_priv.h"
#include <m_ctype.h>
#include "sql_select.h"
#include "sql_parse.h" // check_stack_overrun
#include "sql_time.h" // make_truncated_value_warning
#include "sql_base.h" // dynamic_column_error_message
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, Item **items, uint nitems)
{
Item **item, **item_end;
my_bool unsigned_flag= 0;
*type= STRING_RESULT;
/* 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);
}
}
/**
find an temporal type (item) that others will be converted to
for the purpose of comparison.
this is the type that will be used in warnings like
"Incorrect <<TYPE>> value".
*/
Item *find_date_time_item(Item **args, uint nargs, uint col)
{
Item *date_arg= 0, **arg, **arg_end;
for (arg= args, arg_end= args + nargs; arg != arg_end ; arg++)
{
Item *item= arg[0]->element_index(col);
if (item->cmp_type() != TIME_RESULT)
continue;
if (item->field_type() == MYSQL_TYPE_DATETIME)
return item;
if (!date_arg)
date_arg= item;
}
return date_arg;
}
/*
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]->cmp_type();
for (i= 1 ; i < nitems ; i++)
{
type[0]= item_cmp_type(type[0], items[i]);
/*
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 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_cmp_type= items[0]->cmp_type();
DBUG_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_cmp_type == ROW_RESULT ||
items[i]->cmp_type() == ROW_RESULT) &&
cmp_row_type(items[0], items[i]))
return 0;
found_types|= 1U << (uint) item_cmp_type(left_cmp_type, items[i]);
}
/*
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_cmp_type;
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);
}
/*
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()
{
DBUG_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()
{
DBUG_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()
{
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()
{
DBUG_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_const_to_int(THD *thd, Item_field *field_item,
Item **item)
{
Field *field= field_item->field;
int result= 0;
/*
We don't need to convert an integer to an integer,
pretend it's already converted.
But we still convert it if it is compared with a Field_year,
as YEAR(2) may change the value of an integer when converting it
to an integer (say, 0 to 70).
*/
if ((*item)->cmp_type() == INT_RESULT &&
field_item->field_type() != MYSQL_TYPE_YEAR)
return 1;
if ((*item)->const_item() && !(*item)->is_expensive())
{
TABLE *table= field->table;
ulonglong 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 UNINIT_VAR(orig_field_val); /* original field value if valid */
LINT_INIT_STRUCT(old_maps);
/* table->read_set may not be set if we come here from a CREATE TABLE */
if (table && table->read_set)
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 because the call to save_in_field
below overrides that value. Don't save field value if no data has been
read yet.
*/
bool save_field_value= (field_item->const_item() ||
!(field->table->status & STATUS_NO_RECORD));
if (save_field_value)
orig_field_val= field->val_int();
if (!(*item)->save_in_field(field, 1) && !field->is_null())
{
int field_cmp= 0;
// If item is a decimal value, we must reject it if it was truncated.
if (field->type() == MYSQL_TYPE_LONGLONG)
{
field_cmp= stored_field_cmp_to_item(thd, field, *item);
DBUG_PRINT("info", ("convert_const_to_int %d", field_cmp));
}
if (0 == field_cmp)
{
Item *tmp= new (thd->mem_root) Item_int_with_ref(thd, 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. */
DBUG_ASSERT(!result);
}
thd->variables.sql_mode= orig_sql_mode;
thd->count_cuted_fields= orig_count_cuted_fields;
if (table && table->read_set)
dbug_tmp_restore_column_maps(table->read_set, table->write_set, old_maps);
}
return result;
}
/*
Make a special case of compare with fields to get nicer comparisons
of bigint numbers with constant string.
This directly contradicts the manual (number and a string should
be compared as doubles), but seems to provide more
"intuitive" behavior in some cases (but less intuitive in others).
*/
void Item_func::convert_const_compared_to_int_field(THD *thd)
{
DBUG_ASSERT(arg_count == 2);
if (!thd->lex->is_ps_or_view_context_analysis())
{
int field;
if (args[field= 0]->real_item()->type() == FIELD_ITEM ||
args[field= 1]->real_item()->type() == FIELD_ITEM)
{
Item_field *field_item= (Item_field*) (args[field]->real_item());
if ((field_item->field_type() == MYSQL_TYPE_LONGLONG ||
field_item->field_type() == MYSQL_TYPE_YEAR))
convert_const_to_int(thd, field_item, &args[!field]);
}
}
}
bool Item_func::setup_args_and_comparator(THD *thd, Arg_comparator *cmp)
{
DBUG_ASSERT(arg_count == 2);
if (args[0]->cmp_type() == STRING_RESULT &&
args[1]->cmp_type() == STRING_RESULT &&
agg_arg_charsets_for_comparison(cmp->cmp_collation, args, 2))
return true;
// Convert constants when compared to int/year field
DBUG_ASSERT(functype() != LIKE_FUNC);
convert_const_compared_to_int_field(thd);
return cmp->set_cmp_func(this, tmp_arg, tmp_arg + 1, true);
}
void Item_bool_rowready_func2::fix_length_and_dec()
{
max_length= 1; // Function returns 0 or 1
/*
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;
setup_args_and_comparator(current_thd, &cmp);
}
int Arg_comparator::set_compare_func(Item_func_or_sum *item, Item_result type)
{
owner= item;
func= comparator_matrix[type]
[is_owner_equal_func()];
switch (type) {
case TIME_RESULT:
cmp_collation.collation= &my_charset_numeric;
break;
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;
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:
{
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, FALSE, (uchar*) 0);
(*b)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0);
}
break;
}
case INT_RESULT:
{
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[MY_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;
}
}
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.
The date is used for comparison, that is fuzzy dates are allowed
independently of sql_mode.
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;
int flags= TIME_FUZZY_DATES | MODE_INVALID_DATES;
ErrConvString err(str);
DBUG_ASSERT(warn_type != MYSQL_TIMESTAMP_TIME);
if (!str_to_datetime(str->charset(), str->ptr(), str->length(),
l_time, flags, &status))
{
DBUG_ASSERT(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
{
DBUG_ASSERT(l_time->time_type != MYSQL_TIMESTAMP_TIME);
DBUG_ASSERT(status.warnings != 0); // Must be set by set_to_datetime()
value= TRUE;
}
if (status.warnings > 0)
make_truncated_value_warning(thd, Sql_condition::WARN_LEVEL_WARN,
&err, warn_type, warn_name);
return value;
}
/**
Aggregate comparator argument charsets for comparison.
One of the arguments ("a" or "b") can be replaced,
typically by Item_string or Item_func_conv_charset.
@return Aggregation result
@retval false - if no conversion is needed,
or if one of the arguments was converted
@retval true - on error, if arguments are not comparable.
TODO: get rid of this method eventually and refactor the calling code.
Argument conversion should happen on the Item_func level.
Arg_comparator should get comparable arguments.
*/
bool Arg_comparator::agg_arg_charsets_for_comparison()
{
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 true;
}
if (agg_item_set_converter(cmp_collation, owner->func_name(),
a, 1, MY_COLL_CMP_CONV, 1) ||
agg_item_set_converter(cmp_collation, owner->func_name(),
b, 1, MY_COLL_CMP_CONV, 1))
return true;
return false;
}
/**
Prepare the comparator (set the comparison function) for comparing
items *a1 and *a2 in the context of 'type'.
@param[in] owner_arg Item, peforming the comparison (e.g. Item_func_eq)
@param[in,out] a1 first argument to compare
@param[in,out] a2 second argument to compare
@param[in] type type context to compare in
Both *a1 and *a2 can be replaced by this method - typically by constant
items, holding the cached converted value of the original (constant) item.
*/
int Arg_comparator::set_cmp_func(Item_func_or_sum *owner_arg,
Item **a1, Item **a2,
Item_result type)
{
thd= current_thd;
owner= owner_arg;
set_null= set_null && owner_arg;
a= a1;
b= a2;
m_compare_type= type;
if (type == STRING_RESULT &&
(*a)->result_type() == STRING_RESULT &&
(*b)->result_type() == STRING_RESULT)
{
/*
We must set cmp_collation here as we may be called from for an automatic
generated item, like in natural join
*/
if (agg_arg_charsets_for_comparison())
return 1;
}
if (type == INT_RESULT &&
(*a)->field_type() == MYSQL_TYPE_YEAR &&
(*b)->field_type() == MYSQL_TYPE_YEAR)
type= TIME_RESULT;
a= cache_converted_constant(thd, a, &a_cache, type);
b= cache_converted_constant(thd, b, &b_cache, type);
return set_compare_func(owner_arg, type);
}
/**
Convert and cache a constant.
@param value [in] An item to cache
@param cache_item [out] Placeholder for the cache item
@param type [in] Comparison type
@details
When given item is a constant and its type differs from comparison type
then cache its value to avoid type conversion of this constant on each
evaluation. In this case the value is cached and the reference to the cache
is returned.
Original value is returned otherwise.
@return cache item or original value.
*/
Item** Arg_comparator::cache_converted_constant(THD *thd_arg, Item **value,
Item **cache_item,
Item_result type)
{
/*
Don't need cache if doing context analysis only.
Also, get_datetime_value creates Item_cache internally.
Unless fixed, we should not do it here.
*/
if (!thd_arg->lex->is_ps_or_view_context_analysis() &&
(*value)->const_item() && type != (*value)->result_type() &&
type != TIME_RESULT)
{
Item_cache *cache= Item_cache::get_cache(thd_arg, *value, type);
cache->setup(thd_arg, *value);
*cache_item= cache;
return cache_item;
}
return value;
}
void Arg_comparator::set_datetime_cmp_func(Item_func_or_sum *owner_arg,
Item **a1, Item **b1)
{
thd= current_thd;
owner= owner_arg;
a= a1;
b= b1;
a_cache= 0;
b_cache= 0;
func= comparator_matrix[TIME_RESULT][is_owner_equal_func()];
}
/**
Retrieves correct DATETIME value from given item.
@param[in] thd thread handle
@param[in,out] item_arg item to retrieve DATETIME value from
@param[in,out] cache_arg pointer to place to store the caching item to
@param[in] warn_item item for issuing the conversion warning
@param[out] is_null TRUE <=> the item_arg is null
@details
Retrieves the correct DATETIME value from given item for comparison by the
compare_datetime() function.
If the value should be compared as time (TIME_RESULT), it's retrieved as
MYSQL_TIME. Otherwise it's read as a number/string and converted to time.
Constant items are cached, so the convertion is only done once for them.
Note the f_type behavior: if the item can be compared as time, then
f_type is this item's field_type(). Otherwise it's field_type() of
warn_item (which is the other operand of the comparison operator).
This logic provides correct string/number to date/time conversion
depending on the other operand (when comparing a string with a date, it's
parsed as a date, when comparing a string with a time it's parsed as a time)
If the item is a constant it is replaced by the Item_cache_int, that
holds the packed datetime value.
@return
MYSQL_TIME value, packed in a longlong, suitable for comparison.
*/
longlong
get_datetime_value(THD *thd, Item ***item_arg, Item **cache_arg,
Item *warn_item, bool *is_null)
{
longlong UNINIT_VAR(value);
Item *item= **item_arg;
enum_field_types f_type= item->cmp_type() == TIME_RESULT ?
item->field_type() : warn_item->field_type();
if (item->result_type() == INT_RESULT &&
item->cmp_type() == TIME_RESULT &&
item->type() == Item::CACHE_ITEM)
{
/* it's our Item_cache_temporal, as created below */
DBUG_ASSERT(is_temporal_type(((Item_cache *) item)->field_type()));
value= ((Item_cache_temporal*) item)->val_temporal_packed();
}
else
{
MYSQL_TIME ltime;
uint fuzzydate= TIME_FUZZY_DATES | TIME_INVALID_DATES;
if ((item->field_type() == MYSQL_TYPE_TIME &&
is_temporal_type_with_date(warn_item->field_type())) ?
item->get_date_with_conversion(<ime, fuzzydate) :
item->get_date(<ime, fuzzydate |
(f_type == MYSQL_TYPE_TIME ? TIME_TIME_ONLY : 0)))
value= 0; /* invalid date */
else
value= pack_time(<ime);
}
if ((*is_null= item->null_value))
return ~(ulonglong) 0;
if (cache_arg && item->const_item() &&
!(item->type() == Item::CACHE_ITEM && item->cmp_type() == TIME_RESULT))
{
Query_arena backup;
Query_arena *save_arena= thd->switch_to_arena_for_cached_items(&backup);
Item_cache_temporal *cache= new (thd->mem_root) Item_cache_temporal(thd, f_type);
if (save_arena)
thd->set_query_arena(save_arena);
cache->store_packed(value, item);
*cache_arg= cache;
*item_arg= cache_arg;
}
return value;
}
/*
Compare items values as dates.
SYNOPSIS
Arg_comparator::compare_datetime()
DESCRIPTION
Compare items values as DATE/DATETIME for both EQUAL_FUNC and from other
comparison functions. The correct DATETIME values are obtained
with help of the get_datetime_value() function.
RETURN
-1 a < b or at least one item is null
0 a == b
1 a > b
*/
int Arg_comparator::compare_datetime()
{
bool a_is_null, b_is_null;
longlong a_value, b_value;
if (set_null)
owner->null_value= 1;
/* Get DATE/DATETIME/TIME value of the 'a' item. */
a_value= get_datetime_value(thd, &a, &a_cache, *b, &a_is_null);
if (a_is_null)
return -1;
/* Get DATE/DATETIME/TIME value of the 'b' item. */
b_value= get_datetime_value(thd, &b, &b_cache, *a, &b_is_null);
if (b_is_null)
return -1;
/* Here we have two not-NULL values. */
if (set_null)
owner->null_value= 0;
/* Compare values. */
return a_value < b_value ? -1 : a_value > b_value ? 1 : 0;
}
int Arg_comparator::compare_e_datetime()
{
bool a_is_null, b_is_null;
longlong a_value, b_value;
/* Get DATE/DATETIME/TIME value of the 'a' item. */
a_value= get_datetime_value(thd, &a, &a_cache, *b, &a_is_null);
/* Get DATE/DATETIME/TIME value of the 'b' item. */
b_value= get_datetime_value(thd, &b, &b_cache, *a, &b_is_null);
return a_is_null || b_is_null ? a_is_null == b_is_null
: a_value == b_value;
}
int Arg_comparator::compare_string()
{
String *res1,*res2;
if ((res1= (*a)->val_str(&value1)))
{
if ((res2= (*b)->val_str(&value2)))
{
if (set_null)
owner->null_value= 0;
return sortcmp(res1,res2,cmp_collation.collation);
}
}
if (set_null)
owner->null_value= 1;
return -1;
}
/**
Compare strings byte by byte. End spaces are also compared.
@retval
<0 *a < *b
@retval
0 *b == *b
@retval
>0 *a > *b
*/
int Arg_comparator::compare_binary_string()
{
String *res1,*res2;
if ((res1= (*a)->val_str(&value1)))
{
if ((res2= (*b)->val_str(&value2)))
{
if (set_null)
owner->null_value= 0;
uint res1_length= res1->length();
uint res2_length= res2->length();
int cmp= memcmp(res1->ptr(), res2->ptr(), MY_MIN(res1_length,res2_length));
return cmp ? cmp : (int) (res1_length - res2_length);
}
}
if (set_null)
owner->null_value= 1;
return -1;
}
/**
Compare strings, but take into account that NULL == NULL.
*/
int Arg_comparator::compare_e_string()
{
String *res1,*res2;