1
/* Copyright (C) 2000-2006 MySQL AB
3
This program is free software; you can redistribute it and/or modify
4
it under the terms of the GNU General Public License as published by
5
the Free Software Foundation; version 2 of the License.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
21
This file defines all compare functions
24
#ifdef USE_PRAGMA_IMPLEMENTATION
25
#pragma implementation // gcc: Class implementation
28
#include "mysql_priv.h"
30
#include "sql_select.h"
32
static bool convert_constant_item(THD *, Item_field *, Item **);
34
get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
35
Item *warn_item, bool *is_null);
37
static Item_result item_store_type(Item_result a, Item *item,
38
my_bool unsigned_flag)
40
Item_result b= item->result_type();
42
if (a == STRING_RESULT || b == STRING_RESULT)
44
else if (a == REAL_RESULT || b == REAL_RESULT)
46
else if (a == DECIMAL_RESULT || b == DECIMAL_RESULT ||
47
unsigned_flag != item->unsigned_flag)
48
return DECIMAL_RESULT;
53
static void agg_result_type(Item_result *type, Item **items, uint nitems)
55
Item **item, **item_end;
56
my_bool unsigned_flag= 0;
59
/* Skip beginning NULL items */
60
for (item= items, item_end= item + nitems; item < item_end; item++)
62
if ((*item)->type() != Item::NULL_ITEM)
64
*type= (*item)->result_type();
65
unsigned_flag= (*item)->unsigned_flag;
70
/* Combine result types. Note: NULL items don't affect the result */
71
for (; item < item_end; item++)
73
if ((*item)->type() != Item::NULL_ITEM)
74
*type= item_store_type(*type, *item, unsigned_flag);
80
Compare row signature of two expressions
84
item1 the first expression
85
item2 the second expression
88
The function checks that two expressions have compatible row signatures
89
i.e. that the number of columns they return are the same and that if they
90
are both row expressions then each component from the first expression has
91
a row signature compatible with the signature of the corresponding component
92
of the second expression.
95
1 type incompatibility has been detected
99
static int cmp_row_type(Item* item1, Item* item2)
101
uint n= item1->cols();
102
if (item2->check_cols(n))
104
for (uint i=0; i<n; i++)
106
if (item2->element_index(i)->check_cols(item1->element_index(i)->cols()) ||
107
(item1->element_index(i)->result_type() == ROW_RESULT &&
108
cmp_row_type(item1->element_index(i), item2->element_index(i))))
116
Aggregates result types from the array of items.
120
type [out] the aggregated type
121
items array of items to aggregate the type from
122
nitems number of items in the array
125
This function aggregates result types from the array of items. Found type
126
supposed to be used later for comparison of values of these items.
127
Aggregation itself is performed by the item_cmp_type() function.
128
@param[out] type the aggregated type
129
@param items array of items to aggregate the type from
130
@param nitems number of items in the array
133
1 type incompatibility has been detected
138
static int agg_cmp_type(Item_result *type, Item **items, uint nitems)
141
type[0]= items[0]->result_type();
142
for (i= 1 ; i < nitems ; i++)
144
type[0]= item_cmp_type(type[0], items[i]->result_type());
146
When aggregating types of two row expressions we have to check
147
that they have the same cardinality and that each component
148
of the first row expression has a compatible row signature with
149
the signature of the corresponding component of the second row
152
if (type[0] == ROW_RESULT && cmp_row_type(items[0], items[i]))
153
return 1; // error found: invalid usage of rows
160
@brief Aggregates field types from the array of items.
162
@param[in] items array of items to aggregate the type from
163
@paran[in] nitems number of items in the array
165
@details This function aggregates field types from the array of items.
166
Found type is supposed to be used later as the result field type
167
of a multi-argument function.
168
Aggregation itself is performed by the Field::field_type_merge()
171
@note The term "aggregation" is used here in the sense of inferring the
172
result type of a function from its argument types.
174
@return aggregated field type.
177
enum_field_types agg_field_type(Item **items, uint nitems)
180
if (!nitems || items[0]->result_type() == ROW_RESULT )
181
return (enum_field_types)-1;
182
enum_field_types res= items[0]->field_type();
183
for (i= 1 ; i < nitems ; i++)
184
res= Field::field_type_merge(res, items[i]->field_type());
189
Collects different types for comparison of first item with each other items
193
items Array of items to collect types from
194
nitems Number of items in the array
195
skip_nulls Don't collect types of NULL items if TRUE
198
This function collects different result types for comparison of the first
199
item in the list with each of the remaining items in the 'items' array.
202
0 - if row type incompatibility has been detected (see cmp_row_type)
203
Bitmap of collected types - otherwise
206
static uint collect_cmp_types(Item **items, uint nitems, bool skip_nulls= FALSE)
210
Item_result left_result= items[0]->result_type();
211
DBUG_ASSERT(nitems > 1);
213
for (i= 1; i < nitems ; i++)
215
if (skip_nulls && items[i]->type() == Item::NULL_ITEM)
216
continue; // Skip NULL constant items
217
if ((left_result == ROW_RESULT ||
218
items[i]->result_type() == ROW_RESULT) &&
219
cmp_row_type(items[0], items[i]))
221
found_types|= 1<< (uint)item_cmp_type(left_result,
222
items[i]->result_type());
225
Even if all right-hand items are NULLs and we are skipping them all, we need
226
at least one type bit in the found_type bitmask.
228
if (skip_nulls && !found_types)
229
found_types= 1 << (uint)left_result;
233
static void my_coll_agg_error(DTCollation &c1, DTCollation &c2,
236
my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
237
c1.collation->name,c1.derivation_name(),
238
c2.collation->name,c2.derivation_name(),
243
Item_bool_func2* Eq_creator::create(Item *a, Item *b) const
245
return new Item_func_eq(a, b);
249
Item_bool_func2* Ne_creator::create(Item *a, Item *b) const
251
return new Item_func_ne(a, b);
255
Item_bool_func2* Gt_creator::create(Item *a, Item *b) const
257
return new Item_func_gt(a, b);
261
Item_bool_func2* Lt_creator::create(Item *a, Item *b) const
263
return new Item_func_lt(a, b);
267
Item_bool_func2* Ge_creator::create(Item *a, Item *b) const
269
return new Item_func_ge(a, b);
273
Item_bool_func2* Le_creator::create(Item *a, Item *b) const
275
return new Item_func_le(a, b);
280
Most of these returns 0LL if false and 1LL if true and
281
NULL if some arg is NULL.
284
longlong Item_func_not::val_int()
286
DBUG_ASSERT(fixed == 1);
287
bool value= args[0]->val_bool();
288
null_value=args[0]->null_value;
289
return ((!null_value && value == 0) ? 1 : 0);
293
We put any NOT expression into parenthesis to avoid
294
possible problems with internal view representations where
295
any '!' is converted to NOT. It may cause a problem if
296
'!' is used in an expression together with other operators
297
whose precedence is lower than the precedence of '!' yet
298
higher than the precedence of NOT.
301
void Item_func_not::print(String *str, enum_query_type query_type)
304
Item_func::print(str, query_type);
309
special NOT for ALL subquery.
313
longlong Item_func_not_all::val_int()
315
DBUG_ASSERT(fixed == 1);
316
bool value= args[0]->val_bool();
319
return TRUE if there was records in underlying select in max/min
320
optimization (ALL subquery)
322
if (empty_underlying_subquery())
325
null_value= args[0]->null_value;
326
return ((!null_value && value == 0) ? 1 : 0);
330
bool Item_func_not_all::empty_underlying_subquery()
332
return ((test_sum_item && !test_sum_item->any_value()) ||
333
(test_sub_item && !test_sub_item->any_value()));
336
void Item_func_not_all::print(String *str, enum_query_type query_type)
339
Item_func::print(str, query_type);
341
args[0]->print(str, query_type);
346
Special NOP (No OPeration) for ALL subquery. It is like
350
(return TRUE if underlying subquery do not return rows) but if subquery
351
returns some rows it return same value as argument (TRUE/FALSE).
354
longlong Item_func_nop_all::val_int()
356
DBUG_ASSERT(fixed == 1);
357
longlong value= args[0]->val_int();
360
return FALSE if there was records in underlying select in max/min
361
optimization (SAME/ANY subquery)
363
if (empty_underlying_subquery())
366
null_value= args[0]->null_value;
367
return (null_value || value == 0) ? 0 : 1;
372
Convert a constant item to an int and replace the original item.
374
The function converts a constant expression or string to an integer.
375
On successful conversion the original item is substituted for the
376
result of the item evaluation.
377
This is done when comparing DATE/TIME of different formats and
378
also when comparing bigint to strings (in which case strings
379
are converted to bigints).
381
@param thd thread handle
382
@param field item will be converted using the type of this field
383
@param[in,out] item reference to the item to convert
386
This function is called only at prepare stage.
387
As all derived tables are filled only after all derived tables
388
are prepared we do not evaluate items with subselects here because
389
they can contain derived tables and thus we may attempt to use a
390
table that has not been populated yet.
395
1 Item was replaced with an integer version of the item
398
static bool convert_constant_item(THD *thd, Item_field *field_item,
401
Field *field= field_item->field;
404
if (!(*item)->with_subselect && (*item)->const_item())
406
TABLE *table= field->table;
407
ulong orig_sql_mode= thd->variables.sql_mode;
408
enum_check_fields orig_count_cuted_fields= thd->count_cuted_fields;
409
my_bitmap_map *old_maps[2];
410
ulonglong UNINIT_VAR(orig_field_val); /* original field value if valid */
412
LINT_INIT(old_maps[0]);
413
LINT_INIT(old_maps[1]);
416
dbug_tmp_use_all_columns(table, old_maps,
417
table->read_set, table->write_set);
418
/* For comparison purposes allow invalid dates like 2000-01-32 */
419
thd->variables.sql_mode= (orig_sql_mode & ~MODE_NO_ZERO_DATE) |
421
thd->count_cuted_fields= CHECK_FIELD_IGNORE;
424
Store the value of the field/constant if it references an outer field
425
because the call to save_in_field below overrides that value.
426
Don't save field value if no data has been read yet.
427
Outer constant values are always saved.
429
bool save_field_value= (field_item->depended_from &&
430
(field_item->const_item() ||
431
!(field->table->status & STATUS_NO_RECORD)));
432
if (save_field_value)
433
orig_field_val= field->val_int();
434
if (!(*item)->is_null() && !(*item)->save_in_field(field, 1))
436
Item *tmp= new Item_int_with_ref(field->val_int(), *item,
437
test(field->flags & UNSIGNED_FLAG));
439
thd->change_item_tree(item, tmp);
440
result= 1; // Item was replaced
442
/* Restore the original field value. */
443
if (save_field_value)
445
result= field->store(orig_field_val, TRUE);
446
/* orig_field_val must be a valid value that can be restored back. */
447
DBUG_ASSERT(!result);
449
thd->variables.sql_mode= orig_sql_mode;
450
thd->count_cuted_fields= orig_count_cuted_fields;
452
dbug_tmp_restore_column_maps(table->read_set, table->write_set, old_maps);
458
void Item_bool_func2::fix_length_and_dec()
460
max_length= 1; // Function returns 0 or 1
464
As some compare functions are generated after sql_yacc,
465
we have to check for out of memory conditions here
467
if (!args[0] || !args[1])
471
We allow to convert to Unicode character sets in some cases.
472
The conditions when conversion is possible are:
473
- arguments A and B have different charsets
474
- A wins according to coercibility rules
475
- character set of A is superset for character set of B
477
If all of the above is true, then it's possible to convert
478
B into the character set of A, and then compare according
479
to the collation of A.
484
if (args[0]->result_type() == STRING_RESULT &&
485
args[1]->result_type() == STRING_RESULT &&
486
agg_arg_charsets(coll, args, 2, MY_COLL_CMP_CONV, 1))
489
args[0]->cmp_context= args[1]->cmp_context=
490
item_cmp_type(args[0]->result_type(), args[1]->result_type());
491
// Make a special case of compare with fields to get nicer DATE comparisons
493
if (functype() == LIKE_FUNC) // Disable conversion in case of LIKE function.
500
if (!thd->is_context_analysis_only())
502
if (args[0]->real_item()->type() == FIELD_ITEM)
504
Item_field *field_item= (Item_field*) (args[0]->real_item());
505
if (field_item->field->can_be_compared_as_longlong() &&
506
!(field_item->is_datetime() &&
507
args[1]->result_type() == STRING_RESULT))
509
if (convert_constant_item(thd, field_item, &args[1]))
511
cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
512
INT_RESULT); // Works for all types.
513
args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
518
if (args[1]->real_item()->type() == FIELD_ITEM)
520
Item_field *field_item= (Item_field*) (args[1]->real_item());
521
if (field_item->field->can_be_compared_as_longlong() &&
522
!(field_item->is_datetime() &&
523
args[0]->result_type() == STRING_RESULT))
525
if (convert_constant_item(thd, field_item, &args[0]))
527
cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
528
INT_RESULT); // Works for all types.
529
args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
539
int Arg_comparator::set_compare_func(Item_result_field *item, Item_result type)
542
func= comparator_matrix[type]
543
[is_owner_equal_func()];
548
uint n= (*a)->cols();
549
if (n != (*b)->cols())
551
my_error(ER_OPERAND_COLUMNS, MYF(0), n);
555
if (!(comparators= new Arg_comparator[n]))
557
for (uint i=0; i < n; i++)
559
if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols())
561
my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
564
if (comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i),
573
We must set cmp_charset here as we may be called from for an automatic
574
generated item, like in natural join
576
if (cmp_collation.set((*a)->collation, (*b)->collation) ||
577
cmp_collation.derivation == DERIVATION_NONE)
579
my_coll_agg_error((*a)->collation, (*b)->collation,
583
if (cmp_collation.collation == &my_charset_bin)
586
We are using BLOB/BINARY/VARBINARY, change to compare byte by byte,
587
without removing end space
589
if (func == &Arg_comparator::compare_string)
590
func= &Arg_comparator::compare_binary_string;
591
else if (func == &Arg_comparator::compare_e_string)
592
func= &Arg_comparator::compare_e_binary_string;
595
As this is binary compassion, mark all fields that they can't be
596
transformed. Otherwise we would get into trouble with comparisons
598
WHERE col= 'j' AND col LIKE BINARY 'j'
599
which would be transformed to:
602
(*a)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0);
603
(*b)->walk(&Item::set_no_const_sub, FALSE, (uchar*) 0);
609
if (func == &Arg_comparator::compare_int_signed)
611
if ((*a)->unsigned_flag)
612
func= (((*b)->unsigned_flag)?
613
&Arg_comparator::compare_int_unsigned :
614
&Arg_comparator::compare_int_unsigned_signed);
615
else if ((*b)->unsigned_flag)
616
func= &Arg_comparator::compare_int_signed_unsigned;
618
else if (func== &Arg_comparator::compare_e_int)
620
if ((*a)->unsigned_flag ^ (*b)->unsigned_flag)
621
func= &Arg_comparator::compare_e_int_diff_signedness;
629
if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC)
631
precision= 5 / log_10[max((*a)->decimals, (*b)->decimals) + 1];
632
if (func == &Arg_comparator::compare_real)
633
func= &Arg_comparator::compare_real_fixed;
634
else if (func == &Arg_comparator::compare_e_real)
635
func= &Arg_comparator::compare_e_real_fixed;
646
Parse date provided in a string to a MYSQL_TIME.
648
@param[in] thd Thread handle
649
@param[in] str A string to convert
650
@param[in] warn_type Type of the timestamp for issuing the warning
651
@param[in] warn_name Field name for issuing the warning
652
@param[out] l_time The MYSQL_TIME objects is initialized.
654
Parses a date provided in the string str into a MYSQL_TIME object. If the
655
string contains an incorrect date or doesn't correspond to a date at all
656
then a warning is issued. The warn_type and the warn_name arguments are used
657
as the name and the type of the field when issuing the warning. If any input
658
was discarded (trailing or non-timestamp-y characters), return value will be
662
@retval FALSE Success.
663
@retval True Indicates failure.
666
bool get_mysql_time_from_str(THD *thd, String *str, timestamp_type warn_type,
667
const char *warn_name, MYSQL_TIME *l_time)
671
enum_mysql_timestamp_type timestamp_type;
674
str_to_datetime(str->ptr(), str->length(), l_time,
675
(TIME_FUZZY_DATE | MODE_INVALID_DATES |
676
(thd->variables.sql_mode &
677
(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE))),
680
if (timestamp_type == MYSQL_TIMESTAMP_DATETIME ||
681
timestamp_type == MYSQL_TIMESTAMP_DATE)
683
Do not return yet, we may still want to throw a "trailing garbage"
690
error= 1; /* force warning */
694
make_truncated_value_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
695
str->ptr(), str->length(),
696
warn_type, warn_name);
703
@brief Convert date provided in a string to the int representation.
705
@param[in] thd thread handle
706
@param[in] str a string to convert
707
@param[in] warn_type type of the timestamp for issuing the warning
708
@param[in] warn_name field name for issuing the warning
709
@param[out] error_arg could not extract a DATE or DATETIME
711
@details Convert date provided in the string str to the int
712
representation. If the string contains wrong date or doesn't
713
contain it at all then a warning is issued. The warn_type and
714
the warn_name arguments are used as the name and the type of the
715
field when issuing the warning.
718
converted value. 0 on error and on zero-dates -- check 'failure'
720
static ulonglong get_date_from_str(THD *thd, String *str,
721
timestamp_type warn_type,
722
const char *warn_name, bool *error_arg)
725
*error_arg= get_mysql_time_from_str(thd, str, warn_type, warn_name, &l_time);
729
return TIME_to_ulonglong_datetime(&l_time);
734
Check whether compare_datetime() can be used to compare items.
737
Arg_comparator::can_compare_as_dates()
738
a, b [in] items to be compared
739
const_value [out] converted value of the string constant, if any
742
Check several cases when the DATE/DATETIME comparator should be used.
743
The following cases are checked:
744
1. Both a and b is a DATE/DATETIME field/function returning string or
746
2. Only a or b is a DATE/DATETIME field/function returning string or
747
int result and the other item (b or a) is an item with string result.
748
If the second item is a constant one then it's checked to be
749
convertible to the DATE/DATETIME type. If the constant can't be
750
converted to a DATE/DATETIME then the compare_datetime() comparator
751
isn't used and the warning about wrong DATE/DATETIME value is issued.
752
In all other cases (date-[int|real|decimal]/[int|real|decimal]-date)
753
the comparison is handled by other comparators.
754
If the datetime comparator can be used and one the operands of the
755
comparison is a string constant that was successfully converted to a
756
DATE/DATETIME type then the result of the conversion is returned in the
757
const_value if it is provided. If there is no constant or
758
compare_datetime() isn't applicable then the *const_value remains
762
the found type of date comparison
765
enum Arg_comparator::enum_date_cmp_type
766
Arg_comparator::can_compare_as_dates(Item *a, Item *b, ulonglong *const_value)
768
enum enum_date_cmp_type cmp_type= CMP_DATE_DFLT;
769
Item *str_arg= 0, *date_arg= 0;
771
if (a->type() == Item::ROW_ITEM || b->type() == Item::ROW_ITEM)
772
return CMP_DATE_DFLT;
774
if (a->is_datetime())
776
if (b->is_datetime())
777
cmp_type= CMP_DATE_WITH_DATE;
778
else if (b->result_type() == STRING_RESULT)
780
cmp_type= CMP_DATE_WITH_STR;
785
else if (b->is_datetime() && a->result_type() == STRING_RESULT)
787
cmp_type= CMP_STR_WITH_DATE;
792
if (cmp_type != CMP_DATE_DFLT)
794
THD *thd= current_thd;
796
Do not cache GET_USER_VAR() function as its const_item() may return TRUE
797
for the current thread but it still may change during the execution.
798
Don't use cache while in the context analysis mode only (i.e. for
799
EXPLAIN/CREATE VIEW and similar queries). Cache is useless in such
800
cases and can cause problems. For example evaluating subqueries can
801
confuse storage engines since in context analysis mode tables
804
if (!thd->is_context_analysis_only() &&
805
cmp_type != CMP_DATE_WITH_DATE && str_arg->const_item() &&
806
(str_arg->type() != Item::FUNC_ITEM ||
807
((Item_func*)str_arg)->functype() != Item_func::GUSERVAR_FUNC))
811
String tmp, *str_val= 0;
812
timestamp_type t_type= (date_arg->field_type() == MYSQL_TYPE_DATE ?
813
MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME);
815
str_val= str_arg->val_str(&tmp);
816
if (str_arg->null_value)
817
return CMP_DATE_DFLT;
818
value= get_date_from_str(thd, str_val, t_type, date_arg->name, &error);
820
return CMP_DATE_DFLT;
830
Retrieves correct TIME value from the given item.
835
item_arg [in/out] item to retrieve TIME value from
836
cache_arg [in/out] pointer to place to store the cache item to
837
warn_item [in] unused
838
is_null [out] TRUE <=> the item_arg is null
841
Retrieves the correct TIME value from given item for comparison by the
842
compare_datetime() function.
843
If item's result can be compared as longlong then its int value is used
844
and a value returned by get_time function is used otherwise.
845
If an item is a constant one then its value is cached and it isn't
846
get parsed again. An Item_cache_int object is used for for cached values.
847
It seamlessly substitutes the original item. The cache item is marked as
848
non-constant to prevent re-caching it again.
855
get_time_value(THD *thd, Item ***item_arg, Item **cache_arg,
856
Item *warn_item, bool *is_null)
859
Item *item= **item_arg;
862
if (item->result_as_longlong())
864
value= item->val_int();
865
*is_null= item->null_value;
869
*is_null= item->get_time(<ime);
870
value= !*is_null ? (longlong) TIME_to_ulonglong_datetime(<ime) : 0;
873
Do not cache GET_USER_VAR() function as its const_item() may return TRUE
874
for the current thread but it still may change during the execution.
876
if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM ||
877
((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
879
Item_cache_int *cache= new Item_cache_int();
880
/* Mark the cache as non-const to prevent re-caching. */
881
cache->set_used_tables(1);
882
cache->store(item, value);
884
*item_arg= cache_arg;
890
int Arg_comparator::set_cmp_func(Item_result_field *owner_arg,
891
Item **a1, Item **a2,
894
enum enum_date_cmp_type cmp_type;
895
ulonglong const_value= (ulonglong)-1;
898
set_null= set_null && owner_arg;
903
if ((cmp_type= can_compare_as_dates(*a, *b, &const_value)))
905
a_type= (*a)->field_type();
906
b_type= (*b)->field_type();
910
if (const_value != (ulonglong)-1)
913
cache_converted_constant can't be used here because it can't
914
correctly convert a DATETIME value from string to int representation.
916
Item_cache_int *cache= new Item_cache_int();
917
/* Mark the cache as non-const to prevent re-caching. */
918
cache->set_used_tables(1);
919
if (!(*a)->is_datetime())
921
cache->store((*a), const_value);
923
a= (Item **)&a_cache;
927
cache->store((*b), const_value);
929
b= (Item **)&b_cache;
932
is_nulls_eq= is_owner_equal_func();
933
func= &Arg_comparator::compare_datetime;
934
get_value_a_func= &get_datetime_value;
935
get_value_b_func= &get_datetime_value;
938
else if (type == STRING_RESULT && (*a)->field_type() == MYSQL_TYPE_TIME &&
939
(*b)->field_type() == MYSQL_TYPE_TIME)
941
/* Compare TIME values as integers. */
944
is_nulls_eq= is_owner_equal_func();
945
func= &Arg_comparator::compare_datetime;
946
get_value_a_func= &get_time_value;
947
get_value_b_func= &get_time_value;
950
else if (type == STRING_RESULT &&
951
(*a)->result_type() == STRING_RESULT &&
952
(*b)->result_type() == STRING_RESULT)
955
coll.set((*a)->collation.collation);
956
if (agg_item_set_converter(coll, owner->func_name(),
957
b, 1, MY_COLL_CMP_CONV, 1))
960
else if (try_year_cmp_func(type))
963
a= cache_converted_constant(thd, a, &a_cache, type);
964
b= cache_converted_constant(thd, b, &b_cache, type);
965
return set_compare_func(owner_arg, type);
970
Helper function to call from Arg_comparator::set_cmp_func()
973
bool Arg_comparator::try_year_cmp_func(Item_result type)
975
if (type == ROW_RESULT)
978
bool a_is_year= (*a)->field_type() == MYSQL_TYPE_YEAR;
979
bool b_is_year= (*b)->field_type() == MYSQL_TYPE_YEAR;
981
if (!a_is_year && !b_is_year)
984
if (a_is_year && b_is_year)
986
get_value_a_func= &get_year_value;
987
get_value_b_func= &get_year_value;
989
else if (a_is_year && (*b)->is_datetime())
991
get_value_a_func= &get_year_value;
992
get_value_b_func= &get_datetime_value;
994
else if (b_is_year && (*a)->is_datetime())
996
get_value_b_func= &get_year_value;
997
get_value_a_func= &get_datetime_value;
1002
is_nulls_eq= is_owner_equal_func();
1003
func= &Arg_comparator::compare_datetime;
1009
Convert and cache a constant.
1011
@param value [in] An item to cache
1012
@param cache_item [out] Placeholder for the cache item
1013
@param type [in] Comparison type
1016
When given item is a constant and its type differs from comparison type
1017
then cache its value to avoid type conversion of this constant on each
1018
evaluation. In this case the value is cached and the reference to the cache
1020
Original value is returned otherwise.
1022
@return cache item or original value.
1025
Item** Arg_comparator::cache_converted_constant(THD *thd, Item **value,
1029
/* Don't need cache if doing context analysis only. */
1030
if (!thd->is_context_analysis_only() &&
1031
(*value)->const_item() && type != (*value)->result_type())
1033
Item_cache *cache= Item_cache::get_cache(*value, type);
1034
cache->setup(*value);
1042
void Arg_comparator::set_datetime_cmp_func(Item_result_field *owner_arg,
1043
Item **a1, Item **b1)
1049
a_type= (*a)->field_type();
1050
b_type= (*b)->field_type();
1054
func= &Arg_comparator::compare_datetime;
1055
get_value_a_func= &get_datetime_value;
1056
get_value_b_func= &get_datetime_value;
1061
Retrieves correct DATETIME value from given item.
1064
get_datetime_value()
1066
item_arg [in/out] item to retrieve DATETIME value from
1067
cache_arg [in/out] pointer to place to store the caching item to
1068
warn_item [in] item for issuing the conversion warning
1069
is_null [out] TRUE <=> the item_arg is null
1072
Retrieves the correct DATETIME value from given item for comparison by the
1073
compare_datetime() function.
1074
If item's result can be compared as longlong then its int value is used
1075
and its string value is used otherwise. Strings are always parsed and
1076
converted to int values by the get_date_from_str() function.
1077
This allows us to compare correctly string dates with missed insignificant
1078
zeros. If an item is a constant one then its value is cached and it isn't
1079
get parsed again. An Item_cache_int object is used for caching values. It
1080
seamlessly substitutes the original item. The cache item is marked as
1081
non-constant to prevent re-caching it again. In order to compare
1082
correctly DATE and DATETIME items the result of the former are treated as
1083
a DATETIME with zero time (00:00:00).
1090
get_datetime_value(THD *thd, Item ***item_arg, Item **cache_arg,
1091
Item *warn_item, bool *is_null)
1094
String buf, *str= 0;
1095
Item *item= **item_arg;
1097
if (item->result_as_longlong())
1099
value= item->val_int();
1100
*is_null= item->null_value;
1101
enum_field_types f_type= item->field_type();
1103
Item_date_add_interval may return MYSQL_TYPE_STRING as the result
1104
field type. To detect that the DATE value has been returned we
1105
compare it with 100000000L - any DATE value should be less than it.
1106
Don't shift cached DATETIME values up for the second time.
1108
if (f_type == MYSQL_TYPE_DATE ||
1109
(f_type != MYSQL_TYPE_DATETIME && value < 100000000L))
1114
str= item->val_str(&buf);
1115
*is_null= item->null_value;
1118
return ~(ulonglong) 0;
1120
Convert strings to the integer DATE/DATETIME representation.
1121
Even if both dates provided in strings we can't compare them directly as
1122
strings as there is no warranty that they are correct and do not miss
1123
some insignificant zeros.
1128
enum_field_types f_type= warn_item->field_type();
1129
timestamp_type t_type= f_type ==
1130
MYSQL_TYPE_DATE ? MYSQL_TIMESTAMP_DATE : MYSQL_TIMESTAMP_DATETIME;
1131
value= (longlong) get_date_from_str(thd, str, t_type, warn_item->name, &error);
1133
If str did not contain a valid date according to the current
1134
SQL_MODE, get_date_from_str() has already thrown a warning,
1135
and we don't want to throw NULL on invalid date (see 5.2.6
1136
"SQL modes" in the manual), so we're done here.
1140
Do not cache GET_USER_VAR() function as its const_item() may return TRUE
1141
for the current thread but it still may change during the execution.
1143
if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM ||
1144
((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
1146
Item_cache_int *cache= new Item_cache_int(MYSQL_TYPE_DATETIME);
1147
/* Mark the cache as non-const to prevent re-caching. */
1148
cache->set_used_tables(1);
1149
cache->store(item, value);
1151
*item_arg= cache_arg;
1158
Retrieves YEAR value of 19XX-00-00 00:00:00 form from given item.
1163
item_arg [in/out] item to retrieve YEAR value from
1164
cache_arg [in/out] pointer to place to store the caching item to
1165
warn_item [in] item for issuing the conversion warning
1166
is_null [out] TRUE <=> the item_arg is null
1169
Retrieves the YEAR value of 19XX form from given item for comparison by the
1170
compare_datetime() function.
1171
Converts year to DATETIME of form YYYY-00-00 00:00:00 for the compatibility
1172
with the get_datetime_value function result.
1179
get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
1180
Item *warn_item, bool *is_null)
1183
Item *item= **item_arg;
1185
value= item->val_int();
1186
*is_null= item->null_value;
1188
return ~(ulonglong) 0;
1191
Coerce value to the 19XX form in order to correctly compare
1192
YEAR(2) & YEAR(4) types.
1199
/* Convert year to DATETIME of form YYYY-00-00 00:00:00 (YYYY0000000000). */
1200
value*= 10000000000LL;
1207
Compare items values as dates.
1210
Arg_comparator::compare_datetime()
1213
Compare items values as DATE/DATETIME for both EQUAL_FUNC and from other
1214
comparison functions. The correct DATETIME values are obtained
1215
with help of the get_datetime_value() function.
1218
If is_nulls_eq is TRUE:
1219
1 if items are equal or both are null
1221
If is_nulls_eq is FALSE:
1222
-1 a < b or at least one item is null
1226
is_nulls_eq | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 |
1227
a_is_null | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
1228
b_is_null | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 |
1229
result | 1 | 0 | 0 |0/1|-1 |-1 |-1 |-1/0/1|
1232
int Arg_comparator::compare_datetime()
1234
bool a_is_null, b_is_null;
1235
longlong a_value, b_value;
1237
/* Get DATE/DATETIME/TIME value of the 'a' item. */
1238
a_value= (*get_value_a_func)(thd, &a, &a_cache, *b, &a_is_null);
1239
if (!is_nulls_eq && a_is_null)
1242
owner->null_value= 1;
1246
/* Get DATE/DATETIME/TIME value of the 'b' item. */
1247
b_value= (*get_value_b_func)(thd, &b, &b_cache, *a, &b_is_null);
1248
if (a_is_null || b_is_null)
1251
owner->null_value= is_nulls_eq ? 0 : 1;
1252
return is_nulls_eq ? (a_is_null == b_is_null) : -1;
1255
/* Here we have two not-NULL values. */
1257
owner->null_value= 0;
1259
/* Compare values. */
1261
return (a_value == b_value);
1262
return a_value < b_value ? -1 : (a_value > b_value ? 1 : 0);
1266
int Arg_comparator::compare_string()
1269
if ((res1= (*a)->val_str(&value1)))
1271
if ((res2= (*b)->val_str(&value2)))
1274
owner->null_value= 0;
1275
return sortcmp(res1,res2,cmp_collation.collation);
1279
owner->null_value= 1;
1285
Compare strings byte by byte. End spaces are also compared.
1295
int Arg_comparator::compare_binary_string()
1298
if ((res1= (*a)->val_str(&value1)))
1300
if ((res2= (*b)->val_str(&value2)))
1303
owner->null_value= 0;
1304
uint res1_length= res1->length();
1305
uint res2_length= res2->length();
1306
int cmp= memcmp(res1->ptr(), res2->ptr(), min(res1_length,res2_length));
1307
return cmp ? cmp : (int) (res1_length - res2_length);
1311
owner->null_value= 1;
1317
Compare strings, but take into account that NULL == NULL.
1321
int Arg_comparator::compare_e_string()
1324
res1= (*a)->val_str(&value1);
1325
res2= (*b)->val_str(&value2);
1327
return test(res1 == res2);
1328
return test(sortcmp(res1, res2, cmp_collation.collation) == 0);
1332
int Arg_comparator::compare_e_binary_string()
1335
res1= (*a)->val_str(&value1);
1336
res2= (*b)->val_str(&value2);
1338
return test(res1 == res2);
1339
return test(stringcmp(res1, res2) == 0);
1343
int Arg_comparator::compare_real()
1346
Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1347
gcc to flush double values out of 80-bit Intel FPU registers before
1348
performing the comparison.
1350
volatile double val1, val2;
1351
val1= (*a)->val_real();
1352
if (!(*a)->null_value)
1354
val2= (*b)->val_real();
1355
if (!(*b)->null_value)
1358
owner->null_value= 0;
1359
if (val1 < val2) return -1;
1360
if (val1 == val2) return 0;
1365
owner->null_value= 1;
1369
int Arg_comparator::compare_decimal()
1372
my_decimal *val1= (*a)->val_decimal(&value1);
1373
if (!(*a)->null_value)
1376
my_decimal *val2= (*b)->val_decimal(&value2);
1377
if (!(*b)->null_value)
1380
owner->null_value= 0;
1381
return my_decimal_cmp(val1, val2);
1385
owner->null_value= 1;
1389
int Arg_comparator::compare_e_real()
1391
double val1= (*a)->val_real();
1392
double val2= (*b)->val_real();
1393
if ((*a)->null_value || (*b)->null_value)
1394
return test((*a)->null_value && (*b)->null_value);
1395
return test(val1 == val2);
1398
int Arg_comparator::compare_e_decimal()
1400
my_decimal value1, value2;
1401
my_decimal *val1= (*a)->val_decimal(&value1);
1402
my_decimal *val2= (*b)->val_decimal(&value2);
1403
if ((*a)->null_value || (*b)->null_value)
1404
return test((*a)->null_value && (*b)->null_value);
1405
return test(my_decimal_cmp(val1, val2) == 0);
1409
int Arg_comparator::compare_real_fixed()
1412
Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1413
gcc to flush double values out of 80-bit Intel FPU registers before
1414
performing the comparison.
1416
volatile double val1, val2;
1417
val1= (*a)->val_real();
1418
if (!(*a)->null_value)
1420
val2= (*b)->val_real();
1421
if (!(*b)->null_value)
1424
owner->null_value= 0;
1425
if (val1 == val2 || fabs(val1 - val2) < precision)
1433
owner->null_value= 1;
1438
int Arg_comparator::compare_e_real_fixed()
1440
double val1= (*a)->val_real();
1441
double val2= (*b)->val_real();
1442
if ((*a)->null_value || (*b)->null_value)
1443
return test((*a)->null_value && (*b)->null_value);
1444
return test(val1 == val2 || fabs(val1 - val2) < precision);
1448
int Arg_comparator::compare_int_signed()
1450
longlong val1= (*a)->val_int();
1451
if (!(*a)->null_value)
1453
longlong val2= (*b)->val_int();
1454
if (!(*b)->null_value)
1457
owner->null_value= 0;
1458
if (val1 < val2) return -1;
1459
if (val1 == val2) return 0;
1464
owner->null_value= 1;
1470
Compare values as BIGINT UNSIGNED.
1473
int Arg_comparator::compare_int_unsigned()
1475
ulonglong val1= (*a)->val_int();
1476
if (!(*a)->null_value)
1478
ulonglong val2= (*b)->val_int();
1479
if (!(*b)->null_value)
1482
owner->null_value= 0;
1483
if (val1 < val2) return -1;
1484
if (val1 == val2) return 0;
1489
owner->null_value= 1;
1495
Compare signed (*a) with unsigned (*B)
1498
int Arg_comparator::compare_int_signed_unsigned()
1500
longlong sval1= (*a)->val_int();
1501
if (!(*a)->null_value)
1503
ulonglong uval2= (ulonglong)(*b)->val_int();
1504
if (!(*b)->null_value)
1507
owner->null_value= 0;
1508
if (sval1 < 0 || (ulonglong)sval1 < uval2)
1510
if ((ulonglong)sval1 == uval2)
1516
owner->null_value= 1;
1522
Compare unsigned (*a) with signed (*B)
1525
int Arg_comparator::compare_int_unsigned_signed()
1527
ulonglong uval1= (ulonglong)(*a)->val_int();
1528
if (!(*a)->null_value)
1530
longlong sval2= (*b)->val_int();
1531
if (!(*b)->null_value)
1534
owner->null_value= 0;
1537
if (uval1 < (ulonglong)sval2)
1539
if (uval1 == (ulonglong)sval2)
1545
owner->null_value= 1;
1550
int Arg_comparator::compare_e_int()
1552
longlong val1= (*a)->val_int();
1553
longlong val2= (*b)->val_int();
1554
if ((*a)->null_value || (*b)->null_value)
1555
return test((*a)->null_value && (*b)->null_value);
1556
return test(val1 == val2);
1560
Compare unsigned *a with signed *b or signed *a with unsigned *b.
1562
int Arg_comparator::compare_e_int_diff_signedness()
1564
longlong val1= (*a)->val_int();
1565
longlong val2= (*b)->val_int();
1566
if ((*a)->null_value || (*b)->null_value)
1567
return test((*a)->null_value && (*b)->null_value);
1568
return (val1 >= 0) && test(val1 == val2);
1571
int Arg_comparator::compare_row()
1575
(*a)->bring_value();
1576
(*b)->bring_value();
1577
uint n= (*a)->cols();
1578
for (uint i= 0; i<n; i++)
1580
res= comparators[i].compare();
1581
/* Aggregate functions don't need special null handling. */
1582
if (owner->null_value && owner->type() == Item::FUNC_ITEM)
1584
// NULL was compared
1585
switch (((Item_func*)owner)->functype()) {
1586
case Item_func::NE_FUNC:
1587
break; // NE never aborts on NULL even if abort_on_null is set
1588
case Item_func::LT_FUNC:
1589
case Item_func::LE_FUNC:
1590
case Item_func::GT_FUNC:
1591
case Item_func::GE_FUNC:
1592
return -1; // <, <=, > and >= always fail on NULL
1594
if (((Item_bool_func2*)owner)->abort_on_null)
1595
return -1; // We do not need correct NULL returning
1598
owner->null_value= 0;
1599
res= 0; // continue comparison (maybe we will meet explicit difference)
1607
There was NULL(s) in comparison in some parts, but there was no
1608
explicit difference in other parts, so we have to return NULL.
1610
owner->null_value= 1;
1617
int Arg_comparator::compare_e_row()
1619
(*a)->bring_value();
1620
(*b)->bring_value();
1621
uint n= (*a)->cols();
1622
for (uint i= 0; i<n; i++)
1624
if (!comparators[i].compare())
1631
void Item_func_truth::fix_length_and_dec()
1640
void Item_func_truth::print(String *str, enum_query_type query_type)
1643
args[0]->print(str, query_type);
1644
str->append(STRING_WITH_LEN(" is "));
1646
str->append(STRING_WITH_LEN("not "));
1648
str->append(STRING_WITH_LEN("true"));
1650
str->append(STRING_WITH_LEN("false"));
1655
bool Item_func_truth::val_bool()
1657
bool val= args[0]->val_bool();
1658
if (args[0]->null_value)
1661
NULL val IS {TRUE, FALSE} --> FALSE
1662
NULL val IS NOT {TRUE, FALSE} --> TRUE
1664
return (! affirmative);
1669
/* {TRUE, FALSE} val IS {TRUE, FALSE} value */
1670
return (val == value);
1673
/* {TRUE, FALSE} val IS NOT {TRUE, FALSE} value */
1674
return (val != value);
1678
longlong Item_func_truth::val_int()
1680
return (val_bool() ? 1 : 0);
1684
bool Item_in_optimizer::fix_left(THD *thd, Item **ref)
1686
if ((!args[0]->fixed && args[0]->fix_fields(thd, args)) ||
1687
(!cache && !(cache= Item_cache::get_cache(args[0]))))
1690
cache->setup(args[0]);
1691
if (cache->cols() == 1)
1693
if ((used_tables_cache= args[0]->used_tables()))
1694
cache->set_used_tables(OUTER_REF_TABLE_BIT);
1696
cache->set_used_tables(0);
1700
uint n= cache->cols();
1701
for (uint i= 0; i < n; i++)
1703
if (args[0]->element_index(i)->used_tables())
1704
((Item_cache *)cache->element_index(i))->set_used_tables(OUTER_REF_TABLE_BIT);
1706
((Item_cache *)cache->element_index(i))->set_used_tables(0);
1708
used_tables_cache= args[0]->used_tables();
1710
not_null_tables_cache= args[0]->not_null_tables();
1711
with_sum_func= args[0]->with_sum_func;
1712
if ((const_item_cache= args[0]->const_item()))
1713
cache->store(args[0]);
1718
bool Item_in_optimizer::fix_fields(THD *thd, Item **ref)
1720
DBUG_ASSERT(fixed == 0);
1721
if (fix_left(thd, ref))
1723
if (args[0]->maybe_null)
1726
if (!args[1]->fixed && args[1]->fix_fields(thd, args+1))
1728
Item_in_subselect * sub= (Item_in_subselect *)args[1];
1729
if (args[0]->cols() != sub->engine->cols())
1731
my_error(ER_OPERAND_COLUMNS, MYF(0), args[0]->cols());
1734
if (args[1]->maybe_null)
1736
with_sum_func= with_sum_func || args[1]->with_sum_func;
1737
used_tables_cache|= args[1]->used_tables();
1738
not_null_tables_cache|= args[1]->not_null_tables();
1739
const_item_cache&= args[1]->const_item();
1745
longlong Item_in_optimizer::val_int()
1748
DBUG_ASSERT(fixed == 1);
1749
cache->store(args[0]);
1750
cache->cache_value();
1752
if (cache->null_value)
1756
"<outer_value_list> [NOT] IN (SELECT <inner_value_list>...)"
1757
where one or more of the outer values is NULL.
1759
if (((Item_in_subselect*)args[1])->is_top_level_item())
1762
We're evaluating a top level item, e.g.
1763
"<outer_value_list> IN (SELECT <inner_value_list>...)",
1764
and in this case a NULL value in the outer_value_list means
1765
that the result shall be NULL/FALSE (makes no difference for
1766
top level items). The cached value is NULL, so just return
1774
We're evaluating an item where a NULL value in either the
1775
outer or inner value list does not automatically mean that we
1776
can return NULL/FALSE. An example of such a query is
1777
"<outer_value_list> NOT IN (SELECT <inner_value_list>...)"
1778
The result when there is at least one NULL value is: NULL if the
1779
SELECT evaluated over the non-NULL values produces at least
1780
one row, FALSE otherwise
1782
Item_in_subselect *item_subs=(Item_in_subselect*)args[1];
1783
bool all_left_cols_null= true;
1784
const uint ncols= cache->cols();
1787
Turn off the predicates that are based on column compares for
1788
which the left part is currently NULL
1790
for (uint i= 0; i < ncols; i++)
1792
if (cache->element_index(i)->null_value)
1793
item_subs->set_cond_guard_var(i, FALSE);
1795
all_left_cols_null= false;
1798
if (!((Item_in_subselect*)args[1])->is_correlated &&
1799
all_left_cols_null && result_for_null_param != UNKNOWN)
1802
This is a non-correlated subquery, all values in the outer
1803
value list are NULL, and we have already evaluated the
1804
subquery for all NULL values: Return the same result we
1805
did last time without evaluating the subquery.
1807
null_value= result_for_null_param;
1811
/* The subquery has to be evaluated */
1812
(void) args[1]->val_bool_result();
1813
null_value= !item_subs->engine->no_rows();
1814
if (all_left_cols_null)
1815
result_for_null_param= null_value;
1818
/* Turn all predicates back on */
1819
for (uint i= 0; i < ncols; i++)
1820
item_subs->set_cond_guard_var(i, TRUE);
1824
tmp= args[1]->val_bool_result();
1825
null_value= args[1]->null_value;
1830
void Item_in_optimizer::keep_top_level_cache()
1832
cache->keep_array();
1837
void Item_in_optimizer::cleanup()
1839
DBUG_ENTER("Item_in_optimizer::cleanup");
1840
Item_bool_func::cleanup();
1847
bool Item_in_optimizer::is_null()
1854
longlong Item_func_eq::val_int()
1856
DBUG_ASSERT(fixed == 1);
1857
int value= cmp.compare();
1858
return value == 0 ? 1 : 0;
1862
/** Same as Item_func_eq, but NULL = NULL. */
1864
void Item_func_equal::fix_length_and_dec()
1866
Item_bool_func2::fix_length_and_dec();
1867
maybe_null=null_value=0;
1870
longlong Item_func_equal::val_int()
1872
DBUG_ASSERT(fixed == 1);
1873
return cmp.compare();
1876
longlong Item_func_ne::val_int()
1878
DBUG_ASSERT(fixed == 1);
1879
int value= cmp.compare();
1880
return value != 0 && !null_value ? 1 : 0;
1884
longlong Item_func_ge::val_int()
1886
DBUG_ASSERT(fixed == 1);
1887
int value= cmp.compare();
1888
return value >= 0 ? 1 : 0;
1892
longlong Item_func_gt::val_int()
1894
DBUG_ASSERT(fixed == 1);
1895
int value= cmp.compare();
1896
return value > 0 ? 1 : 0;
1899
longlong Item_func_le::val_int()
1901
DBUG_ASSERT(fixed == 1);
1902
int value= cmp.compare();
1903
return value <= 0 && !null_value ? 1 : 0;
1907
longlong Item_func_lt::val_int()
1909
DBUG_ASSERT(fixed == 1);
1910
int value= cmp.compare();
1911
return value < 0 && !null_value ? 1 : 0;
1915
longlong Item_func_strcmp::val_int()
1917
DBUG_ASSERT(fixed == 1);
1918
String *a=args[0]->val_str(&cmp.value1);
1919
String *b=args[1]->val_str(&cmp.value2);
1925
int value= sortcmp(a,b,cmp.cmp_collation.collation);
1927
return !value ? 0 : (value < 0 ? (longlong) -1 : (longlong) 1);
1931
bool Item_func_opt_neg::eq(const Item *item, bool binary_cmp) const
1933
/* Assume we don't have rtti */
1936
if (item->type() != FUNC_ITEM)
1938
Item_func *item_func=(Item_func*) item;
1939
if (arg_count != item_func->arg_count ||
1940
functype() != item_func->functype())
1942
if (negated != ((Item_func_opt_neg *) item_func)->negated)
1944
for (uint i=0; i < arg_count ; i++)
1945
if (!args[i]->eq(item_func->arguments()[i], binary_cmp))
1951
void Item_func_interval::fix_length_and_dec()
1953
uint rows= row->cols();
1955
use_decimal_comparison= ((row->element_index(0)->result_type() ==
1957
(row->element_index(0)->result_type() ==
1961
bool not_null_consts= TRUE;
1963
for (uint i= 1; not_null_consts && i < rows; i++)
1965
Item *el= row->element_index(i);
1966
not_null_consts&= el->const_item() & !el->is_null();
1969
if (not_null_consts &&
1971
(interval_range*) sql_alloc(sizeof(interval_range) * (rows - 1))))
1973
if (use_decimal_comparison)
1975
for (uint i= 1; i < rows; i++)
1977
Item *el= row->element_index(i);
1978
interval_range *range= intervals + (i-1);
1979
if ((el->result_type() == DECIMAL_RESULT) ||
1980
(el->result_type() == INT_RESULT))
1982
range->type= DECIMAL_RESULT;
1984
my_decimal *dec= el->val_decimal(&range->dec);
1985
if (dec != &range->dec)
1988
range->dec.fix_buffer_pointer();
1993
range->type= REAL_RESULT;
1994
range->dbl= el->val_real();
2000
for (uint i= 1; i < rows; i++)
2002
intervals[i-1].dbl= row->element_index(i)->val_real();
2009
used_tables_cache|= row->used_tables();
2010
not_null_tables_cache= row->not_null_tables();
2011
with_sum_func= with_sum_func || row->with_sum_func;
2012
const_item_cache&= row->const_item();
2017
Execute Item_func_interval().
2020
If we are doing a decimal comparison, we are evaluating the first
2025
- 0 if lower than lowest
2026
- 1 - arg_count-1 if between args[n] and args[n+1]
2027
- arg_count if higher than biggest argument
2030
longlong Item_func_interval::val_int()
2032
DBUG_ASSERT(fixed == 1);
2034
my_decimal dec_buf, *dec= NULL;
2037
if (use_decimal_comparison)
2039
dec= row->element_index(0)->val_decimal(&dec_buf);
2040
if (row->element_index(0)->null_value)
2042
my_decimal2double(E_DEC_FATAL_ERROR, dec, &value);
2046
value= row->element_index(0)->val_real();
2047
if (row->element_index(0)->null_value)
2052
{ // Use binary search to find interval
2056
while (start != end)
2058
uint mid= (start + end + 1) / 2;
2059
interval_range *range= intervals + mid;
2062
The values in the range intervall may have different types,
2063
Only do a decimal comparision of the first argument is a decimal
2064
and we are comparing against a decimal
2066
if (dec && range->type == DECIMAL_RESULT)
2067
cmp_result= my_decimal_cmp(&range->dec, dec) <= 0;
2069
cmp_result= (range->dbl <= value);
2075
interval_range *range= intervals+start;
2076
return ((dec && range->type == DECIMAL_RESULT) ?
2077
my_decimal_cmp(dec, &range->dec) < 0 :
2078
value < range->dbl) ? 0 : start + 1;
2081
for (i=1 ; i < row->cols() ; i++)
2083
Item *el= row->element_index(i);
2084
if (use_decimal_comparison &&
2085
((el->result_type() == DECIMAL_RESULT) ||
2086
(el->result_type() == INT_RESULT)))
2088
my_decimal e_dec_buf, *e_dec= el->val_decimal(&e_dec_buf);
2089
/* Skip NULL ranges. */
2092
if (my_decimal_cmp(e_dec, dec) > 0)
2097
double val= el->val_real();
2098
/* Skip NULL ranges. */
2110
Perform context analysis of a BETWEEN item tree.
2112
This function performs context analysis (name resolution) and calculates
2113
various attributes of the item tree with Item_func_between as its root.
2114
The function saves in ref the pointer to the item or to a newly created
2115
item that is considered as a replacement for the original one.
2117
@param thd reference to the global context of the query thread
2118
@param ref pointer to Item* variable where pointer to resulting "fixed"
2119
item is to be assigned
2122
Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
2123
a predicate/function level. Then it's easy to show that:
2125
T0(e BETWEEN e1 AND e2) = union(T1(e),T1(e1),T1(e2))
2126
T1(e BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
2127
T0(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
2128
T1(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
2137
bool Item_func_between::fix_fields(THD *thd, Item **ref)
2139
if (Item_func_opt_neg::fix_fields(thd, ref))
2142
thd->lex->current_select->between_count++;
2144
/* not_null_tables_cache == union(T1(e),T1(e1),T1(e2)) */
2145
if (pred_level && !negated)
2148
/* not_null_tables_cache == union(T1(e), intersection(T1(e1),T1(e2))) */
2149
not_null_tables_cache= (args[0]->not_null_tables() |
2150
(args[1]->not_null_tables() &
2151
args[2]->not_null_tables()));
2157
void Item_func_between::fix_length_and_dec()
2161
bool datetime_found= FALSE;
2162
int time_items_found= 0;
2163
compare_as_dates= TRUE;
2164
THD *thd= current_thd;
2167
As some compare functions are generated after sql_yacc,
2168
we have to check for out of memory conditions here
2170
if (!args[0] || !args[1] || !args[2])
2172
if ( agg_cmp_type(&cmp_type, args, 3))
2174
if (cmp_type == STRING_RESULT &&
2175
agg_arg_charsets(cmp_collation, args, 3, MY_COLL_CMP_CONV, 1))
2179
Detect the comparison of DATE/DATETIME items.
2180
At least one of items should be a DATE/DATETIME item and other items
2181
should return the STRING result.
2183
if (cmp_type == STRING_RESULT)
2185
for (i= 0; i < 3; i++)
2187
if (args[i]->is_datetime())
2189
datetime_found= TRUE;
2192
if (args[i]->field_type() == MYSQL_TYPE_TIME &&
2193
args[i]->result_as_longlong())
2197
if (!datetime_found)
2198
compare_as_dates= FALSE;
2200
if (compare_as_dates)
2202
ge_cmp.set_datetime_cmp_func(this, args, args + 1);
2203
le_cmp.set_datetime_cmp_func(this, args, args + 2);
2205
else if (time_items_found == 3)
2207
/* Compare TIME items as integers. */
2208
cmp_type= INT_RESULT;
2210
else if (args[0]->real_item()->type() == FIELD_ITEM &&
2211
thd->lex->sql_command != SQLCOM_CREATE_VIEW &&
2212
thd->lex->sql_command != SQLCOM_SHOW_CREATE)
2214
Item_field *field_item= (Item_field*) (args[0]->real_item());
2215
if (field_item->field->can_be_compared_as_longlong())
2218
The following can't be recoded with || as convert_constant_item
2219
changes the argument
2221
if (convert_constant_item(thd, field_item, &args[1]))
2222
cmp_type=INT_RESULT; // Works for all types.
2223
if (convert_constant_item(thd, field_item, &args[2]))
2224
cmp_type=INT_RESULT; // Works for all types.
2230
longlong Item_func_between::val_int()
2232
DBUG_ASSERT(fixed == 1);
2233
if (compare_as_dates)
2237
ge_res= ge_cmp.compare();
2238
if ((null_value= args[0]->null_value))
2240
le_res= le_cmp.compare();
2242
if (!args[1]->null_value && !args[2]->null_value)
2243
return (longlong) ((ge_res >= 0 && le_res <=0) != negated);
2244
else if (args[1]->null_value)
2246
null_value= le_res > 0; // not null if false range.
2250
null_value= ge_res < 0;
2253
else if (cmp_type == STRING_RESULT)
2255
String *value,*a,*b;
2256
value=args[0]->val_str(&value0);
2257
if ((null_value=args[0]->null_value))
2259
a=args[1]->val_str(&value1);
2260
b=args[2]->val_str(&value2);
2261
if (!args[1]->null_value && !args[2]->null_value)
2262
return (longlong) ((sortcmp(value,a,cmp_collation.collation) >= 0 &&
2263
sortcmp(value,b,cmp_collation.collation) <= 0) !=
2265
if (args[1]->null_value && args[2]->null_value)
2267
else if (args[1]->null_value)
2269
// Set to not null if false range.
2270
null_value= sortcmp(value,b,cmp_collation.collation) <= 0;
2274
// Set to not null if false range.
2275
null_value= sortcmp(value,a,cmp_collation.collation) >= 0;
2278
else if (cmp_type == INT_RESULT)
2280
longlong value=args[0]->val_int(), a, b;
2281
if ((null_value=args[0]->null_value))
2282
return 0; /* purecov: inspected */
2283
a=args[1]->val_int();
2284
b=args[2]->val_int();
2285
if (!args[1]->null_value && !args[2]->null_value)
2286
return (longlong) ((value >= a && value <= b) != negated);
2287
if (args[1]->null_value && args[2]->null_value)
2289
else if (args[1]->null_value)
2291
null_value= value <= b; // not null if false range.
2295
null_value= value >= a;
2298
else if (cmp_type == DECIMAL_RESULT)
2300
my_decimal dec_buf, *dec= args[0]->val_decimal(&dec_buf),
2301
a_buf, *a_dec, b_buf, *b_dec;
2302
if ((null_value=args[0]->null_value))
2303
return 0; /* purecov: inspected */
2304
a_dec= args[1]->val_decimal(&a_buf);
2305
b_dec= args[2]->val_decimal(&b_buf);
2306
if (!args[1]->null_value && !args[2]->null_value)
2307
return (longlong) ((my_decimal_cmp(dec, a_dec) >= 0 &&
2308
my_decimal_cmp(dec, b_dec) <= 0) != negated);
2309
if (args[1]->null_value && args[2]->null_value)
2311
else if (args[1]->null_value)
2312
null_value= (my_decimal_cmp(dec, b_dec) <= 0);
2314
null_value= (my_decimal_cmp(dec, a_dec) >= 0);
2318
double value= args[0]->val_real(),a,b;
2319
if ((null_value=args[0]->null_value))
2320
return 0; /* purecov: inspected */
2321
a= args[1]->val_real();
2322
b= args[2]->val_real();
2323
if (!args[1]->null_value && !args[2]->null_value)
2324
return (longlong) ((value >= a && value <= b) != negated);
2325
if (args[1]->null_value && args[2]->null_value)
2327
else if (args[1]->null_value)
2329
null_value= value <= b; // not null if false range.
2333
null_value= value >= a;
2336
return (longlong) (!null_value && negated);
2340
void Item_func_between::print(String *str, enum_query_type query_type)
2343
args[0]->print(str, query_type);
2345
str->append(STRING_WITH_LEN(" not"));
2346
str->append(STRING_WITH_LEN(" between "));
2347
args[1]->print(str, query_type);
2348
str->append(STRING_WITH_LEN(" and "));
2349
args[2]->print(str, query_type);
2354
Item_func_ifnull::fix_length_and_dec()
2356
agg_result_type(&hybrid_type, args, 2);
2357
maybe_null=args[1]->maybe_null;
2358
decimals= max(args[0]->decimals, args[1]->decimals);
2359
unsigned_flag= args[0]->unsigned_flag && args[1]->unsigned_flag;
2361
if (hybrid_type == DECIMAL_RESULT || hybrid_type == INT_RESULT)
2363
int len0= args[0]->max_length - args[0]->decimals
2364
- (args[0]->unsigned_flag ? 0 : 1);
2366
int len1= args[1]->max_length - args[1]->decimals
2367
- (args[1]->unsigned_flag ? 0 : 1);
2369
max_length= max(len0, len1) + decimals + (unsigned_flag ? 0 : 1);
2372
max_length= max(args[0]->max_length, args[1]->max_length);
2374
switch (hybrid_type) {
2376
agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1);
2378
case DECIMAL_RESULT:
2388
cached_field_type= agg_field_type(args, 2);
2392
uint Item_func_ifnull::decimal_precision() const
2394
int arg0_int_part= args[0]->decimal_int_part();
2395
int arg1_int_part= args[1]->decimal_int_part();
2396
int max_int_part= max(arg0_int_part, arg1_int_part);
2397
int precision= max_int_part + decimals;
2398
return min(precision, DECIMAL_MAX_PRECISION);
2402
enum_field_types Item_func_ifnull::field_type() const
2404
return cached_field_type;
2407
Field *Item_func_ifnull::tmp_table_field(TABLE *table)
2409
return tmp_table_field_from_field_type(table, 0);
2413
Item_func_ifnull::real_op()
2415
DBUG_ASSERT(fixed == 1);
2416
double value= args[0]->val_real();
2417
if (!args[0]->null_value)
2422
value= args[1]->val_real();
2423
if ((null_value=args[1]->null_value))
2429
Item_func_ifnull::int_op()
2431
DBUG_ASSERT(fixed == 1);
2432
longlong value=args[0]->val_int();
2433
if (!args[0]->null_value)
2438
value=args[1]->val_int();
2439
if ((null_value=args[1]->null_value))
2445
my_decimal *Item_func_ifnull::decimal_op(my_decimal *decimal_value)
2447
DBUG_ASSERT(fixed == 1);
2448
my_decimal *value= args[0]->val_decimal(decimal_value);
2449
if (!args[0]->null_value)
2454
value= args[1]->val_decimal(decimal_value);
2455
if ((null_value= args[1]->null_value))
2462
Item_func_ifnull::str_op(String *str)
2464
DBUG_ASSERT(fixed == 1);
2465
String *res =args[0]->val_str(str);
2466
if (!args[0]->null_value)
2469
res->set_charset(collation.collation);
2472
res=args[1]->val_str(str);
2473
if ((null_value=args[1]->null_value))
2475
res->set_charset(collation.collation);
2481
Perform context analysis of an IF item tree.
2483
This function performs context analysis (name resolution) and calculates
2484
various attributes of the item tree with Item_func_if as its root.
2485
The function saves in ref the pointer to the item or to a newly created
2486
item that is considered as a replacement for the original one.
2488
@param thd reference to the global context of the query thread
2489
@param ref pointer to Item* variable where pointer to resulting "fixed"
2490
item is to be assigned
2493
Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
2494
a predicate/function level. Then it's easy to show that:
2496
T0(IF(e,e1,e2) = T1(IF(e,e1,e2))
2497
T1(IF(e,e1,e2)) = intersection(T1(e1),T1(e2))
2507
Item_func_if::fix_fields(THD *thd, Item **ref)
2509
DBUG_ASSERT(fixed == 0);
2510
args[0]->top_level_item();
2512
if (Item_func::fix_fields(thd, ref))
2515
not_null_tables_cache= (args[1]->not_null_tables() &
2516
args[2]->not_null_tables());
2523
Item_func_if::fix_length_and_dec()
2525
maybe_null=args[1]->maybe_null || args[2]->maybe_null;
2526
decimals= max(args[1]->decimals, args[2]->decimals);
2527
unsigned_flag=args[1]->unsigned_flag && args[2]->unsigned_flag;
2529
enum Item_result arg1_type=args[1]->result_type();
2530
enum Item_result arg2_type=args[2]->result_type();
2531
bool null1=args[1]->const_item() && args[1]->null_value;
2532
bool null2=args[2]->const_item() && args[2]->null_value;
2536
cached_result_type= arg2_type;
2537
collation.set(args[2]->collation.collation);
2538
cached_field_type= args[2]->field_type();
2542
cached_result_type= arg1_type;
2543
collation.set(args[1]->collation.collation);
2544
cached_field_type= args[1]->field_type();
2548
agg_result_type(&cached_result_type, args+1, 2);
2549
if (cached_result_type == STRING_RESULT)
2551
if (agg_arg_charsets(collation, args+1, 2, MY_COLL_ALLOW_CONV, 1))
2556
collation.set(&my_charset_bin); // Number
2558
cached_field_type= agg_field_type(args + 1, 2);
2561
if ((cached_result_type == DECIMAL_RESULT )
2562
|| (cached_result_type == INT_RESULT))
2564
int len1= args[1]->max_length - args[1]->decimals
2565
- (args[1]->unsigned_flag ? 0 : 1);
2567
int len2= args[2]->max_length - args[2]->decimals
2568
- (args[2]->unsigned_flag ? 0 : 1);
2570
max_length=max(len1, len2) + decimals + (unsigned_flag ? 0 : 1);
2573
max_length= max(args[1]->max_length, args[2]->max_length);
2577
uint Item_func_if::decimal_precision() const
2579
int arg1_prec= args[1]->decimal_int_part();
2580
int arg2_prec= args[2]->decimal_int_part();
2581
int precision=max(arg1_prec,arg2_prec) + decimals;
2582
return min(precision, DECIMAL_MAX_PRECISION);
2587
Item_func_if::val_real()
2589
DBUG_ASSERT(fixed == 1);
2590
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2591
double value= arg->val_real();
2592
null_value=arg->null_value;
2597
Item_func_if::val_int()
2599
DBUG_ASSERT(fixed == 1);
2600
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2601
longlong value=arg->val_int();
2602
null_value=arg->null_value;
2607
Item_func_if::val_str(String *str)
2609
DBUG_ASSERT(fixed == 1);
2610
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2611
String *res=arg->val_str(str);
2613
res->set_charset(collation.collation);
2614
null_value=arg->null_value;
2620
Item_func_if::val_decimal(my_decimal *decimal_value)
2622
DBUG_ASSERT(fixed == 1);
2623
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2624
my_decimal *value= arg->val_decimal(decimal_value);
2625
null_value= arg->null_value;
2631
Item_func_nullif::fix_length_and_dec()
2633
Item_bool_func2::fix_length_and_dec();
2635
if (args[0]) // Only false if EOM
2637
max_length=args[0]->max_length;
2638
decimals=args[0]->decimals;
2639
unsigned_flag= args[0]->unsigned_flag;
2640
cached_result_type= args[0]->result_type();
2641
if (cached_result_type == STRING_RESULT &&
2642
agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1))
2650
Note that we have to evaluate the first argument twice as the compare
2651
may have been done with a different type than return value
2653
NULL if arguments are equal
2655
the first argument if not equal
2659
Item_func_nullif::val_real()
2661
DBUG_ASSERT(fixed == 1);
2668
value= args[0]->val_real();
2669
null_value=args[0]->null_value;
2674
Item_func_nullif::val_int()
2676
DBUG_ASSERT(fixed == 1);
2683
value=args[0]->val_int();
2684
null_value=args[0]->null_value;
2689
Item_func_nullif::val_str(String *str)
2691
DBUG_ASSERT(fixed == 1);
2698
res=args[0]->val_str(str);
2699
null_value=args[0]->null_value;
2705
Item_func_nullif::val_decimal(my_decimal * decimal_value)
2707
DBUG_ASSERT(fixed == 1);
2714
res= args[0]->val_decimal(decimal_value);
2715
null_value= args[0]->null_value;
2721
Item_func_nullif::is_null()
2723
return (null_value= (!cmp.compare() ? 1 : args[0]->null_value));
2728
Find and return matching items for CASE or ELSE item if all compares
2729
are failed or NULL if ELSE item isn't defined.
2732
In order to do correct comparisons of the CASE expression (the expression
2733
between CASE and the first WHEN) with each WHEN expression several
2734
comparators are used. One for each result type. CASE expression can be
2735
evaluated up to # of different result types are used. To check whether
2736
the CASE expression already was evaluated for a particular result type
2737
a bit mapped variable value_added_map is used. Result types are mapped
2738
to it according to their int values i.e. STRING_RESULT is mapped to bit
2739
0, REAL_RESULT to bit 1, so on.
2742
NULL Nothing found and there is no ELSE expression defined
2744
item Found item or ELSE item if defined and all comparisons are
2748
Item *Item_func_case::find_item(String *str)
2750
uint value_added_map= 0;
2752
if (first_expr_num == -1)
2754
for (uint i=0 ; i < ncases ; i+=2)
2756
// No expression between CASE and the first WHEN
2757
if (args[i]->val_bool())
2764
/* Compare every WHEN argument with it and return the first match */
2765
for (uint i=0 ; i < ncases ; i+=2)
2767
cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
2768
DBUG_ASSERT(cmp_type != ROW_RESULT);
2769
DBUG_ASSERT(cmp_items[(uint)cmp_type]);
2770
if (!(value_added_map & (1<<(uint)cmp_type)))
2772
cmp_items[(uint)cmp_type]->store_value(args[first_expr_num]);
2773
if ((null_value=args[first_expr_num]->null_value))
2774
return else_expr_num != -1 ? args[else_expr_num] : 0;
2775
value_added_map|= 1<<(uint)cmp_type;
2777
if (!cmp_items[(uint)cmp_type]->cmp(args[i]) && !args[i]->null_value)
2781
// No, WHEN clauses all missed, return ELSE expression
2782
return else_expr_num != -1 ? args[else_expr_num] : 0;
2786
String *Item_func_case::val_str(String *str)
2788
DBUG_ASSERT(fixed == 1);
2790
Item *item=find_item(str);
2798
if (!(res=item->val_str(str)))
2804
longlong Item_func_case::val_int()
2806
DBUG_ASSERT(fixed == 1);
2807
char buff[MAX_FIELD_WIDTH];
2808
String dummy_str(buff,sizeof(buff),default_charset());
2809
Item *item=find_item(&dummy_str);
2817
res=item->val_int();
2818
null_value=item->null_value;
2822
double Item_func_case::val_real()
2824
DBUG_ASSERT(fixed == 1);
2825
char buff[MAX_FIELD_WIDTH];
2826
String dummy_str(buff,sizeof(buff),default_charset());
2827
Item *item=find_item(&dummy_str);
2835
res= item->val_real();
2836
null_value=item->null_value;
2841
my_decimal *Item_func_case::val_decimal(my_decimal *decimal_value)
2843
DBUG_ASSERT(fixed == 1);
2844
char buff[MAX_FIELD_WIDTH];
2845
String dummy_str(buff, sizeof(buff), default_charset());
2846
Item *item= find_item(&dummy_str);
2855
res= item->val_decimal(decimal_value);
2856
null_value= item->null_value;
2861
bool Item_func_case::fix_fields(THD *thd, Item **ref)
2864
buff should match stack usage from
2865
Item_func_case::val_int() -> Item_func_case::find_item()
2867
#ifndef EMBEDDED_LIBRARY
2868
uchar buff[MAX_FIELD_WIDTH*2+sizeof(String)*2+sizeof(String*)*2+sizeof(double)*2+sizeof(longlong)*2];
2870
bool res= Item_func::fix_fields(thd, ref);
2872
Call check_stack_overrun after fix_fields to be sure that stack variable
2873
is not optimized away
2875
if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
2876
return TRUE; // Fatal error flag is set!
2881
void Item_func_case::agg_str_lengths(Item* arg)
2883
set_if_bigger(max_length, arg->max_length);
2884
set_if_bigger(decimals, arg->decimals);
2885
unsigned_flag= unsigned_flag && arg->unsigned_flag;
2889
void Item_func_case::agg_num_lengths(Item *arg)
2891
uint len= my_decimal_length_to_precision(arg->max_length, arg->decimals,
2892
arg->unsigned_flag) - arg->decimals;
2893
set_if_bigger(max_length, len);
2894
set_if_bigger(decimals, arg->decimals);
2895
unsigned_flag= unsigned_flag && arg->unsigned_flag;
2899
void Item_func_case::fix_length_and_dec()
2903
uint found_types= 0;
2904
if (!(agg= (Item**) sql_alloc(sizeof(Item*)*(ncases+1))))
2908
Aggregate all THEN and ELSE expression types
2909
and collations when string result
2912
for (nagg= 0 ; nagg < ncases/2 ; nagg++)
2913
agg[nagg]= args[nagg*2+1];
2915
if (else_expr_num != -1)
2916
agg[nagg++]= args[else_expr_num];
2918
agg_result_type(&cached_result_type, agg, nagg);
2919
if ((cached_result_type == STRING_RESULT) &&
2920
agg_arg_charsets(collation, agg, nagg, MY_COLL_ALLOW_CONV, 1))
2923
cached_field_type= agg_field_type(agg, nagg);
2925
Aggregate first expression and all THEN expression types
2926
and collations when string comparison
2928
if (first_expr_num != -1)
2931
agg[0]= args[first_expr_num];
2932
left_result_type= agg[0]->result_type();
2934
for (nagg= 0; nagg < ncases/2 ; nagg++)
2935
agg[nagg+1]= args[nagg*2];
2937
if (!(found_types= collect_cmp_types(agg, nagg)))
2940
for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
2942
if (found_types & (1 << i) && !cmp_items[i])
2944
DBUG_ASSERT((Item_result)i != ROW_RESULT);
2945
if ((Item_result)i == STRING_RESULT &&
2946
agg_arg_charsets(cmp_collation, agg, nagg, MY_COLL_CMP_CONV, 1))
2949
cmp_item::get_comparator((Item_result)i,
2950
cmp_collation.collation)))
2956
if (else_expr_num == -1 || args[else_expr_num]->maybe_null)
2961
unsigned_flag= TRUE;
2962
if (cached_result_type == STRING_RESULT)
2964
for (uint i= 0; i < ncases; i+= 2)
2965
agg_str_lengths(args[i + 1]);
2966
if (else_expr_num != -1)
2967
agg_str_lengths(args[else_expr_num]);
2971
for (uint i= 0; i < ncases; i+= 2)
2972
agg_num_lengths(args[i + 1]);
2973
if (else_expr_num != -1)
2974
agg_num_lengths(args[else_expr_num]);
2975
max_length= my_decimal_precision_to_length_no_truncation(max_length +
2982
uint Item_func_case::decimal_precision() const
2985
for (uint i=0 ; i < ncases ; i+=2)
2986
set_if_bigger(max_int_part, args[i+1]->decimal_int_part());
2988
if (else_expr_num != -1)
2989
set_if_bigger(max_int_part, args[else_expr_num]->decimal_int_part());
2990
return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
2996
Fix this so that it prints the whole CASE expression
2999
void Item_func_case::print(String *str, enum_query_type query_type)
3001
str->append(STRING_WITH_LEN("(case "));
3002
if (first_expr_num != -1)
3004
args[first_expr_num]->print(str, query_type);
3007
for (uint i=0 ; i < ncases ; i+=2)
3009
str->append(STRING_WITH_LEN("when "));
3010
args[i]->print(str, query_type);
3011
str->append(STRING_WITH_LEN(" then "));
3012
args[i+1]->print(str, query_type);
3015
if (else_expr_num != -1)
3017
str->append(STRING_WITH_LEN("else "));
3018
args[else_expr_num]->print(str, query_type);
3021
str->append(STRING_WITH_LEN("end)"));
3025
void Item_func_case::cleanup()
3028
DBUG_ENTER("Item_func_case::cleanup");
3029
Item_func::cleanup();
3030
for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
3032
delete cmp_items[i];
3040
Coalesce - return first not NULL argument.
3043
String *Item_func_coalesce::str_op(String *str)
3045
DBUG_ASSERT(fixed == 1);
3047
for (uint i=0 ; i < arg_count ; i++)
3050
if ((res=args[i]->val_str(str)))
3057
longlong Item_func_coalesce::int_op()
3059
DBUG_ASSERT(fixed == 1);
3061
for (uint i=0 ; i < arg_count ; i++)
3063
longlong res=args[i]->val_int();
3064
if (!args[i]->null_value)
3071
double Item_func_coalesce::real_op()
3073
DBUG_ASSERT(fixed == 1);
3075
for (uint i=0 ; i < arg_count ; i++)
3077
double res= args[i]->val_real();
3078
if (!args[i]->null_value)
3086
my_decimal *Item_func_coalesce::decimal_op(my_decimal *decimal_value)
3088
DBUG_ASSERT(fixed == 1);
3090
for (uint i= 0; i < arg_count; i++)
3092
my_decimal *res= args[i]->val_decimal(decimal_value);
3093
if (!args[i]->null_value)
3101
void Item_func_coalesce::fix_length_and_dec()
3103
cached_field_type= agg_field_type(args, arg_count);
3104
agg_result_type(&hybrid_type, args, arg_count);
3105
switch (hybrid_type) {
3107
count_only_length();
3108
decimals= NOT_FIXED_DEC;
3109
agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1);
3111
case DECIMAL_RESULT:
3112
count_decimal_length();
3115
count_real_length();
3118
count_only_length();
3127
/****************************************************************************
3128
Classes and function for the IN operator
3129
****************************************************************************/
3132
Determine which of the signed longlong arguments is bigger
3137
b_val right argument
3140
This function will compare two signed longlong arguments
3141
and will return -1, 0, or 1 if left argument is smaller than,
3142
equal to or greater than the right argument.
3145
-1 left argument is smaller than the right argument.
3146
0 left argument is equal to the right argument.
3147
1 left argument is greater than the right argument.
3149
static inline int cmp_longs (longlong a_val, longlong b_val)
3151
return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3156
Determine which of the unsigned longlong arguments is bigger
3161
b_val right argument
3164
This function will compare two unsigned longlong arguments
3165
and will return -1, 0, or 1 if left argument is smaller than,
3166
equal to or greater than the right argument.
3169
-1 left argument is smaller than the right argument.
3170
0 left argument is equal to the right argument.
3171
1 left argument is greater than the right argument.
3173
static inline int cmp_ulongs (ulonglong a_val, ulonglong b_val)
3175
return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3180
Compare two integers in IN value list format (packed_longlong)
3184
cmp_arg an argument passed to the calling function (my_qsort2)
3189
This function will compare two integer arguments in the IN value list
3190
format and will return -1, 0, or 1 if left argument is smaller than,
3191
equal to or greater than the right argument.
3192
It's used in sorting the IN values list and finding an element in it.
3193
Depending on the signedness of the arguments cmp_longlong() will
3194
compare them as either signed (using cmp_longs()) or unsigned (using
3198
-1 left argument is smaller than the right argument.
3199
0 left argument is equal to the right argument.
3200
1 left argument is greater than the right argument.
3202
int cmp_longlong(void *cmp_arg,
3203
in_longlong::packed_longlong *a,
3204
in_longlong::packed_longlong *b)
3206
if (a->unsigned_flag != b->unsigned_flag)
3209
One of the args is unsigned and is too big to fit into the
3210
positive signed range. Report no match.
3212
if ((a->unsigned_flag && ((ulonglong) a->val) > (ulonglong) LONGLONG_MAX) ||
3213
(b->unsigned_flag && ((ulonglong) b->val) > (ulonglong) LONGLONG_MAX))
3214
return a->unsigned_flag ? 1 : -1;
3216
Although the signedness differs both args can fit into the signed
3217
positive range. Make them signed and compare as usual.
3219
return cmp_longs (a->val, b->val);
3221
if (a->unsigned_flag)
3222
return cmp_ulongs ((ulonglong) a->val, (ulonglong) b->val);
3224
return cmp_longs (a->val, b->val);
3227
static int cmp_double(void *cmp_arg, double *a,double *b)
3229
return *a < *b ? -1 : *a == *b ? 0 : 1;
3232
static int cmp_row(void *cmp_arg, cmp_item_row *a, cmp_item_row *b)
3234
return a->compare(b);
3238
static int cmp_decimal(void *cmp_arg, my_decimal *a, my_decimal *b)
3241
We need call of fixing buffer pointer, because fast sort just copy
3242
decimal buffers in memory and pointers left pointing on old buffer place
3244
a->fix_buffer_pointer();
3245
b->fix_buffer_pointer();
3246
return my_decimal_cmp(a, b);
3250
int in_vector::find(Item *item)
3252
uchar *result=get_value(item);
3253
if (!result || !used_count)
3254
return 0; // Null value
3257
start=0; end=used_count-1;
3258
while (start != end)
3260
uint mid=(start+end+1)/2;
3262
if ((res=(*compare)(collation, base+mid*size, result)) == 0)
3269
return (int) ((*compare)(collation, base+start*size, result) == 0);
3272
in_string::in_string(uint elements,qsort2_cmp cmp_func, CHARSET_INFO *cs)
3273
:in_vector(elements, sizeof(String), cmp_func, cs),
3274
tmp(buff, sizeof(buff), &my_charset_bin)
3277
in_string::~in_string()
3281
// base was allocated with help of sql_alloc => following is OK
3282
for (uint i=0 ; i < count ; i++)
3283
((String*) base)[i].free();
3287
void in_string::set(uint pos,Item *item)
3289
String *str=((String*) base)+pos;
3290
String *res=item->val_str(str);
3291
if (res && res != str)
3293
if (res->uses_buffer_owned_by(str))
3295
if (item->type() == Item::FUNC_ITEM)
3300
if (!str->charset())
3303
if (!(cs= item->collation.collation))
3304
cs= &my_charset_bin; // Should never happen for STR items
3305
str->set_charset(cs);
3310
uchar *in_string::get_value(Item *item)
3312
return (uchar*) item->val_str(&tmp);
3315
in_row::in_row(uint elements, Item * item)
3317
base= (char*) new cmp_item_row[count= elements];
3318
size= sizeof(cmp_item_row);
3319
compare= (qsort2_cmp) cmp_row;
3321
We need to reset these as otherwise we will call sort() with
3322
uninitialized (even if not used) elements
3324
used_count= elements;
3331
delete [] (cmp_item_row*) base;
3334
uchar *in_row::get_value(Item *item)
3336
tmp.store_value(item);
3337
if (item->is_null())
3339
return (uchar *)&tmp;
3342
void in_row::set(uint pos, Item *item)
3344
DBUG_ENTER("in_row::set");
3345
DBUG_PRINT("enter", ("pos: %u item: 0x%lx", pos, (ulong) item));
3346
((cmp_item_row*) base)[pos].store_value_by_template(&tmp, item);
3350
in_longlong::in_longlong(uint elements)
3351
:in_vector(elements,sizeof(packed_longlong),(qsort2_cmp) cmp_longlong, 0)
3354
void in_longlong::set(uint pos,Item *item)
3356
struct packed_longlong *buff= &((packed_longlong*) base)[pos];
3358
buff->val= item->val_int();
3359
buff->unsigned_flag= item->unsigned_flag;
3362
uchar *in_longlong::get_value(Item *item)
3364
tmp.val= item->val_int();
3365
if (item->null_value)
3367
tmp.unsigned_flag= item->unsigned_flag;
3368
return (uchar*) &tmp;
3371
void in_datetime::set(uint pos,Item *item)
3373
Item **tmp_item= &item;
3375
struct packed_longlong *buff= &((packed_longlong*) base)[pos];
3377
buff->val= get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null);
3378
buff->unsigned_flag= 1L;
3381
uchar *in_datetime::get_value(Item *item)
3384
Item **tmp_item= lval_cache ? &lval_cache : &item;
3385
tmp.val= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null);
3386
if (item->null_value)
3388
tmp.unsigned_flag= 1L;
3389
return (uchar*) &tmp;
3392
in_double::in_double(uint elements)
3393
:in_vector(elements,sizeof(double),(qsort2_cmp) cmp_double, 0)
3396
void in_double::set(uint pos,Item *item)
3398
((double*) base)[pos]= item->val_real();
3401
uchar *in_double::get_value(Item *item)
3403
tmp= item->val_real();
3404
if (item->null_value)
3405
return 0; /* purecov: inspected */
3406
return (uchar*) &tmp;
3410
in_decimal::in_decimal(uint elements)
3411
:in_vector(elements, sizeof(my_decimal),(qsort2_cmp) cmp_decimal, 0)
3415
void in_decimal::set(uint pos, Item *item)
3417
/* as far as 'item' is constant, we can store reference on my_decimal */
3418
my_decimal *dec= ((my_decimal *)base) + pos;
3419
dec->len= DECIMAL_BUFF_LENGTH;
3420
dec->fix_buffer_pointer();
3421
my_decimal *res= item->val_decimal(dec);
3422
/* if item->val_decimal() is evaluated to NULL then res == 0 */
3423
if (!item->null_value && res != dec)
3424
my_decimal2decimal(res, dec);
3428
uchar *in_decimal::get_value(Item *item)
3430
my_decimal *result= item->val_decimal(&val);
3431
if (item->null_value)
3433
return (uchar *)result;
3437
cmp_item* cmp_item::get_comparator(Item_result type,
3442
return new cmp_item_sort_string(cs);
3444
return new cmp_item_int;
3446
return new cmp_item_real;
3448
return new cmp_item_row;
3449
case DECIMAL_RESULT:
3450
return new cmp_item_decimal;
3455
return 0; // to satisfy compiler :)
3459
cmp_item* cmp_item_sort_string::make_same()
3461
return new cmp_item_sort_string_in_static(cmp_charset);
3464
cmp_item* cmp_item_int::make_same()
3466
return new cmp_item_int();
3469
cmp_item* cmp_item_real::make_same()
3471
return new cmp_item_real();
3474
cmp_item* cmp_item_row::make_same()
3476
return new cmp_item_row();
3480
cmp_item_row::~cmp_item_row()
3482
DBUG_ENTER("~cmp_item_row");
3483
DBUG_PRINT("enter",("this: 0x%lx", (long) this));
3486
for (uint i= 0; i < n; i++)
3489
delete comparators[i];
3496
void cmp_item_row::alloc_comparators()
3499
comparators= (cmp_item **) current_thd->calloc(sizeof(cmp_item *)*n);
3503
void cmp_item_row::store_value(Item *item)
3505
DBUG_ENTER("cmp_item_row::store_value");
3507
alloc_comparators();
3510
item->bring_value();
3511
item->null_value= 0;
3512
for (uint i=0; i < n; i++)
3514
if (!comparators[i])
3515
if (!(comparators[i]=
3516
cmp_item::get_comparator(item->element_index(i)->result_type(),
3517
item->element_index(i)->collation.collation)))
3518
break; // new failed
3519
comparators[i]->store_value(item->element_index(i));
3520
item->null_value|= item->element_index(i)->null_value;
3527
void cmp_item_row::store_value_by_template(cmp_item *t, Item *item)
3529
cmp_item_row *tmpl= (cmp_item_row*) t;
3530
if (tmpl->n != item->cols())
3532
my_error(ER_OPERAND_COLUMNS, MYF(0), tmpl->n);
3536
if ((comparators= (cmp_item **) sql_alloc(sizeof(cmp_item *)*n)))
3538
item->bring_value();
3539
item->null_value= 0;
3540
for (uint i=0; i < n; i++)
3542
if (!(comparators[i]= tmpl->comparators[i]->make_same()))
3543
break; // new failed
3544
comparators[i]->store_value_by_template(tmpl->comparators[i],
3545
item->element_index(i));
3546
item->null_value|= item->element_index(i)->null_value;
3552
int cmp_item_row::cmp(Item *arg)
3555
if (arg->cols() != n)
3557
my_error(ER_OPERAND_COLUMNS, MYF(0), n);
3562
for (uint i=0; i < n; i++)
3564
if (comparators[i]->cmp(arg->element_index(i)))
3566
if (!arg->element_index(i)->null_value)
3571
return (arg->null_value= was_null);
3575
int cmp_item_row::compare(cmp_item *c)
3577
cmp_item_row *l_cmp= (cmp_item_row *) c;
3578
for (uint i=0; i < n; i++)
3581
if ((res= comparators[i]->compare(l_cmp->comparators[i])))
3588
void cmp_item_decimal::store_value(Item *item)
3590
my_decimal *val= item->val_decimal(&value);
3591
/* val may be zero if item is nnull */
3592
if (val && val != &value)
3593
my_decimal2decimal(val, &value);
3597
int cmp_item_decimal::cmp(Item *arg)
3599
my_decimal tmp_buf, *tmp= arg->val_decimal(&tmp_buf);
3600
if (arg->null_value)
3602
return my_decimal_cmp(&value, tmp);
3606
int cmp_item_decimal::compare(cmp_item *arg)
3608
cmp_item_decimal *l_cmp= (cmp_item_decimal*) arg;
3609
return my_decimal_cmp(&value, &l_cmp->value);
3613
cmp_item* cmp_item_decimal::make_same()
3615
return new cmp_item_decimal();
3619
void cmp_item_datetime::store_value(Item *item)
3622
Item **tmp_item= lval_cache ? &lval_cache : &item;
3623
value= get_datetime_value(thd, &tmp_item, &lval_cache, warn_item, &is_null);
3627
int cmp_item_datetime::cmp(Item *arg)
3630
Item **tmp_item= &arg;
3632
get_datetime_value(thd, &tmp_item, 0, warn_item, &is_null);
3636
int cmp_item_datetime::compare(cmp_item *ci)
3638
cmp_item_datetime *l_cmp= (cmp_item_datetime *)ci;
3639
return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1);
3643
cmp_item *cmp_item_datetime::make_same()
3645
return new cmp_item_datetime(warn_item);
3649
bool Item_func_in::nulls_in_row()
3651
Item **arg,**arg_end;
3652
for (arg= args+1, arg_end= args+arg_count; arg != arg_end ; arg++)
3654
if ((*arg)->null_inside())
3662
Perform context analysis of an IN item tree.
3664
This function performs context analysis (name resolution) and calculates
3665
various attributes of the item tree with Item_func_in as its root.
3666
The function saves in ref the pointer to the item or to a newly created
3667
item that is considered as a replacement for the original one.
3669
@param thd reference to the global context of the query thread
3670
@param ref pointer to Item* variable where pointer to resulting "fixed"
3671
item is to be assigned
3674
Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
3675
a predicate/function level. Then it's easy to show that:
3677
T0(e IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
3678
T1(e IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
3679
T0(e NOT IN(e1,...,en)) = union(T1(e),union(T1(ei)))
3680
T1(e NOT IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
3690
Item_func_in::fix_fields(THD *thd, Item **ref)
3692
Item **arg, **arg_end;
3694
if (Item_func_opt_neg::fix_fields(thd, ref))
3697
/* not_null_tables_cache == union(T1(e),union(T1(ei))) */
3698
if (pred_level && negated)
3701
/* not_null_tables_cache = union(T1(e),intersection(T1(ei))) */
3702
not_null_tables_cache= ~(table_map) 0;
3703
for (arg= args + 1, arg_end= args + arg_count; arg != arg_end; arg++)
3704
not_null_tables_cache&= (*arg)->not_null_tables();
3705
not_null_tables_cache|= (*args)->not_null_tables();
3710
static int srtcmp_in(CHARSET_INFO *cs, const String *x,const String *y)
3712
return cs->coll->strnncollsp(cs,
3713
(uchar *) x->ptr(),x->length(),
3714
(uchar *) y->ptr(),y->length(), 0);
3718
void Item_func_in::fix_length_and_dec()
3720
Item **arg, **arg_end;
3722
THD *thd= current_thd;
3723
bool datetime_found= FALSE;
3724
/* TRUE <=> arguments values will be compared as DATETIMEs. */
3725
bool compare_as_datetime= FALSE;
3727
uint found_types= 0;
3728
uint type_cnt= 0, i;
3729
Item_result cmp_type= STRING_RESULT;
3730
left_result_type= args[0]->result_type();
3731
if (!(found_types= collect_cmp_types(args, arg_count, true)))
3734
for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
3736
if (!arg[0]->const_item())
3742
for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
3744
if (found_types & 1 << i)
3747
cmp_type= (Item_result) i;
3753
if (cmp_type == STRING_RESULT &&
3754
agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1))
3756
arg_types_compatible= TRUE;
3761
When comparing rows create the row comparator object beforehand to ease
3762
the DATETIME comparison detection procedure.
3764
if (cmp_type == ROW_RESULT)
3766
cmp_item_row *cmp= 0;
3767
if (const_itm && !nulls_in_row())
3769
array= new in_row(arg_count-1, 0);
3770
cmp= &((in_row*)array)->tmp;
3774
if (!(cmp= new cmp_item_row))
3776
cmp_items[ROW_RESULT]= cmp;
3778
cmp->n= args[0]->cols();
3779
cmp->alloc_comparators();
3781
/* All DATE/DATETIME fields/functions has the STRING result type. */
3782
if (cmp_type == STRING_RESULT || cmp_type == ROW_RESULT)
3784
uint col, cols= args[0]->cols();
3786
for (col= 0; col < cols; col++)
3788
bool skip_column= FALSE;
3790
Check that all items to be compared has the STRING result type and at
3791
least one of them is a DATE/DATETIME item.
3793
for (arg= args, arg_end= args + arg_count; arg != arg_end ; arg++)
3795
Item *itm= ((cmp_type == STRING_RESULT) ? arg[0] :
3796
arg[0]->element_index(col));
3797
if (itm->result_type() != STRING_RESULT)
3802
else if (itm->is_datetime())
3804
datetime_found= TRUE;
3806
Internally all DATE/DATETIME values are converted to the DATETIME
3807
type. So try to find a DATETIME item to issue correct warnings.
3811
else if (itm->field_type() == MYSQL_TYPE_DATETIME)
3814
/* All arguments are already checked to have the STRING result. */
3815
if (cmp_type == STRING_RESULT)
3824
if (cmp_type == ROW_RESULT)
3828
cmp= ((in_row*)array)->tmp.comparators + col;
3830
cmp= ((cmp_item_row*)cmp_items[ROW_RESULT])->comparators + col;
3831
*cmp= new cmp_item_datetime(date_arg);
3832
/* Reset variables for the next column. */
3834
datetime_found= FALSE;
3837
compare_as_datetime= TRUE;
3843
Row item with NULLs inside can return NULL or FALSE =>
3844
they can't be processed as static
3846
if (type_cnt == 1 && const_itm && !nulls_in_row())
3848
if (compare_as_datetime)
3849
array= new in_datetime(date_arg, arg_count - 1);
3853
IN must compare INT columns and constants as int values (the same
3854
way as equality does).
3855
So we must check here if the column on the left and all the constant
3856
values on the right can be compared as integers and adjust the
3857
comparison type accordingly.
3859
if (args[0]->real_item()->type() == FIELD_ITEM &&
3860
thd->lex->sql_command != SQLCOM_CREATE_VIEW &&
3861
thd->lex->sql_command != SQLCOM_SHOW_CREATE &&
3862
cmp_type != INT_RESULT)
3864
Item_field *field_item= (Item_field*) (args[0]->real_item());
3865
if (field_item->field->can_be_compared_as_longlong())
3867
bool all_converted= TRUE;
3868
for (arg=args+1, arg_end=args+arg_count; arg != arg_end ; arg++)
3870
if (!convert_constant_item (thd, field_item, &arg[0]))
3871
all_converted= FALSE;
3874
cmp_type= INT_RESULT;
3879
array=new in_string(arg_count-1,(qsort2_cmp) srtcmp_in,
3880
cmp_collation.collation);
3883
array= new in_longlong(arg_count-1);
3886
array= new in_double(arg_count-1);
3890
The row comparator was created at the beginning but only DATETIME
3891
items comparators were initialized. Call store_value() to setup
3894
((in_row*)array)->tmp.store_value(args[0]);
3896
case DECIMAL_RESULT:
3897
array= new in_decimal(arg_count - 1);
3904
if (array && !(thd->is_fatal_error)) // If not EOM
3907
for (uint i=1 ; i < arg_count ; i++)
3909
if (!args[i]->null_value) // Skip NULL values
3911
array->set(j,args[i]);
3917
if ((array->used_count= j))
3923
if (compare_as_datetime)
3924
cmp_items[STRING_RESULT]= new cmp_item_datetime(date_arg);
3927
for (i= 0; i <= (uint) DECIMAL_RESULT; i++)
3929
if (found_types & (1 << i) && !cmp_items[i])
3931
if ((Item_result)i == STRING_RESULT &&
3932
agg_arg_charsets(cmp_collation, args, arg_count,
3933
MY_COLL_CMP_CONV, 1))
3935
if (!cmp_items[i] && !(cmp_items[i]=
3936
cmp_item::get_comparator((Item_result)i,
3937
cmp_collation.collation)))
3947
void Item_func_in::print(String *str, enum_query_type query_type)
3950
args[0]->print(str, query_type);
3952
str->append(STRING_WITH_LEN(" not"));
3953
str->append(STRING_WITH_LEN(" in ("));
3954
print_args(str, 1, query_type);
3955
str->append(STRING_WITH_LEN("))"));
3960
Evaluate the function and return its value.
3966
Evaluate the function and return its value.
3969
If the array object is defined then the value of the function is
3970
calculated by means of this array.
3971
Otherwise several cmp_item objects are used in order to do correct
3972
comparison of left expression and an expression from the values list.
3973
One cmp_item object correspond to one used comparison type. Left
3974
expression can be evaluated up to number of different used comparison
3975
types. A bit mapped variable value_added_map is used to check whether
3976
the left expression already was evaluated for a particular result type.
3977
Result types are mapped to it according to their integer values i.e.
3978
STRING_RESULT is mapped to bit 0, REAL_RESULT to bit 1, so on.
3981
Value of the function
3984
longlong Item_func_in::val_int()
3987
DBUG_ASSERT(fixed == 1);
3988
uint value_added_map= 0;
3991
int tmp=array->find(args[0]);
3992
null_value=args[0]->null_value || (!tmp && have_null);
3993
return (longlong) (!null_value && tmp != negated);
3997
for (uint i= 1 ; i < arg_count ; i++)
3999
Item_result cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
4000
in_item= cmp_items[(uint)cmp_type];
4001
DBUG_ASSERT(in_item);
4002
if (!(value_added_map & (1 << (uint)cmp_type)))
4004
in_item->store_value(args[0]);
4005
if ((null_value= args[0]->null_value))
4007
value_added_map|= 1 << (uint)cmp_type;
4009
if (!in_item->cmp(args[i]) && !args[i]->null_value)
4010
return (longlong) (!negated);
4011
have_null|= args[i]->null_value;
4014
null_value= have_null;
4015
return (longlong) (!null_value && negated);
4019
longlong Item_func_bit_or::val_int()
4021
DBUG_ASSERT(fixed == 1);
4022
ulonglong arg1= (ulonglong) args[0]->val_int();
4023
if (args[0]->null_value)
4025
null_value=1; /* purecov: inspected */
4026
return 0; /* purecov: inspected */
4028
ulonglong arg2= (ulonglong) args[1]->val_int();
4029
if (args[1]->null_value)
4035
return (longlong) (arg1 | arg2);
4039
longlong Item_func_bit_and::val_int()
4041
DBUG_ASSERT(fixed == 1);
4042
ulonglong arg1= (ulonglong) args[0]->val_int();
4043
if (args[0]->null_value)
4045
null_value=1; /* purecov: inspected */
4046
return 0; /* purecov: inspected */
4048
ulonglong arg2= (ulonglong) args[1]->val_int();
4049
if (args[1]->null_value)
4051
null_value=1; /* purecov: inspected */
4052
return 0; /* purecov: inspected */
4055
return (longlong) (arg1 & arg2);
4058
Item_cond::Item_cond(THD *thd, Item_cond *item)
4059
:Item_bool_func(thd, item),
4060
abort_on_null(item->abort_on_null),
4061
and_tables_cache(item->and_tables_cache)
4064
item->list will be copied by copy_andor_arguments() call
4069
void Item_cond::copy_andor_arguments(THD *thd, Item_cond *item)
4071
List_iterator_fast<Item> li(item->list);
4072
while (Item *it= li++)
4073
list.push_back(it->copy_andor_structure(thd));
4078
Item_cond::fix_fields(THD *thd, Item **ref)
4080
DBUG_ASSERT(fixed == 0);
4081
List_iterator<Item> li(list);
4083
#ifndef EMBEDDED_LIBRARY
4084
uchar buff[sizeof(char*)]; // Max local vars in function
4086
not_null_tables_cache= used_tables_cache= 0;
4087
const_item_cache= 1;
4089
and_table_cache is the value that Item_cond_or() returns for
4092
and_tables_cache= ~(table_map) 0;
4094
if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
4095
return TRUE; // Fatal error flag is set!
4097
The following optimization reduces the depth of an AND-OR tree.
4098
E.g. a WHERE clause like
4099
F1 AND (F2 AND (F2 AND F4))
4100
is parsed into a tree with the same nested structure as defined
4101
by braces. This optimization will transform such tree into
4102
AND (F1, F2, F3, F4).
4103
Trees of OR items are flattened as well:
4104
((F1 OR F2) OR (F3 OR F4)) => OR (F1, F2, F3, F4)
4105
Items for removed AND/OR levels will dangle until the death of the
4107
The optimization is currently prepared statements and stored procedures
4108
friendly as it doesn't allocate any memory and its effects are durable
4109
(i.e. do not depend on PS/SP arguments).
4113
table_map tmp_table_map;
4114
while (item->type() == Item::COND_ITEM &&
4115
((Item_cond*) item)->functype() == functype() &&
4116
!((Item_cond*) item)->list.is_empty())
4117
{ // Identical function
4118
li.replace(((Item_cond*) item)->list);
4119
((Item_cond*) item)->list.empty();
4120
item= *li.ref(); // new current item
4123
item->top_level_item();
4125
// item can be substituted in fix_fields
4126
if ((!item->fixed &&
4127
item->fix_fields(thd, li.ref())) ||
4128
(item= *li.ref())->check_cols(1))
4129
return TRUE; /* purecov: inspected */
4130
used_tables_cache|= item->used_tables();
4131
if (item->const_item())
4132
and_tables_cache= (table_map) 0;
4135
tmp_table_map= item->not_null_tables();
4136
not_null_tables_cache|= tmp_table_map;
4137
and_tables_cache&= tmp_table_map;
4138
const_item_cache= FALSE;
4140
with_sum_func= with_sum_func || item->with_sum_func;
4141
with_subselect|= item->with_subselect;
4142
if (item->maybe_null)
4145
thd->lex->current_select->cond_count+= list.elements;
4146
fix_length_and_dec();
4151
bool Item_cond::walk(Item_processor processor, bool walk_subquery, uchar *arg)
4153
List_iterator_fast<Item> li(list);
4155
while ((item= li++))
4156
if (item->walk(processor, walk_subquery, arg))
4158
return Item_func::walk(processor, walk_subquery, arg);
4163
Transform an Item_cond object with a transformer callback function.
4165
The function recursively applies the transform method to each
4166
member item of the condition list.
4167
If the call of the method for a member item returns a new item
4168
the old item is substituted for a new one.
4169
After this the transformer is applied to the root node
4170
of the Item_cond object.
4172
@param transformer the transformer callback function to be applied to
4173
the nodes of the tree of the object
4174
@param arg parameter to be passed to the transformer
4177
Item returned as the result of transformation of the root node
4180
Item *Item_cond::transform(Item_transformer transformer, uchar *arg)
4182
DBUG_ASSERT(!current_thd->is_stmt_prepare());
4184
List_iterator<Item> li(list);
4186
while ((item= li++))
4188
Item *new_item= item->transform(transformer, arg);
4193
THD::change_item_tree() should be called only if the tree was
4194
really transformed, i.e. when a new item has been created.
4195
Otherwise we'll be allocating a lot of unnecessary memory for
4196
change records at each execution.
4198
if (new_item != item)
4199
current_thd->change_item_tree(li.ref(), new_item);
4201
return Item_func::transform(transformer, arg);
4206
Compile Item_cond object with a processor and a transformer
4209
First the function applies the analyzer to the root node of
4210
the Item_func object. Then if the analyzer succeeeds (returns TRUE)
4211
the function recursively applies the compile method to member
4212
item of the condition list.
4213
If the call of the method for a member item returns a new item
4214
the old item is substituted for a new one.
4215
After this the transformer is applied to the root node
4216
of the Item_cond object.
4218
@param analyzer the analyzer callback function to be applied to the
4219
nodes of the tree of the object
4220
@param[in,out] arg_p parameter to be passed to the analyzer
4221
@param transformer the transformer callback function to be applied to the
4222
nodes of the tree of the object
4223
@param arg_t parameter to be passed to the transformer
4226
Item returned as the result of transformation of the root node
4229
Item *Item_cond::compile(Item_analyzer analyzer, uchar **arg_p,
4230
Item_transformer transformer, uchar *arg_t)
4232
if (!(this->*analyzer)(arg_p))
4235
List_iterator<Item> li(list);
4237
while ((item= li++))
4240
The same parameter value of arg_p must be passed
4241
to analyze any argument of the condition formula.
4243
uchar *arg_v= *arg_p;
4244
Item *new_item= item->compile(analyzer, &arg_v, transformer, arg_t);
4245
if (new_item && new_item != item)
4246
current_thd->change_item_tree(li.ref(), new_item);
4248
return Item_func::transform(transformer, arg_t);
4251
void Item_cond::traverse_cond(Cond_traverser traverser,
4252
void *arg, traverse_order order)
4254
List_iterator<Item> li(list);
4259
(*traverser)(this, arg);
4260
while ((item= li++))
4262
item->traverse_cond(traverser, arg, order);
4264
(*traverser)(NULL, arg);
4267
while ((item= li++))
4269
item->traverse_cond(traverser, arg, order);
4271
(*traverser)(this, arg);
4276
Move SUM items out from item tree and replace with reference.
4278
The split is done to get an unique item for each SUM function
4279
so that we can easily find and calculate them.
4280
(Calculation done by update_sum_func() and copy_sum_funcs() in
4283
@param thd Thread handler
4284
@param ref_pointer_array Pointer to array of reference fields
4285
@param fields All fields in select
4288
This function is run on all expression (SELECT list, WHERE, HAVING etc)
4289
that have or refer (HAVING) to a SUM expression.
4292
void Item_cond::split_sum_func(THD *thd, Item **ref_pointer_array,
4295
List_iterator<Item> li(list);
4297
while ((item= li++))
4298
item->split_sum_func2(thd, ref_pointer_array, fields, li.ref(), TRUE);
4303
Item_cond::used_tables() const
4304
{ // This caches used_tables
4305
return used_tables_cache;
4309
void Item_cond::update_used_tables()
4311
List_iterator_fast<Item> li(list);
4314
used_tables_cache=0;
4318
item->update_used_tables();
4319
used_tables_cache|= item->used_tables();
4320
const_item_cache&= item->const_item();
4325
void Item_cond::print(String *str, enum_query_type query_type)
4328
List_iterator_fast<Item> li(list);
4331
item->print(str, query_type);
4335
str->append(func_name());
4337
item->print(str, query_type);
4343
void Item_cond::neg_arguments(THD *thd)
4345
List_iterator<Item> li(list);
4347
while ((item= li++)) /* Apply not transformation to the arguments */
4349
Item *new_item= item->neg_transformer(thd);
4352
if (!(new_item= new Item_func_not(item)))
4353
return; // Fatal OEM error
4355
VOID(li.replace(new_item));
4361
Evaluation of AND(expr, expr, expr ...).
4364
abort_if_null is set for AND expressions for which we don't care if the
4365
result is NULL or 0. This is set for:
4371
1 If all expressions are true
4373
0 If all expressions are false or if we find a NULL expression and
4374
'abort_on_null' is set.
4376
NULL if all expression are either 1 or NULL
4380
longlong Item_cond_and::val_int()
4382
DBUG_ASSERT(fixed == 1);
4383
List_iterator_fast<Item> li(list);
4388
if (!item->val_bool())
4390
if (abort_on_null || !(null_value= item->null_value))
4391
return 0; // return FALSE
4394
return null_value ? 0 : 1;
4398
longlong Item_cond_or::val_int()
4400
DBUG_ASSERT(fixed == 1);
4401
List_iterator_fast<Item> li(list);
4406
if (item->val_bool())
4411
if (item->null_value)
4418
Create an AND expression from two expressions.
4420
@param a expression or NULL
4421
@param b expression.
4422
@param org_item Don't modify a if a == *org_item.
4423
If a == NULL, org_item is set to point at b,
4424
to ensure that future calls will not modify b.
4427
This will not modify item pointed to by org_item or b
4428
The idea is that one can call this in a loop and create and
4429
'and' over all items without modifying any of the original items.
4437
Item *and_expressions(Item *a, Item *b, Item **org_item)
4440
return (*org_item= (Item*) b);
4444
if ((res= new Item_cond_and(a, (Item*) b)))
4446
res->used_tables_cache= a->used_tables() | b->used_tables();
4447
res->not_null_tables_cache= a->not_null_tables() | b->not_null_tables();
4451
if (((Item_cond_and*) a)->add((Item*) b))
4453
((Item_cond_and*) a)->used_tables_cache|= b->used_tables();
4454
((Item_cond_and*) a)->not_null_tables_cache|= b->not_null_tables();
4459
longlong Item_func_isnull::val_int()
4461
DBUG_ASSERT(fixed == 1);
4463
Handle optimization if the argument can't be null
4464
This has to be here because of the test in update_used_tables().
4466
if (!used_tables_cache && !with_subselect)
4467
return cached_value;
4468
return args[0]->is_null() ? 1: 0;
4471
longlong Item_is_not_null_test::val_int()
4473
DBUG_ASSERT(fixed == 1);
4474
DBUG_ENTER("Item_is_not_null_test::val_int");
4475
if (!used_tables_cache && !with_subselect)
4477
owner->was_null|= (!cached_value);
4478
DBUG_PRINT("info", ("cached: %ld", (long) cached_value));
4479
DBUG_RETURN(cached_value);
4481
if (args[0]->is_null())
4483
DBUG_PRINT("info", ("null"));
4484
owner->was_null|= 1;
4492
Optimize case of not_null_column IS NULL.
4494
void Item_is_not_null_test::update_used_tables()
4496
if (!args[0]->maybe_null)
4498
used_tables_cache= 0; /* is always true */
4499
cached_value= (longlong) 1;
4503
args[0]->update_used_tables();
4504
if (!(used_tables_cache=args[0]->used_tables()) && !with_subselect)
4506
/* Remember if the value is always NULL or never NULL */
4507
cached_value= (longlong) !args[0]->is_null();
4513
longlong Item_func_isnotnull::val_int()
4515
DBUG_ASSERT(fixed == 1);
4516
return args[0]->is_null() ? 0 : 1;
4520
void Item_func_isnotnull::print(String *str, enum_query_type query_type)
4523
args[0]->print(str, query_type);
4524
str->append(STRING_WITH_LEN(" is not null)"));
4528
longlong Item_func_like::val_int()
4530
DBUG_ASSERT(fixed == 1);
4531
String* res = args[0]->val_str(&cmp.value1);
4532
if (args[0]->null_value)
4537
String* res2 = args[1]->val_str(&cmp.value2);
4538
if (args[1]->null_value)
4545
return turboBM_matches(res->ptr(), res->length()) ? 1 : 0;
4546
return my_wildcmp(cmp.cmp_collation.collation,
4547
res->ptr(),res->ptr()+res->length(),
4548
res2->ptr(),res2->ptr()+res2->length(),
4549
escape,wild_one,wild_many) ? 0 : 1;
4554
We can optimize a where if first character isn't a wildcard
4557
Item_func::optimize_type Item_func_like::select_optimize() const
4559
if (args[1]->const_item())
4561
String* res2= args[1]->val_str((String *)&cmp.value2);
4564
return OPTIMIZE_NONE;
4566
if (*res2->ptr() != wild_many)
4568
if (args[0]->result_type() != STRING_RESULT || *res2->ptr() != wild_one)
4572
return OPTIMIZE_NONE;
4576
bool Item_func_like::fix_fields(THD *thd, Item **ref)
4578
DBUG_ASSERT(fixed == 0);
4579
if (Item_bool_func2::fix_fields(thd, ref) ||
4580
escape_item->fix_fields(thd, &escape_item))
4583
if (!escape_item->const_during_execution())
4585
my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
4589
if (escape_item->const_item())
4591
/* If we are on execution stage */
4592
String *escape_str= escape_item->val_str(&cmp.value1);
4595
if (escape_used_in_parsing && (
4596
(((thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
4597
escape_str->numchars() != 1) ||
4598
escape_str->numchars() > 1)))
4600
my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
4604
if (use_mb(cmp.cmp_collation.collation))
4606
CHARSET_INFO *cs= escape_str->charset();
4608
int rc= cs->cset->mb_wc(cs, &wc,
4609
(const uchar*) escape_str->ptr(),
4610
(const uchar*) escape_str->ptr() +
4611
escape_str->length());
4612
escape= (int) (rc > 0 ? wc : '\\');
4617
In the case of 8bit character set, we pass native
4618
code instead of Unicode code as "escape" argument.
4619
Convert to "cs" if charset of escape differs.
4621
CHARSET_INFO *cs= cmp.cmp_collation.collation;
4623
if (escape_str->needs_conversion(escape_str->length(),
4624
escape_str->charset(), cs, &unused))
4628
uint32 cnvlen= copy_and_convert(&ch, 1, cs, escape_str->ptr(),
4629
escape_str->length(),
4630
escape_str->charset(), &errors);
4631
escape= cnvlen ? ch : '\\';
4634
escape= *(escape_str->ptr());
4641
We could also do boyer-more for non-const items, but as we would have to
4642
recompute the tables for each row it's not worth it.
4644
if (args[1]->const_item() && !use_strnxfrm(collation.collation) &&
4645
!(specialflag & SPECIAL_NO_NEW_FUNC))
4647
String* res2 = args[1]->val_str(&cmp.value2);
4649
return FALSE; // Null argument
4651
const size_t len = res2->length();
4652
const char* first = res2->ptr();
4653
const char* last = first + len - 1;
4655
len must be > 2 ('%pattern%')
4656
heuristic: only do TurboBM for pattern_len > 2
4659
if (len > MIN_TURBOBM_PATTERN_LEN + 2 &&
4660
*first == wild_many &&
4663
const char* tmp = first + 1;
4664
for (; *tmp != wild_many && *tmp != wild_one && *tmp != escape; tmp++) ;
4665
canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation);
4669
pattern = first + 1;
4670
pattern_len = (int) len - 2;
4671
DBUG_PRINT("info", ("Initializing pattern: '%s'", first));
4672
int *suff = (int*) thd->alloc((int) (sizeof(int)*
4673
((pattern_len + 1)*2+
4675
bmGs = suff + pattern_len + 1;
4676
bmBc = bmGs + pattern_len + 1;
4677
turboBM_compute_good_suffix_shifts(suff);
4678
turboBM_compute_bad_character_shifts();
4679
DBUG_PRINT("info",("done"));
4686
void Item_func_like::cleanup()
4688
canDoTurboBM= FALSE;
4689
Item_bool_func2::cleanup();
4695
@brief Compile regular expression.
4697
@param[in] send_error send error message if any.
4699
@details Make necessary character set conversion then
4700
compile regular expression passed in the args[1].
4703
@retval 1 error occurred.
4704
@retval -1 given null regular expression.
4707
int Item_func_regex::regcomp(bool send_error)
4709
char buff[MAX_FIELD_WIDTH];
4710
String tmp(buff,sizeof(buff),&my_charset_bin);
4711
String *res= args[1]->val_str(&tmp);
4714
if (args[1]->null_value)
4719
if (!stringcmp(res, &prev_regexp))
4721
prev_regexp.copy(*res);
4726
if (cmp_collation.collation != regex_lib_charset)
4728
/* Convert UCS2 strings to UTF8 */
4730
if (conv.copy(res->ptr(), res->length(), res->charset(),
4731
regex_lib_charset, &dummy_errors))
4736
if ((error= my_regcomp(&preg, res->c_ptr_safe(),
4737
regex_lib_flags, regex_lib_charset)))
4741
(void) my_regerror(error, &preg, buff, sizeof(buff));
4742
my_error(ER_REGEXP_ERROR, MYF(0), buff);
4752
Item_func_regex::fix_fields(THD *thd, Item **ref)
4754
DBUG_ASSERT(fixed == 0);
4755
if ((!args[0]->fixed &&
4756
args[0]->fix_fields(thd, args)) || args[0]->check_cols(1) ||
4758
args[1]->fix_fields(thd, args + 1)) || args[1]->check_cols(1))
4759
return TRUE; /* purecov: inspected */
4760
with_sum_func=args[0]->with_sum_func || args[1]->with_sum_func;
4764
if (agg_arg_charsets(cmp_collation, args, 2, MY_COLL_CMP_CONV, 1))
4767
regex_lib_flags= (cmp_collation.collation->state &
4768
(MY_CS_BINSORT | MY_CS_CSSORT)) ?
4769
REG_EXTENDED | REG_NOSUB :
4770
REG_EXTENDED | REG_NOSUB | REG_ICASE;
4772
If the case of UCS2 and other non-ASCII character sets,
4773
we will convert patterns and strings to UTF8.
4775
regex_lib_charset= (cmp_collation.collation->mbminlen > 1) ?
4776
&my_charset_utf8_general_ci :
4777
cmp_collation.collation;
4779
used_tables_cache=args[0]->used_tables() | args[1]->used_tables();
4780
not_null_tables_cache= (args[0]->not_null_tables() |
4781
args[1]->not_null_tables());
4782
const_item_cache=args[0]->const_item() && args[1]->const_item();
4783
if (!regex_compiled && args[1]->const_item())
4785
int comp_res= regcomp(TRUE);
4787
{ // Will always return NULL
4795
maybe_null= args[0]->maybe_null;
4804
longlong Item_func_regex::val_int()
4806
DBUG_ASSERT(fixed == 1);
4807
char buff[MAX_FIELD_WIDTH];
4808
String tmp(buff,sizeof(buff),&my_charset_bin);
4809
String *res= args[0]->val_str(&tmp);
4811
if ((null_value= (args[0]->null_value ||
4812
(!regex_is_const && regcomp(FALSE)))))
4815
if (cmp_collation.collation != regex_lib_charset)
4817
/* Convert UCS2 strings to UTF8 */
4819
if (conv.copy(res->ptr(), res->length(), res->charset(),
4820
regex_lib_charset, &dummy_errors))
4827
return my_regexec(&preg,res->c_ptr_safe(),0,(my_regmatch_t*) 0,0) ? 0 : 1;
4831
void Item_func_regex::cleanup()
4833
DBUG_ENTER("Item_func_regex::cleanup");
4834
Item_bool_func::cleanup();
4839
prev_regexp.length(0);
4845
#endif /* USE_REGEX */
4848
#ifdef LIKE_CMP_TOUPPER
4849
#define likeconv(cs,A) (uchar) (cs)->toupper(A)
4851
#define likeconv(cs,A) (uchar) (cs)->sort_order[(uchar) (A)]
4856
Precomputation dependent only on pattern_len.
4859
void Item_func_like::turboBM_compute_suffixes(int *suff)
4861
const int plm1 = pattern_len - 1;
4864
int *const splm1 = suff + plm1;
4865
CHARSET_INFO *cs= cmp.cmp_collation.collation;
4867
*splm1 = pattern_len;
4869
if (!cs->sort_order)
4872
for (i = pattern_len - 2; i >= 0; i--)
4874
int tmp = *(splm1 + i - f);
4875
if (g < i && tmp < i - g)
4880
g = i; // g = min(i, g)
4882
while (g >= 0 && pattern[g] == pattern[g + plm1 - f])
4891
for (i = pattern_len - 2; 0 <= i; --i)
4893
int tmp = *(splm1 + i - f);
4894
if (g < i && tmp < i - g)
4899
g = i; // g = min(i, g)
4902
likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f]))
4912
Precomputation dependent only on pattern_len.
4915
void Item_func_like::turboBM_compute_good_suffix_shifts(int *suff)
4917
turboBM_compute_suffixes(suff);
4919
int *end = bmGs + pattern_len;
4921
for (k = bmGs; k < end; k++)
4927
const int plm1 = pattern_len - 1;
4928
for (i = plm1; i > -1; i--)
4930
if (suff[i] == i + 1)
4932
for (tmp = plm1 - i; j < tmp; j++)
4934
int *tmp2 = bmGs + j;
4935
if (*tmp2 == pattern_len)
4942
for (tmp = plm1 - i; j < tmp; j++)
4945
if (*tmp2 == pattern_len)
4950
for (i = 0; i <= pattern_len - 2; i++)
4951
*(tmp2 - suff[i]) = plm1 - i;
4956
Precomputation dependent on pattern_len.
4959
void Item_func_like::turboBM_compute_bad_character_shifts()
4962
int *end = bmBc + alphabet_size;
4964
const int plm1 = pattern_len - 1;
4965
CHARSET_INFO *cs= cmp.cmp_collation.collation;
4967
for (i = bmBc; i < end; i++)
4970
if (!cs->sort_order)
4972
for (j = 0; j < plm1; j++)
4973
bmBc[(uint) (uchar) pattern[j]] = plm1 - j;
4977
for (j = 0; j < plm1; j++)
4978
bmBc[(uint) likeconv(cs,pattern[j])] = plm1 - j;
4984
Search for pattern in text.
4987
returns true/false for match/no match
4990
bool Item_func_like::turboBM_matches(const char* text, int text_len) const
4992
register int bcShift;
4993
register int turboShift;
4994
int shift = pattern_len;
4997
CHARSET_INFO *cs= cmp.cmp_collation.collation;
4999
const int plm1= pattern_len - 1;
5000
const int tlmpl= text_len - pattern_len;
5003
if (!cs->sort_order)
5007
register int i= plm1;
5008
while (i >= 0 && pattern[i] == text[i + j])
5011
if (i == plm1 - shift)
5017
register const int v = plm1 - i;
5019
bcShift = bmBc[(uint) (uchar) text[i + j]] - plm1 + i;
5020
shift = max(turboShift, bcShift);
5021
shift = max(shift, bmGs[i]);
5022
if (shift == bmGs[i])
5023
u = min(pattern_len - shift, v);
5026
if (turboShift < bcShift)
5027
shift = max(shift, u + 1);
5038
register int i = plm1;
5039
while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
5042
if (i == plm1 - shift)
5048
register const int v = plm1 - i;
5050
bcShift = bmBc[(uint) likeconv(cs, text[i + j])] - plm1 + i;
5051
shift = max(turboShift, bcShift);
5052
shift = max(shift, bmGs[i]);
5053
if (shift == bmGs[i])
5054
u = min(pattern_len - shift, v);
5057
if (turboShift < bcShift)
5058
shift = max(shift, u + 1);
5069
Make a logical XOR of the arguments.
5071
If either operator is NULL, return NULL.
5074
(low priority) Change this to be optimized as: @n
5075
A XOR B -> (A) == 1 AND (B) <> 1) OR (A <> 1 AND (B) == 1) @n
5076
To be able to do this, we would however first have to extend the MySQL
5077
range optimizer to handle OR better.
5080
As we don't do any index optimization on XOR this is not going to be
5084
longlong Item_cond_xor::val_int()
5086
DBUG_ASSERT(fixed == 1);
5087
List_iterator<Item> li(list);
5093
result^= (item->val_int() != 0);
5094
if (item->null_value)
5100
return (longlong) result;
5104
Apply NOT transformation to the item and return a new one.
5107
Transform the item using next rules:
5109
a AND b AND ... -> NOT(a) OR NOT(b) OR ...
5110
a OR b OR ... -> NOT(a) AND NOT(b) AND ...
5118
IS NULL(a) -> IS NOT NULL(a)
5119
IS NOT NULL(a) -> IS NULL(a)
5122
@param thd thread handler
5126
NULL if we cannot apply NOT transformation (see Item::neg_transformer()).
5129
Item *Item_func_not::neg_transformer(THD *thd) /* NOT(x) -> x */
5135
Item *Item_bool_rowready_func2::neg_transformer(THD *thd)
5137
Item *item= negated_item();
5143
a IS NULL -> a IS NOT NULL.
5145
Item *Item_func_isnull::neg_transformer(THD *thd)
5147
Item *item= new Item_func_isnotnull(args[0]);
5153
a IS NOT NULL -> a IS NULL.
5155
Item *Item_func_isnotnull::neg_transformer(THD *thd)
5157
Item *item= new Item_func_isnull(args[0]);
5162
Item *Item_cond_and::neg_transformer(THD *thd) /* NOT(a AND b AND ...) -> */
5163
/* NOT a OR NOT b OR ... */
5166
Item *item= new Item_cond_or(list);
5171
Item *Item_cond_or::neg_transformer(THD *thd) /* NOT(a OR b OR ...) -> */
5172
/* NOT a AND NOT b AND ... */
5175
Item *item= new Item_cond_and(list);
5180
Item *Item_func_nop_all::neg_transformer(THD *thd)
5182
/* "NOT (e $cmp$ ANY (SELECT ...)) -> e $rev_cmp$" ALL (SELECT ...) */
5183
Item_func_not_all *new_item= new Item_func_not_all(args[0]);
5184
Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
5185
allany->func= allany->func_creator(FALSE);
5186
allany->all= !allany->all;
5187
allany->upper_item= new_item;
5191
Item *Item_func_not_all::neg_transformer(THD *thd)
5193
/* "NOT (e $cmp$ ALL (SELECT ...)) -> e $rev_cmp$" ANY (SELECT ...) */
5194
Item_func_nop_all *new_item= new Item_func_nop_all(args[0]);
5195
Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
5196
allany->all= !allany->all;
5197
allany->func= allany->func_creator(TRUE);
5198
allany->upper_item= new_item;
5202
Item *Item_func_eq::negated_item() /* a = b -> a != b */
5204
return new Item_func_ne(args[0], args[1]);
5208
Item *Item_func_ne::negated_item() /* a != b -> a = b */
5210
return new Item_func_eq(args[0], args[1]);
5214
Item *Item_func_lt::negated_item() /* a < b -> a >= b */
5216
return new Item_func_ge(args[0], args[1]);
5220
Item *Item_func_ge::negated_item() /* a >= b -> a < b */
5222
return new Item_func_lt(args[0], args[1]);
5226
Item *Item_func_gt::negated_item() /* a > b -> a <= b */
5228
return new Item_func_le(args[0], args[1]);
5232
Item *Item_func_le::negated_item() /* a <= b -> a > b */
5234
return new Item_func_gt(args[0], args[1]);
5238
just fake method, should never be called.
5240
Item *Item_bool_rowready_func2::negated_item()
5246
Item_equal::Item_equal(Item_field *f1, Item_field *f2)
5247
: Item_bool_func(), const_item(0), eval_item(0), cond_false(0),
5248
compare_as_dates(FALSE)
5250
const_item_cache= 0;
5251
fields.push_back(f1);
5252
fields.push_back(f2);
5255
Item_equal::Item_equal(Item *c, Item_field *f)
5256
: Item_bool_func(), eval_item(0), cond_false(0)
5258
const_item_cache= 0;
5259
fields.push_back(f);
5261
compare_as_dates= f->is_datetime();
5265
Item_equal::Item_equal(Item_equal *item_equal)
5266
: Item_bool_func(), eval_item(0), cond_false(0)
5268
const_item_cache= 0;
5269
List_iterator_fast<Item_field> li(item_equal->fields);
5271
while ((item= li++))
5273
fields.push_back(item);
5275
const_item= item_equal->const_item;
5276
compare_as_dates= item_equal->compare_as_dates;
5277
cond_false= item_equal->cond_false;
5281
void Item_equal::compare_const(Item *c)
5283
if (compare_as_dates)
5285
cmp.set_datetime_cmp_func(this, &c, &const_item);
5286
cond_false= cmp.compare();
5290
Item_func_eq *func= new Item_func_eq(c, const_item);
5291
func->set_cmp_func();
5292
func->quick_fix_field();
5293
cond_false= !func->val_int();
5296
const_item_cache= 1;
5300
void Item_equal::add(Item *c, Item_field *f)
5308
compare_as_dates= f->is_datetime();
5315
void Item_equal::add(Item *c)
5327
void Item_equal::add(Item_field *f)
5329
fields.push_back(f);
5332
uint Item_equal::members()
5334
return fields.elements;
5339
Check whether a field is referred in the multiple equality.
5341
The function checks whether field is occurred in the Item_equal object .
5343
@param field field whose occurrence is to be checked
5346
1 if nultiple equality contains a reference to field
5351
bool Item_equal::contains(Field *field)
5353
List_iterator_fast<Item_field> it(fields);
5355
while ((item= it++))
5357
if (field->eq(item->field))
5365
Join members of another Item_equal object.
5367
The function actually merges two multiple equalities.
5368
After this operation the Item_equal object additionally contains
5369
the field items of another item of the type Item_equal.
5370
If the optional constant items are not equal the cond_false flag is
5372
@param item multiple equality whose members are to be joined
5375
void Item_equal::merge(Item_equal *item)
5377
fields.concat(&item->fields);
5378
Item *c= item->const_item;
5382
The flag cond_false will be set to 1 after this, if
5383
the multiple equality already contains a constant and its
5384
value is not equal to the value of c.
5388
cond_false|= item->cond_false;
5393
Order field items in multiple equality according to a sorting criteria.
5395
The function perform ordering of the field items in the Item_equal
5396
object according to the criteria determined by the cmp callback parameter.
5397
If cmp(item_field1,item_field2,arg)<0 than item_field1 must be
5398
placed after item_fiel2.
5400
The function sorts field items by the exchange sort algorithm.
5401
The list of field items is looked through and whenever two neighboring
5402
members follow in a wrong order they are swapped. This is performed
5403
again and again until we get all members in a right order.
5405
@param cmp function to compare field item
5406
@param arg context extra parameter for the cmp function
5409
void Item_equal::sort(Item_field_cmpfunc cmp, void *arg)
5412
List_iterator<Item_field> it(fields);
5415
Item_field *item1= it++;
5416
Item_field **ref1= it.ref();
5420
while ((item2= it++))
5422
Item_field **ref2= it.ref();
5423
if (cmp(item1, item2, arg) < 0)
5425
Item_field *item= *ref1;
5442
Check appearance of new constant items in the multiple equality object.
5444
The function checks appearance of new constant items among
5445
the members of multiple equalities. Each new constant item is
5446
compared with the designated constant item if there is any in the
5447
multiple equality. If there is none the first new constant item
5451
void Item_equal::update_const()
5453
List_iterator<Item_field> it(fields);
5455
while ((item= it++))
5457
if (item->const_item())
5465
bool Item_equal::fix_fields(THD *thd, Item **ref)
5467
List_iterator_fast<Item_field> li(fields);
5469
not_null_tables_cache= used_tables_cache= 0;
5470
const_item_cache= 0;
5471
while ((item= li++))
5473
table_map tmp_table_map;
5474
used_tables_cache|= item->used_tables();
5475
tmp_table_map= item->not_null_tables();
5476
not_null_tables_cache|= tmp_table_map;
5477
if (item->maybe_null)
5480
fix_length_and_dec();
5485
void Item_equal::update_used_tables()
5487
List_iterator_fast<Item_field> li(fields);
5489
not_null_tables_cache= used_tables_cache= 0;
5490
if ((const_item_cache= cond_false))
5494
item->update_used_tables();
5495
used_tables_cache|= item->used_tables();
5496
const_item_cache&= item->const_item();
5500
longlong Item_equal::val_int()
5502
Item_field *item_field;
5505
List_iterator_fast<Item_field> it(fields);
5506
Item *item= const_item ? const_item : it++;
5507
if ((null_value= item->null_value))
5509
eval_item->store_value(item);
5510
while ((item_field= it++))
5512
/* Skip fields of non-const tables. They haven't been read yet */
5513
if (item_field->field->table->const_table)
5515
if ((null_value= item_field->null_value) || eval_item->cmp(item_field))
5522
void Item_equal::fix_length_and_dec()
5524
Item *item= get_first();
5525
eval_item= cmp_item::get_comparator(item->result_type(),
5526
item->collation.collation);
5529
bool Item_equal::walk(Item_processor processor, bool walk_subquery, uchar *arg)
5531
List_iterator_fast<Item_field> it(fields);
5533
while ((item= it++))
5535
if (item->walk(processor, walk_subquery, arg))
5538
return Item_func::walk(processor, walk_subquery, arg);
5541
Item *Item_equal::transform(Item_transformer transformer, uchar *arg)
5543
DBUG_ASSERT(!current_thd->is_stmt_prepare());
5545
List_iterator<Item_field> it(fields);
5547
while ((item= it++))
5549
Item *new_item= item->transform(transformer, arg);
5554
THD::change_item_tree() should be called only if the tree was
5555
really transformed, i.e. when a new item has been created.
5556
Otherwise we'll be allocating a lot of unnecessary memory for
5557
change records at each execution.
5559
if (new_item != item)
5560
current_thd->change_item_tree((Item **) it.ref(), new_item);
5562
return Item_func::transform(transformer, arg);
5565
void Item_equal::print(String *str, enum_query_type query_type)
5567
str->append(func_name());
5569
List_iterator_fast<Item_field> it(fields);
5572
const_item->print(str, query_type);
5576
item->print(str, query_type);
5578
while ((item= it++))
5582
item->print(str, query_type);