drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
cmpfunc.cc
Go to the documentation of this file.
1/* Copyright (C) 2000-2006 MySQL AB
2
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.
6
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.
11
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15
16
23
24#include <config.h>
25
26#include <drizzled/cached_item.h>
27#include <drizzled/check_stack_overrun.h>
28#include <drizzled/current_session.h>
29#include <drizzled/error.h>
30#include <drizzled/internal/my_sys.h>
31#include <drizzled/item/cache_int.h>
32#include <drizzled/item/cmpfunc.h>
33#include <drizzled/item/int_with_ref.h>
34#include <drizzled/item/subselect.h>
35#include <drizzled/session.h>
36#include <drizzled/sql_lex.h>
37#include <drizzled/sql_select.h>
38#include <drizzled/system_variables.h>
39#include <drizzled/temporal.h>
40#include <drizzled/time_functions.h>
41
42#include <math.h>
43#include <algorithm>
44
45using namespace std;
46
47namespace drizzled {
48
49extern const double log_10[309];
50
51static Eq_creator eq_creator;
52static Ne_creator ne_creator;
53static Gt_creator gt_creator;
54static Lt_creator lt_creator;
55static Ge_creator ge_creator;
56static Le_creator le_creator;
57
58static bool convert_constant_item(Session *, Item_field *, Item **);
59
60static Item_result item_store_type(Item_result a, Item *item,
61 bool unsigned_flag)
62{
63 Item_result b= item->result_type();
64
65 if (a == STRING_RESULT || b == STRING_RESULT)
66 return STRING_RESULT;
67 else if (a == REAL_RESULT || b == REAL_RESULT)
68 return REAL_RESULT;
69 else if (a == DECIMAL_RESULT || b == DECIMAL_RESULT ||
70 unsigned_flag != item->unsigned_flag)
71 return DECIMAL_RESULT;
72 else
73 return INT_RESULT;
74}
75
76static void agg_result_type(Item_result *type, Item **items, uint32_t nitems)
77{
78 Item **item, **item_end;
79 bool unsigned_flag= 0;
80
81 *type= STRING_RESULT;
82 /* Skip beginning NULL items */
83 for (item= items, item_end= item + nitems; item < item_end; item++)
84 {
85 if ((*item)->type() != Item::NULL_ITEM)
86 {
87 *type= (*item)->result_type();
88 unsigned_flag= (*item)->unsigned_flag;
89 item++;
90 break;
91 }
92 }
93 /* Combine result types. Note: NULL items don't affect the result */
94 for (; item < item_end; item++)
95 {
96 if ((*item)->type() != Item::NULL_ITEM)
97 {
98 *type= item_store_type(*type, *item, unsigned_flag);
99 }
100 }
101}
102
103
104/*
105 Compare row signature of two expressions
106
107 SYNOPSIS:
108 cmp_row_type()
109 item1 the first expression
110 item2 the second expression
111
112 DESCRIPTION
113 The function checks that two expressions have compatible row signatures
114 i.e. that the number of columns they return are the same and that if they
115 are both row expressions then each component from the first expression has
116 a row signature compatible with the signature of the corresponding component
117 of the second expression.
118
119 RETURN VALUES
120 1 type incompatibility has been detected
121 0 otherwise
122*/
123
124static int cmp_row_type(Item* item1, Item* item2)
125{
126 uint32_t n= item1->cols();
127 if (item2->check_cols(n))
128 return 1;
129 for (uint32_t i=0; i<n; i++)
130 {
131 if (item2->element_index(i)->check_cols(item1->element_index(i)->cols()) ||
132 (item1->element_index(i)->result_type() == ROW_RESULT &&
133 cmp_row_type(item1->element_index(i), item2->element_index(i))))
134 return 1;
135 }
136 return 0;
137}
138
139
162
163static int agg_cmp_type(Item_result *type, Item **items, uint32_t nitems)
164{
165 uint32_t i;
166 type[0]= items[0]->result_type();
167 for (i= 1 ; i < nitems ; i++)
168 {
169 type[0]= item_cmp_type(type[0], items[i]->result_type());
170 /*
171 When aggregating types of two row expressions we have to check
172 that they have the same cardinality and that each component
173 of the first row expression has a compatible row signature with
174 the signature of the corresponding component of the second row
175 expression.
176 */
177 if (type[0] == ROW_RESULT && cmp_row_type(items[0], items[i]))
178 return 1; // error found: invalid usage of rows
179 }
180 return 0;
181}
182
183
201
202enum_field_types agg_field_type(Item **items, uint32_t nitems)
203{
204 uint32_t i;
205 if (!nitems || items[0]->result_type() == ROW_RESULT )
206 return (enum_field_types)-1;
207 enum_field_types res= items[0]->field_type();
208 for (i= 1 ; i < nitems ; i++)
209 res= Field::field_type_merge(res, items[i]->field_type());
210 return res;
211}
212
213/*
214 Collects different types for comparison of first item with each other items
215
216 SYNOPSIS
217 collect_cmp_types()
218 items Array of items to collect types from
219 nitems Number of items in the array
220 skip_nulls Don't collect types of NULL items if TRUE
221
222 DESCRIPTION
223 This function collects different result types for comparison of the first
224 item in the list with each of the remaining items in the 'items' array.
225
226 RETURN
227 0 - if row type incompatibility has been detected (see cmp_row_type)
228 Bitmap of collected types - otherwise
229*/
230
231static uint32_t collect_cmp_types(Item **items, uint32_t nitems, bool skip_nulls= false)
232{
233 uint32_t i;
234 uint32_t found_types;
235 Item_result left_result= items[0]->result_type();
236 assert(nitems > 1);
237 found_types= 0;
238 for (i= 1; i < nitems ; i++)
239 {
240 if (skip_nulls && items[i]->type() == Item::NULL_ITEM)
241 continue; // Skip NULL constant items
242 if ((left_result == ROW_RESULT ||
243 items[i]->result_type() == ROW_RESULT) &&
244 cmp_row_type(items[0], items[i]))
245 return 0;
246 found_types|= 1<< (uint32_t)item_cmp_type(left_result,
247 items[i]->result_type());
248 }
249 /*
250 Even if all right-hand items are NULLs and we are skipping them all, we need
251 at least one type bit in the found_type bitmask.
252 */
253 if (skip_nulls && !found_types)
254 found_types= 1 << (uint)left_result;
255 return found_types;
256}
257
258
259Item_bool_func2* Eq_creator::create(Item *a, Item *b) const
260{
261 return new Item_func_eq(a, b);
262}
263
264
265const Eq_creator* Eq_creator::instance()
266{
267 return &eq_creator;
268}
269
270
271Item_bool_func2* Ne_creator::create(Item *a, Item *b) const
272{
273 return new Item_func_ne(a, b);
274}
275
276
277const Ne_creator* Ne_creator::instance()
278{
279 return &ne_creator;
280}
281
282
283Item_bool_func2* Gt_creator::create(Item *a, Item *b) const
284{
285 return new Item_func_gt(a, b);
286}
287
288
289const Gt_creator* Gt_creator::instance()
290{
291 return &gt_creator;
292}
293
294
295Item_bool_func2* Lt_creator::create(Item *a, Item *b) const
296{
297 return new Item_func_lt(a, b);
298}
299
300
301const Lt_creator* Lt_creator::instance()
302{
303 return &lt_creator;
304}
305
306
307Item_bool_func2* Ge_creator::create(Item *a, Item *b) const
308{
309 return new Item_func_ge(a, b);
310}
311
312
313const Ge_creator* Ge_creator::instance()
314{
315 return &ge_creator;
316}
317
318
319Item_bool_func2* Le_creator::create(Item *a, Item *b) const
320{
321 return new Item_func_le(a, b);
322}
323
324const Le_creator* Le_creator::instance()
325{
326 return &le_creator;
327}
328
329
330/*
331 Test functions
332 Most of these returns 0LL if false and 1LL if true and
333 NULL if some arg is NULL.
334*/
335
337{
338 assert(fixed == 1);
339 bool value= args[0]->val_bool();
340 null_value=args[0]->null_value;
341 return ((!null_value && value == 0) ? 1 : 0);
342}
343
344/*
345 We put any NOT expression into parenthesis to avoid
346 possible problems with internal view representations where
347 any '!' is converted to NOT. It may cause a problem if
348 '!' is used in an expression together with other operators
349 whose precedence is lower than the precedence of '!' yet
350 higher than the precedence of NOT.
351*/
352
354{
355 str->append('(');
356 Item_func::print(str);
357 str->append(')');
358}
359
363
364
366{
367 assert(fixed == 1);
368 bool value= args[0]->val_bool();
369
370 /*
371 return true if there was records in underlying select in max/min
372 optimization (ALL subquery)
373 */
374 if (empty_underlying_subquery())
375 return 1;
376
377 null_value= args[0]->null_value;
378 return ((!null_value && value == 0) ? 1 : 0);
379}
380
381
382bool Item_func_not_all::empty_underlying_subquery()
383{
384 return ((test_sum_item && !test_sum_item->any_value()) ||
385 (test_sub_item && !test_sub_item->any_value()));
386}
387
389{
390 if (show)
391 Item_func::print(str);
392 else
393 args[0]->print(str);
394}
395
396
405
407{
408 assert(fixed == 1);
409 int64_t value= args[0]->val_int();
410
411 /*
412 return false if there was records in underlying select in max/min
413 optimization (SAME/ANY subquery)
414 */
415 if (empty_underlying_subquery())
416 return 0;
417
418 null_value= args[0]->null_value;
419 return (null_value || value == 0) ? 0 : 1;
420}
421
422
449
450static bool convert_constant_item(Session *session, Item_field *field_item,
451 Item **item)
452{
453 Field *field= field_item->field;
454 int result= 0;
455
456 field->setWriteSet();
457
458 if (!(*item)->with_subselect && (*item)->const_item())
459 {
460 ulong orig_sql_mode= session->variables.sql_mode;
461 enum_check_fields orig_count_cuted_fields= session->count_cuted_fields;
462 uint64_t orig_field_val= 0; /* original field value if valid */
463
464 /* For comparison purposes allow invalid dates like 2000-01-32 */
465 session->variables.sql_mode= (orig_sql_mode & ~MODE_NO_ZERO_DATE) |
466 MODE_INVALID_DATES;
467 session->count_cuted_fields= CHECK_FIELD_IGNORE;
468
469 /*
470 Store the value of the field if it references an outer field because
471 the call to save_in_field below overrides that value.
472 */
473 if (field_item->depended_from)
474 {
475 orig_field_val= field->val_int();
476 }
477
478 if (!(*item)->is_null() && !(*item)->save_in_field(field, 1))
479 {
480 Item *tmp= new Item_int_with_ref(field->val_int(), *item,
481 test(field->flags & UNSIGNED_FLAG));
482 if (tmp)
483 *item= tmp;
484 result= 1; // Item was replaced
485 }
486
487 /* Restore the original field value. */
488 if (field_item->depended_from)
489 {
490 result= field->store(orig_field_val, field->isUnsigned());
491 /* orig_field_val must be a valid value that can be restored back. */
492 assert(!result);
493 }
494 session->variables.sql_mode= orig_sql_mode;
495 session->count_cuted_fields= orig_count_cuted_fields;
496 }
497 return result;
498}
499
500
501void Item_bool_func2::fix_length_and_dec()
502{
503 max_length= 1; // Function returns 0 or 1
504
505 /*
506 As some compare functions are generated after sql_yacc,
507 we have to check for out of memory conditions here
508 */
509 if (!args[0] || !args[1])
510 return;
511
512 /*
513 We allow to convert to Unicode character sets in some cases.
514 The conditions when conversion is possible are:
515 - arguments A and B have different charsets
516 - A wins according to coercibility rules
517 - character set of A is superset for character set of B
518
519 If all of the above is true, then it's possible to convert
520 B into the character set of A, and then compare according
521 to the collation of A.
522 */
523
524
525 DTCollation coll;
526 if (args[0]->result_type() == STRING_RESULT &&
527 args[1]->result_type() == STRING_RESULT &&
528 agg_arg_charsets(coll, args, 2, MY_COLL_CMP_CONV, 1))
529 return;
530
531 args[0]->cmp_context= args[1]->cmp_context=
532 item_cmp_type(args[0]->result_type(), args[1]->result_type());
533 // Make a special case of compare with fields to get nicer DATE comparisons
534
535 if (functype() == LIKE_FUNC) // Disable conversion in case of LIKE function.
536 {
537 set_cmp_func();
538 return;
539 }
540
541 Item_field *field_item= NULL;
542
543 if (args[0]->real_item()->type() == FIELD_ITEM)
544 {
545 field_item= static_cast<Item_field*>(args[0]->real_item());
546 if (field_item->field->can_be_compared_as_int64_t() &&
547 !(field_item->is_datetime() && args[1]->result_type() == STRING_RESULT))
548 {
549 if (convert_constant_item(&getSession(), field_item, &args[1]))
550 {
551 cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
552 INT_RESULT); // Works for all types.
553 args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
554 return;
555 }
556 }
557
558 if (args[1]->real_item()->type() == FIELD_ITEM)
559 {
560 field_item= static_cast<Item_field*>(args[1]->real_item());
561 if (field_item->field->can_be_compared_as_int64_t() &&
562 !(field_item->is_datetime() &&
563 args[0]->result_type() == STRING_RESULT))
564 {
565 if (convert_constant_item(&getSession(), field_item, &args[0]))
566 {
567 cmp.set_cmp_func(this, tmp_arg, tmp_arg+1,
568 INT_RESULT); // Works for all types.
569 args[0]->cmp_context= args[1]->cmp_context= INT_RESULT;
570 return;
571 }
572 }
573 }
574 }
575 set_cmp_func();
576}
577
578Arg_comparator::Arg_comparator():
579 session(current_session),
580 a_cache(0),
581 b_cache(0)
582{}
583
584Arg_comparator::Arg_comparator(Item **a1, Item **a2):
585 a(a1),
586 b(a2),
587 session(current_session),
588 a_cache(0),
589 b_cache(0)
590{}
591
592int Arg_comparator::set_compare_func(Item_bool_func2 *item, Item_result type)
593{
594 owner= item;
595 func= comparator_matrix[type]
596 [test(owner->functype() == Item_func::EQUAL_FUNC)];
597
598 switch (type) {
599 case ROW_RESULT:
600 {
601 uint32_t n= (*a)->cols();
602 if (n != (*b)->cols())
603 {
604 my_error(ER_OPERAND_COLUMNS, MYF(0), n);
605 comparators= 0;
606 return 1;
607 }
608 comparators= new Arg_comparator[n];
609 for (uint32_t i=0; i < n; i++)
610 {
611 if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols())
612 {
613 my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
614 return 1;
615 }
616 comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i));
617 }
618 break;
619 }
620
621 case STRING_RESULT:
622 {
623 /*
624 We must set cmp_charset here as we may be called from for an automatic
625 generated item, like in natural join
626 */
627 if (cmp_collation.set((*a)->collation, (*b)->collation) ||
628 cmp_collation.derivation == DERIVATION_NONE)
629 {
630 my_coll_agg_error((*a)->collation, (*b)->collation, owner->func_name());
631 return 1;
632 }
633 if (cmp_collation.collation == &my_charset_bin)
634 {
635 /*
636 We are using BLOB/BINARY/VARBINARY, change to compare byte by byte,
637 without removing end space
638 */
639 if (func == &Arg_comparator::compare_string)
640 func= &Arg_comparator::compare_binary_string;
641 else if (func == &Arg_comparator::compare_e_string)
642 func= &Arg_comparator::compare_e_binary_string;
643
644 /*
645 As this is binary compassion, mark all fields that they can't be
646 transformed. Otherwise we would get into trouble with comparisons
647like:
648WHERE col= 'j' AND col LIKE BINARY 'j'
649which would be transformed to:
650WHERE col= 'j'
651 */
652 (*a)->walk(&Item::set_no_const_sub, false, (unsigned char*) 0);
653 (*b)->walk(&Item::set_no_const_sub, false, (unsigned char*) 0);
654 }
655 break;
656 }
657 case INT_RESULT:
658 {
659 if (func == &Arg_comparator::compare_int_signed)
660 {
661 if ((*a)->unsigned_flag)
662 func= (((*b)->unsigned_flag)?
663 &Arg_comparator::compare_int_unsigned :
664 &Arg_comparator::compare_int_unsigned_signed);
665 else if ((*b)->unsigned_flag)
666 func= &Arg_comparator::compare_int_signed_unsigned;
667 }
668 else if (func== &Arg_comparator::compare_e_int)
669 {
670 if ((*a)->unsigned_flag ^ (*b)->unsigned_flag)
671 func= &Arg_comparator::compare_e_int_diff_signedness;
672 }
673 break;
674 }
675 case DECIMAL_RESULT:
676 break;
677 case REAL_RESULT:
678 {
679 if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC)
680 {
681 precision= 5 / log_10[max((*a)->decimals, (*b)->decimals) + 1];
682 if (func == &Arg_comparator::compare_real)
683 func= &Arg_comparator::compare_real_fixed;
684 else if (func == &Arg_comparator::compare_e_real)
685 func= &Arg_comparator::compare_e_real_fixed;
686 }
687 break;
688 }
689 }
690
691 return 0;
692}
693
694
716
717static int64_t
718get_date_from_str(Session *session, String *str, type::timestamp_t warn_type, const char *warn_name, bool *error_arg)
719{
720 int64_t value= 0;
721 type::cut_t error= type::VALID;
722 type::Time l_time;
723 type::timestamp_t ret;
724
725 ret= l_time.store(str->ptr(), str->length(),
726 (TIME_FUZZY_DATE | MODE_INVALID_DATES | (session->variables.sql_mode & MODE_NO_ZERO_DATE)),
727 error);
728
729 if (ret == type::DRIZZLE_TIMESTAMP_DATETIME || ret == type::DRIZZLE_TIMESTAMP_DATE)
730 {
731 /*
732 Do not return yet, we may still want to throw a "trailing garbage"
733 warning.
734 */
735 *error_arg= false;
736 l_time.convert(value);
737 }
738 else
739 {
740 *error_arg= true;
741 error= type::CUT; /* force warning */
742 }
743
744 if (error != type::VALID)
745 {
746 make_truncated_value_warning(*session, DRIZZLE_ERROR::WARN_LEVEL_WARN, *str, warn_type, warn_name);
747 }
748
749 return value;
750}
751
752
753/*
754 Check whether compare_datetime() can be used to compare items.
755
756 SYNOPSIS
757 Arg_comparator::can_compare_as_dates()
758 a, b [in] items to be compared
759 const_value [out] converted value of the string constant, if any
760
761 DESCRIPTION
762 Check several cases when the DATE/DATETIME comparator should be used.
763 The following cases are checked:
764 1. Both a and b is a DATE/DATETIME field/function returning string or
765 int result.
766 2. Only a or b is a DATE/DATETIME field/function returning string or
767 int result and the other item (b or a) is an item with string result.
768 If the second item is a constant one then it's checked to be
769 convertible to the DATE/DATETIME type. If the constant can't be
770 converted to a DATE/DATETIME then an error is issued back to the Session.
771 In all other cases (date-[int|real|decimal]/[int|real|decimal]-date)
772 the comparison is handled by other comparators.
773
774 If the datetime comparator can be used and one the operands of the
775 comparison is a string constant that was successfully converted to a
776 DATE/DATETIME type then the result of the conversion is returned in the
777 const_value if it is provided. If there is no constant or
778 compare_datetime() isn't applicable then the *const_value remains
779 unchanged.
780
781 RETURN
782 the found type of date comparison
783*/
784
785enum Arg_comparator::enum_date_cmp_type
786Arg_comparator::can_compare_as_dates(Item *in_a, Item *in_b,
787 int64_t *const_value)
788{
789 enum enum_date_cmp_type cmp_type= CMP_DATE_DFLT;
790 Item *str_arg= 0;
791
792 if (in_a->type() == Item::ROW_ITEM || in_b->type() == Item::ROW_ITEM)
793 return CMP_DATE_DFLT;
794
795 if (in_a->is_datetime())
796 {
797 if (in_b->is_datetime())
798 {
799 cmp_type= CMP_DATE_WITH_DATE;
800 }
801 else if (in_b->result_type() == STRING_RESULT)
802 {
803 cmp_type= CMP_DATE_WITH_STR;
804 str_arg= in_b;
805 }
806 }
807 else if (in_b->is_datetime() && in_a->result_type() == STRING_RESULT)
808 {
809 cmp_type= CMP_STR_WITH_DATE;
810 str_arg= in_a;
811 }
812
813 if (cmp_type != CMP_DATE_DFLT)
814 {
815 /*
816 Do not cache GET_USER_VAR() function as its const_item() may return true
817 for the current thread but it still may change during the execution.
818 */
819 if (cmp_type != CMP_DATE_WITH_DATE && str_arg->const_item() &&
820 (str_arg->type() != Item::FUNC_ITEM ||
821 ((Item_func*)str_arg)->functype() != Item_func::GUSERVAR_FUNC))
822 {
823 /*
824 * OK, we are here if we've got a date field (or something which can be
825 * compared as a date field) on one side of the equation, and a constant
826 * string on the other side. In this case, we must verify that the constant
827 * string expression can indeed be evaluated as a datetime. If it cannot,
828 * we throw an error here and stop processsing. Bad data should ALWAYS
829 * produce an error, and no implicit conversion or truncation should take place.
830 *
831 * If the conversion to a DateTime temporal is successful, then we convert
832 * the Temporal instance to a uint64_t for the comparison operator, which
833 * compares date(times) using int64_t semantics.
834 *
835 * @TODO
836 *
837 * Does a uint64_t conversion really have to happen here? Fields return int64_t
838 * from val_int(), not uint64_t...
839 */
840 int64_t value;
841 String *str_val;
842 String tmp;
843 /* DateTime used to pick up as many string conversion possibilities as possible. */
844 DateTime temporal;
845
846 str_val= str_arg->val_str(&tmp);
847 if (! str_val)
848 {
849 /*
850 * If we are here, it is most likely due to the comparison item
851 * being a NULL. Although this is incorrect (SQL demands that the term IS NULL
852 * be used, not = NULL since no item can be equal to NULL).
853 *
854 * So, return gracefully.
855 */
856 return CMP_DATE_DFLT;
857 }
858 if (temporal.from_string(str_val->c_ptr(), str_val->length()))
859 {
860 /* String conversion was good. Convert to an integer for comparison purposes. */
861 temporal.to_int64_t(&value);
862 }
863 else
864 {
865 /* We aren't a DATETIME but still could be a TIME */
866 Time timevalue;
867 if (timevalue.from_string(str_val->c_ptr(), str_val->length()))
868 {
869 uint64_t timeint;
870 timevalue.to_uint64_t(timeint);
871 value= static_cast<int64_t>(timeint);
872 }
873 else
874 {
875 /* Chuck an error. Bad datetime input. */
876 my_error(ER_INVALID_DATETIME_VALUE, MYF(ME_FATALERROR), str_val->c_ptr());
877 return CMP_DATE_DFLT; /* :( What else can I return... */
878 }
879 }
880
881 if (const_value)
882 *const_value= value;
883 }
884 }
885 return cmp_type;
886}
887
888
889int Arg_comparator::set_cmp_func(Item_bool_func2 *owner_arg,
890 Item **a1, Item **a2,
891 Item_result type)
892{
893 enum_date_cmp_type cmp_type;
894 int64_t const_value= -1;
895 a= a1;
896 b= a2;
897
898 if ((cmp_type= can_compare_as_dates(*a, *b, &const_value)))
899 {
900 owner= owner_arg;
901 a_type= (*a)->field_type();
902 b_type= (*b)->field_type();
903 a_cache= 0;
904 b_cache= 0;
905
906 if (const_value != -1)
907 {
908 Item_cache_int *cache= new Item_cache_int();
909 /* Mark the cache as non-const to prevent re-caching. */
910 cache->set_used_tables(1);
911 if (!(*a)->is_datetime())
912 {
913 cache->store((*a), const_value);
914 a_cache= cache;
915 a= (Item **)&a_cache;
916 }
917 else
918 {
919 cache->store((*b), const_value);
920 b_cache= cache;
921 b= (Item **)&b_cache;
922 }
923 }
924 is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC);
925 func= &Arg_comparator::compare_datetime;
926 get_value_func= &get_datetime_value;
927
928 return 0;
929 }
930
931 return set_compare_func(owner_arg, type);
932}
933
934
935void Arg_comparator::set_datetime_cmp_func(Item **a1, Item **b1)
936{
937 /* A caller will handle null values by itself. */
938 owner= NULL;
939 a= a1;
940 b= b1;
941 a_type= (*a)->field_type();
942 b_type= (*b)->field_type();
943 a_cache= 0;
944 b_cache= 0;
945 is_nulls_eq= false;
946 func= &Arg_comparator::compare_datetime;
947 get_value_func= &get_datetime_value;
948}
949
950
951/*
952 Retrieves correct DATETIME value from given item.
953
954 SYNOPSIS
955 get_datetime_value()
956 session thread handle
957 item_arg [in/out] item to retrieve DATETIME value from
958 cache_arg [in/out] pointer to place to store the caching item to
959 warn_item [in] item for issuing the conversion warning
960 is_null [out] true <=> the item_arg is null
961
962 DESCRIPTION
963 Retrieves the correct DATETIME value from given item for comparison by the
964 compare_datetime() function.
965 If item's result can be compared as int64_t then its int value is used
966 and its string value is used otherwise. Strings are always parsed and
967 converted to int values by the get_date_from_str() function.
968 This allows us to compare correctly string dates with missed insignificant
969 zeros. If an item is a constant one then its value is cached and it isn't
970 get parsed again. An Item_cache_int object is used for caching values. It
971 seamlessly substitutes the original item. The cache item is marked as
972 non-constant to prevent re-caching it again. In order to compare
973 correctly DATE and DATETIME items the result of the former are treated as
974 a DATETIME with zero time (00:00:00).
975
976 RETURN
977 obtained value
978*/
979
980int64_t
981get_datetime_value(Session *session, Item ***item_arg, Item **cache_arg,
982 Item *warn_item, bool *is_null)
983{
984 int64_t value= 0;
985 String buf, *str= 0;
986 Item *item= **item_arg;
987
988 if (item->result_as_int64_t())
989 {
990 value= item->val_int();
991 *is_null= item->null_value;
992 enum_field_types f_type= item->field_type();
993 /*
994 Item_date_add_interval may return DRIZZLE_TYPE_STRING as the result
995 field type. To detect that the DATE value has been returned we
996 compare it with 100000000L - any DATE value should be less than it.
997 Don't shift cached DATETIME values up for the second time.
998 */
999 if (f_type == DRIZZLE_TYPE_DATE ||
1000 (f_type != DRIZZLE_TYPE_DATETIME && value < 100000000L))
1001 value*= 1000000L;
1002 }
1003 else
1004 {
1005 str= item->val_str(&buf);
1006 *is_null= item->null_value;
1007 }
1008
1009 if (*is_null)
1010 return ~(uint64_t) 0;
1011
1012 /*
1013 Convert strings to the integer DATE/DATETIME representation.
1014 Even if both dates provided in strings we can't compare them directly as
1015 strings as there is no warranty that they are correct and do not miss
1016 some insignificant zeros.
1017 */
1018 if (str)
1019 {
1020 bool error;
1021 enum_field_types f_type= warn_item->field_type();
1022 type::timestamp_t t_type= f_type == DRIZZLE_TYPE_DATE ? type::DRIZZLE_TIMESTAMP_DATE : type::DRIZZLE_TIMESTAMP_DATETIME;
1023 value= get_date_from_str(session, str, t_type, warn_item->name, &error);
1024 /*
1025 If str did not contain a valid date according to the current
1026 SQL_MODE, get_date_from_str() has already thrown a warning,
1027 and we don't want to throw NULL on invalid date (see 5.2.6
1028 "SQL modes" in the manual), so we're done here.
1029 */
1030 }
1031 /*
1032 Do not cache GET_USER_VAR() function as its const_item() may return true
1033 for the current thread but it still may change during the execution.
1034 */
1035 if (item->const_item() && cache_arg && (item->type() != Item::FUNC_ITEM ||
1036 ((Item_func*)item)->functype() != Item_func::GUSERVAR_FUNC))
1037 {
1038 Item_cache_int *cache= new Item_cache_int(DRIZZLE_TYPE_DATETIME);
1039 /* Mark the cache as non-const to prevent re-caching. */
1040 cache->set_used_tables(1);
1041 cache->store(item, value);
1042 *cache_arg= cache;
1043 *item_arg= cache_arg;
1044 }
1045
1046 return value;
1047}
1048
1049/*
1050 Compare items values as dates.
1051
1052 SYNOPSIS
1053 Arg_comparator::compare_datetime()
1054
1055 DESCRIPTION
1056 Compare items values as DATE/DATETIME for both EQUAL_FUNC and from other
1057 comparison functions. The correct DATETIME values are obtained
1058 with help of the get_datetime_value() function.
1059
1060 RETURN
1061 If is_nulls_eq is true:
1062 1 if items are equal or both are null
1063 0 otherwise
1064 If is_nulls_eq is false:
1065 -1 a < b or one of items is null
1066 0 a == b
1067 1 a > b
1068*/
1069
1070int Arg_comparator::compare_datetime()
1071{
1072 bool is_null= false;
1073 uint64_t a_value, b_value;
1074
1075 /* Get DATE/DATETIME/TIME value of the 'a' item. */
1076 a_value= (*get_value_func)(session, &a, &a_cache, *b, &is_null);
1077 if (!is_nulls_eq && is_null)
1078 {
1079 if (owner)
1080 owner->null_value= 1;
1081 return -1;
1082 }
1083
1084 /* Get DATE/DATETIME/TIME value of the 'b' item. */
1085 b_value= (*get_value_func)(session, &b, &b_cache, *a, &is_null);
1086 if (is_null)
1087 {
1088 if (owner)
1089 owner->null_value= is_nulls_eq ? 0 : 1;
1090 return is_nulls_eq ? 1 : -1;
1091 }
1092
1093 if (owner)
1094 owner->null_value= 0;
1095
1096 /* Compare values. */
1097 if (is_nulls_eq)
1098 return (a_value == b_value);
1099 return (a_value < b_value) ? -1 : ((a_value > b_value) ? 1 : 0);
1100}
1101
1102
1103int Arg_comparator::compare_string()
1104{
1105 String *res1,*res2;
1106 if ((res1= (*a)->val_str(&owner->tmp_value1)))
1107 {
1108 if ((res2= (*b)->val_str(&owner->tmp_value2)))
1109 {
1110 owner->null_value= 0;
1111 return sortcmp(res1,res2,cmp_collation.collation);
1112 }
1113 }
1114 owner->null_value= 1;
1115 return -1;
1116}
1117
1118
1129
1131{
1132 String *res1,*res2;
1133 if ((res1= (*a)->val_str(&owner->tmp_value1)))
1134 {
1135 if ((res2= (*b)->val_str(&owner->tmp_value2)))
1136 {
1137 owner->null_value= 0;
1138 uint32_t res1_length= res1->length();
1139 uint32_t res2_length= res2->length();
1140 int cmp= memcmp(res1->ptr(), res2->ptr(), min(res1_length,res2_length));
1141 return cmp ? cmp : (int) (res1_length - res2_length);
1142 }
1143 }
1144 owner->null_value= 1;
1145 return -1;
1146}
1147
1148
1152
1153
1155{
1156 String *res1,*res2;
1157 res1= (*a)->val_str(&owner->tmp_value1);
1158 res2= (*b)->val_str(&owner->tmp_value2);
1159 if (!res1 || !res2)
1160 return test(res1 == res2);
1161 return test(sortcmp(res1, res2, cmp_collation.collation) == 0);
1162}
1163
1164
1165int Arg_comparator::compare_e_binary_string()
1166{
1167 String *res1,*res2;
1168 res1= (*a)->val_str(&owner->tmp_value1);
1169 res2= (*b)->val_str(&owner->tmp_value2);
1170 if (!res1 || !res2)
1171 return test(res1 == res2);
1172 return test(stringcmp(res1, res2) == 0);
1173}
1174
1175
1176int Arg_comparator::compare_real()
1177{
1178 /*
1179 Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1180 gcc to flush double values out of 80-bit Intel FPU registers before
1181 performing the comparison.
1182 */
1183 volatile double val1, val2;
1184 val1= (*a)->val_real();
1185 if (!(*a)->null_value)
1186 {
1187 val2= (*b)->val_real();
1188 if (!(*b)->null_value)
1189 {
1190 owner->null_value= 0;
1191 if (val1 < val2) return -1;
1192 if (compare_double(val1, val2)) return 0;
1193 return 1;
1194 }
1195 }
1196 owner->null_value= 1;
1197 return -1;
1198}
1199
1200int Arg_comparator::compare_decimal()
1201{
1202 type::Decimal value1;
1203 type::Decimal *val1= (*a)->val_decimal(&value1);
1204 if (!(*a)->null_value)
1205 {
1206 type::Decimal value2;
1207 type::Decimal *val2= (*b)->val_decimal(&value2);
1208 if (!(*b)->null_value)
1209 {
1210 owner->null_value= 0;
1211 return class_decimal_cmp(val1, val2);
1212 }
1213 }
1214 owner->null_value= 1;
1215 return -1;
1216}
1217
1218int Arg_comparator::compare_e_real()
1219{
1220 double val1= (*a)->val_real();
1221 double val2= (*b)->val_real();
1222 if ((*a)->null_value || (*b)->null_value)
1223 return test((*a)->null_value && (*b)->null_value);
1224 return test(compare_double(val1, val2));
1225}
1226
1227int Arg_comparator::compare_e_decimal()
1228{
1229 type::Decimal value1, value2;
1230 type::Decimal *val1= (*a)->val_decimal(&value1);
1231 type::Decimal *val2= (*b)->val_decimal(&value2);
1232 if ((*a)->null_value || (*b)->null_value)
1233 return test((*a)->null_value && (*b)->null_value);
1234 return test(class_decimal_cmp(val1, val2) == 0);
1235}
1236
1237
1238int Arg_comparator::compare_real_fixed()
1239{
1240 /*
1241 Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
1242 gcc to flush double values out of 80-bit Intel FPU registers before
1243 performing the comparison.
1244 */
1245 volatile double val1, val2;
1246 val1= (*a)->val_real();
1247 if (!(*a)->null_value)
1248 {
1249 val2= (*b)->val_real();
1250 if (!(*b)->null_value)
1251 {
1252 owner->null_value= 0;
1253 if (compare_double(val1, val2) || fabs(val1 - val2) < precision)
1254 return 0;
1255 if (val1 < val2)
1256 return -1;
1257 return 1;
1258 }
1259 }
1260 owner->null_value= 1;
1261 return -1;
1262}
1263
1264
1265int Arg_comparator::compare_e_real_fixed()
1266{
1267 double val1= (*a)->val_real();
1268 double val2= (*b)->val_real();
1269 if ((*a)->null_value || (*b)->null_value)
1270 return test((*a)->null_value && (*b)->null_value);
1271 return test(compare_double(val1, val2) || fabs(val1 - val2) < precision);
1272}
1273
1274
1275int Arg_comparator::compare_int_signed()
1276{
1277 int64_t val1= (*a)->val_int();
1278 if (!(*a)->null_value)
1279 {
1280 int64_t val2= (*b)->val_int();
1281 if (!(*b)->null_value)
1282 {
1283 owner->null_value= 0;
1284 if (val1 < val2) return -1;
1285 if (val1 == val2) return 0;
1286 return 1;
1287 }
1288 }
1289 owner->null_value= 1;
1290 return -1;
1291}
1292
1293
1297
1299{
1300 uint64_t val1= (*a)->val_int();
1301 if (!(*a)->null_value)
1302 {
1303 uint64_t val2= (*b)->val_int();
1304 if (!(*b)->null_value)
1305 {
1306 owner->null_value= 0;
1307 if (val1 < val2) return -1;
1308 if (val1 == val2) return 0;
1309 return 1;
1310 }
1311 }
1312 owner->null_value= 1;
1313 return -1;
1314}
1315
1316
1320
1322{
1323 int64_t sval1= (*a)->val_int();
1324 if (!(*a)->null_value)
1325 {
1326 uint64_t uval2= (uint64_t)(*b)->val_int();
1327 if (!(*b)->null_value)
1328 {
1329 owner->null_value= 0;
1330 if (sval1 < 0 || (uint64_t)sval1 < uval2)
1331 return -1;
1332 if ((uint64_t)sval1 == uval2)
1333 return 0;
1334 return 1;
1335 }
1336 }
1337 owner->null_value= 1;
1338 return -1;
1339}
1340
1341
1345
1347{
1348 uint64_t uval1= (uint64_t)(*a)->val_int();
1349 if (!(*a)->null_value)
1350 {
1351 int64_t sval2= (*b)->val_int();
1352 if (!(*b)->null_value)
1353 {
1354 owner->null_value= 0;
1355 if (sval2 < 0)
1356 return 1;
1357 if (uval1 < (uint64_t)sval2)
1358 return -1;
1359 if (uval1 == (uint64_t)sval2)
1360 return 0;
1361 return 1;
1362 }
1363 }
1364 owner->null_value= 1;
1365 return -1;
1366}
1367
1368
1369int Arg_comparator::compare_e_int()
1370{
1371 int64_t val1= (*a)->val_int();
1372 int64_t val2= (*b)->val_int();
1373 if ((*a)->null_value || (*b)->null_value)
1374 return test((*a)->null_value && (*b)->null_value);
1375 return test(val1 == val2);
1376}
1377
1382{
1383 int64_t val1= (*a)->val_int();
1384 int64_t val2= (*b)->val_int();
1385 if ((*a)->null_value || (*b)->null_value)
1386 return test((*a)->null_value && (*b)->null_value);
1387 return (val1 >= 0) && test(val1 == val2);
1388}
1389
1390int Arg_comparator::compare_row()
1391{
1392 int res= 0;
1393 bool was_null= 0;
1394 (*a)->bring_value();
1395 (*b)->bring_value();
1396 uint32_t n= (*a)->cols();
1397 for (uint32_t i= 0; i<n; i++)
1398 {
1399 res= comparators[i].compare();
1400 if (owner->null_value)
1401 {
1402 // NULL was compared
1403 switch (owner->functype()) {
1404 case Item_func::NE_FUNC:
1405 break; // NE never aborts on NULL even if abort_on_null is set
1406 case Item_func::LT_FUNC:
1407 case Item_func::LE_FUNC:
1408 case Item_func::GT_FUNC:
1409 case Item_func::GE_FUNC:
1410 return -1; // <, <=, > and >= always fail on NULL
1411 default: // EQ_FUNC
1412 if (owner->abort_on_null)
1413 return -1; // We do not need correct NULL returning
1414 }
1415 was_null= 1;
1416 owner->null_value= 0;
1417 res= 0; // continue comparison (maybe we will meet explicit difference)
1418 }
1419 else if (res)
1420 return res;
1421 }
1422 if (was_null)
1423 {
1424 /*
1425 There was NULL(s) in comparison in some parts, but there was no
1426 explicit difference in other parts, so we have to return NULL.
1427 */
1428 owner->null_value= 1;
1429 return -1;
1430 }
1431 return 0;
1432}
1433
1434
1435int Arg_comparator::compare_e_row()
1436{
1437 (*a)->bring_value();
1438 (*b)->bring_value();
1439 uint32_t n= (*a)->cols();
1440 for (uint32_t i= 0; i<n; i++)
1441 {
1442 if (!comparators[i].compare())
1443 return 0;
1444 }
1445 return 1;
1446}
1447
1448
1449void Item_func_truth::fix_length_and_dec()
1450{
1451 maybe_null= 0;
1452 null_value= 0;
1453 decimals= 0;
1454 max_length= 1;
1455}
1456
1457
1459{
1460 str->append('(');
1461 args[0]->print(str);
1462 str->append(STRING_WITH_LEN(" is "));
1463 if (! affirmative)
1464 str->append(STRING_WITH_LEN("not "));
1465 if (value)
1466 str->append(STRING_WITH_LEN("true"));
1467 else
1468 str->append(STRING_WITH_LEN("false"));
1469 str->append(')');
1470}
1471
1472
1474{
1475 bool val= args[0]->val_bool();
1476 if (args[0]->null_value)
1477 {
1478 /*
1479 NULL val IS {true, false} --> false
1480 NULL val IS NOT {true, false} --> true
1481 */
1482 return (! affirmative);
1483 }
1484
1485 if (affirmative)
1486 {
1487 /* {true, false} val IS {true, false} value */
1488 return (val == value);
1489 }
1490
1491 /* {true, false} val IS NOT {true, false} value */
1492 return (val != value);
1493}
1494
1495
1497{
1498 return (val_bool() ? 1 : 0);
1499}
1500
1501
1502bool Item_in_optimizer::fix_left(Session *session, Item **)
1503{
1504 if ((!args[0]->fixed && args[0]->fix_fields(session, args)) ||
1505 (!cache && !(cache= Item_cache::get_cache(args[0]))))
1506 return 1;
1507
1508 cache->setup(args[0]);
1509 if (cache->cols() == 1)
1510 {
1511 if ((used_tables_cache= args[0]->used_tables()))
1512 cache->set_used_tables(OUTER_REF_TABLE_BIT);
1513 else
1514 cache->set_used_tables(0);
1515 }
1516 else
1517 {
1518 uint32_t n= cache->cols();
1519 for (uint32_t i= 0; i < n; i++)
1520 {
1521 if (args[0]->element_index(i)->used_tables())
1522 ((Item_cache *)cache->element_index(i))->set_used_tables(OUTER_REF_TABLE_BIT);
1523 else
1524 ((Item_cache *)cache->element_index(i))->set_used_tables(0);
1525 }
1526 used_tables_cache= args[0]->used_tables();
1527 }
1528 not_null_tables_cache= args[0]->not_null_tables();
1529 with_sum_func= args[0]->with_sum_func;
1530 if ((const_item_cache= args[0]->const_item()))
1531 cache->store(args[0]);
1532 return 0;
1533}
1534
1535
1536bool Item_in_optimizer::fix_fields(Session *session, Item **ref)
1537{
1538 assert(fixed == 0);
1539 if (fix_left(session, ref))
1540 return true;
1541 if (args[0]->maybe_null)
1542 maybe_null=1;
1543
1544 if (!args[1]->fixed && args[1]->fix_fields(session, args+1))
1545 return true;
1546 Item_in_subselect * sub= (Item_in_subselect *)args[1];
1547 if (args[0]->cols() != sub->engine->cols())
1548 {
1549 my_error(ER_OPERAND_COLUMNS, MYF(0), args[0]->cols());
1550 return true;
1551 }
1552 if (args[1]->maybe_null)
1553 maybe_null=1;
1554 with_sum_func= with_sum_func || args[1]->with_sum_func;
1555 used_tables_cache|= args[1]->used_tables();
1556 not_null_tables_cache|= args[1]->not_null_tables();
1557 const_item_cache&= args[1]->const_item();
1558 fixed= 1;
1559 return false;
1560}
1561
1562
1564{
1565 bool tmp;
1566 assert(fixed == 1);
1567 cache->store(args[0]);
1568
1569 if (cache->null_value)
1570 {
1571 if (((Item_in_subselect*)args[1])->is_top_level_item())
1572 {
1573 /*
1574 We're evaluating "NULL IN (SELECT ...)". The result can be NULL or
1575 false, and we can return one instead of another. Just return NULL.
1576 */
1577 null_value= 1;
1578 }
1579 else
1580 {
1581 if (!((Item_in_subselect*)args[1])->is_correlated &&
1582 result_for_null_param != UNKNOWN)
1583 {
1584 /* Use cached value from previous execution */
1585 null_value= result_for_null_param;
1586 }
1587 else
1588 {
1589 /*
1590 We're evaluating "NULL IN (SELECT ...)". The result is:
1591 false if SELECT produces an empty set, or
1592 NULL otherwise.
1593 We disable the predicates we've pushed down into subselect, run the
1594 subselect and see if it has produced any rows.
1595 */
1596 Item_in_subselect *item_subs=(Item_in_subselect*)args[1];
1597 if (cache->cols() == 1)
1598 {
1599 item_subs->set_cond_guard_var(0, false);
1600 (void) args[1]->val_bool_result();
1601 result_for_null_param= null_value= !item_subs->engine->no_rows();
1602 item_subs->set_cond_guard_var(0, true);
1603 }
1604 else
1605 {
1606 uint32_t i;
1607 uint32_t ncols= cache->cols();
1608 /*
1609 Turn off the predicates that are based on column compares for
1610 which the left part is currently NULL
1611 */
1612 for (i= 0; i < ncols; i++)
1613 {
1614 if (cache->element_index(i)->null_value)
1615 item_subs->set_cond_guard_var(i, false);
1616 }
1617
1618 (void) args[1]->val_bool_result();
1619 result_for_null_param= null_value= !item_subs->engine->no_rows();
1620
1621 /* Turn all predicates back on */
1622 for (i= 0; i < ncols; i++)
1623 item_subs->set_cond_guard_var(i, true);
1624 }
1625 }
1626 }
1627 return 0;
1628 }
1629 tmp= args[1]->val_bool_result();
1630 null_value= args[1]->null_value;
1631 return tmp;
1632}
1633
1634
1635void Item_in_optimizer::keep_top_level_cache()
1636{
1637 cache->keep_array();
1638 save_cache= 1;
1639}
1640
1641
1642void Item_in_optimizer::cleanup()
1643{
1644 item::function::Boolean::cleanup();
1645 if (!save_cache)
1646 cache= 0;
1647 return;
1648}
1649
1650
1652{
1653 cache->store(args[0]);
1654 return (null_value= (cache->null_value || args[1]->is_null()));
1655}
1656
1657
1679
1680Item *Item_in_optimizer::transform(Item_transformer transformer, unsigned char *argument)
1681{
1682 Item *new_item;
1683
1684 assert(arg_count == 2);
1685
1686 /* Transform the left IN operand. */
1687 new_item= (*args)->transform(transformer, argument);
1688 if (!new_item)
1689 return 0;
1690 *args= new_item;
1691
1692 /*
1693 Transform the right IN operand which should be an Item_in_subselect or a
1694 subclass of it. The left operand of the IN must be the same as the left
1695 operand of this Item_in_optimizer, so in this case there is no further
1696 transformation, we only make both operands the same.
1697 TODO: is it the way it should be?
1698 */
1699 assert((args[1])->type() == Item::SUBSELECT_ITEM &&
1700 (((Item_subselect*)(args[1]))->substype() ==
1701 Item_subselect::IN_SUBS ||
1702 ((Item_subselect*)(args[1]))->substype() ==
1703 Item_subselect::ALL_SUBS ||
1704 ((Item_subselect*)(args[1]))->substype() ==
1705 Item_subselect::ANY_SUBS));
1706
1707 Item_in_subselect *in_arg= (Item_in_subselect*)args[1];
1708 in_arg->left_expr= args[0];
1709
1710 return (this->*transformer)(argument);
1711}
1712
1713
1714
1716{
1717 assert(fixed == 1);
1718 int value= cmp.compare();
1719 return value == 0 ? 1 : 0;
1720}
1721
1722
1724
1726{
1727 Item_bool_func2::fix_length_and_dec();
1729}
1730
1732{
1733 assert(fixed == 1);
1734 return cmp.compare();
1735}
1736
1738{
1739 assert(fixed == 1);
1740 int value= cmp.compare();
1741 return value != 0 && !null_value ? 1 : 0;
1742}
1743
1744
1746{
1747 assert(fixed == 1);
1748 int value= cmp.compare();
1749 return value >= 0 ? 1 : 0;
1750}
1751
1752
1754{
1755 assert(fixed == 1);
1756 int value= cmp.compare();
1757 return value > 0 ? 1 : 0;
1758}
1759
1761{
1762 assert(fixed == 1);
1763 int value= cmp.compare();
1764 return value <= 0 && !null_value ? 1 : 0;
1765}
1766
1767
1769{
1770 assert(fixed == 1);
1771 int value= cmp.compare();
1772 return value < 0 && !null_value ? 1 : 0;
1773}
1774
1775
1777{
1778 assert(fixed == 1);
1779 String *a=args[0]->val_str(&tmp_value1);
1780 String *b=args[1]->val_str(&tmp_value2);
1781 if (!a || !b)
1782 {
1783 null_value=1;
1784 return 0;
1785 }
1786 int value= sortcmp(a,b,cmp.cmp_collation.collation);
1787 null_value=0;
1788 return !value ? 0 : (value < 0 ? (int64_t) -1 : (int64_t) 1);
1789}
1790
1791
1792bool Item_func_opt_neg::eq(const Item *item, bool binary_cmp) const
1793{
1794 /* Assume we don't have rtti */
1795 if (this == item)
1796 return 1;
1797 if (item->type() != FUNC_ITEM)
1798 return 0;
1799 Item_func *item_func=(Item_func*) item;
1800 if (arg_count != item_func->arg_count ||
1801 functype() != item_func->functype())
1802 return 0;
1803 if (negated != ((Item_func_opt_neg *) item_func)->negated)
1804 return 0;
1805 for (uint32_t i=0; i < arg_count ; i++)
1806 if (!args[i]->eq(item_func->arguments()[i], binary_cmp))
1807 return 0;
1808 return 1;
1809}
1810
1811
1812void Item_func_interval::fix_length_and_dec()
1813{
1814 uint32_t rows= row->cols();
1815
1816 use_decimal_comparison= ((row->element_index(0)->result_type() ==
1817 DECIMAL_RESULT) ||
1818 (row->element_index(0)->result_type() ==
1819 INT_RESULT));
1820 if (rows > 8)
1821 {
1822 bool not_null_consts= true;
1823
1824 for (uint32_t i= 1; not_null_consts && i < rows; i++)
1825 {
1826 Item *el= row->element_index(i);
1827 not_null_consts&= el->const_item() & !el->is_null();
1828 }
1829
1830 if (not_null_consts &&
1831 (intervals=
1832 (interval_range*) memory::sql_alloc(sizeof(interval_range) * (rows - 1))))
1833 {
1834 if (use_decimal_comparison)
1835 {
1836 for (uint32_t i= 1; i < rows; i++)
1837 {
1838 Item *el= row->element_index(i);
1839 interval_range *range= intervals + (i-1);
1840 if ((el->result_type() == DECIMAL_RESULT) ||
1841 (el->result_type() == INT_RESULT))
1842 {
1843 range->type= DECIMAL_RESULT;
1844 range->dec.init();
1845 type::Decimal *dec= el->val_decimal(&range->dec);
1846 if (dec != &range->dec)
1847 {
1848 range->dec= *dec;
1849 range->dec.fix_buffer_pointer();
1850 }
1851 }
1852 else
1853 {
1854 range->type= REAL_RESULT;
1855 range->dbl= el->val_real();
1856 }
1857 }
1858 }
1859 else
1860 {
1861 for (uint32_t i= 1; i < rows; i++)
1862 {
1863 intervals[i-1].dbl= row->element_index(i)->val_real();
1864 }
1865 }
1866 }
1867 }
1868 maybe_null= 0;
1869 max_length= 2;
1870 used_tables_cache|= row->used_tables();
1871 not_null_tables_cache= row->not_null_tables();
1872 with_sum_func= with_sum_func || row->with_sum_func;
1873 const_item_cache&= row->const_item();
1874}
1875
1876
1890
1892{
1893 assert(fixed == 1);
1894 double value;
1895 type::Decimal dec_buf, *dec= NULL;
1896 uint32_t i;
1897
1898 if (use_decimal_comparison)
1899 {
1900 dec= row->element_index(0)->val_decimal(&dec_buf);
1901 if (row->element_index(0)->null_value)
1902 return -1;
1903 class_decimal2double(E_DEC_FATAL_ERROR, dec, &value);
1904 }
1905 else
1906 {
1907 value= row->element_index(0)->val_real();
1908 if (row->element_index(0)->null_value)
1909 return -1;
1910 }
1911
1912 if (intervals)
1913 { // Use binary search to find interval
1914 uint32_t start,end;
1915 start= 0;
1916 end= row->cols()-2;
1917 while (start != end)
1918 {
1919 uint32_t mid= (start + end + 1) / 2;
1920 interval_range *range= intervals + mid;
1921 bool cmp_result;
1922 /*
1923 The values in the range intervall may have different types,
1924 Only do a decimal comparision of the first argument is a decimal
1925 and we are comparing against a decimal
1926 */
1927 if (dec && range->type == DECIMAL_RESULT)
1928 cmp_result= class_decimal_cmp(&range->dec, dec) <= 0;
1929 else
1930 cmp_result= (range->dbl <= value);
1931 if (cmp_result)
1932 start= mid;
1933 else
1934 end= mid - 1;
1935 }
1936 interval_range *range= intervals+start;
1937 return ((dec && range->type == DECIMAL_RESULT) ?
1938 class_decimal_cmp(dec, &range->dec) < 0 :
1939 value < range->dbl) ? 0 : start + 1;
1940 }
1941
1942 for (i=1 ; i < row->cols() ; i++)
1943 {
1944 Item *el= row->element_index(i);
1945 if (use_decimal_comparison &&
1946 ((el->result_type() == DECIMAL_RESULT) ||
1947 (el->result_type() == INT_RESULT)))
1948 {
1949 type::Decimal e_dec_buf, *e_dec= el->val_decimal(&e_dec_buf);
1950 /* Skip NULL ranges. */
1951 if (el->null_value)
1952 continue;
1953 if (class_decimal_cmp(e_dec, dec) > 0)
1954 return i - 1;
1955 }
1956 else
1957 {
1958 double val= el->val_real();
1959 /* Skip NULL ranges. */
1960 if (el->null_value)
1961 continue;
1962 if (val > value)
1963 return i - 1;
1964 }
1965 }
1966 return i-1;
1967}
1968
1969
1997
1999{
2000 if (Item_func_opt_neg::fix_fields(session, ref))
2001 return 1;
2002
2003 session->lex().current_select->between_count++;
2004
2005 /* not_null_tables_cache == union(T1(e),T1(e1),T1(e2)) */
2006 if (pred_level && !negated)
2007 return 0;
2008
2009 /* not_null_tables_cache == union(T1(e), intersection(T1(e1),T1(e2))) */
2010 not_null_tables_cache= (args[0]->not_null_tables() |
2011 (args[1]->not_null_tables() &
2012 args[2]->not_null_tables()));
2013
2014 return 0;
2015}
2016
2017
2018void Item_func_between::fix_length_and_dec()
2019{
2020 max_length= 1;
2021 int i;
2022 bool datetime_found= false;
2023 compare_as_dates= true;
2024
2025 /*
2026 As some compare functions are generated after sql_yacc,
2027 we have to check for out of memory conditions here
2028 */
2029 if (!args[0] || !args[1] || !args[2])
2030 return;
2031 if ( agg_cmp_type(&cmp_type, args, 3))
2032 return;
2033 if (cmp_type == STRING_RESULT &&
2034 agg_arg_charsets(cmp_collation, args, 3, MY_COLL_CMP_CONV, 1))
2035 return;
2036
2037 /*
2038 Detect the comparison of DATE/DATETIME items.
2039 At least one of items should be a DATE/DATETIME item and other items
2040 should return the STRING result.
2041 */
2042 if (cmp_type == STRING_RESULT)
2043 {
2044 for (i= 0; i < 3; i++)
2045 {
2046 if (args[i]->is_datetime())
2047 {
2048 datetime_found= true;
2049 continue;
2050 }
2051 }
2052 }
2053 if (!datetime_found)
2054 compare_as_dates= false;
2055
2056 if (compare_as_dates)
2057 {
2058 ge_cmp.set_datetime_cmp_func(args, args + 1);
2059 le_cmp.set_datetime_cmp_func(args, args + 2);
2060 }
2061 else if (args[0]->real_item()->type() == FIELD_ITEM)
2062 {
2063 Item_field *field_item= (Item_field*) (args[0]->real_item());
2064 if (field_item->field->can_be_compared_as_int64_t())
2065 {
2066 /*
2067 The following can't be recoded with || as convert_constant_item
2068 changes the argument
2069 */
2070 if (convert_constant_item(&getSession(), field_item, &args[1]))
2071 cmp_type=INT_RESULT; // Works for all types.
2072 if (convert_constant_item(&getSession(), field_item, &args[2]))
2073 cmp_type=INT_RESULT; // Works for all types.
2074 }
2075 }
2076}
2077
2078
2080{ // ANSI BETWEEN
2081 assert(fixed == 1);
2082 if (compare_as_dates)
2083 {
2084 int ge_res, le_res;
2085
2086 ge_res= ge_cmp.compare();
2087 if ((null_value= args[0]->null_value))
2088 return 0;
2089 le_res= le_cmp.compare();
2090
2091 if (!args[1]->null_value && !args[2]->null_value)
2092 return (int64_t) ((ge_res >= 0 && le_res <=0) != negated);
2093 else if (args[1]->null_value)
2094 {
2095 null_value= le_res > 0; // not null if false range.
2096 }
2097 else
2098 {
2099 null_value= ge_res < 0;
2100 }
2101 }
2102 else if (cmp_type == STRING_RESULT)
2103 {
2104 String *value,*a,*b;
2105 value=args[0]->val_str(&value0);
2106 if ((null_value=args[0]->null_value))
2107 return 0;
2108 a=args[1]->val_str(&value1);
2109 b=args[2]->val_str(&value2);
2110 if (!args[1]->null_value && !args[2]->null_value)
2111 return (int64_t) ((sortcmp(value,a,cmp_collation.collation) >= 0 &&
2112 sortcmp(value,b,cmp_collation.collation) <= 0) !=
2113 negated);
2114 if (args[1]->null_value && args[2]->null_value)
2115 null_value=1;
2116 else if (args[1]->null_value)
2117 {
2118 // Set to not null if false range.
2119 null_value= sortcmp(value,b,cmp_collation.collation) <= 0;
2120 }
2121 else
2122 {
2123 // Set to not null if false range.
2124 null_value= sortcmp(value,a,cmp_collation.collation) >= 0;
2125 }
2126 }
2127 else if (cmp_type == INT_RESULT)
2128 {
2129 int64_t value=args[0]->val_int(), a, b;
2130 if ((null_value=args[0]->null_value))
2131 return 0;
2132 a=args[1]->val_int();
2133 b=args[2]->val_int();
2134 if (!args[1]->null_value && !args[2]->null_value)
2135 return (int64_t) ((value >= a && value <= b) != negated);
2136 if (args[1]->null_value && args[2]->null_value)
2137 null_value=1;
2138 else if (args[1]->null_value)
2139 {
2140 null_value= value <= b; // not null if false range.
2141 }
2142 else
2143 {
2144 null_value= value >= a;
2145 }
2146 }
2147 else if (cmp_type == DECIMAL_RESULT)
2148 {
2149 type::Decimal dec_buf, *dec= args[0]->val_decimal(&dec_buf),
2150 a_buf, *a_dec, b_buf, *b_dec;
2151 if ((null_value=args[0]->null_value))
2152 return 0;
2153 a_dec= args[1]->val_decimal(&a_buf);
2154 b_dec= args[2]->val_decimal(&b_buf);
2155 if (!args[1]->null_value && !args[2]->null_value)
2156 return (int64_t) ((class_decimal_cmp(dec, a_dec) >= 0 &&
2157 class_decimal_cmp(dec, b_dec) <= 0) != negated);
2158 if (args[1]->null_value && args[2]->null_value)
2159 null_value=1;
2160 else if (args[1]->null_value)
2161 null_value= (class_decimal_cmp(dec, b_dec) <= 0);
2162 else
2163 null_value= (class_decimal_cmp(dec, a_dec) >= 0);
2164 }
2165 else
2166 {
2167 double value= args[0]->val_real(),a,b;
2168 if ((null_value=args[0]->null_value))
2169 return 0;
2170 a= args[1]->val_real();
2171 b= args[2]->val_real();
2172 if (!args[1]->null_value && !args[2]->null_value)
2173 return (int64_t) ((value >= a && value <= b) != negated);
2174 if (args[1]->null_value && args[2]->null_value)
2175 null_value=1;
2176 else if (args[1]->null_value)
2177 {
2178 null_value= value <= b; // not null if false range.
2179 }
2180 else
2181 {
2182 null_value= value >= a;
2183 }
2184 }
2185 return (int64_t) (!null_value && negated);
2186}
2187
2188
2190{
2191 str->append('(');
2192 args[0]->print(str);
2193 if (negated)
2194 str->append(STRING_WITH_LEN(" not"));
2195 str->append(STRING_WITH_LEN(" between "));
2196 args[1]->print(str);
2197 str->append(STRING_WITH_LEN(" and "));
2198 args[2]->print(str);
2199 str->append(')');
2200}
2201
2202void
2203Item_func_ifnull::fix_length_and_dec()
2204{
2205 agg_result_type(&hybrid_type, args, 2);
2206 maybe_null= args[1]->maybe_null;
2207 decimals= max(args[0]->decimals, args[1]->decimals);
2208 unsigned_flag= args[0]->unsigned_flag && args[1]->unsigned_flag;
2209
2210 if (hybrid_type == DECIMAL_RESULT || hybrid_type == INT_RESULT)
2211 {
2212 int len0= args[0]->max_length - args[0]->decimals
2213 - (args[0]->unsigned_flag ? 0 : 1);
2214
2215 int len1= args[1]->max_length - args[1]->decimals
2216 - (args[1]->unsigned_flag ? 0 : 1);
2217
2218 max_length= max(len0, len1) + decimals + (unsigned_flag ? 0 : 1);
2219 }
2220 else
2221 {
2222 max_length= max(args[0]->max_length, args[1]->max_length);
2223 }
2224
2225 switch (hybrid_type)
2226 {
2227 case STRING_RESULT:
2228 agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1);
2229 break;
2230
2231 case DECIMAL_RESULT:
2232 case REAL_RESULT:
2233 break;
2234
2235 case INT_RESULT:
2236 decimals= 0;
2237 break;
2238
2239 case ROW_RESULT:
2240 assert(0);
2241 }
2242
2243 cached_field_type= agg_field_type(args, 2);
2244}
2245
2246
2247uint32_t Item_func_ifnull::decimal_precision() const
2248{
2249 int max_int_part= max(args[0]->decimal_int_part(),args[1]->decimal_int_part());
2250 return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
2251}
2252
2253
2254enum_field_types Item_func_ifnull::field_type() const
2255{
2256 return cached_field_type;
2257}
2258
2259Field *Item_func_ifnull::tmp_table_field(Table *table)
2260{
2261 return tmp_table_field_from_field_type(table, 0);
2262}
2263
2264double
2266{
2267 assert(fixed == 1);
2268 double value= args[0]->val_real();
2269 if (!args[0]->null_value)
2270 {
2271 null_value=0;
2272 return value;
2273 }
2274 value= args[1]->val_real();
2275 if ((null_value=args[1]->null_value))
2276 return 0.0;
2277 return value;
2278}
2279
2280int64_t
2282{
2283 assert(fixed == 1);
2284 int64_t value=args[0]->val_int();
2285 if (!args[0]->null_value)
2286 {
2287 null_value=0;
2288 return value;
2289 }
2290 value=args[1]->val_int();
2291 if ((null_value=args[1]->null_value))
2292 return 0;
2293 return value;
2294}
2295
2296
2298{
2299 assert(fixed == 1);
2300 type::Decimal *value= args[0]->val_decimal(decimal_value);
2301 if (!args[0]->null_value)
2302 {
2303 null_value= 0;
2304 return value;
2305 }
2306 value= args[1]->val_decimal(decimal_value);
2307 if ((null_value= args[1]->null_value))
2308 return 0;
2309 return value;
2310}
2311
2312
2313String *
2315{
2316 assert(fixed == 1);
2317 String *res =args[0]->val_str(str);
2318 if (!args[0]->null_value)
2319 {
2320 null_value=0;
2321 res->set_charset(collation.collation);
2322 return res;
2323 }
2324 res=args[1]->val_str(str);
2325 if ((null_value=args[1]->null_value))
2326 return 0;
2327 res->set_charset(collation.collation);
2328 return res;
2329}
2330
2331
2357
2358bool
2360{
2361 assert(fixed == 0);
2362 args[0]->top_level_item();
2363
2364 if (Item_func::fix_fields(session, ref))
2365 return 1;
2366
2367 not_null_tables_cache= (args[1]->not_null_tables() &
2368 args[2]->not_null_tables());
2369
2370 return 0;
2371}
2372
2373
2374void Item_func_if::fix_length_and_dec()
2375{
2376 maybe_null= args[1]->maybe_null || args[2]->maybe_null;
2377 decimals= max(args[1]->decimals, args[2]->decimals);
2378 unsigned_flag= args[1]->unsigned_flag && args[2]->unsigned_flag;
2379
2380 enum Item_result arg1_type= args[1]->result_type();
2381 enum Item_result arg2_type= args[2]->result_type();
2382 bool null1= args[1]->const_item() && args[1]->null_value;
2383 bool null2= args[2]->const_item() && args[2]->null_value;
2384
2385 if (null1)
2386 {
2387 cached_result_type= arg2_type;
2388 collation.set(args[2]->collation.collation);
2389 cached_field_type= args[2]->field_type();
2390 }
2391 else if (null2)
2392 {
2393 cached_result_type= arg1_type;
2394 collation.set(args[1]->collation.collation);
2395 cached_field_type= args[1]->field_type();
2396 }
2397 else
2398 {
2399 agg_result_type(&cached_result_type, args +1, 2);
2400 if (cached_result_type == STRING_RESULT)
2401 {
2402 if (agg_arg_charsets(collation, args +1, 2, MY_COLL_ALLOW_CONV, 1))
2403 return;
2404 }
2405 else
2406 {
2407 collation.set(&my_charset_bin); // Number
2408 }
2409 cached_field_type= agg_field_type(args +1, 2);
2410 }
2411
2412 switch (cached_result_type)
2413 {
2414 case DECIMAL_RESULT:
2415 case INT_RESULT:
2416 {
2417 int len1= args[1]->max_length -args[1]->decimals -(args[1]->unsigned_flag ? 0 : 1);
2418 int len2= args[2]->max_length -args[2]->decimals -(args[2]->unsigned_flag ? 0 : 1);
2419 max_length= max(len1, len2) + decimals + (unsigned_flag ? 0 : 1);
2420 }
2421 break;
2422 case REAL_RESULT:
2423 case STRING_RESULT:
2424 max_length= max(args[1]->max_length, args[2]->max_length);
2425 break;
2426
2427 case ROW_RESULT:
2428 assert(0);
2429 break;
2430 }
2431}
2432
2433
2434uint32_t Item_func_if::decimal_precision() const
2435{
2436 int precision= (max(args[1]->decimal_int_part(),args[2]->decimal_int_part())+
2437 decimals);
2438 return min(precision, DECIMAL_MAX_PRECISION);
2439}
2440
2441
2442double
2444{
2445 assert(fixed == 1);
2446 Item *arg= args[0]->val_bool() ? args[1] : args[2];
2447 double value= arg->val_real();
2449 return value;
2450}
2451
2452int64_t
2454{
2455 assert(fixed == 1);
2456 Item *arg= args[0]->val_bool() ? args[1] : args[2];
2457 int64_t value= arg->val_int();
2458 null_value= arg->null_value;
2459 return value;
2460}
2461
2462String *
2464{
2465 assert(fixed == 1);
2466 Item *arg= args[0]->val_bool() ? args[1] : args[2];
2467 String *res= arg->val_str(str);
2468 if (res)
2469 {
2470 res->set_charset(collation.collation);
2471 }
2472 null_value= arg->null_value;
2473 return res;
2474}
2475
2476
2479{
2480 assert(fixed == 1);
2481 Item *arg= args[0]->val_bool() ? args[1] : args[2];
2482 type::Decimal *value= arg->val_decimal(decimal_value);
2483 null_value= arg->null_value;
2484 return value;
2485}
2486
2487
2488void
2489Item_func_nullif::fix_length_and_dec()
2490{
2491 Item_bool_func2::fix_length_and_dec();
2492 maybe_null=1;
2493 if (args[0]) // Only false if EOM
2494 {
2495 max_length=args[0]->max_length;
2496 decimals=args[0]->decimals;
2497 unsigned_flag= args[0]->unsigned_flag;
2498 cached_result_type= args[0]->result_type();
2499 if (cached_result_type == STRING_RESULT &&
2500 agg_arg_charsets(collation, args, arg_count, MY_COLL_CMP_CONV, 1))
2501 return;
2502 }
2503}
2504
2505
2515
2516double
2518{
2519 assert(fixed == 1);
2520 double value;
2521 if (!cmp.compare())
2522 {
2523 null_value=1;
2524 return 0.0;
2525 }
2526 value= args[0]->val_real();
2527 null_value=args[0]->null_value;
2528 return value;
2529}
2530
2531int64_t
2533{
2534 assert(fixed == 1);
2535 int64_t value;
2536 if (!cmp.compare())
2537 {
2538 null_value=1;
2539 return 0;
2540 }
2541 value=args[0]->val_int();
2542 null_value=args[0]->null_value;
2543 return value;
2544}
2545
2546String *
2548{
2549 assert(fixed == 1);
2550 String *res;
2551 if (!cmp.compare())
2552 {
2553 null_value=1;
2554 return 0;
2555 }
2556 res=args[0]->val_str(str);
2557 null_value=args[0]->null_value;
2558 return res;
2559}
2560
2561
2564{
2565 assert(fixed == 1);
2566 type::Decimal *res;
2567 if (!cmp.compare())
2568 {
2569 null_value=1;
2570 return 0;
2571 }
2572 res= args[0]->val_decimal(decimal_value);
2573 null_value= args[0]->null_value;
2574 return res;
2575}
2576
2577
2578bool
2580{
2581 return (null_value= (!cmp.compare() ? 1 : args[0]->null_value));
2582}
2583
2584
2605
2607{
2608 uint32_t value_added_map= 0;
2609
2610 if (first_expr_num == -1)
2611 {
2612 for (uint32_t i=0 ; i < ncases ; i+=2)
2613 {
2614 // No expression between CASE and the first WHEN
2615 if (args[i]->val_bool())
2616 return args[i+1];
2617 continue;
2618 }
2619 }
2620 else
2621 {
2622 /* Compare every WHEN argument with it and return the first match */
2623 for (uint32_t i=0 ; i < ncases ; i+=2)
2624 {
2625 cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
2626 assert(cmp_type != ROW_RESULT);
2627 assert(cmp_items[(uint32_t)cmp_type]);
2628 if (!(value_added_map & (1<<(uint32_t)cmp_type)))
2629 {
2630 cmp_items[(uint32_t)cmp_type]->store_value(args[first_expr_num]);
2631 if ((null_value=args[first_expr_num]->null_value))
2632 return else_expr_num != -1 ? args[else_expr_num] : 0;
2633 value_added_map|= 1<<(uint32_t)cmp_type;
2634 }
2635 if (!cmp_items[(uint32_t)cmp_type]->cmp(args[i]) && !args[i]->null_value)
2636 return args[i + 1];
2637 }
2638 }
2639 // No, WHEN clauses all missed, return ELSE expression
2640 return else_expr_num != -1 ? args[else_expr_num] : 0;
2641}
2642
2643
2645{
2646 assert(fixed == 1);
2647 String *res;
2648 Item *item=find_item(str);
2649
2650 if (!item)
2651 {
2652 null_value=1;
2653 return 0;
2654 }
2655 null_value= 0;
2656 if (!(res=item->val_str(str)))
2657 null_value= 1;
2658 return res;
2659}
2660
2661
2663{
2664 assert(fixed == 1);
2665 char buff[MAX_FIELD_WIDTH];
2666 String dummy_str(buff,sizeof(buff),default_charset());
2667 Item *item=find_item(&dummy_str);
2668 int64_t res;
2669
2670 if (!item)
2671 {
2672 null_value=1;
2673 return 0;
2674 }
2675 res=item->val_int();
2676 null_value=item->null_value;
2677 return res;
2678}
2679
2681{
2682 assert(fixed == 1);
2683 char buff[MAX_FIELD_WIDTH];
2684 String dummy_str(buff,sizeof(buff),default_charset());
2685 Item *item=find_item(&dummy_str);
2686 double res;
2687
2688 if (!item)
2689 {
2690 null_value=1;
2691 return 0;
2692 }
2693 res= item->val_real();
2694 null_value=item->null_value;
2695 return res;
2696}
2697
2698
2700{
2701 assert(fixed == 1);
2702 char buff[MAX_FIELD_WIDTH];
2703 String dummy_str(buff, sizeof(buff), default_charset());
2704 Item *item= find_item(&dummy_str);
2705 type::Decimal *res;
2706
2707 if (!item)
2708 {
2709 null_value=1;
2710 return 0;
2711 }
2712
2713 res= item->val_decimal(decimal_value);
2714 null_value= item->null_value;
2715 return res;
2716}
2717
2718
2719bool Item_func_case::fix_fields(Session *session, Item **ref)
2720{
2721 /*
2722 buff should match stack usage from
2723 Item_func_case::val_int() -> Item_func_case::find_item()
2724 */
2725 unsigned char buff[MAX_FIELD_WIDTH*2+sizeof(String)*2+sizeof(String*)*2
2726 +sizeof(double)*2+sizeof(int64_t)*2];
2727 bool res= Item_func::fix_fields(session, ref);
2728 /*
2729 Call check_stack_overrun after fix_fields to be sure that stack variable
2730 is not optimized away
2731 */
2732 if (check_stack_overrun(session, STACK_MIN_SIZE, buff))
2733 return true; // Fatal error flag is set!
2734 return res;
2735}
2736
2737
2738void Item_func_case::agg_str_lengths(Item* arg)
2739{
2740 set_if_bigger(max_length, arg->max_length);
2741 set_if_bigger(decimals, arg->decimals);
2742 unsigned_flag= unsigned_flag && arg->unsigned_flag;
2743}
2744
2745
2746void Item_func_case::agg_num_lengths(Item *arg)
2747{
2748 uint32_t len= class_decimal_length_to_precision(arg->max_length, arg->decimals,
2749 arg->unsigned_flag) - arg->decimals;
2750 set_if_bigger(max_length, len);
2751 set_if_bigger(decimals, arg->decimals);
2752 unsigned_flag= unsigned_flag && arg->unsigned_flag;
2753}
2754
2755
2756void Item_func_case::fix_length_and_dec()
2757{
2758 Item **agg;
2759 uint32_t nagg;
2760 uint32_t found_types= 0;
2761 if (!(agg= (Item**) memory::sql_alloc(sizeof(Item*)*(ncases+1))))
2762 return;
2763
2764 /*
2765 Aggregate all THEN and ELSE expression types
2766 and collations when string result
2767 */
2768
2769 for (nagg= 0 ; nagg < ncases/2 ; nagg++)
2770 agg[nagg]= args[nagg*2+1];
2771
2772 if (else_expr_num != -1)
2773 agg[nagg++]= args[else_expr_num];
2774
2775 agg_result_type(&cached_result_type, agg, nagg);
2776 if ((cached_result_type == STRING_RESULT) &&
2777 agg_arg_charsets(collation, agg, nagg, MY_COLL_ALLOW_CONV, 1))
2778 return;
2779
2780 cached_field_type= agg_field_type(agg, nagg);
2781 /*
2782 Aggregate first expression and all THEN expression types
2783 and collations when string comparison
2784 */
2785 if (first_expr_num != -1)
2786 {
2787 agg[0]= args[first_expr_num];
2788 left_result_type= agg[0]->result_type();
2789
2790 for (nagg= 0; nagg < ncases/2 ; nagg++)
2791 agg[nagg+1]= args[nagg*2];
2792 nagg++;
2793 if (!(found_types= collect_cmp_types(agg, nagg)))
2794 return;
2795
2796 for (int i= STRING_RESULT; i <= DECIMAL_RESULT; i++)
2797 {
2798 if (found_types & (1 << i) && !cmp_items[i])
2799 {
2800 assert((Item_result)i != ROW_RESULT);
2801 if ((Item_result)i == STRING_RESULT &&
2802 agg_arg_charsets(cmp_collation, agg, nagg, MY_COLL_CMP_CONV, 1))
2803 return;
2804 if (!(cmp_items[i]=
2805 cmp_item::get_comparator((Item_result)i,
2806 cmp_collation.collation)))
2807 return;
2808 }
2809 }
2810 }
2811
2812 if (else_expr_num == -1 || args[else_expr_num]->maybe_null)
2813 maybe_null=1;
2814
2815 max_length=0;
2816 decimals=0;
2817 unsigned_flag= true;
2818 if (cached_result_type == STRING_RESULT)
2819 {
2820 for (uint32_t i= 0; i < ncases; i+= 2)
2821 agg_str_lengths(args[i + 1]);
2822 if (else_expr_num != -1)
2823 agg_str_lengths(args[else_expr_num]);
2824 }
2825 else
2826 {
2827 for (uint32_t i= 0; i < ncases; i+= 2)
2828 agg_num_lengths(args[i + 1]);
2829 if (else_expr_num != -1)
2830 agg_num_lengths(args[else_expr_num]);
2831 max_length= class_decimal_precision_to_length(max_length + decimals, decimals,
2832 unsigned_flag);
2833 }
2834}
2835
2836
2837uint32_t Item_func_case::decimal_precision() const
2838{
2839 int max_int_part=0;
2840 for (uint32_t i=0 ; i < ncases ; i+=2)
2841 set_if_bigger(max_int_part, args[i+1]->decimal_int_part());
2842
2843 if (else_expr_num != -1)
2844 set_if_bigger(max_int_part, args[else_expr_num]->decimal_int_part());
2845 return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
2846}
2847
2848
2853
2855{
2856 str->append(STRING_WITH_LEN("(case "));
2857 if (first_expr_num != -1)
2858 {
2859 args[first_expr_num]->print(str);
2860 str->append(' ');
2861 }
2862 for (uint32_t i=0 ; i < ncases ; i+=2)
2863 {
2864 str->append(STRING_WITH_LEN("when "));
2865 args[i]->print(str);
2866 str->append(STRING_WITH_LEN(" then "));
2867 args[i+1]->print(str);
2868 str->append(' ');
2869 }
2870 if (else_expr_num != -1)
2871 {
2872 str->append(STRING_WITH_LEN("else "));
2873 args[else_expr_num]->print(str);
2874 str->append(' ');
2875 }
2876 str->append(STRING_WITH_LEN("end)"));
2877}
2878
2879
2880void Item_func_case::cleanup()
2881{
2882 Item_func::cleanup();
2883 for (int i= STRING_RESULT; i <= DECIMAL_RESULT; i++)
2884 {
2885 delete cmp_items[i];
2886 cmp_items[i]= 0;
2887 }
2888}
2889
2890
2894
2896{
2897 assert(fixed == 1);
2898 null_value=0;
2899 for (uint32_t i=0 ; i < arg_count ; i++)
2900 {
2901 String *res;
2902 if ((res=args[i]->val_str(str)))
2903 return res;
2904 }
2905 null_value=1;
2906 return 0;
2907}
2908
2910{
2911 assert(fixed == 1);
2912 null_value=0;
2913 for (uint32_t i=0 ; i < arg_count ; i++)
2914 {
2915 int64_t res=args[i]->val_int();
2916 if (!args[i]->null_value)
2917 return res;
2918 }
2919 null_value=1;
2920 return 0;
2921}
2922
2924{
2925 assert(fixed == 1);
2926 null_value=0;
2927 for (uint32_t i=0 ; i < arg_count ; i++)
2928 {
2929 double res= args[i]->val_real();
2930 if (!args[i]->null_value)
2931 return res;
2932 }
2933 null_value=1;
2934 return 0;
2935}
2936
2937
2939{
2940 assert(fixed == 1);
2941 null_value= 0;
2942 for (uint32_t i= 0; i < arg_count; i++)
2943 {
2944 type::Decimal *res= args[i]->val_decimal(decimal_value);
2945 if (!args[i]->null_value)
2946 return res;
2947 }
2948 null_value=1;
2949 return 0;
2950}
2951
2952
2953void Item_func_coalesce::fix_length_and_dec()
2954{
2955 cached_field_type= agg_field_type(args, arg_count);
2956 agg_result_type(&hybrid_type, args, arg_count);
2957
2958 switch (hybrid_type) {
2959 case STRING_RESULT:
2960 count_only_length();
2961 decimals= NOT_FIXED_DEC;
2962 agg_arg_charsets(collation, args, arg_count, MY_COLL_ALLOW_CONV, 1);
2963 break;
2964
2965 case DECIMAL_RESULT:
2966 count_decimal_length();
2967 break;
2968
2969 case REAL_RESULT:
2970 count_real_length();
2971 break;
2972
2973 case INT_RESULT:
2974 count_only_length();
2975 decimals= 0;
2976 break;
2977
2978 case ROW_RESULT:
2979 assert(0);
2980 }
2981}
2982
2983/****************************************************************************
2984 Classes and function for the IN operator
2985****************************************************************************/
2986
2987/*
2988 Determine which of the signed int64_t arguments is bigger
2989
2990 SYNOPSIS
2991 cmp_longs()
2992 a_val left argument
2993 b_val right argument
2994
2995 DESCRIPTION
2996 This function will compare two signed int64_t arguments
2997 and will return -1, 0, or 1 if left argument is smaller than,
2998 equal to or greater than the right argument.
2999
3000 RETURN VALUE
3001 -1 left argument is smaller than the right argument.
3002 0 left argument is equal to the right argument.
3003 1 left argument is greater than the right argument.
3004*/
3005static inline int cmp_longs (int64_t a_val, int64_t b_val)
3006{
3007 return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3008}
3009
3010
3011/*
3012 Determine which of the unsigned int64_t arguments is bigger
3013
3014 SYNOPSIS
3015 cmp_ulongs()
3016 a_val left argument
3017 b_val right argument
3018
3019 DESCRIPTION
3020 This function will compare two unsigned int64_t arguments
3021 and will return -1, 0, or 1 if left argument is smaller than,
3022 equal to or greater than the right argument.
3023
3024 RETURN VALUE
3025 -1 left argument is smaller than the right argument.
3026 0 left argument is equal to the right argument.
3027 1 left argument is greater than the right argument.
3028*/
3029static inline int cmp_ulongs (uint64_t a_val, uint64_t b_val)
3030{
3031 return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3032}
3033
3034
3035/*
3036 Compare two integers in IN value list format (packed_int64_t)
3037
3038 SYNOPSIS
3039 cmp_int64_t()
3040 cmp_arg an argument passed to the calling function (my_qsort2)
3041 a left argument
3042 b right argument
3043
3044 DESCRIPTION
3045 This function will compare two integer arguments in the IN value list
3046 format and will return -1, 0, or 1 if left argument is smaller than,
3047 equal to or greater than the right argument.
3048 It's used in sorting the IN values list and finding an element in it.
3049 Depending on the signedness of the arguments cmp_int64_t() will
3050 compare them as either signed (using cmp_longs()) or unsigned (using
3051 cmp_ulongs()).
3052
3053 RETURN VALUE
3054 -1 left argument is smaller than the right argument.
3055 0 left argument is equal to the right argument.
3056 1 left argument is greater than the right argument.
3057*/
3058int cmp_int64_t(void *, in_int64_t::packed_int64_t *a,
3059 in_int64_t::packed_int64_t *b)
3060{
3061 if (a->unsigned_flag != b->unsigned_flag)
3062 {
3063 /*
3064 One of the args is unsigned and is too big to fit into the
3065 positive signed range. Report no match.
3066 */
3067 if ((a->unsigned_flag && ((uint64_t) a->val) > (uint64_t) INT64_MAX) ||
3068 (b->unsigned_flag && ((uint64_t) b->val) > (uint64_t) INT64_MAX))
3069 return a->unsigned_flag ? 1 : -1;
3070 /*
3071 Although the signedness differs both args can fit into the signed
3072 positive range. Make them signed and compare as usual.
3073 */
3074 return cmp_longs (a->val, b->val);
3075 }
3076 if (a->unsigned_flag)
3077 return cmp_ulongs ((uint64_t) a->val, (uint64_t) b->val);
3078 else
3079 return cmp_longs (a->val, b->val);
3080}
3081
3082static int cmp_double(void *, double *a, double *b)
3083{
3084 return *a < *b ? -1 : compare_double(*a, *b) ? 0 : 1;
3085}
3086
3087static int cmp_row(void *, cmp_item_row *a, cmp_item_row *b)
3088{
3089 return a->compare(b);
3090}
3091
3092
3093static int cmp_decimal(void *, type::Decimal *a, type::Decimal *b)
3094{
3095 /*
3096 We need call of fixing buffer pointer, because fast sort just copy
3097 decimal buffers in memory and pointers left pointing on old buffer place
3098 */
3099 a->fix_buffer_pointer();
3100 b->fix_buffer_pointer();
3101 return class_decimal_cmp(a, b);
3102}
3103
3104
3105void in_vector::sort()
3106{
3107 internal::my_qsort2(base,used_count,size,compare, (void *) collation);
3108}
3109
3110
3111int in_vector::find(Item *item)
3112{
3113 unsigned char *result=get_value(item);
3114 if (!result || !used_count)
3115 return 0; // Null value
3116
3117 uint32_t start,end;
3118 start=0; end=used_count-1;
3119 while (start != end)
3120 {
3121 uint32_t mid=(start+end+1)/2;
3122 int res;
3123 if ((res=(*compare)(collation, base+mid*size, result)) == 0)
3124 return 1;
3125 if (res < 0)
3126 start=mid;
3127 else
3128 end=mid-1;
3129 }
3130 return (int) ((*compare)(collation, base+start*size, result) == 0);
3131}
3132
3133in_string::in_string(uint32_t elements,qsort2_cmp cmp_func, const charset_info_st * const cs)
3134 :in_vector(elements, sizeof(String), cmp_func, cs),
3135 tmp(buff, sizeof(buff), &my_charset_bin)
3136{}
3137
3138in_string::~in_string()
3139{
3140 if (base)
3141 {
3142 // base was allocated with help of memory::sql_alloc => following is OK
3143 for (uint32_t i=0 ; i < count ; i++)
3144 ((String*) base)[i].free();
3145 }
3146}
3147
3148void in_string::set(uint32_t pos,Item *item)
3149{
3150 String *str=((String*) base)+pos;
3151 String *res=item->val_str(str);
3152 if (res && res != str)
3153 {
3154 if (res->uses_buffer_owned_by(str))
3155 res->copy();
3156 if (item->type() == Item::FUNC_ITEM)
3157 str->copy(*res);
3158 else
3159 *str= *res;
3160 }
3161 if (!str->charset())
3162 {
3163 const charset_info_st *cs;
3164 if (!(cs= item->collation.collation))
3165 cs= &my_charset_bin; // Should never happen for STR items
3166 str->set_charset(cs);
3167 }
3168}
3169
3170
3171unsigned char *in_string::get_value(Item *item)
3172{
3173 return (unsigned char*) item->val_str(&tmp);
3174}
3175
3176in_row::in_row(uint32_t elements, Item *)
3177{
3178 base= (char*) new cmp_item_row[count= elements];
3179 size= sizeof(cmp_item_row);
3180 compare= (qsort2_cmp) cmp_row;
3181 /*
3182 We need to reset these as otherwise we will call sort() with
3183 uninitialized (even if not used) elements
3184 */
3185 used_count= elements;
3186 collation= 0;
3187}
3188
3189in_row::~in_row()
3190{
3191 delete[] (cmp_item_row*) base;
3192}
3193
3194unsigned char *in_row::get_value(Item *item)
3195{
3196 tmp.store_value(item);
3197 if (item->is_null())
3198 return 0;
3199 return (unsigned char *)&tmp;
3200}
3201
3202void in_row::set(uint32_t pos, Item *item)
3203{
3204 ((cmp_item_row*) base)[pos].store_value_by_template(&tmp, item);
3205 return;
3206}
3207
3208in_int64_t::in_int64_t(uint32_t elements) :
3209 in_vector(elements, sizeof(packed_int64_t),(qsort2_cmp) cmp_int64_t, 0)
3210{}
3211
3212void in_int64_t::set(uint32_t pos,Item *item)
3213{
3214 struct packed_int64_t *buff= &((packed_int64_t*) base)[pos];
3215
3216 buff->val= item->val_int();
3217 buff->unsigned_flag= item->unsigned_flag;
3218}
3219
3220unsigned char *in_int64_t::get_value(Item *item)
3221{
3222 tmp.val= item->val_int();
3223 if (item->null_value)
3224 return 0;
3225 tmp.unsigned_flag= item->unsigned_flag;
3226 return (unsigned char*) &tmp;
3227}
3228
3229in_datetime::in_datetime(Item *warn_item_arg, uint32_t elements) :
3230 in_int64_t(elements),
3231 session(current_session),
3232 warn_item(warn_item_arg),
3233 lval_cache(0)
3234{}
3235
3236void in_datetime::set(uint32_t pos, Item *item)
3237{
3238 Item **tmp_item= &item;
3239 bool is_null;
3240 struct packed_int64_t *buff= &((packed_int64_t*) base)[pos];
3241
3242 buff->val= get_datetime_value(session, &tmp_item, 0, warn_item, &is_null);
3243 buff->unsigned_flag= 1L;
3244}
3245
3246unsigned char *in_datetime::get_value(Item *item)
3247{
3248 bool is_null;
3249 Item **tmp_item= lval_cache ? &lval_cache : &item;
3250 tmp.val= get_datetime_value(session, &tmp_item, &lval_cache, warn_item, &is_null);
3251 if (item->null_value)
3252 return 0;
3253 tmp.unsigned_flag= 1L;
3254 return (unsigned char*) &tmp;
3255}
3256
3257in_double::in_double(uint32_t elements)
3258 :in_vector(elements,sizeof(double),(qsort2_cmp) cmp_double, 0)
3259{}
3260
3261void in_double::set(uint32_t pos,Item *item)
3262{
3263 ((double*) base)[pos]= item->val_real();
3264}
3265
3266unsigned char *in_double::get_value(Item *item)
3267{
3268 tmp= item->val_real();
3269 if (item->null_value)
3270 return 0;
3271 return (unsigned char*) &tmp;
3272}
3273
3274
3275in_decimal::in_decimal(uint32_t elements)
3276 :in_vector(elements, sizeof(type::Decimal),(qsort2_cmp) cmp_decimal, 0)
3277{}
3278
3279
3280void in_decimal::set(uint32_t pos, Item *item)
3281{
3282 /* as far as 'item' is constant, we can store reference on type::Decimal */
3283 type::Decimal *dec= ((type::Decimal *)base) + pos;
3284 dec->len= DECIMAL_BUFF_LENGTH;
3285 dec->fix_buffer_pointer();
3286 type::Decimal *res= item->val_decimal(dec);
3287 /* if item->val_decimal() is evaluated to NULL then res == 0 */
3288 if (!item->null_value && res != dec)
3289 class_decimal2decimal(res, dec);
3290}
3291
3292
3293unsigned char *in_decimal::get_value(Item *item)
3294{
3295 type::Decimal *result= item->val_decimal(&val);
3296 if (item->null_value)
3297 return 0;
3298 return (unsigned char *)result;
3299}
3300
3301
3302cmp_item* cmp_item::get_comparator(Item_result type,
3303 const charset_info_st * const cs)
3304{
3305 switch (type) {
3306 case STRING_RESULT:
3307 return new cmp_item_sort_string(cs);
3308
3309 case INT_RESULT:
3310 return new cmp_item_int;
3311
3312 case REAL_RESULT:
3313 return new cmp_item_real;
3314
3315 case ROW_RESULT:
3316 return new cmp_item_row;
3317
3318 case DECIMAL_RESULT:
3319 return new cmp_item_decimal;
3320 }
3321
3322 return 0; // to satisfy compiler :)
3323}
3324
3325
3326cmp_item* cmp_item_sort_string::make_same()
3327{
3328 return new cmp_item_sort_string_in_static(cmp_charset);
3329}
3330
3331cmp_item* cmp_item_int::make_same()
3332{
3333 return new cmp_item_int();
3334}
3335
3336cmp_item* cmp_item_real::make_same()
3337{
3338 return new cmp_item_real();
3339}
3340
3341cmp_item* cmp_item_row::make_same()
3342{
3343 return new cmp_item_row();
3344}
3345
3346
3347cmp_item_row::~cmp_item_row()
3348{
3349 if (comparators)
3350 {
3351 for (uint32_t i= 0; i < n; i++)
3352 {
3353 if (comparators[i])
3354 delete comparators[i];
3355 }
3356 }
3357 return;
3358}
3359
3360
3361void cmp_item_row::alloc_comparators()
3362{
3363 if (!comparators)
3364 comparators= (cmp_item **) current_session->mem.calloc(sizeof(cmp_item *)*n);
3365}
3366
3367
3368void cmp_item_row::store_value(Item *item)
3369{
3370 n= item->cols();
3371 alloc_comparators();
3372 if (comparators)
3373 {
3374 item->bring_value();
3375 item->null_value= 0;
3376 for (uint32_t i=0; i < n; i++)
3377 {
3378 if (!comparators[i])
3379 if (!(comparators[i]=
3380 cmp_item::get_comparator(item->element_index(i)->result_type(),
3381 item->element_index(i)->collation.collation)))
3382 break; // new failed
3383 comparators[i]->store_value(item->element_index(i));
3384 item->null_value|= item->element_index(i)->null_value;
3385 }
3386 }
3387 return;
3388}
3389
3390
3391void cmp_item_row::store_value_by_template(cmp_item *t, Item *item)
3392{
3393 cmp_item_row *tmpl= (cmp_item_row*) t;
3394 if (tmpl->n != item->cols())
3395 {
3396 my_error(ER_OPERAND_COLUMNS, MYF(0), tmpl->n);
3397 return;
3398 }
3399 n= tmpl->n;
3400 if ((comparators= (cmp_item **) memory::sql_alloc(sizeof(cmp_item *)*n)))
3401 {
3402 item->bring_value();
3403 item->null_value= 0;
3404 for (uint32_t i=0; i < n; i++)
3405 {
3406 if (!(comparators[i]= tmpl->comparators[i]->make_same()))
3407 break; // new failed
3408 comparators[i]->store_value_by_template(tmpl->comparators[i],
3409 item->element_index(i));
3410 item->null_value|= item->element_index(i)->null_value;
3411 }
3412 }
3413}
3414
3415
3416int cmp_item_row::cmp(Item *arg)
3417{
3418 arg->null_value= 0;
3419 if (arg->cols() != n)
3420 {
3421 my_error(ER_OPERAND_COLUMNS, MYF(0), n);
3422 return 1;
3423 }
3424 bool was_null= 0;
3425 arg->bring_value();
3426 for (uint32_t i=0; i < n; i++)
3427 {
3428 if (comparators[i]->cmp(arg->element_index(i)))
3429 {
3430 if (!arg->element_index(i)->null_value)
3431 return 1;
3432 was_null= 1;
3433 }
3434 }
3435 return (arg->null_value= was_null);
3436}
3437
3438
3439int cmp_item_row::compare(cmp_item *c)
3440{
3441 cmp_item_row *l_cmp= (cmp_item_row *) c;
3442 for (uint32_t i=0; i < n; i++)
3443 {
3444 int res;
3445 if ((res= comparators[i]->compare(l_cmp->comparators[i])))
3446 return res;
3447 }
3448 return 0;
3449}
3450
3451
3452void cmp_item_decimal::store_value(Item *item)
3453{
3454 type::Decimal *val= item->val_decimal(&value);
3455 /* val may be zero if item is nnull */
3456 if (val && val != &value)
3457 class_decimal2decimal(val, &value);
3458}
3459
3460
3461int cmp_item_decimal::cmp(Item *arg)
3462{
3463 type::Decimal tmp_buf, *tmp= arg->val_decimal(&tmp_buf);
3464 if (arg->null_value)
3465 return 1;
3466 return class_decimal_cmp(&value, tmp);
3467}
3468
3469
3470int cmp_item_decimal::compare(cmp_item *arg)
3471{
3472 cmp_item_decimal *l_cmp= (cmp_item_decimal*) arg;
3473 return class_decimal_cmp(&value, &l_cmp->value);
3474}
3475
3476
3477cmp_item* cmp_item_decimal::make_same()
3478{
3479 return new cmp_item_decimal();
3480}
3481
3482
3483void cmp_item_datetime::store_value(Item *item)
3484{
3485 bool is_null;
3486 Item **tmp_item= lval_cache ? &lval_cache : &item;
3487 value= get_datetime_value(session, &tmp_item, &lval_cache, warn_item, &is_null);
3488}
3489
3490
3491int cmp_item_datetime::cmp(Item *arg)
3492{
3493 bool is_null;
3494 Item **tmp_item= &arg;
3495 return value !=
3496 get_datetime_value(session, &tmp_item, 0, warn_item, &is_null);
3497}
3498
3499
3500int cmp_item_datetime::compare(cmp_item *ci)
3501{
3502 cmp_item_datetime *l_cmp= (cmp_item_datetime *)ci;
3503 return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1);
3504}
3505
3506
3507cmp_item *cmp_item_datetime::make_same()
3508{
3509 return new cmp_item_datetime(warn_item);
3510}
3511
3512
3513bool Item_func_in::nulls_in_row()
3514{
3515 Item **arg,**arg_end;
3516 for (arg= args+1, arg_end= args+arg_count; arg != arg_end ; arg++)
3517 {
3518 if ((*arg)->null_inside())
3519 return 1;
3520 }
3521 return 0;
3522}
3523
3524
3552
3553bool
3555{
3556 Item **arg, **arg_end;
3557
3558 if (Item_func_opt_neg::fix_fields(session, ref))
3559 return 1;
3560
3561 /* not_null_tables_cache == union(T1(e),union(T1(ei))) */
3562 if (pred_level && negated)
3563 return 0;
3564
3565 /* not_null_tables_cache = union(T1(e),intersection(T1(ei))) */
3566 not_null_tables_cache= ~(table_map) 0;
3567 for (arg= args + 1, arg_end= args + arg_count; arg != arg_end; arg++)
3568 not_null_tables_cache&= (*arg)->not_null_tables();
3569 not_null_tables_cache|= (*args)->not_null_tables();
3570 return 0;
3571}
3572
3573
3574static int srtcmp_in(const charset_info_st * const cs, const String *x,const String *y)
3575{
3576 return cs->coll->strnncollsp(cs,
3577 (unsigned char *) x->ptr(),x->length(),
3578 (unsigned char *) y->ptr(),y->length(), 0);
3579}
3580
3581
3582void Item_func_in::fix_length_and_dec()
3583{
3584 Item **arg, **arg_end;
3585 bool const_itm= 1;
3586 bool datetime_found= false;
3587 /* true <=> arguments values will be compared as DATETIMEs. */
3588 bool compare_as_datetime= false;
3589 Item *date_arg= 0;
3590 uint32_t found_types= 0;
3591 uint32_t type_cnt= 0;
3592 Item_result cmp_type= STRING_RESULT;
3593 left_result_type= args[0]->result_type();
3594 if (!(found_types= collect_cmp_types(args, arg_count, true)))
3595 return;
3596
3597 for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
3598 {
3599 if (!arg[0]->const_item())
3600 {
3601 const_itm= 0;
3602 break;
3603 }
3604 }
3605 for (int i= STRING_RESULT; i <= DECIMAL_RESULT; i++)
3606 {
3607 if (found_types & 1 << i)
3608 {
3609 (type_cnt)++;
3610 cmp_type= (Item_result) i;
3611 }
3612 }
3613
3614 if (type_cnt == 1)
3615 {
3616 if (cmp_type == STRING_RESULT &&
3617 agg_arg_charsets(cmp_collation, args, arg_count, MY_COLL_CMP_CONV, 1))
3618 return;
3619 arg_types_compatible= true;
3620 }
3621 if (type_cnt == 1)
3622 {
3623 /*
3624 When comparing rows create the row comparator object beforehand to ease
3625 the DATETIME comparison detection procedure.
3626 */
3627 if (cmp_type == ROW_RESULT)
3628 {
3629 cmp_item_row *cmp= 0;
3630 if (const_itm && !nulls_in_row())
3631 {
3632 array= new in_row(arg_count-1, 0);
3633 cmp= &((in_row*)array)->tmp;
3634 }
3635 else
3636 {
3637 cmp= new cmp_item_row;
3638 cmp_items[ROW_RESULT]= cmp;
3639 }
3640 cmp->n= args[0]->cols();
3641 cmp->alloc_comparators();
3642 }
3643 /* All DATE/DATETIME fields/functions has the STRING result type. */
3644 if (cmp_type == STRING_RESULT || cmp_type == ROW_RESULT)
3645 {
3646 uint32_t col, num_cols= args[0]->cols();
3647
3648 for (col= 0; col < num_cols; col++)
3649 {
3650 bool skip_column= false;
3651 /*
3652 Check that all items to be compared has the STRING result type and at
3653 least one of them is a DATE/DATETIME item.
3654 */
3655 for (arg= args, arg_end= args + arg_count; arg != arg_end ; arg++)
3656 {
3657 Item *itm= ((cmp_type == STRING_RESULT) ? arg[0] :
3658 arg[0]->element_index(col));
3659 if (itm->result_type() != STRING_RESULT)
3660 {
3661 skip_column= true;
3662 break;
3663 }
3664 else if (itm->is_datetime())
3665 {
3666 datetime_found= true;
3667 /*
3668 Internally all DATE/DATETIME values are converted to the DATETIME
3669 type. So try to find a DATETIME item to issue correct warnings.
3670 */
3671 if (!date_arg)
3672 date_arg= itm;
3673 else if (itm->field_type() == DRIZZLE_TYPE_DATETIME)
3674 {
3675 date_arg= itm;
3676 /* All arguments are already checked to have the STRING result. */
3677 if (cmp_type == STRING_RESULT)
3678 break;
3679 }
3680 }
3681 }
3682 if (skip_column)
3683 continue;
3684 if (datetime_found)
3685 {
3686 if (cmp_type == ROW_RESULT)
3687 {
3688 cmp_item **cmp= 0;
3689 if (array)
3690 cmp= ((in_row*)array)->tmp.comparators + col;
3691 else
3692 cmp= ((cmp_item_row*)cmp_items[ROW_RESULT])->comparators + col;
3693 *cmp= new cmp_item_datetime(date_arg);
3694 /* Reset variables for the next column. */
3695 date_arg= 0;
3696 datetime_found= false;
3697 }
3698 else
3699 compare_as_datetime= true;
3700 }
3701 }
3702 }
3703 }
3704 /*
3705 Row item with NULLs inside can return NULL or false =>
3706 they can't be processed as static
3707 */
3708 if (type_cnt == 1 && const_itm && !nulls_in_row())
3709 {
3710 if (compare_as_datetime)
3711 {
3712 array= new in_datetime(date_arg, arg_count - 1);
3713 }
3714 else
3715 {
3716 /*
3717 IN must compare INT columns and constants as int values (the same
3718 way as equality does).
3719 So we must check here if the column on the left and all the constant
3720 values on the right can be compared as integers and adjust the
3721 comparison type accordingly.
3722 */
3723 if (args[0]->real_item()->type() == FIELD_ITEM &&
3724 cmp_type != INT_RESULT)
3725 {
3726 Item_field *field_item= (Item_field*) (args[0]->real_item());
3727 if (field_item->field->can_be_compared_as_int64_t())
3728 {
3729 bool all_converted= true;
3730 for (arg=args+1, arg_end=args+arg_count; arg != arg_end ; arg++)
3731 {
3732 if (!convert_constant_item (&getSession(), field_item, &arg[0]))
3733 all_converted= false;
3734 }
3735 if (all_converted)
3736 cmp_type= INT_RESULT;
3737 }
3738 }
3739
3740 switch (cmp_type) {
3741 case STRING_RESULT:
3742 array=new in_string(arg_count-1,(qsort2_cmp) srtcmp_in,
3743 cmp_collation.collation);
3744 break;
3745
3746 case INT_RESULT:
3747 array= new in_int64_t(arg_count-1);
3748 break;
3749
3750 case REAL_RESULT:
3751 array= new in_double(arg_count-1);
3752 break;
3753
3754 case ROW_RESULT:
3755 /*
3756 The row comparator was created at the beginning but only DATETIME
3757 items comparators were initialized. Call store_value() to setup
3758 others.
3759 */
3760 ((in_row*)array)->tmp.store_value(args[0]);
3761 break;
3762
3763 case DECIMAL_RESULT:
3764 array= new in_decimal(arg_count - 1);
3765 break;
3766 }
3767 }
3768
3769 if (array && !(getSession().is_fatal_error)) // If not EOM
3770 {
3771 uint32_t j=0;
3772 for (uint32_t arg_num=1 ; arg_num < arg_count ; arg_num++)
3773 {
3774 if (!args[arg_num]->null_value) // Skip NULL values
3775 {
3776 array->set(j,args[arg_num]);
3777 j++;
3778 }
3779 else
3780 have_null= 1;
3781 }
3782 if ((array->used_count= j))
3783 array->sort();
3784 }
3785 }
3786 else
3787 {
3788 if (compare_as_datetime)
3789 cmp_items[STRING_RESULT]= new cmp_item_datetime(date_arg);
3790 else
3791 {
3792 for (int i= STRING_RESULT; i <= DECIMAL_RESULT; i++)
3793 {
3794 if (found_types & (1 << i) && !cmp_items[i])
3795 {
3796 if ((Item_result)i == STRING_RESULT &&
3797 agg_arg_charsets(cmp_collation, args, arg_count,
3798 MY_COLL_CMP_CONV, 1))
3799 return;
3800 if (!cmp_items[i] && !(cmp_items[i]=
3801 cmp_item::get_comparator((Item_result)i,
3802 cmp_collation.collation)))
3803 return;
3804 }
3805 }
3806 }
3807 }
3808 max_length= 1;
3809}
3810
3811
3813{
3814 str->append('(');
3815 args[0]->print(str);
3816 if (negated)
3817 str->append(STRING_WITH_LEN(" not"));
3818 str->append(STRING_WITH_LEN(" in ("));
3819 print_args(str, 1);
3820 str->append(STRING_WITH_LEN("))"));
3821}
3822
3823
3824/*
3825 Evaluate the function and return its value.
3826
3827 SYNOPSIS
3828 val_int()
3829
3830 DESCRIPTION
3831 Evaluate the function and return its value.
3832
3833 IMPLEMENTATION
3834 If the array object is defined then the value of the function is
3835 calculated by means of this array.
3836 Otherwise several cmp_item objects are used in order to do correct
3837 comparison of left expression and an expression from the values list.
3838 One cmp_item object correspond to one used comparison type. Left
3839 expression can be evaluated up to number of different used comparison
3840 types. A bit mapped variable value_added_map is used to check whether
3841 the left expression already was evaluated for a particular result type.
3842 Result types are mapped to it according to their integer values i.e.
3843 STRING_RESULT is mapped to bit 0, REAL_RESULT to bit 1, so on.
3844
3845 RETURN
3846 Value of the function
3847*/
3848
3850{
3851 cmp_item *in_item;
3852 assert(fixed == 1);
3853 uint32_t value_added_map= 0;
3854 if (array)
3855 {
3856 int tmp=array->find(args[0]);
3857 null_value=args[0]->null_value || (!tmp && have_null);
3858 return (int64_t) (!null_value && tmp != negated);
3859 }
3860
3861 for (uint32_t i= 1 ; i < arg_count ; i++)
3862 {
3863 Item_result cmp_type= item_cmp_type(left_result_type, args[i]->result_type());
3864 in_item= cmp_items[(uint32_t)cmp_type];
3865 assert(in_item);
3866 if (!(value_added_map & (1 << (uint32_t)cmp_type)))
3867 {
3868 in_item->store_value(args[0]);
3869 if ((null_value=args[0]->null_value))
3870 return 0;
3871 have_null= 0;
3872 value_added_map|= 1 << (uint32_t)cmp_type;
3873 }
3874 if (!in_item->cmp(args[i]) && !args[i]->null_value)
3875 return (int64_t) (!negated);
3876 have_null|= args[i]->null_value;
3877 }
3878
3879 null_value= have_null;
3880 return (int64_t) (!null_value && negated);
3881}
3882
3883
3884Item_cond::Item_cond(Session *session, Item_cond *item)
3885 :item::function::Boolean(session, item),
3886 abort_on_null(item->abort_on_null),
3887 and_tables_cache(item->and_tables_cache)
3888{
3889 /*
3890 item->list will be copied by copy_andor_arguments() call
3891 */
3892}
3893
3894
3895void Item_cond::copy_andor_arguments(Session *session, Item_cond *item)
3896{
3897 List<Item>::iterator li(item->list.begin());
3898 while (Item *it= li++)
3899 list.push_back(it->copy_andor_structure(session));
3900}
3901
3902
3903bool
3904Item_cond::fix_fields(Session *session, Item **)
3905{
3906 assert(fixed == 0);
3907 List<Item>::iterator li(list.begin());
3908 Item *item;
3909 void *orig_session_marker= session->session_marker;
3910 unsigned char buff[sizeof(char*)]; // Max local vars in function
3911 not_null_tables_cache= used_tables_cache= 0;
3912 const_item_cache= true;
3913
3914 if (functype() == COND_OR_FUNC)
3915 session->session_marker= 0;
3916 /*
3917 and_table_cache is the value that Item_cond_or() returns for
3918 not_null_tables()
3919 */
3920 and_tables_cache= ~(table_map) 0;
3921
3922 if (check_stack_overrun(session, STACK_MIN_SIZE, buff))
3923 return true; // Fatal error flag is set!
3924 /*
3925 The following optimization reduces the depth of an AND-OR tree.
3926 E.g. a WHERE clause like
3927 F1 AND (F2 AND (F2 AND F4))
3928 is parsed into a tree with the same nested structure as defined
3929 by braces. This optimization will transform such tree into
3930 AND (F1, F2, F3, F4).
3931 Trees of OR items are flattened as well:
3932 ((F1 OR F2) OR (F3 OR F4)) => OR (F1, F2, F3, F4)
3933 Items for removed AND/OR levels will dangle until the death of the
3934 entire statement.
3935 The optimization is currently prepared statements and stored procedures
3936 friendly as it doesn't allocate any memory and its effects are durable
3937 (i.e. do not depend on PS/SP arguments).
3938 */
3939 while ((item=li++))
3940 {
3941 table_map tmp_table_map;
3942 while (item->type() == Item::COND_ITEM &&
3943 ((Item_cond*) item)->functype() == functype() &&
3944 !((Item_cond*) item)->list.is_empty())
3945 { // Identical function
3946 li.replace(((Item_cond*) item)->list);
3947 ((Item_cond*) item)->list.clear();
3948 item= &*li; // new current item
3949 }
3950 if (abort_on_null)
3951 item->top_level_item();
3952
3953 // item can be substituted in fix_fields
3954 if ((!item->fixed &&
3955 item->fix_fields(session, li.ref())) ||
3956 (item= &*li)->check_cols(1))
3957 return true;
3958 used_tables_cache|= item->used_tables();
3959 if (item->const_item())
3960 and_tables_cache= (table_map) 0;
3961 else
3962 {
3963 tmp_table_map= item->not_null_tables();
3964 not_null_tables_cache|= tmp_table_map;
3965 and_tables_cache&= tmp_table_map;
3966 const_item_cache= false;
3967 }
3968 with_sum_func= with_sum_func || item->with_sum_func;
3969 with_subselect|= item->with_subselect;
3970 if (item->maybe_null)
3971 maybe_null=1;
3972 }
3973 session->lex().current_select->cond_count+= list.size();
3974 session->session_marker= orig_session_marker;
3975 fix_length_and_dec();
3976 fixed= 1;
3977 return false;
3978}
3979
3980
3981void Item_cond::fix_after_pullout(Select_Lex *new_parent, Item **)
3982{
3983 List<Item>::iterator li(list.begin());
3984 Item *item;
3985
3986 used_tables_cache=0;
3987 const_item_cache= true;
3988
3989 and_tables_cache= ~(table_map) 0; // Here and below we do as fix_fields does
3990 not_null_tables_cache= 0;
3991
3992 while ((item=li++))
3993 {
3994 table_map tmp_table_map;
3995 item->fix_after_pullout(new_parent, li.ref());
3996 item= &*li;
3997 used_tables_cache|= item->used_tables();
3998 const_item_cache&= item->const_item();
3999
4000 if (item->const_item())
4001 and_tables_cache= (table_map) 0;
4002 else
4003 {
4004 tmp_table_map= item->not_null_tables();
4005 not_null_tables_cache|= tmp_table_map;
4006 and_tables_cache&= tmp_table_map;
4007 const_item_cache= false;
4008 }
4009 }
4010}
4011
4012
4013bool Item_cond::walk(Item_processor processor, bool walk_subquery, unsigned char *arg)
4014{
4015 List<Item>::iterator li(list.begin());
4016 Item *item;
4017 while ((item= li++))
4018 if (item->walk(processor, walk_subquery, arg))
4019 return 1;
4020 return Item_func::walk(processor, walk_subquery, arg);
4021}
4022
4023
4041
4042Item *Item_cond::transform(Item_transformer transformer, unsigned char *arg)
4043{
4044 List<Item>::iterator li(list.begin());
4045 Item *item;
4046 while ((item= li++))
4047 {
4048 Item *new_item= item->transform(transformer, arg);
4049 if (!new_item)
4050 return 0;
4051 *li.ref()= new_item;
4052 }
4053 return Item_func::transform(transformer, arg);
4054}
4055
4056
4080
4081Item *Item_cond::compile(Item_analyzer analyzer, unsigned char **arg_p,
4082 Item_transformer transformer, unsigned char *arg_t)
4083{
4084 if (!(this->*analyzer)(arg_p))
4085 return 0;
4086
4087 List<Item>::iterator li(list.begin());
4088 Item *item;
4089 while ((item= li++))
4090 {
4091 /*
4092 The same parameter value of arg_p must be passed
4093 to analyze any argument of the condition formula.
4094 */
4095 unsigned char *arg_v= *arg_p;
4096 Item *new_item= item->compile(analyzer, &arg_v, transformer, arg_t);
4097 if (new_item && new_item != item)
4098 li.replace(new_item);
4099 }
4100 return Item_func::transform(transformer, arg_t);
4101}
4102
4103void Item_cond::traverse_cond(Cond_traverser traverser,
4104 void *arg, traverse_order order)
4105{
4106 List<Item>::iterator li(list.begin());
4107 Item *item;
4108
4109 switch (order) {
4110 case (T_PREFIX):
4111 (*traverser)(this, arg);
4112 while ((item= li++))
4113 {
4114 item->traverse_cond(traverser, arg, order);
4115 }
4116 (*traverser)(NULL, arg);
4117 break;
4118 case (T_POSTFIX):
4119 while ((item= li++))
4120 {
4121 item->traverse_cond(traverser, arg, order);
4122 }
4123 (*traverser)(this, arg);
4124 }
4125}
4126
4143
4144void Item_cond::split_sum_func(Session *session, Item **ref_pointer_array, List<Item> &fields)
4145{
4146 List<Item>::iterator li(list.begin());
4147 Item *item;
4148 while ((item= li++))
4149 item->split_sum_func(session, ref_pointer_array, fields, li.ref(), true);
4150}
4151
4152
4153table_map
4155{ // This caches used_tables
4156 return used_tables_cache;
4157}
4158
4159
4160void Item_cond::update_used_tables()
4161{
4162 List<Item>::iterator li(list.begin());
4163 Item *item;
4164
4165 used_tables_cache=0;
4166 const_item_cache= true;
4167 while ((item=li++))
4168 {
4169 item->update_used_tables();
4170 used_tables_cache|= item->used_tables();
4171 const_item_cache&= item->const_item();
4172 }
4173}
4174
4175
4177{
4178 str->append('(');
4179 List<Item>::iterator li(list.begin());
4180 Item *item;
4181 if ((item=li++))
4182 item->print(str);
4183 while ((item=li++))
4184 {
4185 str->append(' ');
4186 str->append(func_name(), strlen(func_name()));
4187 str->append(' ');
4188 item->print(str);
4189 }
4190 str->append(')');
4191}
4192
4193
4194void Item_cond::neg_arguments(Session *session)
4195{
4196 List<Item>::iterator li(list.begin());
4197 Item *item;
4198 while ((item= li++)) /* Apply not transformation to the arguments */
4199 {
4200 Item *new_item= item->neg_transformer(session);
4201 if (!new_item)
4202 new_item= new Item_func_not(item);
4203 li.replace(new_item);
4204 }
4205}
4206
4207
4226
4227
4229{
4230 assert(fixed == 1);
4231 List<Item>::iterator li(list.begin());
4232 Item *item;
4233 null_value= 0;
4234 while ((item=li++))
4235 {
4236 if (!item->val_bool())
4237 {
4238 if (abort_on_null || !(null_value= item->null_value))
4239 return 0; // return false
4240 }
4241 }
4242 return null_value ? 0 : 1;
4243}
4244
4245
4247{
4248 assert(fixed == 1);
4249 List<Item>::iterator li(list.begin());
4250 Item *item;
4251 null_value=0;
4252 while ((item=li++))
4253 {
4254 if (item->val_bool())
4255 {
4256 null_value=0;
4257 return 1;
4258 }
4259 if (item->null_value)
4260 null_value=1;
4261 }
4262 return 0;
4263}
4264
4284
4285Item *and_expressions(Item *a, Item *b, Item **org_item)
4286{
4287 if (!a)
4288 return (*org_item= (Item*) b);
4289 if (a == *org_item)
4290 {
4291 Item_cond *res;
4292 res= new Item_cond_and(a, (Item*) b);
4293 res->used_tables_cache= a->used_tables() | b->used_tables();
4294 res->not_null_tables_cache= a->not_null_tables() | b->not_null_tables();
4295 return res;
4296 }
4297 ((Item_cond_and*) a)->add((Item*) b);
4298 ((Item_cond_and*) a)->used_tables_cache|= b->used_tables();
4299 ((Item_cond_and*) a)->not_null_tables_cache|= b->not_null_tables();
4300 return a;
4301}
4302
4303
4305{
4306 assert(fixed == 1);
4307 /*
4308 Handle optimization if the argument can't be null
4309 This has to be here because of the test in update_used_tables().
4310 */
4311 if (!used_tables_cache && !with_subselect)
4312 return cached_value;
4313 return args[0]->is_null() ? 1: 0;
4314}
4315
4317{
4318 assert(fixed == 1);
4319 if (!used_tables_cache && !with_subselect)
4320 {
4321 owner->was_null|= (!cached_value);
4322 return(cached_value);
4323 }
4324 if (args[0]->is_null())
4325 {
4326 owner->was_null|= 1;
4327 return 0;
4328 }
4329 else
4330 return 1;
4331}
4332
4337{
4338 if (!args[0]->maybe_null)
4339 {
4340 used_tables_cache= 0; /* is always true */
4341 cached_value= (int64_t) 1;
4342 }
4343 else
4344 {
4345 args[0]->update_used_tables();
4346 if (!(used_tables_cache=args[0]->used_tables()) && !with_subselect)
4347 {
4348 /* Remember if the value is always NULL or never NULL */
4349 cached_value= (int64_t) !args[0]->is_null();
4350 }
4351 }
4352}
4353
4354
4356{
4357 assert(fixed == 1);
4358 return args[0]->is_null() ? 0 : 1;
4359}
4360
4361
4363{
4364 str->append('(');
4365 args[0]->print(str);
4366 str->append(STRING_WITH_LEN(" is not null)"));
4367}
4368
4369
4371{
4372 assert(fixed == 1);
4373 String* res = args[0]->val_str(&tmp_value1);
4374 if (args[0]->null_value)
4375 {
4376 null_value=1;
4377 return 0;
4378 }
4379 String* res2 = args[1]->val_str(&tmp_value2);
4380 if (args[1]->null_value)
4381 {
4382 null_value=1;
4383 return 0;
4384 }
4385 null_value=0;
4386 if (canDoTurboBM)
4387 return turboBM_matches(res->ptr(), res->length()) ? 1 : 0;
4388 return my_wildcmp(cmp.cmp_collation.collation,
4389 res->ptr(),res->ptr()+res->length(),
4390 res2->ptr(),res2->ptr()+res2->length(),
4391 make_escape_code(cmp.cmp_collation.collation, escape), internal::wild_one,internal::wild_many) ? 0 : 1;
4392}
4393
4394
4398
4399Item_func::optimize_type Item_func_like::select_optimize() const
4400{
4401 if (args[1]->const_item())
4402 {
4403 String* res2= args[1]->val_str((String *)&tmp_value2);
4404
4405 if (!res2)
4406 return OPTIMIZE_NONE;
4407
4408 if (*res2->ptr() != internal::wild_many)
4409 {
4410 if (args[0]->result_type() != STRING_RESULT || *res2->ptr() != internal::wild_one)
4411 return OPTIMIZE_OP;
4412 }
4413 }
4414 return OPTIMIZE_NONE;
4415}
4416
4417
4418bool Item_func_like::fix_fields(Session *session, Item **ref)
4419{
4420 assert(fixed == 0);
4421 if (Item_bool_func2::fix_fields(session, ref) ||
4422 escape_item->fix_fields(session, &escape_item))
4423 return true;
4424
4425 if (!escape_item->const_during_execution())
4426 {
4427 my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
4428 return true;
4429 }
4430
4431 if (escape_item->const_item())
4432 {
4433
4434 /* If we are on execution stage */
4435 String *escape_str= escape_item->val_str(&tmp_value1);
4436 if (escape_str)
4437 {
4438 escape= (char *)memory::sql_alloc(escape_str->length());
4439 strcpy(escape, escape_str->ptr());
4440 }
4441 else
4442 {
4443 escape= (char *)memory::sql_alloc(1);
4444 strcpy(escape, "\\");
4445 }
4446
4447 /*
4448 We could also do boyer-more for non-const items, but as we would have to
4449 recompute the tables for each row it's not worth it.
4450 */
4451 if (args[1]->const_item() && not collation.collation->use_strnxfrm())
4452 {
4453 String* res2 = args[1]->val_str(&tmp_value2);
4454 if (!res2)
4455 return false; // Null argument
4456
4457 const size_t len = res2->length();
4458 const char* first = res2->ptr();
4459 const char* last = first + len - 1;
4460 /*
4461 len must be > 2 ('%pattern%')
4462 heuristic: only do TurboBM for pattern_len > 2
4463 */
4464
4465 if (len > MIN_TURBOBM_PATTERN_LEN + 2 &&
4466 *first == internal::wild_many &&
4467 *last == internal::wild_many)
4468 {
4469 const char* tmp = first + 1;
4470 for (; *tmp != internal::wild_many && *tmp != internal::wild_one; tmp++)
4471 {
4472 if (escape == tmp)
4473 break;
4474 }
4475
4476 canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation);
4477 }
4478 if (canDoTurboBM)
4479 {
4480 pattern = first + 1;
4481 pattern_len = (int) len - 2;
4482 int *suff = (int*) session->mem.alloc(sizeof(int) * ((pattern_len + 1)*2+ alphabet_size));
4483 bmGs = suff + pattern_len + 1;
4484 bmBc = bmGs + pattern_len + 1;
4487 }
4488 }
4489 }
4490 return false;
4491}
4492
4493void Item_func_like::cleanup()
4494{
4495 canDoTurboBM= false;
4496 Item_bool_func2::cleanup();
4497}
4498
4499static unsigned char likeconv(const charset_info_st *cs, unsigned char a)
4500{
4501#ifdef LIKE_CMP_TOUPPER
4502 return cs->toupper(a);
4503#else
4504 return cs->sort_order[a];
4505#endif
4506}
4507
4511
4513{
4514 const int plm1 = pattern_len - 1;
4515 int f = 0;
4516 int g = plm1;
4517 int *const splm1 = suff + plm1;
4518 const charset_info_st * const cs= cmp.cmp_collation.collation;
4519
4520 *splm1 = pattern_len;
4521
4522 if (!cs->sort_order)
4523 {
4524 for (int i = pattern_len - 2; i >= 0; i--)
4525 {
4526 int tmp = *(splm1 + i - f);
4527 if (g < i && tmp < i - g)
4528 suff[i] = tmp;
4529 else
4530 {
4531 if (i < g)
4532 g = i;
4533 f = i;
4534 while (g >= 0 && pattern[g] == pattern[g + plm1 - f])
4535 g--;
4536 suff[i] = f - g;
4537 }
4538 }
4539 }
4540 else
4541 {
4542 for (int i = pattern_len - 2; 0 <= i; --i)
4543 {
4544 int tmp = *(splm1 + i - f);
4545 if (g < i && tmp < i - g)
4546 suff[i] = tmp;
4547 else
4548 {
4549 if (i < g)
4550 g = i;
4551 f = i;
4552 while (g >= 0 &&
4553 likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f]))
4554 g--;
4555 suff[i] = f - g;
4556 }
4557 }
4558 }
4559}
4560
4561
4565
4567{
4569
4570 int *end = bmGs + pattern_len;
4571 int *k;
4572 for (k = bmGs; k < end; k++)
4573 *k = pattern_len;
4574
4575 int tmp;
4576 int i;
4577 int j = 0;
4578 const int plm1 = pattern_len - 1;
4579 for (i = plm1; i > -1; i--)
4580 {
4581 if (suff[i] == i + 1)
4582 {
4583 for (tmp = plm1 - i; j < tmp; j++)
4584 {
4585 int *tmp2 = bmGs + j;
4586 if (*tmp2 == pattern_len)
4587 *tmp2 = tmp;
4588 }
4589 }
4590 }
4591
4592 int *tmp2;
4593 for (tmp = plm1 - i; j < tmp; j++)
4594 {
4595 tmp2 = bmGs + j;
4596 if (*tmp2 == pattern_len)
4597 *tmp2 = tmp;
4598 }
4599
4600 tmp2 = bmGs + plm1;
4601 for (i = 0; i <= pattern_len - 2; i++)
4602 *(tmp2 - suff[i]) = plm1 - i;
4603}
4604
4605
4609
4611{
4612 int *i;
4613 int *end = bmBc + alphabet_size;
4614 int j;
4615 const int plm1 = pattern_len - 1;
4616 const charset_info_st *const cs= cmp.cmp_collation.collation;
4617
4618 for (i = bmBc; i < end; i++)
4619 *i = pattern_len;
4620
4621 if (!cs->sort_order)
4622 {
4623 for (j = 0; j < plm1; j++)
4624 bmBc[(uint32_t) (unsigned char) pattern[j]] = plm1 - j;
4625 }
4626 else
4627 {
4628 for (j = 0; j < plm1; j++)
4629 bmBc[(uint32_t) likeconv(cs,pattern[j])] = plm1 - j;
4630 }
4631}
4632
4633
4640
4641bool Item_func_like::turboBM_matches(const char* text, int text_len) const
4642{
4643 int bcShift;
4644 int turboShift;
4645 int shift = pattern_len;
4646 int j = 0;
4647 int u = 0;
4648 const charset_info_st * const cs= cmp.cmp_collation.collation;
4649
4650 const int plm1= pattern_len - 1;
4651 const int tlmpl= text_len - pattern_len;
4652
4653 /* Searching */
4654 if (!cs->sort_order)
4655 {
4656 while (j <= tlmpl)
4657 {
4658 int i= plm1;
4659 while (i >= 0 && pattern[i] == text[i + j])
4660 {
4661 i--;
4662 if (i == plm1 - shift)
4663 i-= u;
4664 }
4665 if (i < 0)
4666 return 1;
4667
4668 const int v = plm1 - i;
4669 turboShift = u - v;
4670 bcShift = bmBc[(uint32_t) (unsigned char) text[i + j]] - plm1 + i;
4671 shift = (turboShift > bcShift) ? turboShift : bcShift;
4672 shift = (shift > bmGs[i]) ? shift : bmGs[i];
4673 if (shift == bmGs[i])
4674 u = (pattern_len - shift < v) ? pattern_len - shift : v;
4675 else
4676 {
4677 if (turboShift < bcShift)
4678 shift= max(shift, u + 1);
4679 u = 0;
4680 }
4681 j+= shift;
4682 }
4683 return 0;
4684 }
4685 else
4686 {
4687 while (j <= tlmpl)
4688 {
4689 int i = plm1;
4690 while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
4691 {
4692 i--;
4693 if (i == plm1 - shift)
4694 i-= u;
4695 }
4696
4697 if (i < 0)
4698 return 1;
4699
4700 const int v= plm1 - i;
4701 turboShift= u - v;
4702 bcShift= bmBc[(uint32_t) likeconv(cs, text[i + j])] - plm1 + i;
4703 shift= (turboShift > bcShift) ? turboShift : bcShift;
4704 shift= max(shift, bmGs[i]);
4705
4706 if (shift == bmGs[i])
4707 u= (pattern_len - shift < v) ? pattern_len - shift : v;
4708 else
4709 {
4710 if (turboShift < bcShift)
4711 shift= max(shift, u + 1);
4712 u = 0;
4713 }
4714
4715 j+= shift;
4716 }
4717 return 0;
4718 }
4719}
4720
4721
4737
4739{
4740 assert(fixed == 1);
4741 List<Item>::iterator li(list.begin());
4742 Item *item;
4743 int result=0;
4744 null_value=0;
4745 while ((item=li++))
4746 {
4747 result^= (item->val_int() != 0);
4748 if (item->null_value)
4749 {
4750 null_value=1;
4751 return 0;
4752 }
4753 }
4754 return (int64_t) result;
4755}
4756
4782
4784{
4785 return args[0];
4786}
4787
4788
4789Item *Item_bool_rowready_func2::neg_transformer(Session *)
4790{
4791 Item *item= negated_item();
4792 return item;
4793}
4794
4795
4800{
4801 Item *item= new Item_func_isnotnull(args[0]);
4802 return item;
4803}
4804
4805
4810{
4811 Item *item= new Item_func_isnull(args[0]);
4812 return item;
4813}
4814
4815
4816Item *Item_cond_and::neg_transformer(Session *session) /* NOT(a AND b AND ...) -> */
4817 /* NOT a OR NOT b OR ... */
4818{
4819 neg_arguments(session);
4820 Item *item= new Item_cond_or(list);
4821 return item;
4822}
4823
4824
4825Item *Item_cond_or::neg_transformer(Session *session) /* NOT(a OR b OR ...) -> */
4826 /* NOT a AND NOT b AND ... */
4827{
4828 neg_arguments(session);
4829 Item *item= new Item_cond_and(list);
4830 return item;
4831}
4832
4833
4834Item *Item_func_nop_all::neg_transformer(Session *)
4835{
4836 /* "NOT (e $cmp$ ANY (SELECT ...)) -> e $rev_cmp$" ALL (SELECT ...) */
4837 Item_func_not_all *new_item= new Item_func_not_all(args[0]);
4838 Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
4839 allany->func= allany->func_creator(false);
4840 allany->all= !allany->all;
4841 allany->upper_item= new_item;
4842 return new_item;
4843}
4844
4846{
4847 /* "NOT (e $cmp$ ALL (SELECT ...)) -> e $rev_cmp$" ANY (SELECT ...) */
4848 Item_func_nop_all *new_item= new Item_func_nop_all(args[0]);
4850 allany->all= !allany->all;
4851 allany->func= allany->func_creator(true);
4852 allany->upper_item= new_item;
4853 return new_item;
4854}
4855
4856Item *Item_func_eq::negated_item() /* a = b -> a != b */
4857{
4858 return new Item_func_ne(args[0], args[1]);
4859}
4860
4861
4862Item *Item_func_ne::negated_item() /* a != b -> a = b */
4863{
4864 return new Item_func_eq(args[0], args[1]);
4865}
4866
4867
4868Item *Item_func_lt::negated_item() /* a < b -> a >= b */
4869{
4870 return new Item_func_ge(args[0], args[1]);
4871}
4872
4873
4874Item *Item_func_ge::negated_item() /* a >= b -> a < b */
4875{
4876 return new Item_func_lt(args[0], args[1]);
4877}
4878
4879
4880Item *Item_func_gt::negated_item() /* a > b -> a <= b */
4881{
4882 return new Item_func_le(args[0], args[1]);
4883}
4884
4885
4886Item *Item_func_le::negated_item() /* a <= b -> a > b */
4887{
4888 return new Item_func_gt(args[0], args[1]);
4889}
4890
4895{
4896 assert(0);
4897 return 0;
4898}
4899
4900Item_equal::Item_equal(Item_field *f1, Item_field *f2)
4901 : item::function::Boolean(), const_item(0), eval_item(0), cond_false(0)
4902{
4903 const_item_cache= false;
4904 fields.push_back(f1);
4905 fields.push_back(f2);
4906}
4907
4908Item_equal::Item_equal(Item *c, Item_field *f)
4909 : item::function::Boolean(), eval_item(0), cond_false(0)
4910{
4911 const_item_cache= false;
4912 fields.push_back(f);
4913 const_item= c;
4914}
4915
4916
4917Item_equal::Item_equal(Item_equal *item_equal)
4918 : item::function::Boolean(), eval_item(0), cond_false(0)
4919{
4920 const_item_cache= false;
4921 List<Item_field>::iterator li(item_equal->fields.begin());
4922 Item_field *item;
4923 while ((item= li++))
4924 {
4925 fields.push_back(item);
4926 }
4927 const_item= item_equal->const_item;
4928 cond_false= item_equal->cond_false;
4929}
4930
4931void Item_equal::add(Item *c)
4932{
4933 if (cond_false)
4934 return;
4935 if (!const_item)
4936 {
4937 const_item= c;
4938 return;
4939 }
4940 Item_func_eq *func= new Item_func_eq(c, const_item);
4941 func->set_cmp_func();
4942 func->quick_fix_field();
4943 if ((cond_false= !func->val_int()))
4944 const_item_cache= true;
4945}
4946
4947void Item_equal::add(Item_field *f)
4948{
4949 fields.push_back(f);
4950}
4951
4952uint32_t Item_equal::members()
4953{
4954 return fields.size();
4955}
4956
4957
4970
4972{
4973 List<Item_field>::iterator it(fields.begin());
4974 Item_field *item;
4975 while ((item= it++))
4976 {
4977 if (field->eq(item->field))
4978 return 1;
4979 }
4980 return 0;
4981}
4982
4983
4994
4995void Item_equal::merge(Item_equal *item)
4996{
4997 fields.concat(&item->fields);
4998 Item *c= item->const_item;
4999 if (c)
5000 {
5001 /*
5002 The flag cond_false will be set to 1 after this, if
5003 the multiple equality already contains a constant and its
5004 value is not equal to the value of c.
5005 */
5006 add(c);
5007 }
5008 cond_false|= item->cond_false;
5009}
5010
5011
5028
5029void Item_equal::sort(Item_field_cmpfunc cmp, void *arg)
5030{
5031 bool swap;
5032 List<Item_field>::iterator it(fields.begin());
5033 do
5034 {
5035 Item_field *item1= it++;
5036 Item_field **ref1= it.ref();
5037 Item_field *item2;
5038
5039 swap= false;
5040 while ((item2= it++))
5041 {
5042 Item_field **ref2= it.ref();
5043 if (cmp(item1, item2, arg) < 0)
5044 {
5045 Item_field *item= *ref1;
5046 *ref1= *ref2;
5047 *ref2= item;
5048 swap= true;
5049 }
5050 else
5051 {
5052 item1= item2;
5053 ref1= ref2;
5054 }
5055 }
5056 it= fields.begin();
5057 } while (swap);
5058}
5059
5060
5070
5072{
5073 List<Item_field>::iterator it(fields.begin());
5074 Item *item;
5075 while ((item= it++))
5076 {
5077 if (item->const_item())
5078 {
5079 it.remove();
5080 add(item);
5081 }
5082 }
5083}
5084
5085bool Item_equal::fix_fields(Session *, Item **)
5086{
5087 List<Item_field>::iterator li(fields.begin());
5088 Item *item;
5089 not_null_tables_cache= used_tables_cache= 0;
5090 const_item_cache= false;
5091 while ((item= li++))
5092 {
5093 table_map tmp_table_map;
5094 used_tables_cache|= item->used_tables();
5095 tmp_table_map= item->not_null_tables();
5096 not_null_tables_cache|= tmp_table_map;
5097 if (item->maybe_null)
5098 maybe_null=1;
5099 }
5100 fix_length_and_dec();
5101 fixed= 1;
5102 return 0;
5103}
5104
5105void Item_equal::update_used_tables()
5106{
5107 List<Item_field>::iterator li(fields.begin());
5108 Item *item;
5109 not_null_tables_cache= used_tables_cache= 0;
5110 if ((const_item_cache= cond_false))
5111 return;
5112 while ((item=li++))
5113 {
5114 item->update_used_tables();
5115 used_tables_cache|= item->used_tables();
5116 const_item_cache&= item->const_item();
5117 }
5118}
5119
5121{
5122 Item_field *item_field;
5123 if (cond_false)
5124 return 0;
5125 List<Item_field>::iterator it(fields.begin());
5126 Item *item= const_item ? const_item : it++;
5127 eval_item->store_value(item);
5128 if ((null_value= item->null_value))
5129 return 0;
5130 while ((item_field= it++))
5131 {
5132 /* Skip fields of non-const tables. They haven't been read yet */
5133 if (item_field->field->getTable()->const_table)
5134 {
5135 if (eval_item->cmp(item_field) || (null_value= item_field->null_value))
5136 return 0;
5137 }
5138 }
5139 return 1;
5140}
5141
5142void Item_equal::fix_length_and_dec()
5143{
5144 Item *item= get_first();
5145 eval_item= cmp_item::get_comparator(item->result_type(),
5146 item->collation.collation);
5147}
5148
5149bool Item_equal::walk(Item_processor processor, bool walk_subquery, unsigned char *arg)
5150{
5151 List<Item_field>::iterator it(fields.begin());
5152 Item *item;
5153 while ((item= it++))
5154 {
5155 if (item->walk(processor, walk_subquery, arg))
5156 return 1;
5157 }
5158 return Item_func::walk(processor, walk_subquery, arg);
5159}
5160
5161Item *Item_equal::transform(Item_transformer transformer, unsigned char *arg)
5162{
5163 List<Item_field>::iterator it(fields.begin());
5164 Item *item;
5165 while ((item= it++))
5166 {
5167 Item *new_item= item->transform(transformer, arg);
5168 if (!new_item)
5169 return 0;
5170 *(Item **)it.ref()= new_item;
5171 }
5172 return Item_func::transform(transformer, arg);
5173}
5174
5176{
5177 str->append(func_name(), strlen(func_name()));
5178 str->append('(');
5179 List<Item_field>::iterator it(fields.begin());
5180 Item *item;
5181 if (const_item)
5182 const_item->print(str);
5183 else
5184 {
5185 item= it++;
5186 item->print(str);
5187 }
5188 while ((item= it++))
5189 {
5190 str->append(',');
5191 str->append(' ');
5192 item->print(str);
5193 }
5194 str->append(')');
5195}
5196
5197cmp_item_datetime::cmp_item_datetime(Item *warn_item_arg) :
5198 session(current_session),
5199 warn_item(warn_item_arg),
5200 lval_cache(0)
5201{}
5202
5203} /* namespace drizzled */
static enum_field_types field_type_merge(enum_field_types, enum_field_types)
Definition field.cc:687
void split_sum_func(Session *session, Item **ref_pointer_array, List< Item > &fields)
Definition cmpfunc.cc:4144
table_map used_tables() const
Definition cmpfunc.cc:4154
Item * compile(Item_analyzer analyzer, unsigned char **arg_p, Item_transformer transformer, unsigned char *arg_t)
Definition cmpfunc.cc:4081
virtual void print(String *str)
Definition cmpfunc.cc:4176
Item * transform(Item_transformer transformer, unsigned char *arg)
Definition cmpfunc.cc:4042
void fix_after_pullout(Select_Lex *new_parent, Item **ref)
Definition cmpfunc.cc:3981
void merge(Item_equal *item)
Definition cmpfunc.cc:4995
void sort(Item_field_cmpfunc cmp, void *arg)
Definition cmpfunc.cc:5029
virtual void print(String *str)
Definition cmpfunc.cc:5175
Item * transform(Item_transformer transformer, unsigned char *arg)
Definition cmpfunc.cc:5161
bool contains(Field *field)
Definition cmpfunc.cc:4971
bool fix_fields(Session *, Item **)
Definition cmpfunc.cc:1998
virtual void print(String *str)
Definition cmpfunc.cc:2189
virtual void print(String *str)
Definition cmpfunc.cc:2854
type::Decimal * val_decimal(type::Decimal *)
Definition cmpfunc.cc:2699
Item * find_item(String *str)
Definition cmpfunc.cc:2606
String * val_str(String *)
Definition cmpfunc.cc:2644
type::Decimal * decimal_op(type::Decimal *)
Performs the operation that this functions implements when the result type is DECIMAL.
Definition cmpfunc.cc:2938
double real_op()
Performs the operation that this functions implements when the result type is REAL.
Definition cmpfunc.cc:2923
String * str_op(String *)
Definition cmpfunc.cc:2895
int64_t int_op()
Performs the operation that this functions implements when the result type is INT.
Definition cmpfunc.cc:2909
String * val_str(String *str)
Definition cmpfunc.cc:2463
type::Decimal * val_decimal(type::Decimal *)
Definition cmpfunc.cc:2478
bool fix_fields(Session *, Item **)
Definition cmpfunc.cc:2359
String * str_op(String *str)
Definition cmpfunc.cc:2314
int64_t int_op()
Performs the operation that this functions implements when the result type is INT.
Definition cmpfunc.cc:2281
type::Decimal * decimal_op(type::Decimal *)
Performs the operation that this functions implements when the result type is DECIMAL.
Definition cmpfunc.cc:2297
double real_op()
Performs the operation that this functions implements when the result type is REAL.
Definition cmpfunc.cc:2265
bool fix_fields(Session *, Item **)
Definition cmpfunc.cc:3554
virtual void print(String *str)
Definition cmpfunc.cc:3812
Item * neg_transformer(Session *session)
Definition cmpfunc.cc:4809
virtual void print(String *str)
Definition cmpfunc.cc:4362
Item * neg_transformer(Session *session)
Definition cmpfunc.cc:4799
optimize_type select_optimize() const
Definition cmpfunc.cc:4399
bool turboBM_matches(const char *text, int text_len) const
Definition cmpfunc.cc:4641
void turboBM_compute_bad_character_shifts()
Definition cmpfunc.cc:4610
void turboBM_compute_good_suffix_shifts(int *suff)
Definition cmpfunc.cc:4566
void turboBM_compute_suffixes(int *suff)
Definition cmpfunc.cc:4512
virtual void print(String *str)
Definition cmpfunc.cc:388
Item * neg_transformer(Session *session)
Definition cmpfunc.cc:4845
virtual void print(String *str)
Definition cmpfunc.cc:353
Item * neg_transformer(Session *session)
Definition cmpfunc.cc:4783
type::Decimal * val_decimal(type::Decimal *)
Definition cmpfunc.cc:2563
String * val_str(String *str)
Definition cmpfunc.cc:2547
String * val_str(String *str)
Definition numhybrid.cc:36
bool eq(const Item *item, bool binary_cmp) const
Definition cmpfunc.cc:1792
virtual bool val_bool()
Definition cmpfunc.cc:1473
virtual void print(String *str)
Definition cmpfunc.cc:1458
virtual int64_t val_int()
Definition cmpfunc.cc:1496
Item * transform(Item_transformer transformer, unsigned char *arg)
Definition func.cc:340
virtual bool const_item() const
table_map not_null_tables() const
Definition func.cc:436
virtual void print(String *str)
Definition func.cc:442
Item * transform(Item_transformer transformer, unsigned char *arg)
Definition cmpfunc.cc:1680
table_map used_tables() const
Definition cmpfunc.h:1318
virtual int64_t val_int()=0
bool fixed
Definition item.h:122
virtual double val_real()=0
virtual table_map not_null_tables() const
Definition item.h:468
virtual Item * transform(Item_transformer transformer, unsigned char *arg)
Definition item.cc:387
virtual void print(String *str)
Definition item.cc:362
virtual bool const_during_execution() const
Definition item.h:505
bool null_value
Definition item.h:124
virtual bool const_item() const
Definition item.h:497
Item_result cmp_context
Definition item.h:146
virtual type::Decimal * val_decimal(type::Decimal *decimal_buffer)=0
bool maybe_null
Definition item.h:123
virtual Item * compile(Item_analyzer analyzer, unsigned char **arg_p, Item_transformer transformer, unsigned char *arg_t)
Definition item.cc:585
bool with_subselect
Definition item.h:144
virtual table_map used_tables() const
Definition item.h:453
virtual bool is_null()
Definition item.cc:513
virtual String * val_str(String *str)=0
virtual bool val_bool()
Definition item.cc:95
unsigned char * alloc(size_t Size)
Allocate a chunk of memory from the Root structure provided, obtaining more memory from the heap if n...
Definition root.cc:140
#define STACK_MIN_SIZE
Abort if less stack during eval.
Convert from decimal to binary representation.
Definition common_fwd.h:215
TODO: Rename this file - func.h is stupid.
static int64_t get_date_from_str(Session *session, String *str, type::timestamp_t warn_type, const char *warn_name, bool *error_arg)
Convert date provided in a string to the int representation.
Definition cmpfunc.cc:718
static int agg_cmp_type(Item_result *type, Item **items, uint32_t nitems)
Definition cmpfunc.cc:163
enum_field_types agg_field_type(Item **items, uint32_t nitems)
Aggregates field types from the array of items.
Definition cmpfunc.cc:202
bool check_stack_overrun(Session *session, long margin, void *)
int class_decimal_cmp(const type::Decimal *a, const type::Decimal *b)
Item * and_expressions(Item *a, Item *b, Item **org_item)
Definition cmpfunc.cc:4285
static bool convert_constant_item(Session *, Item_field *, Item **)
Definition cmpfunc.cc:450
STL namespace.