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
25
#include "drizzled/sql_select.h"
26
#include "drizzled/error.h"
27
#include "drizzled/temporal.h"
28
#include "drizzled/item/cmpfunc.h"
29
#include "drizzled/cached_item.h"
30
#include "drizzled/item/cache_int.h"
31
#include "drizzled/item/int_with_ref.h"
32
#include "drizzled/check_stack_overrun.h"
33
#include "drizzled/time_functions.h"
34
#include "drizzled/internal/my_sys.h"
43
extern const double log_10[309];
45
static Eq_creator eq_creator;
46
static Ne_creator ne_creator;
47
static Gt_creator gt_creator;
48
static Lt_creator lt_creator;
49
static Ge_creator ge_creator;
50
static Le_creator le_creator;
52
static bool convert_constant_item(Session *, Item_field *, Item **);
54
static Item_result item_store_type(Item_result a, Item *item,
57
Item_result b= item->result_type();
59
if (a == STRING_RESULT || b == STRING_RESULT)
61
else if (a == REAL_RESULT || b == REAL_RESULT)
63
else if (a == DECIMAL_RESULT || b == DECIMAL_RESULT ||
64
unsigned_flag != item->unsigned_flag)
65
return DECIMAL_RESULT;
70
static void agg_result_type(Item_result *type, Item **items, uint32_t nitems)
72
Item **item, **item_end;
73
bool unsigned_flag= 0;
76
/* Skip beginning NULL items */
77
for (item= items, item_end= item + nitems; item < item_end; item++)
79
if ((*item)->type() != Item::NULL_ITEM)
81
*type= (*item)->result_type();
82
unsigned_flag= (*item)->unsigned_flag;
87
/* Combine result types. Note: NULL items don't affect the result */
88
for (; item < item_end; item++)
90
if ((*item)->type() != Item::NULL_ITEM)
91
*type= item_store_type(*type, *item, unsigned_flag);
97
Compare row signature of two expressions
101
item1 the first expression
102
item2 the second expression
105
The function checks that two expressions have compatible row signatures
106
i.e. that the number of columns they return are the same and that if they
107
are both row expressions then each component from the first expression has
108
a row signature compatible with the signature of the corresponding component
109
of the second expression.
112
1 type incompatibility has been detected
116
static int cmp_row_type(Item* item1, Item* item2)
118
uint32_t n= item1->cols();
119
if (item2->check_cols(n))
121
for (uint32_t i=0; i<n; i++)
123
if (item2->element_index(i)->check_cols(item1->element_index(i)->cols()) ||
124
(item1->element_index(i)->result_type() == ROW_RESULT &&
125
cmp_row_type(item1->element_index(i), item2->element_index(i))))
133
Aggregates result types from the array of items.
137
type [out] the aggregated type
138
items array of items to aggregate the type from
139
nitems number of items in the array
142
This function aggregates result types from the array of items. Found type
143
supposed to be used later for comparison of values of these items.
144
Aggregation itself is performed by the item_cmp_type() function.
145
@param[out] type the aggregated type
146
@param items array of items to aggregate the type from
147
@param nitems number of items in the array
150
1 type incompatibility has been detected
155
static int agg_cmp_type(Item_result *type, Item **items, uint32_t nitems)
158
type[0]= items[0]->result_type();
159
for (i= 1 ; i < nitems ; i++)
161
type[0]= item_cmp_type(type[0], items[i]->result_type());
163
When aggregating types of two row expressions we have to check
164
that they have the same cardinality and that each component
165
of the first row expression has a compatible row signature with
166
the signature of the corresponding component of the second row
169
if (type[0] == ROW_RESULT && cmp_row_type(items[0], items[i]))
170
return 1; // error found: invalid usage of rows
177
@brief Aggregates field types from the array of items.
179
@param[in] items array of items to aggregate the type from
180
@paran[in] nitems number of items in the array
182
@details This function aggregates field types from the array of items.
183
Found type is supposed to be used later as the result field type
184
of a multi-argument function.
185
Aggregation itself is performed by the Field::field_type_merge()
188
@note The term "aggregation" is used here in the sense of inferring the
189
result type of a function from its argument types.
191
@return aggregated field type.
194
enum_field_types agg_field_type(Item **items, uint32_t nitems)
197
if (!nitems || items[0]->result_type() == ROW_RESULT )
198
return (enum_field_types)-1;
199
enum_field_types res= items[0]->field_type();
200
for (i= 1 ; i < nitems ; i++)
201
res= Field::field_type_merge(res, items[i]->field_type());
206
Collects different types for comparison of first item with each other items
210
items Array of items to collect types from
211
nitems Number of items in the array
212
skip_nulls Don't collect types of NULL items if TRUE
215
This function collects different result types for comparison of the first
216
item in the list with each of the remaining items in the 'items' array.
219
0 - if row type incompatibility has been detected (see cmp_row_type)
220
Bitmap of collected types - otherwise
223
static uint32_t collect_cmp_types(Item **items, uint32_t nitems, bool skip_nulls= false)
226
uint32_t found_types;
227
Item_result left_result= items[0]->result_type();
230
for (i= 1; i < nitems ; i++)
232
if (skip_nulls && items[i]->type() == Item::NULL_ITEM)
233
continue; // Skip NULL constant items
234
if ((left_result == ROW_RESULT ||
235
items[i]->result_type() == ROW_RESULT) &&
236
cmp_row_type(items[0], items[i]))
238
found_types|= 1<< (uint32_t)item_cmp_type(left_result,
239
items[i]->result_type());
242
Even if all right-hand items are NULLs and we are skipping them all, we need
243
at least one type bit in the found_type bitmask.
245
if (skip_nulls && !found_types)
246
found_types= 1 << (uint)left_result;
251
Item_bool_func2* Eq_creator::create(Item *a, Item *b) const
253
return new Item_func_eq(a, b);
257
const Eq_creator* Eq_creator::instance()
263
Item_bool_func2* Ne_creator::create(Item *a, Item *b) const
265
return new Item_func_ne(a, b);
269
const Ne_creator* Ne_creator::instance()
275
Item_bool_func2* Gt_creator::create(Item *a, Item *b) const
277
return new Item_func_gt(a, b);
281
const Gt_creator* Gt_creator::instance()
287
Item_bool_func2* Lt_creator::create(Item *a, Item *b) const
289
return new Item_func_lt(a, b);
293
const Lt_creator* Lt_creator::instance()
299
Item_bool_func2* Ge_creator::create(Item *a, Item *b) const
301
return new Item_func_ge(a, b);
305
const Ge_creator* Ge_creator::instance()
311
Item_bool_func2* Le_creator::create(Item *a, Item *b) const
313
return new Item_func_le(a, b);
316
const Le_creator* Le_creator::instance()
324
Most of these returns 0LL if false and 1LL if true and
325
NULL if some arg is NULL.
328
int64_t Item_func_not::val_int()
331
bool value= args[0]->val_bool();
332
null_value=args[0]->null_value;
333
return ((!null_value && value == 0) ? 1 : 0);
337
We put any NOT expression into parenthesis to avoid
338
possible problems with internal view representations where
339
any '!' is converted to NOT. It may cause a problem if
340
'!' is used in an expression together with other operators
341
whose precedence is lower than the precedence of '!' yet
342
higher than the precedence of NOT.
345
void Item_func_not::print(String *str, enum_query_type query_type)
348
Item_func::print(str, query_type);
353
special NOT for ALL subquery.
357
int64_t Item_func_not_all::val_int()
360
bool value= args[0]->val_bool();
363
return true if there was records in underlying select in max/min
364
optimization (ALL subquery)
366
if (empty_underlying_subquery())
369
null_value= args[0]->null_value;
370
return ((!null_value && value == 0) ? 1 : 0);
374
bool Item_func_not_all::empty_underlying_subquery()
376
return ((test_sum_item && !test_sum_item->any_value()) ||
377
(test_sub_item && !test_sub_item->any_value()));
380
void Item_func_not_all::print(String *str, enum_query_type query_type)
383
Item_func::print(str, query_type);
385
args[0]->print(str, query_type);
390
Special NOP (No OPeration) for ALL subquery. It is like
394
(return true if underlying subquery do not return rows) but if subquery
395
returns some rows it return same value as argument (true/false).
398
int64_t Item_func_nop_all::val_int()
401
int64_t value= args[0]->val_int();
404
return false if there was records in underlying select in max/min
405
optimization (SAME/ANY subquery)
407
if (empty_underlying_subquery())
410
null_value= args[0]->null_value;
411
return (null_value || value == 0) ? 0 : 1;
416
Convert a constant item to an int and replace the original item.
418
The function converts a constant expression or string to an integer.
419
On successful conversion the original item is substituted for the
420
result of the item evaluation.
421
This is done when comparing DATE/TIME of different formats and
422
also when comparing bigint to strings (in which case strings
423
are converted to bigints).
425
@param session thread handle
426
@param field_item item will be converted using the type of this field
427
@param[in,out] item reference to the item to convert
430
This function is called only at prepare stage.
431
As all derived tables are filled only after all derived tables
432
are prepared we do not evaluate items with subselects here because
433
they can contain derived tables and thus we may attempt to use a
434
table that has not been populated yet.
439
1 Item was replaced with an integer version of the item
442
static bool convert_constant_item(Session *session, Item_field *field_item,
445
Field *field= field_item->field;
448
field->setWriteSet();
450
if (!(*item)->with_subselect && (*item)->const_item())
452
ulong orig_sql_mode= session->variables.sql_mode;
453
enum_check_fields orig_count_cuted_fields= session->count_cuted_fields;
454
uint64_t orig_field_val= 0; /* original field value if valid */
456
/* For comparison purposes allow invalid dates like 2000-01-32 */
457
session->variables.sql_mode= (orig_sql_mode & ~MODE_NO_ZERO_DATE) |
459
session->count_cuted_fields= CHECK_FIELD_IGNORE;
462
Store the value of the field if it references an outer field because
463
the call to save_in_field below overrides that value.
465
if (field_item->depended_from)
466
orig_field_val= field->val_int();
467
if (!(*item)->is_null() && !(*item)->save_in_field(field, 1))
469
Item *tmp= new Item_int_with_ref(field->val_int(), *item,
470
test(field->flags & UNSIGNED_FLAG));
472
session->change_item_tree(item, tmp);
473
result= 1; // Item was replaced
475
/* Restore the original field value. */
476
if (field_item->depended_from)
478
result= field->store(orig_field_val, true);
479
/* orig_field_val must be a valid value that can be restored back. */
482
session->variables.sql_mode= orig_sql_mode;
483
session->count_cuted_fields= orig_count_cuted_fields;
489
void Item_bool_func2::fix_length_and_dec()
491
max_length= 1; // Function returns 0 or 1
495
As some compare functions are generated after sql_yacc,
496
we have to check for out of memory conditions here
498
if (!args[0] || !args[1])
502
We allow to convert to Unicode character sets in some cases.
503
The conditions when conversion is possible are:
504
- arguments A and B have different charsets
505
- A wins according to coercibility rules
506
- character set of A is superset for character set of B
508
If all of the above is true, then it's possible to convert
509
B into the character set of A, and then compare according
510
to the collation of A.
515
if (args[0]->result_type() == STRING_RESULT &&
516
args[1]->result_type() == STRING_RESULT &&
517
agg_arg_charsets(coll, args, 2, MY_COLL_CMP_CONV, 1))
520
args[0]->cmp_context= args[1]->cmp_context=
521
item_cmp_type(args[0]->result_type(), args[1]->result_type());
522
// Make a special case of compare with fields to get nicer DATE comparisons
524
if (functype() == LIKE_FUNC) // Disable conversion in case of LIKE function.
530
session= current_session;
531
Item_field *field_item= NULL;
533
if (args[0]->real_item()->type() == FIELD_ITEM)
535
field_item= static_cast<Item_field*>(args[0]->real_item());
536
if (field_item->field->can_be_compared_as_int64_t() &&
537
!(field_item->is_datetime() && args[1]->result_type() == STRING_RESULT))
539
if (convert_constant_item(session, field_item, &args[1]))
541
cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
542
INT_RESULT); // Works for all types.
543
args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
548
if (args[1]->real_item()->type() == FIELD_ITEM)
550
field_item= static_cast<Item_field*>(args[1]->real_item());
551
if (field_item->field->can_be_compared_as_int64_t() &&
552
!(field_item->is_datetime() &&
553
args[0]->result_type() == STRING_RESULT))
555
if (convert_constant_item(session, field_item, &args[0]))
557
cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
558
INT_RESULT); // Works for all types.
559
args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
569
int Arg_comparator::set_compare_func(Item_bool_func2 *item, Item_result type)
572
func= comparator_matrix[type]
573
[test(owner->functype() == Item_func::EQUAL_FUNC)];
577
uint32_t n= (*a)->cols();
578
if (n != (*b)->cols())
580
my_error(ER_OPERAND_COLUMNS, MYF(0), n);
584
if (!(comparators= new Arg_comparator[n]))
586
for (uint32_t i=0; i < n; i++)
588
if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols())
590
my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
593
comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i));
600
We must set cmp_charset here as we may be called from for an automatic
601
generated item, like in natural join
603
if (cmp_collation.set((*a)->collation, (*b)->collation) ||
604
cmp_collation.derivation == DERIVATION_NONE)
606
my_coll_agg_error((*a)->collation, (*b)->collation, owner->func_name());
609
if (cmp_collation.collation == &my_charset_bin)
612
We are using BLOB/BINARY/VARBINARY, change to compare byte by byte,
613
without removing end space
615
if (func == &Arg_comparator::compare_string)
616
func= &Arg_comparator::compare_binary_string;
617
else if (func == &Arg_comparator::compare_e_string)
618
func= &Arg_comparator::compare_e_binary_string;
621
As this is binary compassion, mark all fields that they can't be
622
transformed. Otherwise we would get into trouble with comparisons
624
WHERE col= 'j' AND col LIKE BINARY 'j'
625
which would be transformed to:
628
(*a)->walk(&Item::set_no_const_sub, false, (unsigned char*) 0);
629
(*b)->walk(&Item::set_no_const_sub, false, (unsigned char*) 0);
635
if (func == &Arg_comparator::compare_int_signed)
637
if ((*a)->unsigned_flag)
638
func= (((*b)->unsigned_flag)?
639
&Arg_comparator::compare_int_unsigned :
640
&Arg_comparator::compare_int_unsigned_signed);
641
else if ((*b)->unsigned_flag)
642
func= &Arg_comparator::compare_int_signed_unsigned;
644
else if (func== &Arg_comparator::compare_e_int)
646
if ((*a)->unsigned_flag ^ (*b)->unsigned_flag)
647
func= &Arg_comparator::compare_e_int_diff_signedness;
655
if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC)
657
precision= 5 / log_10[max((*a)->decimals, (*b)->decimals) + 1];
658
if (func == &Arg_comparator::compare_real)
659
func= &Arg_comparator::compare_real_fixed;
660
else if (func == &Arg_comparator::compare_e_real)
661
func= &Arg_comparator::compare_e_real_fixed;
673
@brief Convert date provided in a string to the int representation.
675
@param[in] session thread handle
676
@param[in] str a string to convert
677
@param[in] warn_type type of the timestamp for issuing the warning
678
@param[in] warn_name field name for issuing the warning
679
@param[out] error_arg could not extract a DATE or DATETIME
681
@details Convert date provided in the string str to the int
682
representation. If the string contains wrong date or doesn't
683
contain it at all then a warning is issued. The warn_type and
684
the warn_name arguments are used as the name and the type of the
685
field when issuing the warning. If any input was discarded
686
(trailing or non-timestampy characters), was_cut will be non-zero.
687
was_type will return the type str_to_datetime() could correctly
691
converted value. 0 on error and on zero-dates -- check 'failure'
695
get_date_from_str(Session *session, String *str, enum enum_drizzle_timestamp_type warn_type,
696
char *warn_name, bool *error_arg)
701
enum enum_drizzle_timestamp_type ret;
703
ret= str_to_datetime(str->ptr(), str->length(), &l_time,
704
(TIME_FUZZY_DATE | MODE_INVALID_DATES |
705
(session->variables.sql_mode & MODE_NO_ZERO_DATE)),
708
if (ret == DRIZZLE_TIMESTAMP_DATETIME || ret == DRIZZLE_TIMESTAMP_DATE)
711
Do not return yet, we may still want to throw a "trailing garbage"
715
value= TIME_to_uint64_t_datetime(&l_time);
720
error= 1; /* force warning */
724
make_truncated_value_warning(session, DRIZZLE_ERROR::WARN_LEVEL_WARN,
725
str->ptr(), str->length(),
726
warn_type, warn_name);
733
Check whether compare_datetime() can be used to compare items.
736
Arg_comparator::can_compare_as_dates()
737
a, b [in] items to be compared
738
const_value [out] converted value of the string constant, if any
741
Check several cases when the DATE/DATETIME comparator should be used.
742
The following cases are checked:
743
1. Both a and b is a DATE/DATETIME field/function returning string or
745
2. Only a or b is a DATE/DATETIME field/function returning string or
746
int result and the other item (b or a) is an item with string result.
747
If the second item is a constant one then it's checked to be
748
convertible to the DATE/DATETIME type. If the constant can't be
749
converted to a DATE/DATETIME then an error is issued back to the Session.
750
In all other cases (date-[int|real|decimal]/[int|real|decimal]-date)
751
the comparison is handled by other comparators.
753
If the datetime comparator can be used and one the operands of the
754
comparison is a string constant that was successfully converted to a
755
DATE/DATETIME type then the result of the conversion is returned in the
756
const_value if it is provided. If there is no constant or
757
compare_datetime() isn't applicable then the *const_value remains
761
the found type of date comparison
764
enum Arg_comparator::enum_date_cmp_type
765
Arg_comparator::can_compare_as_dates(Item *a, Item *b, uint64_t *const_value)
767
enum enum_date_cmp_type cmp_type= CMP_DATE_DFLT;
768
Item *str_arg= 0, *date_arg= 0;
770
if (a->type() == Item::ROW_ITEM || b->type() == Item::ROW_ITEM)
771
return CMP_DATE_DFLT;
773
if (a->is_datetime())
775
if (b->is_datetime())
776
cmp_type= CMP_DATE_WITH_DATE;
777
else if (b->result_type() == STRING_RESULT)
779
cmp_type= CMP_DATE_WITH_STR;
784
else if (b->is_datetime() && a->result_type() == STRING_RESULT)
786
cmp_type= CMP_STR_WITH_DATE;
791
if (cmp_type != CMP_DATE_DFLT)
794
Do not cache GET_USER_VAR() function as its const_item() may return true
795
for the current thread but it still may change during the execution.
797
if (cmp_type != CMP_DATE_WITH_DATE && str_arg->const_item() &&
798
(str_arg->type() != Item::FUNC_ITEM ||
799
((Item_func*)str_arg)->functype() != Item_func::GUSERVAR_FUNC))
802
* OK, we are here if we've got a date field (or something which can be
803
* compared as a date field) on one side of the equation, and a constant
804
* string on the other side. In this case, we must verify that the constant
805
* string expression can indeed be evaluated as a datetime. If it cannot,
806
* we throw an error here and stop processsing. Bad data should ALWAYS
807
* produce an error, and no implicit conversion or truncation should take place.
809
* If the conversion to a DateTime temporal is successful, then we convert
810
* the Temporal instance to a uint64_t for the comparison operator, which
811
* compares date(times) using int64_t semantics.
815
* Does a uint64_t conversion really have to happen here? Fields return int64_t
816
* from val_int(), not uint64_t...
821
/* DateTime used to pick up as many string conversion possibilities as possible. */
824
str_val= str_arg->val_str(&tmp);
828
* If we are here, it is most likely due to the comparison item
829
* being a NULL. Although this is incorrect (SQL demands that the term IS NULL
830
* be used, not = NULL since no item can be equal to NULL).
832
* So, return gracefully.
834
return CMP_DATE_DFLT;
836
if (! temporal.from_string(str_val->c_ptr(), str_val->length()))
838
/* Chuck an error. Bad datetime input. */
839
my_error(ER_INVALID_DATETIME_VALUE, MYF(ME_FATALERROR), str_val->c_ptr());
840
return CMP_DATE_DFLT; /* :( What else can I return... */
843
/* String conversion was good. Convert to an integer for comparison purposes. */
845
temporal.to_int64_t(&int_value);
846
value= (uint64_t) int_value;
856
int Arg_comparator::set_cmp_func(Item_bool_func2 *owner_arg,
857
Item **a1, Item **a2,
860
enum enum_date_cmp_type cmp_type;
861
uint64_t const_value= (uint64_t)-1;
865
if ((cmp_type= can_compare_as_dates(*a, *b, &const_value)))
867
session= current_session;
869
a_type= (*a)->field_type();
870
b_type= (*b)->field_type();
874
if (const_value != (uint64_t)-1)
876
Item_cache_int *cache= new Item_cache_int();
877
/* Mark the cache as non-const to prevent re-caching. */
878
cache->set_used_tables(1);
879
if (!(*a)->is_datetime())
881
cache->store((*a), const_value);
883
a= (Item **)&a_cache;
887
cache->store((*b), const_value);
889
b= (Item **)&b_cache;
892
is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC);
893
func= &Arg_comparator::compare_datetime;
894
get_value_func= &get_datetime_value;
898
return set_compare_func(owner_arg, type);
902
void Arg_comparator::set_datetime_cmp_func(Item **a1, Item **b1)
904
session= current_session;
905
/* A caller will handle null values by itself. */
909
a_type= (*a)->field_type();
910
b_type= (*b)->field_type();
914
func= &Arg_comparator::compare_datetime;
915
get_value_func= &get_datetime_value;
920
Retrieves correct DATETIME value from given item.
924
session thread handle
925
item_arg [in/out] item to retrieve DATETIME value from
926
cache_arg [in/out] pointer to place to store the caching item to
927
warn_item [in] item for issuing the conversion warning
928
is_null [out] true <=> the item_arg is null
931
Retrieves the correct DATETIME value from given item for comparison by the
932
compare_datetime() function.
933
If item's result can be compared as int64_t then its int value is used
934
and its string value is used otherwise. Strings are always parsed and
935
converted to int values by the get_date_from_str() function.
936
This allows us to compare correctly string dates with missed insignificant
937
zeros. If an item is a constant one then its value is cached and it isn't
938
get parsed again. An Item_cache_int object is used for caching values. It
939
seamlessly substitutes the original item. The cache item is marked as
940
non-constant to prevent re-caching it again. In order to compare
941
correctly DATE and DATETIME items the result of the former are treated as
942
a DATETIME with zero time (00:00:00).
949
get_datetime_value(Session *session, Item ***item_arg, Item **cache_arg,
950
Item *warn_item, bool *is_null)
954
Item *item= **item_arg;
956
if (item->result_as_int64_t())
958
value= item->val_int();
959
*is_null= item->null_value;
960
enum_field_types f_type= item->field_type();
962
Item_date_add_interval may return DRIZZLE_TYPE_STRING as the result
963
field type. To detect that the DATE value has been returned we
964
compare it with 100000000L - any DATE value should be less than it.
965
Don't shift cached DATETIME values up for the second time.
967
if (f_type == DRIZZLE_TYPE_DATE ||
968
(f_type != DRIZZLE_TYPE_DATETIME && value < 100000000L))
973
str= item->val_str(&buf);
974
*is_null= item->null_value;
977
return ~(uint64_t) 0;
979
Convert strings to the integer DATE/DATETIME representation.
980
Even if both dates provided in strings we can't compare them directly as
981
strings as there is no warranty that they are correct and do not miss
982
some insignificant zeros.
987
enum_field_types f_type= warn_item->field_type();
988
enum enum_drizzle_timestamp_type t_type= f_type ==
989
DRIZZLE_TYPE_DATE ? DRIZZLE_TIMESTAMP_DATE : DRIZZLE_TIMESTAMP_DATETIME;
990
value= get_date_from_str(session, str, t_type, warn_item->name, &error);
992
If str did not contain a valid date according to the current
993
SQL_MODE, get_date_from_str() has already thrown a warning,
994
and we don't want to throw NULL on invalid date (see 5.2.6
995
"SQL modes" in the manual), so we're done here.
999
Do not cache GET_USER_VAR() function as its const_item() may return true
1000
for the current thread but it still may change during the execution.
1002
if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM ||
1003
((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
1005
Item_cache_int *cache= new Item_cache_int(DRIZZLE_TYPE_DATETIME);
1006
/* Mark the cache as non-const to prevent re-caching. */
1007
cache->set_used_tables(1);
1008
cache->store(item, value);
1010
*item_arg= cache_arg;
1016
Compare items values as dates.
1019
Arg_comparator::compare_datetime()
1022
Compare items values as DATE/DATETIME for both EQUAL_FUNC and from other
1023
comparison functions. The correct DATETIME values are obtained
1024
with help of the get_datetime_value() function.
1027
If is_nulls_eq is true:
1028
1 if items are equal or both are null
1030
If is_nulls_eq is false:
1031
-1 a < b or one of items is null
1036
int Arg_comparator::compare_datetime()
1038
bool is_null= false;
1039
uint64_t a_value, b_value;
1041
/* Get DATE/DATETIME/TIME value of the 'a' item. */
1042
a_value= (*get_value_func)(session, &a, &a_cache, *b, &is_null);
1043
if (!is_nulls_eq && is_null)
1046
owner->null_value= 1;
1050
/* Get DATE/DATETIME/TIME value of the 'b' item. */
1051
b_value= (*get_value_func)(session, &b, &b_cache, *a, &is_null);
1055
owner->null_value= is_nulls_eq ? 0 : 1;
1056
return is_nulls_eq ? 1 : -1;
1060
owner->null_value= 0;
1062
/* Compare values. */
1064
return (a_value == b_value);
1065
return (a_value < b_value) ? -1 : ((a_value > b_value) ? 1 : 0);
1069
int Arg_comparator::compare_string()
1072
if ((res1= (*a)->val_str(&owner->tmp_value1)))
1074
if ((res2= (*b)->val_str(&owner->tmp_value2)))
1076
owner->null_value= 0;
1077
return sortcmp(res1,res2,cmp_collation.collation);
1080
owner->null_value= 1;
1086
Compare strings byte by byte. End spaces are also compared.
1096
int Arg_comparator::compare_binary_string()
1099
if ((res1= (*a)->val_str(&owner->tmp_value1)))
1101
if ((res2= (*b)->val_str(&owner->tmp_value2)))
1103
owner->null_value= 0;
1104
uint32_t res1_length= res1->length();
1105
uint32_t res2_length= res2->length();
1106
int cmp= memcmp(res1->ptr(), res2->ptr(), min(res1_length,res2_length));
1107
return cmp ? cmp : (int) (res1_length - res2_length);
1110
owner->null_value= 1;
1116
Compare strings, but take into account that NULL == NULL.
1120
int Arg_comparator::compare_e_string()
1123
res1= (*a)->val_str(&owner->tmp_value1);
1124
res2= (*b)->val_str(&owner->tmp_value2);
1126
return test(res1 == res2);
1127
return test(sortcmp(res1, res2, cmp_collation.collation) == 0);
1131
int Arg_comparator::compare_e_binary_string()
1134
res1= (*a)->val_str(&owner->tmp_value1);
1135
res2= (*b)->val_str(&owner->tmp_value2);
1137
return test(res1 == res2);
1138
return test(stringcmp(res1, res2) == 0);
1142
int Arg_comparator::compare_real()
1145
Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1146
gcc to flush double values out of 80-bit Intel FPU registers before
1147
performing the comparison.
1149
volatile double val1, val2;
1150
val1= (*a)->val_real();
1151
if (!(*a)->null_value)
1153
val2= (*b)->val_real();
1154
if (!(*b)->null_value)
1156
owner->null_value= 0;
1157
if (val1 < val2) return -1;
1158
if (val1 == val2) return 0;
1162
owner->null_value= 1;
1166
int Arg_comparator::compare_decimal()
1169
my_decimal *val1= (*a)->val_decimal(&value1);
1170
if (!(*a)->null_value)
1173
my_decimal *val2= (*b)->val_decimal(&value2);
1174
if (!(*b)->null_value)
1176
owner->null_value= 0;
1177
return my_decimal_cmp(val1, val2);
1180
owner->null_value= 1;
1184
int Arg_comparator::compare_e_real()
1186
double val1= (*a)->val_real();
1187
double val2= (*b)->val_real();
1188
if ((*a)->null_value || (*b)->null_value)
1189
return test((*a)->null_value && (*b)->null_value);
1190
return test(val1 == val2);
1193
int Arg_comparator::compare_e_decimal()
1195
my_decimal value1, value2;
1196
my_decimal *val1= (*a)->val_decimal(&value1);
1197
my_decimal *val2= (*b)->val_decimal(&value2);
1198
if ((*a)->null_value || (*b)->null_value)
1199
return test((*a)->null_value && (*b)->null_value);
1200
return test(my_decimal_cmp(val1, val2) == 0);
1204
int Arg_comparator::compare_real_fixed()
1207
Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1208
gcc to flush double values out of 80-bit Intel FPU registers before
1209
performing the comparison.
1211
volatile double val1, val2;
1212
val1= (*a)->val_real();
1213
if (!(*a)->null_value)
1215
val2= (*b)->val_real();
1216
if (!(*b)->null_value)
1218
owner->null_value= 0;
1219
if (val1 == val2 || fabs(val1 - val2) < precision)
1226
owner->null_value= 1;
1231
int Arg_comparator::compare_e_real_fixed()
1233
double val1= (*a)->val_real();
1234
double val2= (*b)->val_real();
1235
if ((*a)->null_value || (*b)->null_value)
1236
return test((*a)->null_value && (*b)->null_value);
1237
return test(val1 == val2 || fabs(val1 - val2) < precision);
1241
int Arg_comparator::compare_int_signed()
1243
int64_t val1= (*a)->val_int();
1244
if (!(*a)->null_value)
1246
int64_t val2= (*b)->val_int();
1247
if (!(*b)->null_value)
1249
owner->null_value= 0;
1250
if (val1 < val2) return -1;
1251
if (val1 == val2) return 0;
1255
owner->null_value= 1;
1261
Compare values as BIGINT UNSIGNED.
1264
int Arg_comparator::compare_int_unsigned()
1266
uint64_t val1= (*a)->val_int();
1267
if (!(*a)->null_value)
1269
uint64_t val2= (*b)->val_int();
1270
if (!(*b)->null_value)
1272
owner->null_value= 0;
1273
if (val1 < val2) return -1;
1274
if (val1 == val2) return 0;
1278
owner->null_value= 1;
1284
Compare signed (*a) with unsigned (*B)
1287
int Arg_comparator::compare_int_signed_unsigned()
1289
int64_t sval1= (*a)->val_int();
1290
if (!(*a)->null_value)
1292
uint64_t uval2= (uint64_t)(*b)->val_int();
1293
if (!(*b)->null_value)
1295
owner->null_value= 0;
1296
if (sval1 < 0 || (uint64_t)sval1 < uval2)
1298
if ((uint64_t)sval1 == uval2)
1303
owner->null_value= 1;
1309
Compare unsigned (*a) with signed (*B)
1312
int Arg_comparator::compare_int_unsigned_signed()
1314
uint64_t uval1= (uint64_t)(*a)->val_int();
1315
if (!(*a)->null_value)
1317
int64_t sval2= (*b)->val_int();
1318
if (!(*b)->null_value)
1320
owner->null_value= 0;
1323
if (uval1 < (uint64_t)sval2)
1325
if (uval1 == (uint64_t)sval2)
1330
owner->null_value= 1;
1335
int Arg_comparator::compare_e_int()
1337
int64_t val1= (*a)->val_int();
1338
int64_t val2= (*b)->val_int();
1339
if ((*a)->null_value || (*b)->null_value)
1340
return test((*a)->null_value && (*b)->null_value);
1341
return test(val1 == val2);
1345
Compare unsigned *a with signed *b or signed *a with unsigned *b.
1347
int Arg_comparator::compare_e_int_diff_signedness()
1349
int64_t val1= (*a)->val_int();
1350
int64_t val2= (*b)->val_int();
1351
if ((*a)->null_value || (*b)->null_value)
1352
return test((*a)->null_value && (*b)->null_value);
1353
return (val1 >= 0) && test(val1 == val2);
1356
int Arg_comparator::compare_row()
1360
(*a)->bring_value();
1361
(*b)->bring_value();
1362
uint32_t n= (*a)->cols();
1363
for (uint32_t i= 0; i<n; i++)
1365
res= comparators[i].compare();
1366
if (owner->null_value)
1368
// NULL was compared
1369
switch (owner->functype()) {
1370
case Item_func::NE_FUNC:
1371
break; // NE never aborts on NULL even if abort_on_null is set
1372
case Item_func::LT_FUNC:
1373
case Item_func::LE_FUNC:
1374
case Item_func::GT_FUNC:
1375
case Item_func::GE_FUNC:
1376
return -1; // <, <=, > and >= always fail on NULL
1378
if (owner->abort_on_null)
1379
return -1; // We do not need correct NULL returning
1382
owner->null_value= 0;
1383
res= 0; // continue comparison (maybe we will meet explicit difference)
1391
There was NULL(s) in comparison in some parts, but there was no
1392
explicit difference in other parts, so we have to return NULL.
1394
owner->null_value= 1;
1401
int Arg_comparator::compare_e_row()
1403
(*a)->bring_value();
1404
(*b)->bring_value();
1405
uint32_t n= (*a)->cols();
1406
for (uint32_t i= 0; i<n; i++)
1408
if (!comparators[i].compare())
1415
void Item_func_truth::fix_length_and_dec()
1424
void Item_func_truth::print(String *str, enum_query_type query_type)
1427
args[0]->print(str, query_type);
1428
str->append(STRING_WITH_LEN(" is "));
1430
str->append(STRING_WITH_LEN("not "));
1432
str->append(STRING_WITH_LEN("true"));
1434
str->append(STRING_WITH_LEN("false"));
1439
bool Item_func_truth::val_bool()
1441
bool val= args[0]->val_bool();
1442
if (args[0]->null_value)
1445
NULL val IS {true, false} --> false
1446
NULL val IS NOT {true, false} --> true
1448
return (! affirmative);
1453
/* {true, false} val IS {true, false} value */
1454
return (val == value);
1457
/* {true, false} val IS NOT {true, false} value */
1458
return (val != value);
1462
int64_t Item_func_truth::val_int()
1464
return (val_bool() ? 1 : 0);
1468
bool Item_in_optimizer::fix_left(Session *session, Item **)
1470
if ((!args[0]->fixed && args[0]->fix_fields(session, args)) ||
1471
(!cache && !(cache= Item_cache::get_cache(args[0]))))
1474
cache->setup(args[0]);
1475
if (cache->cols() == 1)
1477
if ((used_tables_cache= args[0]->used_tables()))
1478
cache->set_used_tables(OUTER_REF_TABLE_BIT);
1480
cache->set_used_tables(0);
1484
uint32_t n= cache->cols();
1485
for (uint32_t i= 0; i < n; i++)
1487
if (args[0]->element_index(i)->used_tables())
1488
((Item_cache *)cache->element_index(i))->set_used_tables(OUTER_REF_TABLE_BIT);
1490
((Item_cache *)cache->element_index(i))->set_used_tables(0);
1492
used_tables_cache= args[0]->used_tables();
1494
not_null_tables_cache= args[0]->not_null_tables();
1495
with_sum_func= args[0]->with_sum_func;
1496
if ((const_item_cache= args[0]->const_item()))
1497
cache->store(args[0]);
1502
bool Item_in_optimizer::fix_fields(Session *session, Item **ref)
1505
if (fix_left(session, ref))
1507
if (args[0]->maybe_null)
1510
if (!args[1]->fixed && args[1]->fix_fields(session, args+1))
1512
Item_in_subselect * sub= (Item_in_subselect *)args[1];
1513
if (args[0]->cols() != sub->engine->cols())
1515
my_error(ER_OPERAND_COLUMNS, MYF(0), args[0]->cols());
1518
if (args[1]->maybe_null)
1520
with_sum_func= with_sum_func || args[1]->with_sum_func;
1521
used_tables_cache|= args[1]->used_tables();
1522
not_null_tables_cache|= args[1]->not_null_tables();
1523
const_item_cache&= args[1]->const_item();
1529
int64_t Item_in_optimizer::val_int()
1533
cache->store(args[0]);
1535
if (cache->null_value)
1537
if (((Item_in_subselect*)args[1])->is_top_level_item())
1540
We're evaluating "NULL IN (SELECT ...)". The result can be NULL or
1541
false, and we can return one instead of another. Just return NULL.
1547
if (!((Item_in_subselect*)args[1])->is_correlated &&
1548
result_for_null_param != UNKNOWN)
1550
/* Use cached value from previous execution */
1551
null_value= result_for_null_param;
1556
We're evaluating "NULL IN (SELECT ...)". The result is:
1557
false if SELECT produces an empty set, or
1559
We disable the predicates we've pushed down into subselect, run the
1560
subselect and see if it has produced any rows.
1562
Item_in_subselect *item_subs=(Item_in_subselect*)args[1];
1563
if (cache->cols() == 1)
1565
item_subs->set_cond_guard_var(0, false);
1566
(void) args[1]->val_bool_result();
1567
result_for_null_param= null_value= !item_subs->engine->no_rows();
1568
item_subs->set_cond_guard_var(0, true);
1573
uint32_t ncols= cache->cols();
1575
Turn off the predicates that are based on column compares for
1576
which the left part is currently NULL
1578
for (i= 0; i < ncols; i++)
1580
if (cache->element_index(i)->null_value)
1581
item_subs->set_cond_guard_var(i, false);
1584
(void) args[1]->val_bool_result();
1585
result_for_null_param= null_value= !item_subs->engine->no_rows();
1587
/* Turn all predicates back on */
1588
for (i= 0; i < ncols; i++)
1589
item_subs->set_cond_guard_var(i, true);
1595
tmp= args[1]->val_bool_result();
1596
null_value= args[1]->null_value;
1601
void Item_in_optimizer::keep_top_level_cache()
1603
cache->keep_array();
1608
void Item_in_optimizer::cleanup()
1610
Item_bool_func::cleanup();
1617
bool Item_in_optimizer::is_null()
1619
cache->store(args[0]);
1620
return (null_value= (cache->null_value || args[1]->is_null()));
1625
Transform an Item_in_optimizer and its arguments with a callback function.
1627
@param transformer the transformer callback function to be applied to the
1628
nodes of the tree of the object
1629
@param parameter to be passed to the transformer
1632
Recursively transform the left and the right operand of this Item. The
1633
Right operand is an Item_in_subselect or its subclass. To avoid the
1634
creation of new Items, we use the fact the the left operand of the
1635
Item_in_subselect is the same as the one of 'this', so instead of
1636
transforming its operand, we just assign the left operand of the
1637
Item_in_subselect to be equal to the left operand of 'this'.
1638
The transformation is not applied further to the subquery operand
1639
if the IN predicate.
1642
@retval pointer to the transformed item
1643
@retval NULL if an error occurred
1646
Item *Item_in_optimizer::transform(Item_transformer transformer, unsigned char *argument)
1650
assert(arg_count == 2);
1652
/* Transform the left IN operand. */
1653
new_item= (*args)->transform(transformer, argument);
1657
Session::change_item_tree() should be called only if the tree was
1658
really transformed, i.e. when a new item has been created.
1659
Otherwise we'll be allocating a lot of unnecessary memory for
1660
change records at each execution.
1662
if ((*args) != new_item)
1663
current_session->change_item_tree(args, new_item);
1666
Transform the right IN operand which should be an Item_in_subselect or a
1667
subclass of it. The left operand of the IN must be the same as the left
1668
operand of this Item_in_optimizer, so in this case there is no further
1669
transformation, we only make both operands the same.
1670
TODO: is it the way it should be?
1672
assert((args[1])->type() == Item::SUBSELECT_ITEM &&
1673
(((Item_subselect*)(args[1]))->substype() ==
1674
Item_subselect::IN_SUBS ||
1675
((Item_subselect*)(args[1]))->substype() ==
1676
Item_subselect::ALL_SUBS ||
1677
((Item_subselect*)(args[1]))->substype() ==
1678
Item_subselect::ANY_SUBS));
1680
Item_in_subselect *in_arg= (Item_in_subselect*)args[1];
1681
in_arg->left_expr= args[0];
1683
return (this->*transformer)(argument);
1688
int64_t Item_func_eq::val_int()
1691
int value= cmp.compare();
1692
return value == 0 ? 1 : 0;
1696
/** Same as Item_func_eq, but NULL = NULL. */
1698
void Item_func_equal::fix_length_and_dec()
1700
Item_bool_func2::fix_length_and_dec();
1701
maybe_null=null_value=0;
1704
int64_t Item_func_equal::val_int()
1707
return cmp.compare();
1710
int64_t Item_func_ne::val_int()
1713
int value= cmp.compare();
1714
return value != 0 && !null_value ? 1 : 0;
1718
int64_t Item_func_ge::val_int()
1721
int value= cmp.compare();
1722
return value >= 0 ? 1 : 0;
1726
int64_t Item_func_gt::val_int()
1729
int value= cmp.compare();
1730
return value > 0 ? 1 : 0;
1733
int64_t Item_func_le::val_int()
1736
int value= cmp.compare();
1737
return value <= 0 && !null_value ? 1 : 0;
1741
int64_t Item_func_lt::val_int()
1744
int value= cmp.compare();
1745
return value < 0 && !null_value ? 1 : 0;
1749
int64_t Item_func_strcmp::val_int()
1752
String *a=args[0]->val_str(&tmp_value1);
1753
String *b=args[1]->val_str(&tmp_value2);
1759
int value= sortcmp(a,b,cmp.cmp_collation.collation);
1761
return !value ? 0 : (value < 0 ? (int64_t) -1 : (int64_t) 1);
1765
bool Item_func_opt_neg::eq(const Item *item, bool binary_cmp) const
1767
/* Assume we don't have rtti */
1770
if (item->type() != FUNC_ITEM)
1772
Item_func *item_func=(Item_func*) item;
1773
if (arg_count != item_func->arg_count ||
1774
functype() != item_func->functype())
1776
if (negated != ((Item_func_opt_neg *) item_func)->negated)
1778
for (uint32_t i=0; i < arg_count ; i++)
1779
if (!args[i]->eq(item_func->arguments()[i], binary_cmp))
1785
void Item_func_interval::fix_length_and_dec()
1787
uint32_t rows= row->cols();
1789
use_decimal_comparison= ((row->element_index(0)->result_type() ==
1791
(row->element_index(0)->result_type() ==
1795
bool not_null_consts= true;
1797
for (uint32_t i= 1; not_null_consts && i < rows; i++)
1799
Item *el= row->element_index(i);
1800
not_null_consts&= el->const_item() & !el->is_null();
1803
if (not_null_consts &&
1805
(interval_range*) memory::sql_alloc(sizeof(interval_range) * (rows - 1))))
1807
if (use_decimal_comparison)
1809
for (uint32_t i= 1; i < rows; i++)
1811
Item *el= row->element_index(i);
1812
interval_range *range= intervals + (i-1);
1813
if ((el->result_type() == DECIMAL_RESULT) ||
1814
(el->result_type() == INT_RESULT))
1816
range->type= DECIMAL_RESULT;
1818
my_decimal *dec= el->val_decimal(&range->dec);
1819
if (dec != &range->dec)
1822
range->dec.fix_buffer_pointer();
1827
range->type= REAL_RESULT;
1828
range->dbl= el->val_real();
1834
for (uint32_t i= 1; i < rows; i++)
1836
intervals[i-1].dbl= row->element_index(i)->val_real();
1843
used_tables_cache|= row->used_tables();
1844
not_null_tables_cache= row->not_null_tables();
1845
with_sum_func= with_sum_func || row->with_sum_func;
1846
const_item_cache&= row->const_item();
1851
Execute Item_func_interval().
1854
If we are doing a decimal comparison, we are evaluating the first
1859
- 0 if lower than lowest
1860
- 1 - arg_count-1 if between args[n] and args[n+1]
1861
- arg_count if higher than biggest argument
1864
int64_t Item_func_interval::val_int()
1868
my_decimal dec_buf, *dec= NULL;
1871
if (use_decimal_comparison)
1873
dec= row->element_index(0)->val_decimal(&dec_buf);
1874
if (row->element_index(0)->null_value)
1876
my_decimal2double(E_DEC_FATAL_ERROR, dec, &value);
1880
value= row->element_index(0)->val_real();
1881
if (row->element_index(0)->null_value)
1886
{ // Use binary search to find interval
1890
while (start != end)
1892
uint32_t mid= (start + end + 1) / 2;
1893
interval_range *range= intervals + mid;
1896
The values in the range intervall may have different types,
1897
Only do a decimal comparision of the first argument is a decimal
1898
and we are comparing against a decimal
1900
if (dec && range->type == DECIMAL_RESULT)
1901
cmp_result= my_decimal_cmp(&range->dec, dec) <= 0;
1903
cmp_result= (range->dbl <= value);
1909
interval_range *range= intervals+start;
1910
return ((dec && range->type == DECIMAL_RESULT) ?
1911
my_decimal_cmp(dec, &range->dec) < 0 :
1912
value < range->dbl) ? 0 : start + 1;
1915
for (i=1 ; i < row->cols() ; i++)
1917
Item *el= row->element_index(i);
1918
if (use_decimal_comparison &&
1919
((el->result_type() == DECIMAL_RESULT) ||
1920
(el->result_type() == INT_RESULT)))
1922
my_decimal e_dec_buf, *e_dec= el->val_decimal(&e_dec_buf);
1923
/* Skip NULL ranges. */
1926
if (my_decimal_cmp(e_dec, dec) > 0)
1931
double val= el->val_real();
1932
/* Skip NULL ranges. */
1944
Perform context analysis of a BETWEEN item tree.
1946
This function performs context analysis (name resolution) and calculates
1947
various attributes of the item tree with Item_func_between as its root.
1948
The function saves in ref the pointer to the item or to a newly created
1949
item that is considered as a replacement for the original one.
1951
@param session reference to the global context of the query thread
1952
@param ref pointer to Item* variable where pointer to resulting "fixed"
1953
item is to be assigned
1956
Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
1957
a predicate/function level. Then it's easy to show that:
1959
T0(e BETWEEN e1 AND e2) = union(T1(e),T1(e1),T1(e2))
1960
T1(e BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
1961
T0(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
1962
T1(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
1971
bool Item_func_between::fix_fields(Session *session, Item **ref)
1973
if (Item_func_opt_neg::fix_fields(session, ref))
1976
session->lex->current_select->between_count++;
1978
/* not_null_tables_cache == union(T1(e),T1(e1),T1(e2)) */
1979
if (pred_level && !negated)
1982
/* not_null_tables_cache == union(T1(e), intersection(T1(e1),T1(e2))) */
1983
not_null_tables_cache= (args[0]->not_null_tables() |
1984
(args[1]->not_null_tables() &
1985
args[2]->not_null_tables()));
1991
void Item_func_between::fix_length_and_dec()
1995
bool datetime_found= false;
1996
compare_as_dates= true;
1997
Session *session= current_session;
2000
As some compare functions are generated after sql_yacc,
2001
we have to check for out of memory conditions here
2003
if (!args[0] || !args[1] || !args[2])
2005
if ( agg_cmp_type(&cmp_type, args, 3))
2007
if (cmp_type == STRING_RESULT &&
2008
agg_arg_charsets(cmp_collation, args, 3, MY_COLL_CMP_CONV, 1))
2012
Detect the comparison of DATE/DATETIME items.
2013
At least one of items should be a DATE/DATETIME item and other items
2014
should return the STRING result.
2016
if (cmp_type == STRING_RESULT)
2018
for (i= 0; i < 3; i++)
2020
if (args[i]->is_datetime())
2022
datetime_found= true;
2027
if (!datetime_found)
2028
compare_as_dates= false;
2030
if (compare_as_dates)
2032
ge_cmp.set_datetime_cmp_func(args, args + 1);
2033
le_cmp.set_datetime_cmp_func(args, args + 2);
2035
else if (args[0]->real_item()->type() == FIELD_ITEM &&
2036
session->lex->sql_command != SQLCOM_SHOW_CREATE)
2038
Item_field *field_item= (Item_field*) (args[0]->real_item());
2039
if (field_item->field->can_be_compared_as_int64_t())
2042
The following can't be recoded with || as convert_constant_item
2043
changes the argument
2045
if (convert_constant_item(session, field_item, &args[1]))
2046
cmp_type=INT_RESULT; // Works for all types.
2047
if (convert_constant_item(session, field_item, &args[2]))
2048
cmp_type=INT_RESULT; // Works for all types.
2054
int64_t Item_func_between::val_int()
2057
if (compare_as_dates)
2061
ge_res= ge_cmp.compare();
2062
if ((null_value= args[0]->null_value))
2064
le_res= le_cmp.compare();
2066
if (!args[1]->null_value && !args[2]->null_value)
2067
return (int64_t) ((ge_res >= 0 && le_res <=0) != negated);
2068
else if (args[1]->null_value)
2070
null_value= le_res > 0; // not null if false range.
2074
null_value= ge_res < 0;
2077
else if (cmp_type == STRING_RESULT)
2079
String *value,*a,*b;
2080
value=args[0]->val_str(&value0);
2081
if ((null_value=args[0]->null_value))
2083
a=args[1]->val_str(&value1);
2084
b=args[2]->val_str(&value2);
2085
if (!args[1]->null_value && !args[2]->null_value)
2086
return (int64_t) ((sortcmp(value,a,cmp_collation.collation) >= 0 &&
2087
sortcmp(value,b,cmp_collation.collation) <= 0) !=
2089
if (args[1]->null_value && args[2]->null_value)
2091
else if (args[1]->null_value)
2093
// Set to not null if false range.
2094
null_value= sortcmp(value,b,cmp_collation.collation) <= 0;
2098
// Set to not null if false range.
2099
null_value= sortcmp(value,a,cmp_collation.collation) >= 0;
2102
else if (cmp_type == INT_RESULT)
2104
int64_t value=args[0]->val_int(), a, b;
2105
if ((null_value=args[0]->null_value))
2107
a=args[1]->val_int();
2108
b=args[2]->val_int();
2109
if (!args[1]->null_value && !args[2]->null_value)
2110
return (int64_t) ((value >= a && value <= b) != negated);
2111
if (args[1]->null_value && args[2]->null_value)
2113
else if (args[1]->null_value)
2115
null_value= value <= b; // not null if false range.
2119
null_value= value >= a;
2122
else if (cmp_type == DECIMAL_RESULT)
2124
my_decimal dec_buf, *dec= args[0]->val_decimal(&dec_buf),
2125
a_buf, *a_dec, b_buf, *b_dec;
2126
if ((null_value=args[0]->null_value))
2128
a_dec= args[1]->val_decimal(&a_buf);
2129
b_dec= args[2]->val_decimal(&b_buf);
2130
if (!args[1]->null_value && !args[2]->null_value)
2131
return (int64_t) ((my_decimal_cmp(dec, a_dec) >= 0 &&
2132
my_decimal_cmp(dec, b_dec) <= 0) != negated);
2133
if (args[1]->null_value && args[2]->null_value)
2135
else if (args[1]->null_value)
2136
null_value= (my_decimal_cmp(dec, b_dec) <= 0);
2138
null_value= (my_decimal_cmp(dec, a_dec) >= 0);
2142
double value= args[0]->val_real(),a,b;
2143
if ((null_value=args[0]->null_value))
2145
a= args[1]->val_real();
2146
b= args[2]->val_real();
2147
if (!args[1]->null_value && !args[2]->null_value)
2148
return (int64_t) ((value >= a && value <= b) != negated);
2149
if (args[1]->null_value && args[2]->null_value)
2151
else if (args[1]->null_value)
2153
null_value= value <= b; // not null if false range.
2157
null_value= value >= a;
2160
return (int64_t) (!null_value && negated);
2164
void Item_func_between::print(String *str, enum_query_type query_type)
2167
args[0]->print(str, query_type);
2169
str->append(STRING_WITH_LEN(" not"));
2170
str->append(STRING_WITH_LEN(" between "));
2171
args[1]->print(str, query_type);
2172
str->append(STRING_WITH_LEN(" and "));
2173
args[2]->print(str, query_type);
2178
Item_func_ifnull::fix_length_and_dec()
2180
agg_result_type(&hybrid_type, args, 2);
2181
maybe_null= args[1]->maybe_null;
2182
decimals= max(args[0]->decimals, args[1]->decimals);
2183
unsigned_flag= args[0]->unsigned_flag && args[1]->unsigned_flag;
2185
if (hybrid_type == DECIMAL_RESULT || hybrid_type == INT_RESULT)
2187
int len0= args[0]->max_length - args[0]->decimals
2188
- (args[0]->unsigned_flag ? 0 : 1);
2190
int len1= args[1]->max_length - args[1]->decimals
2191
- (args[1]->unsigned_flag ? 0 : 1);
2193
max_length= max(len0, len1) + decimals + (unsigned_flag ? 0 : 1);
2196
max_length= max(args[0]->max_length, args[1]->max_length);
2198
switch (hybrid_type)
2201
agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1);
2203
case DECIMAL_RESULT:
2213
cached_field_type= agg_field_type(args, 2);
2217
uint32_t Item_func_ifnull::decimal_precision() const
2219
int max_int_part= max(args[0]->decimal_int_part(),args[1]->decimal_int_part());
2220
return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
2224
enum_field_types Item_func_ifnull::field_type() const
2226
return cached_field_type;
2229
Field *Item_func_ifnull::tmp_table_field(Table *table)
2231
return tmp_table_field_from_field_type(table, 0);
2235
Item_func_ifnull::real_op()
2238
double value= args[0]->val_real();
2239
if (!args[0]->null_value)
2244
value= args[1]->val_real();
2245
if ((null_value=args[1]->null_value))
2251
Item_func_ifnull::int_op()
2254
int64_t value=args[0]->val_int();
2255
if (!args[0]->null_value)
2260
value=args[1]->val_int();
2261
if ((null_value=args[1]->null_value))
2267
my_decimal *Item_func_ifnull::decimal_op(my_decimal *decimal_value)
2270
my_decimal *value= args[0]->val_decimal(decimal_value);
2271
if (!args[0]->null_value)
2276
value= args[1]->val_decimal(decimal_value);
2277
if ((null_value= args[1]->null_value))
2284
Item_func_ifnull::str_op(String *str)
2287
String *res =args[0]->val_str(str);
2288
if (!args[0]->null_value)
2291
res->set_charset(collation.collation);
2294
res=args[1]->val_str(str);
2295
if ((null_value=args[1]->null_value))
2297
res->set_charset(collation.collation);
2303
Perform context analysis of an IF item tree.
2305
This function performs context analysis (name resolution) and calculates
2306
various attributes of the item tree with Item_func_if as its root.
2307
The function saves in ref the pointer to the item or to a newly created
2308
item that is considered as a replacement for the original one.
2310
@param session reference to the global context of the query thread
2311
@param ref pointer to Item* variable where pointer to resulting "fixed"
2312
item is to be assigned
2315
Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
2316
a predicate/function level. Then it's easy to show that:
2318
T0(IF(e,e1,e2) = T1(IF(e,e1,e2))
2319
T1(IF(e,e1,e2)) = intersection(T1(e1),T1(e2))
2329
Item_func_if::fix_fields(Session *session, Item **ref)
2332
args[0]->top_level_item();
2334
if (Item_func::fix_fields(session, ref))
2337
not_null_tables_cache= (args[1]->not_null_tables() &
2338
args[2]->not_null_tables());
2345
Item_func_if::fix_length_and_dec()
2347
maybe_null= args[1]->maybe_null || args[2]->maybe_null;
2348
decimals= max(args[1]->decimals, args[2]->decimals);
2349
unsigned_flag= args[1]->unsigned_flag && args[2]->unsigned_flag;
2351
enum Item_result arg1_type= args[1]->result_type();
2352
enum Item_result arg2_type= args[2]->result_type();
2353
bool null1= args[1]->const_item() && args[1]->null_value;
2354
bool null2= args[2]->const_item() && args[2]->null_value;
2358
cached_result_type= arg2_type;
2359
collation.set(args[2]->collation.collation);
2360
cached_field_type= args[2]->field_type();
2364
cached_result_type= arg1_type;
2365
collation.set(args[1]->collation.collation);
2366
cached_field_type= args[1]->field_type();
2370
agg_result_type(&cached_result_type, args+1, 2);
2371
if (cached_result_type == STRING_RESULT)
2373
if (agg_arg_charsets(collation, args+1, 2, MY_COLL_ALLOW_CONV, 1))
2378
collation.set(&my_charset_bin); // Number
2380
cached_field_type= agg_field_type(args + 1, 2);
2383
if ((cached_result_type == DECIMAL_RESULT )
2384
|| (cached_result_type == INT_RESULT))
2386
int len1= args[1]->max_length - args[1]->decimals
2387
- (args[1]->unsigned_flag ? 0 : 1);
2389
int len2= args[2]->max_length - args[2]->decimals
2390
- (args[2]->unsigned_flag ? 0 : 1);
2392
max_length= max(len1, len2) + decimals + (unsigned_flag ? 0 : 1);
2395
max_length= max(args[1]->max_length, args[2]->max_length);
2399
uint32_t Item_func_if::decimal_precision() const
2401
int precision= (max(args[1]->decimal_int_part(),args[2]->decimal_int_part())+
2403
return min(precision, DECIMAL_MAX_PRECISION);
2408
Item_func_if::val_real()
2411
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2412
double value= arg->val_real();
2413
null_value=arg->null_value;
2418
Item_func_if::val_int()
2421
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2422
int64_t value=arg->val_int();
2423
null_value=arg->null_value;
2428
Item_func_if::val_str(String *str)
2431
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2432
String *res=arg->val_str(str);
2434
res->set_charset(collation.collation);
2435
null_value=arg->null_value;
2441
Item_func_if::val_decimal(my_decimal *decimal_value)
2444
Item *arg= args[0]->val_bool() ? args[1] : args[2];
2445
my_decimal *value= arg->val_decimal(decimal_value);
2446
null_value= arg->null_value;
2452
Item_func_nullif::fix_length_and_dec()
2454
Item_bool_func2::fix_length_and_dec();
2456
if (args[0]) // Only false if EOM
2458
max_length=args[0]->max_length;
2459
decimals=args[0]->decimals;
2460
unsigned_flag= args[0]->unsigned_flag;
2461
cached_result_type= args[0]->result_type();
2462
if (cached_result_type == STRING_RESULT &&
2463
agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1))
2471
Note that we have to evaluate the first argument twice as the compare
2472
may have been done with a different type than return value
2474
NULL if arguments are equal
2476
the first argument if not equal
2480
Item_func_nullif::val_real()
2489
value= args[0]->val_real();
2490
null_value=args[0]->null_value;
2495
Item_func_nullif::val_int()
2504
value=args[0]->val_int();
2505
null_value=args[0]->null_value;
2510
Item_func_nullif::val_str(String *str)
2519
res=args[0]->val_str(str);
2520
null_value=args[0]->null_value;
2526
Item_func_nullif::val_decimal(my_decimal * decimal_value)
2535
res= args[0]->val_decimal(decimal_value);
2536
null_value= args[0]->null_value;
2542
Item_func_nullif::is_null()
2544
return (null_value= (!cmp.compare() ? 1 : args[0]->null_value));
2549
Find and return matching items for CASE or ELSE item if all compares
2550
are failed or NULL if ELSE item isn't defined.
2553
In order to do correct comparisons of the CASE expression (the expression
2554
between CASE and the first WHEN) with each WHEN expression several
2555
comparators are used. One for each result type. CASE expression can be
2556
evaluated up to # of different result types are used. To check whether
2557
the CASE expression already was evaluated for a particular result type
2558
a bit mapped variable value_added_map is used. Result types are mapped
2559
to it according to their int values i.e. STRING_RESULT is mapped to bit
2560
0, REAL_RESULT to bit 1, so on.
2563
NULL Nothing found and there is no ELSE expression defined
2565
item Found item or ELSE item if defined and all comparisons are
2569
Item *Item_func_case::find_item(String *)
2571
uint32_t value_added_map= 0;
2573
if (first_expr_num == -1)
2575
for (uint32_t i=0 ; i < ncases ; i+=2)
2577
// No expression between CASE and the first WHEN
2578
if (args[i]->val_bool())
2585
/* Compare every WHEN argument with it and return the first match */
2586
for (uint32_t i=0 ; i < ncases ; i+=2)
2588
cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
2589
assert(cmp_type != ROW_RESULT);
2590
assert(cmp_items[(uint32_t)cmp_type]);
2591
if (!(value_added_map & (1<<(uint32_t)cmp_type)))
2593
cmp_items[(uint32_t)cmp_type]->store_value(args[first_expr_num]);
2594
if ((null_value=args[first_expr_num]->null_value))
2595
return else_expr_num != -1 ? args[else_expr_num] : 0;
2596
value_added_map|= 1<<(uint32_t)cmp_type;
2598
if (!cmp_items[(uint32_t)cmp_type]->cmp(args[i]) && !args[i]->null_value)
2602
// No, WHEN clauses all missed, return ELSE expression
2603
return else_expr_num != -1 ? args[else_expr_num] : 0;
2607
String *Item_func_case::val_str(String *str)
2611
Item *item=find_item(str);
2619
if (!(res=item->val_str(str)))
2625
int64_t Item_func_case::val_int()
2628
char buff[MAX_FIELD_WIDTH];
2629
String dummy_str(buff,sizeof(buff),default_charset());
2630
Item *item=find_item(&dummy_str);
2638
res=item->val_int();
2639
null_value=item->null_value;
2643
double Item_func_case::val_real()
2646
char buff[MAX_FIELD_WIDTH];
2647
String dummy_str(buff,sizeof(buff),default_charset());
2648
Item *item=find_item(&dummy_str);
2656
res= item->val_real();
2657
null_value=item->null_value;
2662
my_decimal *Item_func_case::val_decimal(my_decimal *decimal_value)
2665
char buff[MAX_FIELD_WIDTH];
2666
String dummy_str(buff, sizeof(buff), default_charset());
2667
Item *item= find_item(&dummy_str);
2676
res= item->val_decimal(decimal_value);
2677
null_value= item->null_value;
2682
bool Item_func_case::fix_fields(Session *session, Item **ref)
2685
buff should match stack usage from
2686
Item_func_case::val_int() -> Item_func_case::find_item()
2688
unsigned char buff[MAX_FIELD_WIDTH*2+sizeof(String)*2+sizeof(String*)*2
2689
+sizeof(double)*2+sizeof(int64_t)*2];
2690
bool res= Item_func::fix_fields(session, ref);
2692
Call check_stack_overrun after fix_fields to be sure that stack variable
2693
is not optimized away
2695
if (check_stack_overrun(session, STACK_MIN_SIZE, buff))
2696
return true; // Fatal error flag is set!
2701
void Item_func_case::agg_str_lengths(Item* arg)
2703
set_if_bigger(max_length, arg->max_length);
2704
set_if_bigger(decimals, arg->decimals);
2705
unsigned_flag= unsigned_flag && arg->unsigned_flag;
2709
void Item_func_case::agg_num_lengths(Item *arg)
2711
uint32_t len= my_decimal_length_to_precision(arg->max_length, arg->decimals,
2712
arg->unsigned_flag) - arg->decimals;
2713
set_if_bigger(max_length, len);
2714
set_if_bigger(decimals, arg->decimals);
2715
unsigned_flag= unsigned_flag && arg->unsigned_flag;
2719
void Item_func_case::fix_length_and_dec()
2723
uint32_t found_types= 0;
2724
if (!(agg= (Item**) memory::sql_alloc(sizeof(Item*)*(ncases+1))))
2728
Aggregate all THEN and ELSE expression types
2729
and collations when string result
2732
for (nagg= 0 ; nagg < ncases/2 ; nagg++)
2733
agg[nagg]= args[nagg*2+1];
2735
if (else_expr_num != -1)
2736
agg[nagg++]= args[else_expr_num];
2738
agg_result_type(&cached_result_type, agg, nagg);
2739
if ((cached_result_type == STRING_RESULT) &&
2740
agg_arg_charsets(collation, agg, nagg, MY_COLL_ALLOW_CONV, 1))
2743
cached_field_type= agg_field_type(agg, nagg);
2745
Aggregate first expression and all THEN expression types
2746
and collations when string comparison
2748
if (first_expr_num != -1)
2751
agg[0]= args[first_expr_num];
2752
left_result_type= agg[0]->result_type();
2754
for (nagg= 0; nagg < ncases/2 ; nagg++)
2755
agg[nagg+1]= args[nagg*2];
2757
if (!(found_types= collect_cmp_types(agg, nagg)))
2760
for (i= 0; i <= (uint32_t)DECIMAL_RESULT; i++)
2762
if (found_types & (1 << i) && !cmp_items[i])
2764
assert((Item_result)i != ROW_RESULT);
2765
if ((Item_result)i == STRING_RESULT &&
2766
agg_arg_charsets(cmp_collation, agg, nagg, MY_COLL_CMP_CONV, 1))
2769
cmp_item::get_comparator((Item_result)i,
2770
cmp_collation.collation)))
2776
if (else_expr_num == -1 || args[else_expr_num]->maybe_null)
2781
unsigned_flag= true;
2782
if (cached_result_type == STRING_RESULT)
2784
for (uint32_t i= 0; i < ncases; i+= 2)
2785
agg_str_lengths(args[i + 1]);
2786
if (else_expr_num != -1)
2787
agg_str_lengths(args[else_expr_num]);
2791
for (uint32_t i= 0; i < ncases; i+= 2)
2792
agg_num_lengths(args[i + 1]);
2793
if (else_expr_num != -1)
2794
agg_num_lengths(args[else_expr_num]);
2795
max_length= my_decimal_precision_to_length(max_length + decimals, decimals,
2801
uint32_t Item_func_case::decimal_precision() const
2804
for (uint32_t i=0 ; i < ncases ; i+=2)
2805
set_if_bigger(max_int_part, args[i+1]->decimal_int_part());
2807
if (else_expr_num != -1)
2808
set_if_bigger(max_int_part, args[else_expr_num]->decimal_int_part());
2809
return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
2815
Fix this so that it prints the whole CASE expression
2818
void Item_func_case::print(String *str, enum_query_type query_type)
2820
str->append(STRING_WITH_LEN("(case "));
2821
if (first_expr_num != -1)
2823
args[first_expr_num]->print(str, query_type);
2826
for (uint32_t i=0 ; i < ncases ; i+=2)
2828
str->append(STRING_WITH_LEN("when "));
2829
args[i]->print(str, query_type);
2830
str->append(STRING_WITH_LEN(" then "));
2831
args[i+1]->print(str, query_type);
2834
if (else_expr_num != -1)
2836
str->append(STRING_WITH_LEN("else "));
2837
args[else_expr_num]->print(str, query_type);
2840
str->append(STRING_WITH_LEN("end)"));
2844
void Item_func_case::cleanup()
2847
Item_func::cleanup();
2848
for (i= 0; i <= (uint32_t)DECIMAL_RESULT; i++)
2850
delete cmp_items[i];
2858
Coalesce - return first not NULL argument.
2861
String *Item_func_coalesce::str_op(String *str)
2865
for (uint32_t i=0 ; i < arg_count ; i++)
2868
if ((res=args[i]->val_str(str)))
2875
int64_t Item_func_coalesce::int_op()
2879
for (uint32_t i=0 ; i < arg_count ; i++)
2881
int64_t res=args[i]->val_int();
2882
if (!args[i]->null_value)
2889
double Item_func_coalesce::real_op()
2893
for (uint32_t i=0 ; i < arg_count ; i++)
2895
double res= args[i]->val_real();
2896
if (!args[i]->null_value)
2904
my_decimal *Item_func_coalesce::decimal_op(my_decimal *decimal_value)
2908
for (uint32_t i= 0; i < arg_count; i++)
2910
my_decimal *res= args[i]->val_decimal(decimal_value);
2911
if (!args[i]->null_value)
2919
void Item_func_coalesce::fix_length_and_dec()
2921
cached_field_type= agg_field_type(args, arg_count);
2922
agg_result_type(&hybrid_type, args, arg_count);
2923
switch (hybrid_type) {
2925
count_only_length();
2926
decimals= NOT_FIXED_DEC;
2927
agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1);
2929
case DECIMAL_RESULT:
2930
count_decimal_length();
2933
count_real_length();
2936
count_only_length();
2945
/****************************************************************************
2946
Classes and function for the IN operator
2947
****************************************************************************/
2950
Determine which of the signed int64_t arguments is bigger
2955
b_val right argument
2958
This function will compare two signed int64_t arguments
2959
and will return -1, 0, or 1 if left argument is smaller than,
2960
equal to or greater than the right argument.
2963
-1 left argument is smaller than the right argument.
2964
0 left argument is equal to the right argument.
2965
1 left argument is greater than the right argument.
2967
static inline int cmp_longs (int64_t a_val, int64_t b_val)
2969
return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
2974
Determine which of the unsigned int64_t arguments is bigger
2979
b_val right argument
2982
This function will compare two unsigned int64_t arguments
2983
and will return -1, 0, or 1 if left argument is smaller than,
2984
equal to or greater than the right argument.
2987
-1 left argument is smaller than the right argument.
2988
0 left argument is equal to the right argument.
2989
1 left argument is greater than the right argument.
2991
static inline int cmp_ulongs (uint64_t a_val, uint64_t b_val)
2993
return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
2998
Compare two integers in IN value list format (packed_int64_t)
3002
cmp_arg an argument passed to the calling function (my_qsort2)
3007
This function will compare two integer arguments in the IN value list
3008
format and will return -1, 0, or 1 if left argument is smaller than,
3009
equal to or greater than the right argument.
3010
It's used in sorting the IN values list and finding an element in it.
3011
Depending on the signedness of the arguments cmp_int64_t() will
3012
compare them as either signed (using cmp_longs()) or unsigned (using
3016
-1 left argument is smaller than the right argument.
3017
0 left argument is equal to the right argument.
3018
1 left argument is greater than the right argument.
3020
int cmp_int64_t(void *, in_int64_t::packed_int64_t *a,
3021
in_int64_t::packed_int64_t *b)
3023
if (a->unsigned_flag != b->unsigned_flag)
3026
One of the args is unsigned and is too big to fit into the
3027
positive signed range. Report no match.
3029
if ((a->unsigned_flag && ((uint64_t) a->val) > (uint64_t) INT64_MAX) ||
3030
(b->unsigned_flag && ((uint64_t) b->val) > (uint64_t) INT64_MAX))
3031
return a->unsigned_flag ? 1 : -1;
3033
Although the signedness differs both args can fit into the signed
3034
positive range. Make them signed and compare as usual.
3036
return cmp_longs (a->val, b->val);
3038
if (a->unsigned_flag)
3039
return cmp_ulongs ((uint64_t) a->val, (uint64_t) b->val);
3041
return cmp_longs (a->val, b->val);
3044
static int cmp_double(void *, double *a, double *b)
3046
return *a < *b ? -1 : *a == *b ? 0 : 1;
3049
static int cmp_row(void *, cmp_item_row *a, cmp_item_row *b)
3051
return a->compare(b);
3055
static int cmp_decimal(void *, my_decimal *a, my_decimal *b)
3058
We need call of fixing buffer pointer, because fast sort just copy
3059
decimal buffers in memory and pointers left pointing on old buffer place
3061
a->fix_buffer_pointer();
3062
b->fix_buffer_pointer();
3063
return my_decimal_cmp(a, b);
3067
void in_vector::sort()
3069
internal::my_qsort2(base,used_count,size,compare, (void *) collation);
3073
int in_vector::find(Item *item)
3075
unsigned char *result=get_value(item);
3076
if (!result || !used_count)
3077
return 0; // Null value
3080
start=0; end=used_count-1;
3081
while (start != end)
3083
uint32_t mid=(start+end+1)/2;
3085
if ((res=(*compare)(collation, base+mid*size, result)) == 0)
3092
return (int) ((*compare)(collation, base+start*size, result) == 0);
3095
in_string::in_string(uint32_t elements,qsort2_cmp cmp_func, const CHARSET_INFO * const cs)
3096
:in_vector(elements, sizeof(String), cmp_func, cs),
3097
tmp(buff, sizeof(buff), &my_charset_bin)
3100
in_string::~in_string()
3104
// base was allocated with help of memory::sql_alloc => following is OK
3105
for (uint32_t i=0 ; i < count ; i++)
3106
((String*) base)[i].free();
3110
void in_string::set(uint32_t pos,Item *item)
3112
String *str=((String*) base)+pos;
3113
String *res=item->val_str(str);
3114
if (res && res != str)
3116
if (res->uses_buffer_owned_by(str))
3118
if (item->type() == Item::FUNC_ITEM)
3123
if (!str->charset())
3125
const CHARSET_INFO *cs;
3126
if (!(cs= item->collation.collation))
3127
cs= &my_charset_bin; // Should never happen for STR items
3128
str->set_charset(cs);
3133
unsigned char *in_string::get_value(Item *item)
3135
return (unsigned char*) item->val_str(&tmp);
3138
in_row::in_row(uint32_t elements, Item *)
3140
base= (char*) new cmp_item_row[count= elements];
3141
size= sizeof(cmp_item_row);
3142
compare= (qsort2_cmp) cmp_row;
3144
We need to reset these as otherwise we will call sort() with
3145
uninitialized (even if not used) elements
3147
used_count= elements;
3154
delete [] (cmp_item_row*) base;
3157
unsigned char *in_row::get_value(Item *item)
3159
tmp.store_value(item);
3160
if (item->is_null())
3162
return (unsigned char *)&tmp;
3165
void in_row::set(uint32_t pos, Item *item)
3167
((cmp_item_row*) base)[pos].store_value_by_template(&tmp, item);
3171
in_int64_t::in_int64_t(uint32_t elements)
3172
:in_vector(elements,sizeof(packed_int64_t),(qsort2_cmp) cmp_int64_t, 0)
3175
void in_int64_t::set(uint32_t pos,Item *item)
3177
struct packed_int64_t *buff= &((packed_int64_t*) base)[pos];
3179
buff->val= item->val_int();
3180
buff->unsigned_flag= item->unsigned_flag;
3183
unsigned char *in_int64_t::get_value(Item *item)
3185
tmp.val= item->val_int();
3186
if (item->null_value)
3188
tmp.unsigned_flag= item->unsigned_flag;
3189
return (unsigned char*) &tmp;
3192
void in_datetime::set(uint32_t pos,Item *item)
3194
Item **tmp_item= &item;
3196
struct packed_int64_t *buff= &((packed_int64_t*) base)[pos];
3198
buff->val= get_datetime_value(session, &tmp_item, 0, warn_item, &is_null);
3199
buff->unsigned_flag= 1L;
3202
unsigned char *in_datetime::get_value(Item *item)
3205
Item **tmp_item= lval_cache ? &lval_cache : &item;
3206
tmp.val= get_datetime_value(session, &tmp_item, &lval_cache, warn_item, &is_null);
3207
if (item->null_value)
3209
tmp.unsigned_flag= 1L;
3210
return (unsigned char*) &tmp;
3213
in_double::in_double(uint32_t elements)
3214
:in_vector(elements,sizeof(double),(qsort2_cmp) cmp_double, 0)
3217
void in_double::set(uint32_t pos,Item *item)
3219
((double*) base)[pos]= item->val_real();
3222
unsigned char *in_double::get_value(Item *item)
3224
tmp= item->val_real();
3225
if (item->null_value)
3227
return (unsigned char*) &tmp;
3231
in_decimal::in_decimal(uint32_t elements)
3232
:in_vector(elements, sizeof(my_decimal),(qsort2_cmp) cmp_decimal, 0)
3236
void in_decimal::set(uint32_t pos, Item *item)
3238
/* as far as 'item' is constant, we can store reference on my_decimal */
3239
my_decimal *dec= ((my_decimal *)base) + pos;
3240
dec->len= DECIMAL_BUFF_LENGTH;
3241
dec->fix_buffer_pointer();
3242
my_decimal *res= item->val_decimal(dec);
3243
/* if item->val_decimal() is evaluated to NULL then res == 0 */
3244
if (!item->null_value && res != dec)
3245
my_decimal2decimal(res, dec);
3249
unsigned char *in_decimal::get_value(Item *item)
3251
my_decimal *result= item->val_decimal(&val);
3252
if (item->null_value)
3254
return (unsigned char *)result;
3258
cmp_item* cmp_item::get_comparator(Item_result type,
3259
const CHARSET_INFO * const cs)
3263
return new cmp_item_sort_string(cs);
3265
return new cmp_item_int;
3267
return new cmp_item_real;
3269
return new cmp_item_row;
3270
case DECIMAL_RESULT:
3271
return new cmp_item_decimal;
3276
return 0; // to satisfy compiler :)
3280
cmp_item* cmp_item_sort_string::make_same()
3282
return new cmp_item_sort_string_in_static(cmp_charset);
3285
cmp_item* cmp_item_int::make_same()
3287
return new cmp_item_int();
3290
cmp_item* cmp_item_real::make_same()
3292
return new cmp_item_real();
3295
cmp_item* cmp_item_row::make_same()
3297
return new cmp_item_row();
3301
cmp_item_row::~cmp_item_row()
3305
for (uint32_t i= 0; i < n; i++)
3308
delete comparators[i];
3315
void cmp_item_row::alloc_comparators()
3318
comparators= (cmp_item **) current_session->calloc(sizeof(cmp_item *)*n);
3322
void cmp_item_row::store_value(Item *item)
3325
alloc_comparators();
3328
item->bring_value();
3329
item->null_value= 0;
3330
for (uint32_t i=0; i < n; i++)
3332
if (!comparators[i])
3333
if (!(comparators[i]=
3334
cmp_item::get_comparator(item->element_index(i)->result_type(),
3335
item->element_index(i)->collation.collation)))
3336
break; // new failed
3337
comparators[i]->store_value(item->element_index(i));
3338
item->null_value|= item->element_index(i)->null_value;
3345
void cmp_item_row::store_value_by_template(cmp_item *t, Item *item)
3347
cmp_item_row *tmpl= (cmp_item_row*) t;
3348
if (tmpl->n != item->cols())
3350
my_error(ER_OPERAND_COLUMNS, MYF(0), tmpl->n);
3354
if ((comparators= (cmp_item **) memory::sql_alloc(sizeof(cmp_item *)*n)))
3356
item->bring_value();
3357
item->null_value= 0;
3358
for (uint32_t i=0; i < n; i++)
3360
if (!(comparators[i]= tmpl->comparators[i]->make_same()))
3361
break; // new failed
3362
comparators[i]->store_value_by_template(tmpl->comparators[i],
3363
item->element_index(i));
3364
item->null_value|= item->element_index(i)->null_value;
3370
int cmp_item_row::cmp(Item *arg)
3373
if (arg->cols() != n)
3375
my_error(ER_OPERAND_COLUMNS, MYF(0), n);
3380
for (uint32_t i=0; i < n; i++)
3382
if (comparators[i]->cmp(arg->element_index(i)))
3384
if (!arg->element_index(i)->null_value)
3389
return (arg->null_value= was_null);
3393
int cmp_item_row::compare(cmp_item *c)
3395
cmp_item_row *l_cmp= (cmp_item_row *) c;
3396
for (uint32_t i=0; i < n; i++)
3399
if ((res= comparators[i]->compare(l_cmp->comparators[i])))
3406
void cmp_item_decimal::store_value(Item *item)
3408
my_decimal *val= item->val_decimal(&value);
3409
/* val may be zero if item is nnull */
3410
if (val && val != &value)
3411
my_decimal2decimal(val, &value);
3415
int cmp_item_decimal::cmp(Item *arg)
3417
my_decimal tmp_buf, *tmp= arg->val_decimal(&tmp_buf);
3418
if (arg->null_value)
3420
return my_decimal_cmp(&value, tmp);
3424
int cmp_item_decimal::compare(cmp_item *arg)
3426
cmp_item_decimal *l_cmp= (cmp_item_decimal*) arg;
3427
return my_decimal_cmp(&value, &l_cmp->value);
3431
cmp_item* cmp_item_decimal::make_same()
3433
return new cmp_item_decimal();
3437
void cmp_item_datetime::store_value(Item *item)
3440
Item **tmp_item= lval_cache ? &lval_cache : &item;
3441
value= get_datetime_value(session, &tmp_item, &lval_cache, warn_item, &is_null);
3445
int cmp_item_datetime::cmp(Item *arg)
3448
Item **tmp_item= &arg;
3450
get_datetime_value(session, &tmp_item, 0, warn_item, &is_null);
3454
int cmp_item_datetime::compare(cmp_item *ci)
3456
cmp_item_datetime *l_cmp= (cmp_item_datetime *)ci;
3457
return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1);
3461
cmp_item *cmp_item_datetime::make_same()
3463
return new cmp_item_datetime(warn_item);
3467
bool Item_func_in::nulls_in_row()
3469
Item **arg,**arg_end;
3470
for (arg= args+1, arg_end= args+arg_count; arg != arg_end ; arg++)
3472
if ((*arg)->null_inside())
3480
Perform context analysis of an IN item tree.
3482
This function performs context analysis (name resolution) and calculates
3483
various attributes of the item tree with Item_func_in as its root.
3484
The function saves in ref the pointer to the item or to a newly created
3485
item that is considered as a replacement for the original one.
3487
@param session reference to the global context of the query thread
3488
@param ref pointer to Item* variable where pointer to resulting "fixed"
3489
item is to be assigned
3492
Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
3493
a predicate/function level. Then it's easy to show that:
3495
T0(e IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
3496
T1(e IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
3497
T0(e NOT IN(e1,...,en)) = union(T1(e),union(T1(ei)))
3498
T1(e NOT IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
3508
Item_func_in::fix_fields(Session *session, Item **ref)
3510
Item **arg, **arg_end;
3512
if (Item_func_opt_neg::fix_fields(session, ref))
3515
/* not_null_tables_cache == union(T1(e),union(T1(ei))) */
3516
if (pred_level && negated)
3519
/* not_null_tables_cache = union(T1(e),intersection(T1(ei))) */
3520
not_null_tables_cache= ~(table_map) 0;
3521
for (arg= args + 1, arg_end= args + arg_count; arg != arg_end; arg++)
3522
not_null_tables_cache&= (*arg)->not_null_tables();
3523
not_null_tables_cache|= (*args)->not_null_tables();
3528
static int srtcmp_in(const CHARSET_INFO * const cs, const String *x,const String *y)
3530
return cs->coll->strnncollsp(cs,
3531
(unsigned char *) x->ptr(),x->length(),
3532
(unsigned char *) y->ptr(),y->length(), 0);
3536
void Item_func_in::fix_length_and_dec()
3538
Item **arg, **arg_end;
3540
Session *session= current_session;
3541
bool datetime_found= false;
3542
/* true <=> arguments values will be compared as DATETIMEs. */
3543
bool compare_as_datetime= false;
3545
uint32_t found_types= 0;
3546
uint32_t type_cnt= 0, i;
3547
Item_result cmp_type= STRING_RESULT;
3548
left_result_type= args[0]->result_type();
3549
if (!(found_types= collect_cmp_types(args, arg_count, true)))
3552
for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
3554
if (!arg[0]->const_item())
3560
for (i= 0; i <= (uint32_t)DECIMAL_RESULT; i++)
3562
if (found_types & 1 << i)
3565
cmp_type= (Item_result) i;
3571
if (cmp_type == STRING_RESULT &&
3572
agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1))
3574
arg_types_compatible= true;
3579
When comparing rows create the row comparator object beforehand to ease
3580
the DATETIME comparison detection procedure.
3582
if (cmp_type == ROW_RESULT)
3584
cmp_item_row *cmp= 0;
3585
if (const_itm && !nulls_in_row())
3587
array= new in_row(arg_count-1, 0);
3588
cmp= &((in_row*)array)->tmp;
3592
if (!(cmp= new cmp_item_row))
3594
cmp_items[ROW_RESULT]= cmp;
3596
cmp->n= args[0]->cols();
3597
cmp->alloc_comparators();
3599
/* All DATE/DATETIME fields/functions has the STRING result type. */
3600
if (cmp_type == STRING_RESULT || cmp_type == ROW_RESULT)
3602
uint32_t col, num_cols= args[0]->cols();
3604
for (col= 0; col < num_cols; col++)
3606
bool skip_column= false;
3608
Check that all items to be compared has the STRING result type and at
3609
least one of them is a DATE/DATETIME item.
3611
for (arg= args, arg_end= args + arg_count; arg != arg_end ; arg++)
3613
Item *itm= ((cmp_type == STRING_RESULT) ? arg[0] :
3614
arg[0]->element_index(col));
3615
if (itm->result_type() != STRING_RESULT)
3620
else if (itm->is_datetime())
3622
datetime_found= true;
3624
Internally all DATE/DATETIME values are converted to the DATETIME
3625
type. So try to find a DATETIME item to issue correct warnings.
3629
else if (itm->field_type() == DRIZZLE_TYPE_DATETIME)
3632
/* All arguments are already checked to have the STRING result. */
3633
if (cmp_type == STRING_RESULT)
3642
if (cmp_type == ROW_RESULT)
3646
cmp= ((in_row*)array)->tmp.comparators + col;
3648
cmp= ((cmp_item_row*)cmp_items[ROW_RESULT])->comparators + col;
3649
*cmp= new cmp_item_datetime(date_arg);
3650
/* Reset variables for the next column. */
3652
datetime_found= false;
3655
compare_as_datetime= true;
3661
Row item with NULLs inside can return NULL or false =>
3662
they can't be processed as static
3664
if (type_cnt == 1 && const_itm && !nulls_in_row())
3666
if (compare_as_datetime)
3667
array= new in_datetime(date_arg, arg_count - 1);
3671
IN must compare INT columns and constants as int values (the same
3672
way as equality does).
3673
So we must check here if the column on the left and all the constant
3674
values on the right can be compared as integers and adjust the
3675
comparison type accordingly.
3677
if (args[0]->real_item()->type() == FIELD_ITEM &&
3678
session->lex->sql_command != SQLCOM_SHOW_CREATE &&
3679
cmp_type != INT_RESULT)
3681
Item_field *field_item= (Item_field*) (args[0]->real_item());
3682
if (field_item->field->can_be_compared_as_int64_t())
3684
bool all_converted= true;
3685
for (arg=args+1, arg_end=args+arg_count; arg != arg_end ; arg++)
3687
if (!convert_constant_item (session, field_item, &arg[0]))
3688
all_converted= false;
3691
cmp_type= INT_RESULT;
3696
array=new in_string(arg_count-1,(qsort2_cmp) srtcmp_in,
3697
cmp_collation.collation);
3700
array= new in_int64_t(arg_count-1);
3703
array= new in_double(arg_count-1);
3707
The row comparator was created at the beginning but only DATETIME
3708
items comparators were initialized. Call store_value() to setup
3711
((in_row*)array)->tmp.store_value(args[0]);
3713
case DECIMAL_RESULT:
3714
array= new in_decimal(arg_count - 1);
3721
if (array && !(session->is_fatal_error)) // If not EOM
3724
for (uint32_t arg_num=1 ; arg_num < arg_count ; arg_num++)
3726
if (!args[arg_num]->null_value) // Skip NULL values
3728
array->set(j,args[arg_num]);
3734
if ((array->used_count= j))
3740
if (compare_as_datetime)
3741
cmp_items[STRING_RESULT]= new cmp_item_datetime(date_arg);
3744
for (i= 0; i <= (uint32_t) DECIMAL_RESULT; i++)
3746
if (found_types & (1 << i) && !cmp_items[i])
3748
if ((Item_result)i == STRING_RESULT &&
3749
agg_arg_charsets(cmp_collation, args, arg_count,
3750
MY_COLL_CMP_CONV, 1))
3752
if (!cmp_items[i] && !(cmp_items[i]=
3753
cmp_item::get_comparator((Item_result)i,
3754
cmp_collation.collation)))
3764
void Item_func_in::print(String *str, enum_query_type query_type)
3767
args[0]->print(str, query_type);
3769
str->append(STRING_WITH_LEN(" not"));
3770
str->append(STRING_WITH_LEN(" in ("));
3771
print_args(str, 1, query_type);
3772
str->append(STRING_WITH_LEN("))"));
3777
Evaluate the function and return its value.
3783
Evaluate the function and return its value.
3786
If the array object is defined then the value of the function is
3787
calculated by means of this array.
3788
Otherwise several cmp_item objects are used in order to do correct
3789
comparison of left expression and an expression from the values list.
3790
One cmp_item object correspond to one used comparison type. Left
3791
expression can be evaluated up to number of different used comparison
3792
types. A bit mapped variable value_added_map is used to check whether
3793
the left expression already was evaluated for a particular result type.
3794
Result types are mapped to it according to their integer values i.e.
3795
STRING_RESULT is mapped to bit 0, REAL_RESULT to bit 1, so on.
3798
Value of the function
3801
int64_t Item_func_in::val_int()
3805
uint32_t value_added_map= 0;
3808
int tmp=array->find(args[0]);
3809
null_value=args[0]->null_value || (!tmp && have_null);
3810
return (int64_t) (!null_value && tmp != negated);
3813
for (uint32_t i= 1 ; i < arg_count ; i++)
3815
Item_result cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
3816
in_item= cmp_items[(uint32_t)cmp_type];
3818
if (!(value_added_map & (1 << (uint32_t)cmp_type)))
3820
in_item->store_value(args[0]);
3821
if ((null_value=args[0]->null_value))
3824
value_added_map|= 1 << (uint32_t)cmp_type;
3826
if (!in_item->cmp(args[i]) && !args[i]->null_value)
3827
return (int64_t) (!negated);
3828
have_null|= args[i]->null_value;
3831
null_value= have_null;
3832
return (int64_t) (!null_value && negated);
3836
Item_cond::Item_cond(Session *session, Item_cond *item)
3837
:Item_bool_func(session, item),
3838
abort_on_null(item->abort_on_null),
3839
and_tables_cache(item->and_tables_cache)
3842
item->list will be copied by copy_andor_arguments() call
3847
void Item_cond::copy_andor_arguments(Session *session, Item_cond *item)
3849
List_iterator_fast<Item> li(item->list);
3850
while (Item *it= li++)
3851
list.push_back(it->copy_andor_structure(session));
3856
Item_cond::fix_fields(Session *session, Item **)
3859
List_iterator<Item> li(list);
3861
void *orig_session_marker= session->session_marker;
3862
unsigned char buff[sizeof(char*)]; // Max local vars in function
3863
not_null_tables_cache= used_tables_cache= 0;
3864
const_item_cache= 1;
3866
if (functype() == COND_OR_FUNC)
3867
session->session_marker= 0;
3869
and_table_cache is the value that Item_cond_or() returns for
3872
and_tables_cache= ~(table_map) 0;
3874
if (check_stack_overrun(session, STACK_MIN_SIZE, buff))
3875
return true; // Fatal error flag is set!
3877
The following optimization reduces the depth of an AND-OR tree.
3878
E.g. a WHERE clause like
3879
F1 AND (F2 AND (F2 AND F4))
3880
is parsed into a tree with the same nested structure as defined
3881
by braces. This optimization will transform such tree into
3882
AND (F1, F2, F3, F4).
3883
Trees of OR items are flattened as well:
3884
((F1 OR F2) OR (F3 OR F4)) => OR (F1, F2, F3, F4)
3885
Items for removed AND/OR levels will dangle until the death of the
3887
The optimization is currently prepared statements and stored procedures
3888
friendly as it doesn't allocate any memory and its effects are durable
3889
(i.e. do not depend on PS/SP arguments).
3893
table_map tmp_table_map;
3894
while (item->type() == Item::COND_ITEM &&
3895
((Item_cond*) item)->functype() == functype() &&
3896
!((Item_cond*) item)->list.is_empty())
3897
{ // Identical function
3898
li.replace(((Item_cond*) item)->list);
3899
((Item_cond*) item)->list.empty();
3900
item= *li.ref(); // new current item
3903
item->top_level_item();
3905
// item can be substituted in fix_fields
3906
if ((!item->fixed &&
3907
item->fix_fields(session, li.ref())) ||
3908
(item= *li.ref())->check_cols(1))
3910
used_tables_cache|= item->used_tables();
3911
if (item->const_item())
3912
and_tables_cache= (table_map) 0;
3915
tmp_table_map= item->not_null_tables();
3916
not_null_tables_cache|= tmp_table_map;
3917
and_tables_cache&= tmp_table_map;
3918
const_item_cache= false;
3920
with_sum_func= with_sum_func || item->with_sum_func;
3921
with_subselect|= item->with_subselect;
3922
if (item->maybe_null)
3925
session->lex->current_select->cond_count+= list.elements;
3926
session->session_marker= orig_session_marker;
3927
fix_length_and_dec();
3933
void Item_cond::fix_after_pullout(Select_Lex *new_parent, Item **)
3935
List_iterator<Item> li(list);
3938
used_tables_cache=0;
3941
and_tables_cache= ~(table_map) 0; // Here and below we do as fix_fields does
3942
not_null_tables_cache= 0;
3946
table_map tmp_table_map;
3947
item->fix_after_pullout(new_parent, li.ref());
3949
used_tables_cache|= item->used_tables();
3950
const_item_cache&= item->const_item();
3952
if (item->const_item())
3953
and_tables_cache= (table_map) 0;
3956
tmp_table_map= item->not_null_tables();
3957
not_null_tables_cache|= tmp_table_map;
3958
and_tables_cache&= tmp_table_map;
3959
const_item_cache= false;
3965
bool Item_cond::walk(Item_processor processor, bool walk_subquery, unsigned char *arg)
3967
List_iterator_fast<Item> li(list);
3969
while ((item= li++))
3970
if (item->walk(processor, walk_subquery, arg))
3972
return Item_func::walk(processor, walk_subquery, arg);
3977
Transform an Item_cond object with a transformer callback function.
3979
The function recursively applies the transform method to each
3980
member item of the condition list.
3981
If the call of the method for a member item returns a new item
3982
the old item is substituted for a new one.
3983
After this the transformer is applied to the root node
3984
of the Item_cond object.
3986
@param transformer the transformer callback function to be applied to
3987
the nodes of the tree of the object
3988
@param arg parameter to be passed to the transformer
3991
Item returned as the result of transformation of the root node
3994
Item *Item_cond::transform(Item_transformer transformer, unsigned char *arg)
3996
List_iterator<Item> li(list);
3998
while ((item= li++))
4000
Item *new_item= item->transform(transformer, arg);
4005
Session::change_item_tree() should be called only if the tree was
4006
really transformed, i.e. when a new item has been created.
4007
Otherwise we'll be allocating a lot of unnecessary memory for
4008
change records at each execution.
4010
if (new_item != item)
4011
current_session->change_item_tree(li.ref(), new_item);
4013
return Item_func::transform(transformer, arg);
4018
Compile Item_cond object with a processor and a transformer
4021
First the function applies the analyzer to the root node of
4022
the Item_func object. Then if the analyzer succeeeds (returns true)
4023
the function recursively applies the compile method to member
4024
item of the condition list.
4025
If the call of the method for a member item returns a new item
4026
the old item is substituted for a new one.
4027
After this the transformer is applied to the root node
4028
of the Item_cond object.
4030
@param analyzer the analyzer callback function to be applied to the
4031
nodes of the tree of the object
4032
@param[in,out] arg_p parameter to be passed to the analyzer
4033
@param transformer the transformer callback function to be applied to the
4034
nodes of the tree of the object
4035
@param arg_t parameter to be passed to the transformer
4038
Item returned as the result of transformation of the root node
4041
Item *Item_cond::compile(Item_analyzer analyzer, unsigned char **arg_p,
4042
Item_transformer transformer, unsigned char *arg_t)
4044
if (!(this->*analyzer)(arg_p))
4047
List_iterator<Item> li(list);
4049
while ((item= li++))
4052
The same parameter value of arg_p must be passed
4053
to analyze any argument of the condition formula.
4055
unsigned char *arg_v= *arg_p;
4056
Item *new_item= item->compile(analyzer, &arg_v, transformer, arg_t);
4057
if (new_item && new_item != item)
4058
li.replace(new_item);
4060
return Item_func::transform(transformer, arg_t);
4063
void Item_cond::traverse_cond(Cond_traverser traverser,
4064
void *arg, traverse_order order)
4066
List_iterator<Item> li(list);
4071
(*traverser)(this, arg);
4072
while ((item= li++))
4074
item->traverse_cond(traverser, arg, order);
4076
(*traverser)(NULL, arg);
4079
while ((item= li++))
4081
item->traverse_cond(traverser, arg, order);
4083
(*traverser)(this, arg);
4088
Move SUM items out from item tree and replace with reference.
4090
The split is done to get an unique item for each SUM function
4091
so that we can easily find and calculate them.
4092
(Calculation done by update_sum_func() and copy_sum_funcs() in
4095
@param session Thread handler
4096
@param ref_pointer_array Pointer to array of reference fields
4097
@param fields All fields in select
4100
This function is run on all expression (SELECT list, WHERE, HAVING etc)
4101
that have or refer (HAVING) to a SUM expression.
4104
void Item_cond::split_sum_func(Session *session, Item **ref_pointer_array,
4107
List_iterator<Item> li(list);
4109
while ((item= li++))
4110
item->split_sum_func(session, ref_pointer_array,
4111
fields, li.ref(), true);
4116
Item_cond::used_tables() const
4117
{ // This caches used_tables
4118
return used_tables_cache;
4122
void Item_cond::update_used_tables()
4124
List_iterator_fast<Item> li(list);
4127
used_tables_cache=0;
4131
item->update_used_tables();
4132
used_tables_cache|= item->used_tables();
4133
const_item_cache&= item->const_item();
4138
void Item_cond::print(String *str, enum_query_type query_type)
4141
List_iterator_fast<Item> li(list);
4144
item->print(str, query_type);
4148
str->append(func_name());
4150
item->print(str, query_type);
4156
void Item_cond::neg_arguments(Session *session)
4158
List_iterator<Item> li(list);
4160
while ((item= li++)) /* Apply not transformation to the arguments */
4162
Item *new_item= item->neg_transformer(session);
4165
if (!(new_item= new Item_func_not(item)))
4166
return; // Fatal OEM error
4168
li.replace(new_item);
4174
Evaluation of AND(expr, expr, expr ...).
4177
abort_if_null is set for AND expressions for which we don't care if the
4178
result is NULL or 0. This is set for:
4184
1 If all expressions are true
4186
0 If all expressions are false or if we find a NULL expression and
4187
'abort_on_null' is set.
4189
NULL if all expression are either 1 or NULL
4193
int64_t Item_cond_and::val_int()
4196
List_iterator_fast<Item> li(list);
4201
if (!item->val_bool())
4203
if (abort_on_null || !(null_value= item->null_value))
4204
return 0; // return false
4207
return null_value ? 0 : 1;
4211
int64_t Item_cond_or::val_int()
4214
List_iterator_fast<Item> li(list);
4219
if (item->val_bool())
4224
if (item->null_value)
4231
Create an AND expression from two expressions.
4233
@param a expression or NULL
4234
@param b expression.
4235
@param org_item Don't modify a if a == *org_item.
4236
If a == NULL, org_item is set to point at b,
4237
to ensure that future calls will not modify b.
4240
This will not modify item pointed to by org_item or b
4241
The idea is that one can call this in a loop and create and
4242
'and' over all items without modifying any of the original items.
4250
Item *and_expressions(Item *a, Item *b, Item **org_item)
4253
return (*org_item= (Item*) b);
4257
if ((res= new Item_cond_and(a, (Item*) b)))
4259
res->used_tables_cache= a->used_tables() | b->used_tables();
4260
res->not_null_tables_cache= a->not_null_tables() | b->not_null_tables();
4264
if (((Item_cond_and*) a)->add((Item*) b))
4266
((Item_cond_and*) a)->used_tables_cache|= b->used_tables();
4267
((Item_cond_and*) a)->not_null_tables_cache|= b->not_null_tables();
4272
int64_t Item_func_isnull::val_int()
4276
Handle optimization if the argument can't be null
4277
This has to be here because of the test in update_used_tables().
4279
if (!used_tables_cache && !with_subselect)
4280
return cached_value;
4281
return args[0]->is_null() ? 1: 0;
4284
int64_t Item_is_not_null_test::val_int()
4287
if (!used_tables_cache && !with_subselect)
4289
owner->was_null|= (!cached_value);
4290
return(cached_value);
4292
if (args[0]->is_null())
4294
owner->was_null|= 1;
4302
Optimize case of not_null_column IS NULL.
4304
void Item_is_not_null_test::update_used_tables()
4306
if (!args[0]->maybe_null)
4308
used_tables_cache= 0; /* is always true */
4309
cached_value= (int64_t) 1;
4313
args[0]->update_used_tables();
4314
if (!(used_tables_cache=args[0]->used_tables()) && !with_subselect)
4316
/* Remember if the value is always NULL or never NULL */
4317
cached_value= (int64_t) !args[0]->is_null();
4323
int64_t Item_func_isnotnull::val_int()
4326
return args[0]->is_null() ? 0 : 1;
4330
void Item_func_isnotnull::print(String *str, enum_query_type query_type)
4333
args[0]->print(str, query_type);
4334
str->append(STRING_WITH_LEN(" is not null)"));
4338
int64_t Item_func_like::val_int()
4341
String* res = args[0]->val_str(&tmp_value1);
4342
if (args[0]->null_value)
4347
String* res2 = args[1]->val_str(&tmp_value2);
4348
if (args[1]->null_value)
4355
return turboBM_matches(res->ptr(), res->length()) ? 1 : 0;
4356
return my_wildcmp(cmp.cmp_collation.collation,
4357
res->ptr(),res->ptr()+res->length(),
4358
res2->ptr(),res2->ptr()+res2->length(),
4359
make_escape_code(cmp.cmp_collation.collation, escape),
4360
internal::wild_one,internal::wild_many) ? 0 : 1;
4365
We can optimize a where if first character isn't a wildcard
4368
Item_func::optimize_type Item_func_like::select_optimize() const
4370
if (args[1]->const_item())
4372
String* res2= args[1]->val_str((String *)&tmp_value2);
4375
return OPTIMIZE_NONE;
4377
if (*res2->ptr() != internal::wild_many)
4379
if (args[0]->result_type() != STRING_RESULT || *res2->ptr() != internal::wild_one)
4383
return OPTIMIZE_NONE;
4387
bool Item_func_like::fix_fields(Session *session, Item **ref)
4390
if (Item_bool_func2::fix_fields(session, ref) ||
4391
escape_item->fix_fields(session, &escape_item))
4394
if (!escape_item->const_during_execution())
4396
my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
4400
if (escape_item->const_item())
4403
/* If we are on execution stage */
4404
String *escape_str= escape_item->val_str(&tmp_value1);
4407
escape= (char *)memory::sql_alloc(escape_str->length());
4408
strcpy(escape, escape_str->ptr());
4412
escape= (char *)memory::sql_alloc(1);
4413
strcpy(escape, "\\");
4417
We could also do boyer-more for non-const items, but as we would have to
4418
recompute the tables for each row it's not worth it.
4420
if (args[1]->const_item() && !use_strnxfrm(collation.collation))
4422
String* res2 = args[1]->val_str(&tmp_value2);
4424
return false; // Null argument
4426
const size_t len = res2->length();
4427
const char* first = res2->ptr();
4428
const char* last = first + len - 1;
4430
len must be > 2 ('%pattern%')
4431
heuristic: only do TurboBM for pattern_len > 2
4434
if (len > MIN_TURBOBM_PATTERN_LEN + 2 &&
4435
*first == internal::wild_many &&
4436
*last == internal::wild_many)
4438
const char* tmp = first + 1;
4439
for (; *tmp != internal::wild_many && *tmp != internal::wild_one; tmp++)
4445
canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation);
4449
pattern = first + 1;
4450
pattern_len = (int) len - 2;
4451
int *suff = (int*) session->alloc((int) (sizeof(int)*
4452
((pattern_len + 1)*2+
4454
bmGs = suff + pattern_len + 1;
4455
bmBc = bmGs + pattern_len + 1;
4456
turboBM_compute_good_suffix_shifts(suff);
4457
turboBM_compute_bad_character_shifts();
4464
void Item_func_like::cleanup()
4466
canDoTurboBM= false;
4467
Item_bool_func2::cleanup();
4470
#ifdef LIKE_CMP_TOUPPER
4471
#define likeconv(cs,A) (unsigned char) (cs)->toupper(A)
4473
#define likeconv(cs,A) (unsigned char) (cs)->sort_order[(unsigned char) (A)]
4478
Precomputation dependent only on pattern_len.
4481
void Item_func_like::turboBM_compute_suffixes(int *suff)
4483
const int plm1 = pattern_len - 1;
4486
int *const splm1 = suff + plm1;
4487
const CHARSET_INFO * const cs= cmp.cmp_collation.collation;
4489
*splm1 = pattern_len;
4491
if (!cs->sort_order)
4493
for (int i = pattern_len - 2; i >= 0; i--)
4495
int tmp = *(splm1 + i - f);
4496
if (g < i && tmp < i - g)
4503
while (g >= 0 && pattern[g] == pattern[g + plm1 - f])
4511
for (int i = pattern_len - 2; 0 <= i; --i)
4513
int tmp = *(splm1 + i - f);
4514
if (g < i && tmp < i - g)
4522
likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f]))
4532
Precomputation dependent only on pattern_len.
4535
void Item_func_like::turboBM_compute_good_suffix_shifts(int *suff)
4537
turboBM_compute_suffixes(suff);
4539
int *end = bmGs + pattern_len;
4541
for (k = bmGs; k < end; k++)
4547
const int plm1 = pattern_len - 1;
4548
for (i = plm1; i > -1; i--)
4550
if (suff[i] == i + 1)
4552
for (tmp = plm1 - i; j < tmp; j++)
4554
int *tmp2 = bmGs + j;
4555
if (*tmp2 == pattern_len)
4562
for (tmp = plm1 - i; j < tmp; j++)
4565
if (*tmp2 == pattern_len)
4570
for (i = 0; i <= pattern_len - 2; i++)
4571
*(tmp2 - suff[i]) = plm1 - i;
4576
Precomputation dependent on pattern_len.
4579
void Item_func_like::turboBM_compute_bad_character_shifts()
4582
int *end = bmBc + alphabet_size;
4584
const int plm1 = pattern_len - 1;
4585
const CHARSET_INFO *const cs= cmp.cmp_collation.collation;
4587
for (i = bmBc; i < end; i++)
4590
if (!cs->sort_order)
4592
for (j = 0; j < plm1; j++)
4593
bmBc[(uint32_t) (unsigned char) pattern[j]] = plm1 - j;
4597
for (j = 0; j < plm1; j++)
4598
bmBc[(uint32_t) likeconv(cs,pattern[j])] = plm1 - j;
4604
Search for pattern in text.
4607
returns true/false for match/no match
4610
bool Item_func_like::turboBM_matches(const char* text, int text_len) const
4612
register int bcShift;
4613
register int turboShift;
4614
int shift = pattern_len;
4617
const CHARSET_INFO * const cs= cmp.cmp_collation.collation;
4619
const int plm1= pattern_len - 1;
4620
const int tlmpl= text_len - pattern_len;
4623
if (!cs->sort_order)
4627
register int i= plm1;
4628
while (i >= 0 && pattern[i] == text[i + j])
4631
if (i == plm1 - shift)
4637
register const int v = plm1 - i;
4639
bcShift = bmBc[(uint32_t) (unsigned char) text[i + j]] - plm1 + i;
4640
shift = (turboShift > bcShift) ? turboShift : bcShift;
4641
shift = (shift > bmGs[i]) ? shift : bmGs[i];
4642
if (shift == bmGs[i])
4643
u = (pattern_len - shift < v) ? pattern_len - shift : v;
4646
if (turboShift < bcShift)
4647
shift= max(shift, u + 1);
4658
register int i = plm1;
4659
while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
4662
if (i == plm1 - shift)
4669
register const int v= plm1 - i;
4671
bcShift= bmBc[(uint32_t) likeconv(cs, text[i + j])] - plm1 + i;
4672
shift= (turboShift > bcShift) ? turboShift : bcShift;
4673
shift= max(shift, bmGs[i]);
4675
if (shift == bmGs[i])
4676
u= (pattern_len - shift < v) ? pattern_len - shift : v;
4679
if (turboShift < bcShift)
4680
shift= max(shift, u + 1);
4692
Make a logical XOR of the arguments.
4694
If either operator is NULL, return NULL.
4697
(low priority) Change this to be optimized as: @n
4698
A XOR B -> (A) == 1 AND (B) <> 1) OR (A <> 1 AND (B) == 1) @n
4699
To be able to do this, we would however first have to extend the MySQL
4700
range optimizer to handle OR better.
4703
As we don't do any index optimization on XOR this is not going to be
4707
int64_t Item_cond_xor::val_int()
4710
List_iterator<Item> li(list);
4716
result^= (item->val_int() != 0);
4717
if (item->null_value)
4723
return (int64_t) result;
4727
Apply NOT transformation to the item and return a new one.
4730
Transform the item using next rules:
4732
a AND b AND ... -> NOT(a) OR NOT(b) OR ...
4733
a OR b OR ... -> NOT(a) AND NOT(b) AND ...
4741
IS NULL(a) -> IS NOT NULL(a)
4742
IS NOT NULL(a) -> IS NULL(a)
4745
@param session thread handler
4749
NULL if we cannot apply NOT transformation (see Item::neg_transformer()).
4752
Item *Item_func_not::neg_transformer(Session *) /* NOT(x) -> x */
4758
Item *Item_bool_rowready_func2::neg_transformer(Session *)
4760
Item *item= negated_item();
4766
a IS NULL -> a IS NOT NULL.
4768
Item *Item_func_isnull::neg_transformer(Session *)
4770
Item *item= new Item_func_isnotnull(args[0]);
4776
a IS NOT NULL -> a IS NULL.
4778
Item *Item_func_isnotnull::neg_transformer(Session *)
4780
Item *item= new Item_func_isnull(args[0]);
4785
Item *Item_cond_and::neg_transformer(Session *session) /* NOT(a AND b AND ...) -> */
4786
/* NOT a OR NOT b OR ... */
4788
neg_arguments(session);
4789
Item *item= new Item_cond_or(list);
4794
Item *Item_cond_or::neg_transformer(Session *session) /* NOT(a OR b OR ...) -> */
4795
/* NOT a AND NOT b AND ... */
4797
neg_arguments(session);
4798
Item *item= new Item_cond_and(list);
4803
Item *Item_func_nop_all::neg_transformer(Session *)
4805
/* "NOT (e $cmp$ ANY (SELECT ...)) -> e $rev_cmp$" ALL (SELECT ...) */
4806
Item_func_not_all *new_item= new Item_func_not_all(args[0]);
4807
Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
4808
allany->func= allany->func_creator(false);
4809
allany->all= !allany->all;
4810
allany->upper_item= new_item;
4814
Item *Item_func_not_all::neg_transformer(Session *)
4816
/* "NOT (e $cmp$ ALL (SELECT ...)) -> e $rev_cmp$" ANY (SELECT ...) */
4817
Item_func_nop_all *new_item= new Item_func_nop_all(args[0]);
4818
Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
4819
allany->all= !allany->all;
4820
allany->func= allany->func_creator(true);
4821
allany->upper_item= new_item;
4825
Item *Item_func_eq::negated_item() /* a = b -> a != b */
4827
return new Item_func_ne(args[0], args[1]);
4831
Item *Item_func_ne::negated_item() /* a != b -> a = b */
4833
return new Item_func_eq(args[0], args[1]);
4837
Item *Item_func_lt::negated_item() /* a < b -> a >= b */
4839
return new Item_func_ge(args[0], args[1]);
4843
Item *Item_func_ge::negated_item() /* a >= b -> a < b */
4845
return new Item_func_lt(args[0], args[1]);
4849
Item *Item_func_gt::negated_item() /* a > b -> a <= b */
4851
return new Item_func_le(args[0], args[1]);
4855
Item *Item_func_le::negated_item() /* a <= b -> a > b */
4857
return new Item_func_gt(args[0], args[1]);
4861
just fake method, should never be called.
4863
Item *Item_bool_rowready_func2::negated_item()
4869
Item_equal::Item_equal(Item_field *f1, Item_field *f2)
4870
: Item_bool_func(), const_item(0), eval_item(0), cond_false(0)
4872
const_item_cache= 0;
4873
fields.push_back(f1);
4874
fields.push_back(f2);
4877
Item_equal::Item_equal(Item *c, Item_field *f)
4878
: Item_bool_func(), eval_item(0), cond_false(0)
4880
const_item_cache= 0;
4881
fields.push_back(f);
4886
Item_equal::Item_equal(Item_equal *item_equal)
4887
: Item_bool_func(), eval_item(0), cond_false(0)
4889
const_item_cache= 0;
4890
List_iterator_fast<Item_field> li(item_equal->fields);
4892
while ((item= li++))
4894
fields.push_back(item);
4896
const_item= item_equal->const_item;
4897
cond_false= item_equal->cond_false;
4900
void Item_equal::add(Item *c)
4909
Item_func_eq *func= new Item_func_eq(c, const_item);
4910
func->set_cmp_func();
4911
func->quick_fix_field();
4912
if ((cond_false= !func->val_int()))
4913
const_item_cache= 1;
4916
void Item_equal::add(Item_field *f)
4918
fields.push_back(f);
4921
uint32_t Item_equal::members()
4923
return fields.elements;
4928
Check whether a field is referred in the multiple equality.
4930
The function checks whether field is occurred in the Item_equal object .
4932
@param field field whose occurrence is to be checked
4935
1 if nultiple equality contains a reference to field
4940
bool Item_equal::contains(Field *field)
4942
List_iterator_fast<Item_field> it(fields);
4944
while ((item= it++))
4946
if (field->eq(item->field))
4954
Join members of another Item_equal object.
4956
The function actually merges two multiple equalities.
4957
After this operation the Item_equal object additionally contains
4958
the field items of another item of the type Item_equal.
4959
If the optional constant items are not equal the cond_false flag is
4961
@param item multiple equality whose members are to be joined
4964
void Item_equal::merge(Item_equal *item)
4966
fields.concat(&item->fields);
4967
Item *c= item->const_item;
4971
The flag cond_false will be set to 1 after this, if
4972
the multiple equality already contains a constant and its
4973
value is not equal to the value of c.
4977
cond_false|= item->cond_false;
4982
Order field items in multiple equality according to a sorting criteria.
4984
The function perform ordering of the field items in the Item_equal
4985
object according to the criteria determined by the cmp callback parameter.
4986
If cmp(item_field1,item_field2,arg)<0 than item_field1 must be
4987
placed after item_fiel2.
4989
The function sorts field items by the exchange sort algorithm.
4990
The list of field items is looked through and whenever two neighboring
4991
members follow in a wrong order they are swapped. This is performed
4992
again and again until we get all members in a right order.
4994
@param cmp function to compare field item
4995
@param arg context extra parameter for the cmp function
4998
void Item_equal::sort(Item_field_cmpfunc cmp, void *arg)
5001
List_iterator<Item_field> it(fields);
5004
Item_field *item1= it++;
5005
Item_field **ref1= it.ref();
5009
while ((item2= it++))
5011
Item_field **ref2= it.ref();
5012
if (cmp(item1, item2, arg) < 0)
5014
Item_field *item= *ref1;
5031
Check appearance of new constant items in the multiple equality object.
5033
The function checks appearance of new constant items among
5034
the members of multiple equalities. Each new constant item is
5035
compared with the designated constant item if there is any in the
5036
multiple equality. If there is none the first new constant item
5040
void Item_equal::update_const()
5042
List_iterator<Item_field> it(fields);
5044
while ((item= it++))
5046
if (item->const_item())
5054
bool Item_equal::fix_fields(Session *, Item **)
5056
List_iterator_fast<Item_field> li(fields);
5058
not_null_tables_cache= used_tables_cache= 0;
5059
const_item_cache= 0;
5060
while ((item= li++))
5062
table_map tmp_table_map;
5063
used_tables_cache|= item->used_tables();
5064
tmp_table_map= item->not_null_tables();
5065
not_null_tables_cache|= tmp_table_map;
5066
if (item->maybe_null)
5069
fix_length_and_dec();
5074
void Item_equal::update_used_tables()
5076
List_iterator_fast<Item_field> li(fields);
5078
not_null_tables_cache= used_tables_cache= 0;
5079
if ((const_item_cache= cond_false))
5083
item->update_used_tables();
5084
used_tables_cache|= item->used_tables();
5085
const_item_cache&= item->const_item();
5089
int64_t Item_equal::val_int()
5091
Item_field *item_field;
5094
List_iterator_fast<Item_field> it(fields);
5095
Item *item= const_item ? const_item : it++;
5096
if ((null_value= item->null_value))
5098
eval_item->store_value(item);
5099
while ((item_field= it++))
5101
/* Skip fields of non-const tables. They haven't been read yet */
5102
if (item_field->field->table->const_table)
5104
if ((null_value= item_field->null_value) || eval_item->cmp(item_field))
5111
void Item_equal::fix_length_and_dec()
5113
Item *item= get_first();
5114
eval_item= cmp_item::get_comparator(item->result_type(),
5115
item->collation.collation);
5118
bool Item_equal::walk(Item_processor processor, bool walk_subquery, unsigned char *arg)
5120
List_iterator_fast<Item_field> it(fields);
5122
while ((item= it++))
5124
if (item->walk(processor, walk_subquery, arg))
5127
return Item_func::walk(processor, walk_subquery, arg);
5130
Item *Item_equal::transform(Item_transformer transformer, unsigned char *arg)
5132
List_iterator<Item_field> it(fields);
5134
while ((item= it++))
5136
Item *new_item= item->transform(transformer, arg);
5141
Session::change_item_tree() should be called only if the tree was
5142
really transformed, i.e. when a new item has been created.
5143
Otherwise we'll be allocating a lot of unnecessary memory for
5144
change records at each execution.
5146
if (new_item != item)
5147
current_session->change_item_tree((Item **) it.ref(), new_item);
5149
return Item_func::transform(transformer, arg);
5152
void Item_equal::print(String *str, enum_query_type query_type)
5154
str->append(func_name());
5156
List_iterator_fast<Item_field> it(fields);
5159
const_item->print(str, query_type);
5163
item->print(str, query_type);
5165
while ((item= it++))
5169
item->print(str, query_type);
5174
} /* namespace drizzled */