1 /* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
2    Copyright (c) 2009, 2021, MariaDB
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; version 2 of the License.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program; if not, write to the Free Software
15    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1335  USA */
16 
17 
18 /**
19   @file
20 
21   @brief
22   This file defines all compare functions
23 */
24 
25 #ifdef USE_PRAGMA_IMPLEMENTATION
26 #pragma implementation				// gcc: Class implementation
27 #endif
28 
29 #include "mariadb.h"
30 #include "sql_priv.h"
31 #include <m_ctype.h>
32 #include "sql_select.h"
33 #include "sql_parse.h"                          // check_stack_overrun
34 #include "sql_base.h"                  // dynamic_column_error_message
35 
36 
37 /*
38   Compare row signature of two expressions
39 
40   SYNOPSIS:
41     cmp_row_type()
42     item1          the first expression
43     item2         the second expression
44 
45   DESCRIPTION
46     The function checks that two expressions have compatible row signatures
47     i.e. that the number of columns they return are the same and that if they
48     are both row expressions then each component from the first expression has
49     a row signature compatible with the signature of the corresponding component
50     of the second expression.
51 
52   RETURN VALUES
53     1  type incompatibility has been detected
54     0  otherwise
55 */
56 
cmp_row_type(Item * item1,Item * item2)57 static int cmp_row_type(Item* item1, Item* item2)
58 {
59   uint n= item1->cols();
60   if (item2->check_cols(n))
61     return 1;
62   for (uint i=0; i<n; i++)
63   {
64     if (item2->element_index(i)->check_cols(item1->element_index(i)->cols()) ||
65         (item1->element_index(i)->result_type() == ROW_RESULT &&
66          cmp_row_type(item1->element_index(i), item2->element_index(i))))
67       return 1;
68   }
69   return 0;
70 }
71 
72 
73 /**
74   Aggregates result types from the array of items.
75 
76   This method aggregates comparison handler from the array of items.
77   The result handler is used later for comparison of values of these items.
78 
79   aggregate_for_comparison()
80   funcname                      the function or operator name,
81                                 for error reporting
82   items                         array of items to aggregate the type from
83   nitems                        number of items in the array
84   int_uint_as_dec               what to do when comparing INT to UINT:
85                                 set the comparison handler to decimal or int.
86 
87   @retval true  type incompatibility has been detected
88   @retval false otherwise
89 */
90 
91 bool
aggregate_for_comparison(const char * funcname,Item ** items,uint nitems,bool int_uint_as_dec)92 Type_handler_hybrid_field_type::aggregate_for_comparison(const char *funcname,
93                                                          Item **items,
94                                                          uint nitems,
95                                                          bool int_uint_as_dec)
96 {
97   uint unsigned_count= items[0]->unsigned_flag;
98   /*
99     Convert sub-type to super-type (e.g. DATE to DATETIME, INT to BIGINT, etc).
100     Otherwise Predicant_to_list_comparator will treat sub-types of the same
101     super-type as different data types and won't be able to use bisection in
102     many cases.
103   */
104   set_handler(items[0]->type_handler()->type_handler_for_comparison());
105   for (uint i= 1 ; i < nitems ; i++)
106   {
107     unsigned_count+= items[i]->unsigned_flag;
108     if (aggregate_for_comparison(items[i]->type_handler()->
109                                  type_handler_for_comparison()))
110     {
111       /*
112         For more precise error messages if aggregation failed on the first pair
113         {items[0],items[1]}, use the name of items[0]->data_handler().
114         Otherwise use the name of this->type_handler(), which is already a
115         result of aggregation for items[0]..items[i-1].
116       */
117       my_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION, MYF(0),
118                i == 1 ? items[0]->type_handler()->name().ptr() :
119                         type_handler()->name().ptr(),
120                items[i]->type_handler()->name().ptr(),
121                funcname);
122       return true;
123     }
124     /*
125       When aggregating types of two row expressions we have to check
126       that they have the same cardinality and that each component
127       of the first row expression has a compatible row signature with
128       the signature of the corresponding component of the second row
129       expression.
130     */
131     if (cmp_type() == ROW_RESULT && cmp_row_type(items[0], items[i]))
132       return true;     // error found: invalid usage of rows
133   }
134   /**
135     If all arguments are of INT type but have different unsigned_flag values,
136     switch to DECIMAL_RESULT.
137   */
138   if (int_uint_as_dec &&
139       cmp_type() == INT_RESULT &&
140       unsigned_count != nitems && unsigned_count != 0)
141     set_handler(&type_handler_newdecimal);
142   return 0;
143 }
144 
145 
146 /*
147   Collects different types for comparison of first item with each other items
148 
149   SYNOPSIS
150     collect_cmp_types()
151       items             Array of items to collect types from
152       nitems            Number of items in the array
153       skip_nulls        Don't collect types of NULL items if TRUE
154 
155   DESCRIPTION
156     This function collects different result types for comparison of the first
157     item in the list with each of the remaining items in the 'items' array.
158 
159   RETURN
160     0 - if row type incompatibility has been detected (see cmp_row_type)
161     Bitmap of collected types - otherwise
162 */
163 
collect_cmp_types(Item ** items,uint nitems,bool skip_nulls=FALSE)164 static uint collect_cmp_types(Item **items, uint nitems, bool skip_nulls= FALSE)
165 {
166   uint i;
167   uint found_types;
168   Item_result left_cmp_type= items[0]->cmp_type();
169   DBUG_ASSERT(nitems > 1);
170   found_types= 0;
171   for (i= 1; i < nitems ; i++)
172   {
173     if (skip_nulls && items[i]->type() == Item::NULL_ITEM)
174       continue; // Skip NULL constant items
175     if ((left_cmp_type == ROW_RESULT ||
176          items[i]->cmp_type() == ROW_RESULT) &&
177         cmp_row_type(items[0], items[i]))
178       return 0;
179     found_types|= 1U << (uint) item_cmp_type(left_cmp_type, items[i]);
180   }
181   /*
182    Even if all right-hand items are NULLs and we are skipping them all, we need
183    at least one type bit in the found_type bitmask.
184   */
185   if (skip_nulls && !found_types)
186     found_types= 1U << (uint) left_cmp_type;
187   return found_types;
188 }
189 
190 
191 /*
192   Test functions
193   Most of these  returns 0LL if false and 1LL if true and
194   NULL if some arg is NULL.
195 */
196 
val_int()197 longlong Item_func_not::val_int()
198 {
199   DBUG_ASSERT(fixed == 1);
200   bool value= args[0]->val_bool();
201   null_value=args[0]->null_value;
202   return ((!null_value && value == 0) ? 1 : 0);
203 }
204 
print(String * str,enum_query_type query_type)205 void Item_func_not::print(String *str, enum_query_type query_type)
206 {
207   str->append('!');
208   args[0]->print_parenthesised(str, query_type, precedence());
209 }
210 
211 /**
212   special NOT for ALL subquery.
213 */
214 
215 
val_int()216 longlong Item_func_not_all::val_int()
217 {
218   DBUG_ASSERT(fixed == 1);
219   bool value= args[0]->val_bool();
220 
221   /*
222     return TRUE if there was records in underlying select in max/min
223     optimization (ALL subquery)
224   */
225   if (empty_underlying_subquery())
226     return 1;
227 
228   null_value= args[0]->null_value;
229   return ((!null_value && value == 0) ? 1 : 0);
230 }
231 
232 
empty_underlying_subquery()233 bool Item_func_not_all::empty_underlying_subquery()
234 {
235   return ((test_sum_item && !test_sum_item->any_value()) ||
236           (test_sub_item && !test_sub_item->any_value()));
237 }
238 
print(String * str,enum_query_type query_type)239 void Item_func_not_all::print(String *str, enum_query_type query_type)
240 {
241   if (show)
242     Item_func::print(str, query_type);
243   else
244     args[0]->print(str, query_type);
245 }
246 
247 
248 /**
249   Special NOP (No OPeration) for ALL subquery. It is like
250   Item_func_not_all.
251 
252   @return
253     (return TRUE if underlying subquery do not return rows) but if subquery
254     returns some rows it return same value as argument (TRUE/FALSE).
255 */
256 
val_int()257 longlong Item_func_nop_all::val_int()
258 {
259   DBUG_ASSERT(fixed == 1);
260   longlong value= args[0]->val_int();
261 
262   /*
263     return FALSE if there was records in underlying select in max/min
264     optimization (SAME/ANY subquery)
265   */
266   if (empty_underlying_subquery())
267     return 0;
268 
269   null_value= args[0]->null_value;
270   return (null_value || value == 0) ? 0 : 1;
271 }
272 
273 
274 /**
275   Convert a constant item to an int and replace the original item.
276 
277     The function converts a constant expression or string to an integer.
278     On successful conversion the original item is substituted for the
279     result of the item evaluation.
280     This is done when comparing DATE/TIME of different formats and
281     also when comparing bigint to strings (in which case strings
282     are converted to bigints).
283 
284   @param  thd             thread handle
285   @param  field           item will be converted using the type of this field
286   @param[in,out] item     reference to the item to convert
287 
288   @note
289     This function is called only at prepare stage.
290     As all derived tables are filled only after all derived tables
291     are prepared we do not evaluate items with subselects here because
292     they can contain derived tables and thus we may attempt to use a
293     table that has not been populated yet.
294 
295   @retval
296     0  Can't convert item
297   @retval
298     1  Item was replaced with an integer version of the item
299 */
300 
convert_const_to_int(THD * thd,Item_field * field_item,Item ** item)301 static bool convert_const_to_int(THD *thd, Item_field *field_item,
302                                   Item **item)
303 {
304   Field *field= field_item->field;
305   int result= 0;
306 
307   /*
308     We don't need to convert an integer to an integer,
309     pretend it's already converted.
310 
311     But we still convert it if it is compared with a Field_year,
312     as YEAR(2) may change the value of an integer when converting it
313     to an integer (say, 0 to 70).
314   */
315   if ((*item)->cmp_type() == INT_RESULT &&
316       field_item->field_type() != MYSQL_TYPE_YEAR)
317     return 1;
318 
319   if ((*item)->const_item() && !(*item)->is_expensive())
320   {
321     TABLE *table= field->table;
322     Sql_mode_save sql_mode(thd);
323     Check_level_instant_set check_level_save(thd, CHECK_FIELD_IGNORE);
324     MY_BITMAP *old_maps[2] = { NULL, NULL };
325     ulonglong UNINIT_VAR(orig_field_val); /* original field value if valid */
326 
327     /* table->read_set may not be set if we come here from a CREATE TABLE */
328     if (table && table->read_set)
329       dbug_tmp_use_all_columns(table, old_maps,
330                                &table->read_set, &table->write_set);
331     /* For comparison purposes allow invalid dates like 2000-01-32 */
332     thd->variables.sql_mode= (thd->variables.sql_mode & ~MODE_NO_ZERO_DATE) |
333                              MODE_INVALID_DATES;
334 
335     /*
336       Store the value of the field/constant because the call to save_in_field
337       below overrides that value. Don't save field value if no data has been
338       read yet.
339     */
340     bool save_field_value= (field_item->const_item() ||
341                             !(field->table->status & STATUS_NO_RECORD));
342     if (save_field_value)
343       orig_field_val= field->val_int();
344     if (!(*item)->save_in_field(field, 1) && !field->is_null())
345     {
346       int field_cmp= 0;
347       // If item is a decimal value, we must reject it if it was truncated.
348       if (field->type() == MYSQL_TYPE_LONGLONG)
349       {
350         field_cmp= stored_field_cmp_to_item(thd, field, *item);
351         DBUG_PRINT("info", ("convert_const_to_int %d", field_cmp));
352       }
353 
354       if (0 == field_cmp)
355       {
356         Item *tmp= new (thd->mem_root) Item_int_with_ref(thd, field->val_int(), *item,
357                                          MY_TEST(field->flags & UNSIGNED_FLAG));
358         if (tmp)
359           thd->change_item_tree(item, tmp);
360         result= 1;					// Item was replaced
361       }
362     }
363     /* Restore the original field value. */
364     if (save_field_value)
365     {
366       result= field->store(orig_field_val, TRUE);
367       /* orig_field_val must be a valid value that can be restored back. */
368       DBUG_ASSERT(!result);
369     }
370     if (table && table->read_set)
371       dbug_tmp_restore_column_maps(&table->read_set, &table->write_set, old_maps);
372   }
373   return result;
374 }
375 
376 
377 /*
378   Make a special case of compare with fields to get nicer comparisons
379   of bigint numbers with constant string.
380   This directly contradicts the manual (number and a string should
381   be compared as doubles), but seems to provide more
382   "intuitive" behavior in some cases (but less intuitive in others).
383 */
convert_const_compared_to_int_field(THD * thd)384 void Item_func::convert_const_compared_to_int_field(THD *thd)
385 {
386   DBUG_ASSERT(arg_count >= 2); // Item_func_nullif has arg_count == 3
387   if (!thd->lex->is_ps_or_view_context_analysis())
388   {
389     int field;
390     if (args[field= 0]->real_item()->type() == FIELD_ITEM ||
391         args[field= 1]->real_item()->type() == FIELD_ITEM)
392     {
393       Item_field *field_item= (Item_field*) (args[field]->real_item());
394       if (((field_item->field_type() == MYSQL_TYPE_LONGLONG &&
395             field_item->type_handler() != &type_handler_vers_trx_id) ||
396            field_item->field_type() ==  MYSQL_TYPE_YEAR))
397         convert_const_to_int(thd, field_item, &args[!field]);
398     }
399   }
400 }
401 
402 
setup_args_and_comparator(THD * thd,Arg_comparator * cmp)403 bool Item_func::setup_args_and_comparator(THD *thd, Arg_comparator *cmp)
404 {
405   DBUG_ASSERT(arg_count >= 2); // Item_func_nullif has arg_count == 3
406 
407   if (args[0]->cmp_type() == STRING_RESULT &&
408       args[1]->cmp_type() == STRING_RESULT)
409   {
410     DTCollation tmp;
411     if (agg_arg_charsets_for_comparison(tmp, args, 2))
412       return true;
413     cmp->m_compare_collation= tmp.collation;
414   }
415   //  Convert constants when compared to int/year field
416   DBUG_ASSERT(functype() != LIKE_FUNC);
417   convert_const_compared_to_int_field(thd);
418 
419   return cmp->set_cmp_func(this, &args[0], &args[1], true);
420 }
421 
422 
423 /*
424   Comparison operators remove arguments' dependency on PAD_CHAR_TO_FULL_LENGTH
425   in case of PAD SPACE comparison collations: trailing spaces do not affect
426   the comparison result for such collations.
427 */
428 Sql_mode_dependency
value_depends_on_sql_mode() const429 Item_bool_rowready_func2::value_depends_on_sql_mode() const
430 {
431   if (compare_collation()->state & MY_CS_NOPAD)
432     return Item_func::value_depends_on_sql_mode();
433   return ((args[0]->value_depends_on_sql_mode() |
434            args[1]->value_depends_on_sql_mode()) &
435           Sql_mode_dependency(~0, ~MODE_PAD_CHAR_TO_FULL_LENGTH)).
436          soft_to_hard();
437 }
438 
439 
fix_length_and_dec()440 bool Item_bool_rowready_func2::fix_length_and_dec()
441 {
442   max_length= 1;				     // Function returns 0 or 1
443 
444   /*
445     As some compare functions are generated after sql_yacc,
446     we have to check for out of memory conditions here
447   */
448   if (!args[0] || !args[1])
449     return FALSE;
450   return setup_args_and_comparator(current_thd, &cmp);
451 }
452 
453 
454 /**
455   Prepare the comparator (set the comparison function) for comparing
456   items *a1 and *a2 in the context of 'type'.
457 
458   @param[in]      owner_arg  Item, peforming the comparison (e.g. Item_func_eq)
459   @param[in,out]  a1         first argument to compare
460   @param[in,out]  a2         second argument to compare
461   @param[in]      type       type context to compare in
462 
463   Both *a1 and *a2 can be replaced by this method - typically by constant
464   items, holding the cached converted value of the original (constant) item.
465 */
466 
set_cmp_func(Item_func_or_sum * owner_arg,Item ** a1,Item ** a2)467 int Arg_comparator::set_cmp_func(Item_func_or_sum *owner_arg,
468                                  Item **a1, Item **a2)
469 {
470   owner= owner_arg;
471   set_null= set_null && owner_arg;
472   a= a1;
473   b= a2;
474   Item *tmp_args[2]= {*a1, *a2};
475   Type_handler_hybrid_field_type tmp;
476   if (tmp.aggregate_for_comparison(owner_arg->func_name(), tmp_args, 2, false))
477   {
478     DBUG_ASSERT(current_thd->is_error());
479     return 1;
480   }
481   m_compare_handler= tmp.type_handler();
482   return m_compare_handler->set_comparator_func(this);
483 }
484 
485 
set_cmp_func_for_row_arguments()486 bool Arg_comparator::set_cmp_func_for_row_arguments()
487 {
488   uint n= (*a)->cols();
489   if (n != (*b)->cols())
490   {
491     my_error(ER_OPERAND_COLUMNS, MYF(0), n);
492     comparators= 0;
493     return true;
494   }
495   if (!(comparators= new Arg_comparator[n]))
496     return true;
497   for (uint i=0; i < n; i++)
498   {
499     if ((*a)->element_index(i)->cols() != (*b)->element_index(i)->cols())
500     {
501       my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
502       return true;
503     }
504     if (comparators[i].set_cmp_func(owner, (*a)->addr(i),
505                                            (*b)->addr(i), set_null))
506       return true;
507   }
508   return false;
509 }
510 
511 
set_cmp_func_row()512 bool Arg_comparator::set_cmp_func_row()
513 {
514   func= is_owner_equal_func() ? &Arg_comparator::compare_e_row :
515                                 &Arg_comparator::compare_row;
516   return set_cmp_func_for_row_arguments();
517 }
518 
519 
set_cmp_func_string()520 bool Arg_comparator::set_cmp_func_string()
521 {
522   THD *thd= current_thd;
523   func= is_owner_equal_func() ? &Arg_comparator::compare_e_string :
524                                 &Arg_comparator::compare_string;
525   if (compare_type() == STRING_RESULT &&
526       (*a)->result_type() == STRING_RESULT &&
527       (*b)->result_type() == STRING_RESULT)
528   {
529     /*
530       We must set cmp_collation here as we may be called from for an automatic
531       generated item, like in natural join
532     */
533     if (owner->agg_arg_charsets_for_comparison(&m_compare_collation, a, b))
534       return true;
535 
536     if ((*a)->type() == Item::FUNC_ITEM &&
537         ((Item_func *) (*a))->functype() == Item_func::JSON_EXTRACT_FUNC)
538     {
539       func= is_owner_equal_func() ? &Arg_comparator::compare_e_json_str:
540                                     &Arg_comparator::compare_json_str;
541       return 0;
542     }
543     else if ((*b)->type() == Item::FUNC_ITEM &&
544              ((Item_func *) (*b))->functype() == Item_func::JSON_EXTRACT_FUNC)
545     {
546       func= is_owner_equal_func() ? &Arg_comparator::compare_e_json_str:
547                                     &Arg_comparator::compare_str_json;
548       return 0;
549     }
550   }
551 
552   a= cache_converted_constant(thd, a, &a_cache, compare_type_handler());
553   b= cache_converted_constant(thd, b, &b_cache, compare_type_handler());
554   return false;
555 }
556 
557 
set_cmp_func_time()558 bool Arg_comparator::set_cmp_func_time()
559 {
560   THD *thd= current_thd;
561   m_compare_collation= &my_charset_numeric;
562   func= is_owner_equal_func() ? &Arg_comparator::compare_e_time :
563                                 &Arg_comparator::compare_time;
564   a= cache_converted_constant(thd, a, &a_cache, compare_type_handler());
565   b= cache_converted_constant(thd, b, &b_cache, compare_type_handler());
566   return false;
567 }
568 
569 
set_cmp_func_datetime()570 bool Arg_comparator::set_cmp_func_datetime()
571 {
572   THD *thd= current_thd;
573   m_compare_collation= &my_charset_numeric;
574   func= is_owner_equal_func() ? &Arg_comparator::compare_e_datetime :
575                                 &Arg_comparator::compare_datetime;
576   a= cache_converted_constant(thd, a, &a_cache, compare_type_handler());
577   b= cache_converted_constant(thd, b, &b_cache, compare_type_handler());
578   return false;
579 }
580 
581 
set_cmp_func_native()582 bool Arg_comparator::set_cmp_func_native()
583 {
584   THD *thd= current_thd;
585   m_compare_collation= &my_charset_numeric;
586   func= is_owner_equal_func() ? &Arg_comparator::compare_e_native :
587                                 &Arg_comparator::compare_native;
588   a= cache_converted_constant(thd, a, &a_cache, compare_type_handler());
589   b= cache_converted_constant(thd, b, &b_cache, compare_type_handler());
590   return false;
591 }
592 
593 
set_cmp_func_int()594 bool Arg_comparator::set_cmp_func_int()
595 {
596   THD *thd= current_thd;
597   func= is_owner_equal_func() ? &Arg_comparator::compare_e_int :
598                                 &Arg_comparator::compare_int_signed;
599   if ((*a)->field_type() == MYSQL_TYPE_YEAR &&
600       (*b)->field_type() == MYSQL_TYPE_YEAR)
601   {
602     func= is_owner_equal_func() ? &Arg_comparator::compare_e_datetime :
603                                   &Arg_comparator::compare_datetime;
604   }
605   else if (func == &Arg_comparator::compare_int_signed)
606   {
607     if ((*a)->unsigned_flag)
608       func= (((*b)->unsigned_flag)?
609              &Arg_comparator::compare_int_unsigned :
610              &Arg_comparator::compare_int_unsigned_signed);
611     else if ((*b)->unsigned_flag)
612       func= &Arg_comparator::compare_int_signed_unsigned;
613   }
614   else if (func== &Arg_comparator::compare_e_int)
615   {
616     if ((*a)->unsigned_flag ^ (*b)->unsigned_flag)
617       func= &Arg_comparator::compare_e_int_diff_signedness;
618   }
619   a= cache_converted_constant(thd, a, &a_cache, compare_type_handler());
620   b= cache_converted_constant(thd, b, &b_cache, compare_type_handler());
621   return false;
622 }
623 
624 
set_cmp_func_real()625 bool Arg_comparator::set_cmp_func_real()
626 {
627   if ((((*a)->result_type() == DECIMAL_RESULT && !(*a)->const_item() &&
628         (*b)->result_type() == STRING_RESULT  &&  (*b)->const_item()) ||
629       ((*b)->result_type() == DECIMAL_RESULT && !(*b)->const_item() &&
630        (*a)->result_type() == STRING_RESULT  &&  (*a)->const_item())))
631   {
632     /*
633      <non-const decimal expression> <cmp> <const string expression>
634      or
635      <const string expression> <cmp> <non-const decimal expression>
636 
637      Do comparison as decimal rather than float, in order not to lose precision.
638     */
639     m_compare_handler= &type_handler_newdecimal;
640     return set_cmp_func_decimal();
641   }
642 
643   THD *thd= current_thd;
644   func= is_owner_equal_func() ? &Arg_comparator::compare_e_real :
645                                 &Arg_comparator::compare_real;
646   if ((*a)->decimals < NOT_FIXED_DEC && (*b)->decimals < NOT_FIXED_DEC)
647   {
648     precision= 5 / log_10[MY_MAX((*a)->decimals, (*b)->decimals) + 1];
649     if (func == &Arg_comparator::compare_real)
650       func= &Arg_comparator::compare_real_fixed;
651     else if (func == &Arg_comparator::compare_e_real)
652       func= &Arg_comparator::compare_e_real_fixed;
653   }
654   a= cache_converted_constant(thd, a, &a_cache, compare_type_handler());
655   b= cache_converted_constant(thd, b, &b_cache, compare_type_handler());
656   return false;
657 }
658 
set_cmp_func_decimal()659 bool Arg_comparator::set_cmp_func_decimal()
660 {
661   THD *thd= current_thd;
662   func= is_owner_equal_func() ? &Arg_comparator::compare_e_decimal :
663                                 &Arg_comparator::compare_decimal;
664   a= cache_converted_constant(thd, a, &a_cache, compare_type_handler());
665   b= cache_converted_constant(thd, b, &b_cache, compare_type_handler());
666   return false;
667 }
668 
669 
670 /**
671   Convert and cache a constant.
672 
673   @param value      [in]  An item to cache
674   @param cache_item [out] Placeholder for the cache item
675   @param type       [in]  Comparison type
676 
677   @details
678     When given item is a constant and its type differs from comparison type
679     then cache its value to avoid type conversion of this constant on each
680     evaluation. In this case the value is cached and the reference to the cache
681     is returned.
682     Original value is returned otherwise.
683 
684   @return cache item or original value.
685 */
686 
cache_converted_constant(THD * thd_arg,Item ** value,Item ** cache_item,const Type_handler * handler)687 Item** Arg_comparator::cache_converted_constant(THD *thd_arg, Item **value,
688                                                 Item **cache_item,
689                                                 const Type_handler *handler)
690 {
691   /*
692     Don't need cache if doing context analysis only.
693   */
694   if (!thd_arg->lex->is_ps_or_view_context_analysis() &&
695       (*value)->const_item() &&
696       handler->type_handler_for_comparison() !=
697       (*value)->type_handler_for_comparison())
698   {
699     Item_cache *cache= handler->Item_get_cache(thd_arg, *value);
700     cache->setup(thd_arg, *value);
701     *cache_item= cache;
702     return cache_item;
703   }
704   return value;
705 }
706 
707 
compare_time()708 int Arg_comparator::compare_time()
709 {
710   THD *thd= current_thd;
711   longlong val1= (*a)->val_time_packed(thd);
712   if (!(*a)->null_value)
713   {
714     longlong val2= (*b)->val_time_packed(thd);
715     if (!(*b)->null_value)
716       return compare_not_null_values(val1, val2);
717   }
718   if (set_null)
719     owner->null_value= true;
720   return -1;
721 }
722 
723 
compare_e_time()724 int Arg_comparator::compare_e_time()
725 {
726   THD *thd= current_thd;
727   longlong val1= (*a)->val_time_packed(thd);
728   longlong val2= (*b)->val_time_packed(thd);
729   if ((*a)->null_value || (*b)->null_value)
730     return MY_TEST((*a)->null_value && (*b)->null_value);
731   return MY_TEST(val1 == val2);
732 }
733 
734 
735 
compare_datetime()736 int Arg_comparator::compare_datetime()
737 {
738   THD *thd= current_thd;
739   longlong val1= (*a)->val_datetime_packed(thd);
740   if (!(*a)->null_value)
741   {
742     longlong val2= (*b)->val_datetime_packed(thd);
743     if (!(*b)->null_value)
744       return compare_not_null_values(val1, val2);
745   }
746   if (set_null)
747     owner->null_value= true;
748   return -1;
749 }
750 
751 
compare_e_datetime()752 int Arg_comparator::compare_e_datetime()
753 {
754   THD *thd= current_thd;
755   longlong val1= (*a)->val_datetime_packed(thd);
756   longlong val2= (*b)->val_datetime_packed(thd);
757   if ((*a)->null_value || (*b)->null_value)
758     return MY_TEST((*a)->null_value && (*b)->null_value);
759   return MY_TEST(val1 == val2);
760 }
761 
762 
compare_string()763 int Arg_comparator::compare_string()
764 {
765   String *res1,*res2;
766   if ((res1= (*a)->val_str(&value1)))
767   {
768     if ((res2= (*b)->val_str(&value2)))
769     {
770       if (set_null)
771         owner->null_value= 0;
772       return sortcmp(res1, res2, compare_collation());
773     }
774   }
775   if (set_null)
776     owner->null_value= 1;
777   return -1;
778 }
779 
780 
781 /**
782   Compare strings, but take into account that NULL == NULL.
783 */
784 
785 
compare_e_string()786 int Arg_comparator::compare_e_string()
787 {
788   String *res1,*res2;
789   res1= (*a)->val_str(&value1);
790   res2= (*b)->val_str(&value2);
791   if (!res1 || !res2)
792     return MY_TEST(res1 == res2);
793   return MY_TEST(sortcmp(res1, res2, compare_collation()) == 0);
794 }
795 
796 
compare_native()797 int Arg_comparator::compare_native()
798 {
799   THD *thd= current_thd;
800   if (!(*a)->val_native_with_conversion(thd, &m_native1,
801                                         compare_type_handler()))
802   {
803     if (!(*b)->val_native_with_conversion(thd, &m_native2,
804                                           compare_type_handler()))
805     {
806       if (set_null)
807         owner->null_value= 0;
808       return compare_type_handler()->cmp_native(m_native1, m_native2);
809     }
810   }
811   if (set_null)
812     owner->null_value= 1;
813   return -1;
814 }
815 
816 
compare_e_native()817 int Arg_comparator::compare_e_native()
818 {
819   THD *thd= current_thd;
820   bool res1= (*a)->val_native_with_conversion(thd, &m_native1,
821                                               compare_type_handler());
822   bool res2= (*b)->val_native_with_conversion(thd, &m_native2,
823                                               compare_type_handler());
824   if (res1 || res2)
825     return MY_TEST(res1 == res2);
826   return MY_TEST(compare_type_handler()->cmp_native(m_native1, m_native2) == 0);
827 }
828 
829 
compare_real()830 int Arg_comparator::compare_real()
831 {
832   /*
833     Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
834     gcc to flush double values out of 80-bit Intel FPU registers before
835     performing the comparison.
836   */
837   volatile double val1, val2;
838   val1= (*a)->val_real();
839   if (!(*a)->null_value)
840   {
841     val2= (*b)->val_real();
842     if (!(*b)->null_value)
843     {
844       if (set_null)
845         owner->null_value= 0;
846       if (val1 < val2)	return -1;
847       if (val1 == val2) return 0;
848       return 1;
849     }
850   }
851   if (set_null)
852     owner->null_value= 1;
853   return -1;
854 }
855 
compare_decimal()856 int Arg_comparator::compare_decimal()
857 {
858   VDec val1(*a);
859   if (!val1.is_null())
860   {
861     VDec val2(*b);
862     if (!val2.is_null())
863     {
864       if (set_null)
865         owner->null_value= 0;
866       val1.round_self_if_needed((*a)->decimals, HALF_UP);
867       val2.round_self_if_needed((*b)->decimals, HALF_UP);
868       return val1.cmp(val2);
869     }
870   }
871   if (set_null)
872     owner->null_value= 1;
873   return -1;
874 }
875 
compare_e_real()876 int Arg_comparator::compare_e_real()
877 {
878   double val1= (*a)->val_real();
879   double val2= (*b)->val_real();
880   if ((*a)->null_value || (*b)->null_value)
881     return MY_TEST((*a)->null_value && (*b)->null_value);
882   return MY_TEST(val1 == val2);
883 }
884 
compare_e_decimal()885 int Arg_comparator::compare_e_decimal()
886 {
887   VDec val1(*a), val2(*b);
888   if (val1.is_null() || val2.is_null())
889     return MY_TEST(val1.is_null() && val2.is_null());
890   val1.round_self_if_needed((*a)->decimals, HALF_UP);
891   val2.round_self_if_needed((*b)->decimals, HALF_UP);
892   return MY_TEST(val1.cmp(val2) == 0);
893 }
894 
895 
compare_real_fixed()896 int Arg_comparator::compare_real_fixed()
897 {
898   /*
899     Fix yet another manifestation of Bug#2338. 'Volatile' will instruct
900     gcc to flush double values out of 80-bit Intel FPU registers before
901     performing the comparison.
902   */
903   volatile double val1, val2;
904   val1= (*a)->val_real();
905   if (!(*a)->null_value)
906   {
907     val2= (*b)->val_real();
908     if (!(*b)->null_value)
909     {
910       if (set_null)
911         owner->null_value= 0;
912       if (val1 == val2 || fabs(val1 - val2) < precision)
913         return 0;
914       if (val1 < val2)
915         return -1;
916       return 1;
917     }
918   }
919   if (set_null)
920     owner->null_value= 1;
921   return -1;
922 }
923 
924 
compare_e_real_fixed()925 int Arg_comparator::compare_e_real_fixed()
926 {
927   double val1= (*a)->val_real();
928   double val2= (*b)->val_real();
929   if ((*a)->null_value || (*b)->null_value)
930     return MY_TEST((*a)->null_value && (*b)->null_value);
931   return MY_TEST(val1 == val2 || fabs(val1 - val2) < precision);
932 }
933 
934 
compare_int_signed()935 int Arg_comparator::compare_int_signed()
936 {
937   longlong val1= (*a)->val_int();
938   if (!(*a)->null_value)
939   {
940     longlong val2= (*b)->val_int();
941     if (!(*b)->null_value)
942       return compare_not_null_values(val1, val2);
943   }
944   if (set_null)
945     owner->null_value= 1;
946   return -1;
947 }
948 
949 
950 /**
951   Compare values as BIGINT UNSIGNED.
952 */
953 
compare_int_unsigned()954 int Arg_comparator::compare_int_unsigned()
955 {
956   ulonglong val1= (*a)->val_int();
957   if (!(*a)->null_value)
958   {
959     ulonglong val2= (*b)->val_int();
960     if (!(*b)->null_value)
961     {
962       if (set_null)
963         owner->null_value= 0;
964       if (val1 < val2)	return -1;
965       if (val1 == val2)   return 0;
966       return 1;
967     }
968   }
969   if (set_null)
970     owner->null_value= 1;
971   return -1;
972 }
973 
974 
975 /**
976   Compare signed (*a) with unsigned (*B)
977 */
978 
compare_int_signed_unsigned()979 int Arg_comparator::compare_int_signed_unsigned()
980 {
981   longlong sval1= (*a)->val_int();
982   if (!(*a)->null_value)
983   {
984     ulonglong uval2= (ulonglong)(*b)->val_int();
985     if (!(*b)->null_value)
986     {
987       if (set_null)
988         owner->null_value= 0;
989       if (sval1 < 0 || (ulonglong)sval1 < uval2)
990         return -1;
991       if ((ulonglong)sval1 == uval2)
992         return 0;
993       return 1;
994     }
995   }
996   if (set_null)
997     owner->null_value= 1;
998   return -1;
999 }
1000 
1001 
1002 /**
1003   Compare unsigned (*a) with signed (*B)
1004 */
1005 
compare_int_unsigned_signed()1006 int Arg_comparator::compare_int_unsigned_signed()
1007 {
1008   ulonglong uval1= (ulonglong)(*a)->val_int();
1009   if (!(*a)->null_value)
1010   {
1011     longlong sval2= (*b)->val_int();
1012     if (!(*b)->null_value)
1013     {
1014       if (set_null)
1015         owner->null_value= 0;
1016       if (sval2 < 0)
1017         return 1;
1018       if (uval1 < (ulonglong)sval2)
1019         return -1;
1020       if (uval1 == (ulonglong)sval2)
1021         return 0;
1022       return 1;
1023     }
1024   }
1025   if (set_null)
1026     owner->null_value= 1;
1027   return -1;
1028 }
1029 
1030 
compare_e_int()1031 int Arg_comparator::compare_e_int()
1032 {
1033   longlong val1= (*a)->val_int();
1034   longlong val2= (*b)->val_int();
1035   if ((*a)->null_value || (*b)->null_value)
1036     return MY_TEST((*a)->null_value && (*b)->null_value);
1037   return MY_TEST(val1 == val2);
1038 }
1039 
1040 /**
1041   Compare unsigned *a with signed *b or signed *a with unsigned *b.
1042 */
compare_e_int_diff_signedness()1043 int Arg_comparator::compare_e_int_diff_signedness()
1044 {
1045   longlong val1= (*a)->val_int();
1046   longlong val2= (*b)->val_int();
1047   if ((*a)->null_value || (*b)->null_value)
1048     return MY_TEST((*a)->null_value && (*b)->null_value);
1049   return (val1 >= 0) && MY_TEST(val1 == val2);
1050 }
1051 
compare_row()1052 int Arg_comparator::compare_row()
1053 {
1054   int res= 0;
1055   bool was_null= 0;
1056   (*a)->bring_value();
1057   (*b)->bring_value();
1058 
1059   if ((*a)->null_value || (*b)->null_value)
1060   {
1061     owner->null_value= 1;
1062     return -1;
1063   }
1064 
1065   uint n= (*a)->cols();
1066   for (uint i= 0; i<n; i++)
1067   {
1068     res= comparators[i].compare();
1069     /* Aggregate functions don't need special null handling. */
1070     if (owner->null_value && owner->type() == Item::FUNC_ITEM)
1071     {
1072       // NULL was compared
1073       switch (((Item_func*)owner)->functype()) {
1074       case Item_func::NE_FUNC:
1075         break; // NE never aborts on NULL even if abort_on_null is set
1076       case Item_func::LT_FUNC:
1077       case Item_func::LE_FUNC:
1078       case Item_func::GT_FUNC:
1079       case Item_func::GE_FUNC:
1080         return -1; // <, <=, > and >= always fail on NULL
1081       case Item_func::EQ_FUNC:
1082         if (((Item_func_eq*)owner)->abort_on_null)
1083           return -1; // We do not need correct NULL returning
1084         break;
1085       default:
1086         DBUG_ASSERT(0);
1087         break;
1088       }
1089       was_null= 1;
1090       owner->null_value= 0;
1091       res= 0;  // continue comparison (maybe we will meet explicit difference)
1092     }
1093     else if (res)
1094       return res;
1095   }
1096   if (was_null)
1097   {
1098     /*
1099       There was NULL(s) in comparison in some parts, but there was no
1100       explicit difference in other parts, so we have to return NULL.
1101     */
1102     owner->null_value= 1;
1103     return -1;
1104   }
1105   return 0;
1106 }
1107 
1108 
compare_e_row()1109 int Arg_comparator::compare_e_row()
1110 {
1111   (*a)->bring_value();
1112   (*b)->bring_value();
1113   uint n= (*a)->cols();
1114   for (uint i= 0; i<n; i++)
1115   {
1116     if (!comparators[i].compare())
1117       return 0;
1118   }
1119   return 1;
1120 }
1121 
1122 
compare_json_str()1123 int Arg_comparator::compare_json_str()
1124 {
1125   return compare_json_str_basic(*a, *b);
1126 }
1127 
1128 
compare_str_json()1129 int Arg_comparator::compare_str_json()
1130 {
1131   return -compare_json_str_basic(*b, *a);
1132 }
1133 
1134 
compare_e_json_str()1135 int Arg_comparator::compare_e_json_str()
1136 {
1137   return compare_e_json_str_basic(*a, *b);
1138 }
1139 
1140 
compare_e_str_json()1141 int Arg_comparator::compare_e_str_json()
1142 {
1143   return compare_e_json_str_basic(*b, *a);
1144 }
1145 
1146 
fix_length_and_dec()1147 bool Item_func_truth::fix_length_and_dec()
1148 {
1149   maybe_null= 0;
1150   null_value= 0;
1151   decimals= 0;
1152   max_length= 1;
1153   return FALSE;
1154 }
1155 
1156 
print(String * str,enum_query_type query_type)1157 void Item_func_truth::print(String *str, enum_query_type query_type)
1158 {
1159   args[0]->print_parenthesised(str, query_type, precedence());
1160   str->append(STRING_WITH_LEN(" is "));
1161   if (! affirmative)
1162     str->append(STRING_WITH_LEN("not "));
1163   if (value)
1164     str->append(STRING_WITH_LEN("true"));
1165   else
1166     str->append(STRING_WITH_LEN("false"));
1167 }
1168 
1169 
val_bool()1170 bool Item_func_truth::val_bool()
1171 {
1172   bool val= args[0]->val_bool();
1173   if (args[0]->null_value)
1174   {
1175     /*
1176       NULL val IS {TRUE, FALSE} --> FALSE
1177       NULL val IS NOT {TRUE, FALSE} --> TRUE
1178     */
1179     return (! affirmative);
1180   }
1181 
1182   if (affirmative)
1183   {
1184     /* {TRUE, FALSE} val IS {TRUE, FALSE} value */
1185     return (val == value);
1186   }
1187 
1188   /* {TRUE, FALSE} val IS NOT {TRUE, FALSE} value */
1189   return (val != value);
1190 }
1191 
1192 
val_int()1193 longlong Item_func_truth::val_int()
1194 {
1195   return (val_bool() ? 1 : 0);
1196 }
1197 
1198 
is_top_level_item()1199 bool Item_in_optimizer::is_top_level_item()
1200 {
1201   if (!invisible_mode())
1202     return ((Item_in_subselect *)args[1])->is_top_level_item();
1203   return false;
1204 }
1205 
1206 
fix_after_pullout(st_select_lex * new_parent,Item ** ref,bool merge)1207 void Item_in_optimizer::fix_after_pullout(st_select_lex *new_parent,
1208                                           Item **ref, bool merge)
1209 {
1210   DBUG_ASSERT(fixed);
1211   /* This will re-calculate attributes of our Item_in_subselect: */
1212   Item_bool_func::fix_after_pullout(new_parent, ref, merge);
1213 
1214   /* Then, re-calculate not_null_tables_cache: */
1215   eval_not_null_tables(NULL);
1216 }
1217 
1218 
eval_not_null_tables(void * opt_arg)1219 bool Item_in_optimizer::eval_not_null_tables(void *opt_arg)
1220 {
1221   not_null_tables_cache= 0;
1222   if (is_top_level_item())
1223   {
1224     /*
1225       It is possible to determine NULL-rejectedness of the left arguments
1226       of IN only if it is a top-level predicate.
1227     */
1228     not_null_tables_cache= args[0]->not_null_tables();
1229   }
1230   return FALSE;
1231 }
1232 
1233 
print(String * str,enum_query_type query_type)1234 void Item_in_optimizer::print(String *str, enum_query_type query_type)
1235 {
1236   if (query_type & QT_PARSABLE)
1237     args[1]->print(str, query_type);
1238   else
1239   {
1240      restore_first_argument();
1241      Item_func::print(str, query_type);
1242   }
1243 }
1244 
1245 
1246 /**
1247   "Restore" first argument before fix_fields() call (after it is harmless).
1248 
1249   @Note: Main pointer to left part of IN/ALL/ANY subselect is subselect's
1250   lest_expr (see Item_in_optimizer::fix_left) so changes made during
1251   fix_fields will be rolled back there which can make
1252   Item_in_optimizer::args[0] unusable on second execution before fix_left()
1253   call. This call fix the pointer.
1254 */
1255 
restore_first_argument()1256 void Item_in_optimizer::restore_first_argument()
1257 {
1258   if (!invisible_mode())
1259   {
1260     args[0]= ((Item_in_subselect *)args[1])->left_expr;
1261   }
1262 }
1263 
1264 
fix_left(THD * thd)1265 bool Item_in_optimizer::fix_left(THD *thd)
1266 {
1267   DBUG_ENTER("Item_in_optimizer::fix_left");
1268   /*
1269     Here we will store pointer on place of main storage of left expression.
1270     For usual IN (ALL/ANY) it is subquery left_expr.
1271     For other cases (MAX/MIN optimization, non-transformed EXISTS (10.0))
1272     it is args[0].
1273   */
1274   Item **ref0= args;
1275   if (!invisible_mode())
1276   {
1277     /*
1278        left_expr->fix_fields() may cause left_expr to be substituted for
1279        another item. (e.g. an Item_field may be changed into Item_ref). This
1280        transformation is undone at the end of statement execution (e.g. the
1281        Item_ref is deleted). However, Item_in_optimizer::args[0] may keep
1282        the pointer to the post-transformation item. Because of that, on the
1283        next execution we need to copy args[1]->left_expr again.
1284     */
1285     ref0= &(((Item_in_subselect *)args[1])->left_expr);
1286     args[0]= ((Item_in_subselect *)args[1])->left_expr;
1287   }
1288   if ((*ref0)->fix_fields_if_needed(thd, ref0) ||
1289       (!cache && !(cache= (*ref0)->get_cache(thd))))
1290     DBUG_RETURN(1);
1291   /*
1292     During fix_field() expression could be substituted.
1293     So we copy changes before use
1294   */
1295   if (args[0] != (*ref0))
1296     args[0]= (*ref0);
1297   DBUG_PRINT("info", ("actual fix fields"));
1298 
1299   cache->setup(thd, args[0]);
1300   if (cache->cols() == 1)
1301   {
1302     DBUG_ASSERT(args[0]->type() != ROW_ITEM);
1303     /*
1304       Note: there can be cases when used_tables()==0 && !const_item(). See
1305       Item_sum::update_used_tables for details.
1306     */
1307     if ((used_tables_cache= args[0]->used_tables()) || !args[0]->const_item())
1308       cache->set_used_tables(OUTER_REF_TABLE_BIT);
1309     else
1310       cache->set_used_tables(0);
1311   }
1312   else
1313   {
1314     uint n= cache->cols();
1315     for (uint i= 0; i < n; i++)
1316     {
1317       /* Check that the expression (part of row) do not contain a subquery */
1318       if (args[0]->element_index(i)->walk(&Item::is_subquery_processor, 0, 0))
1319       {
1320         my_error(ER_NOT_SUPPORTED_YET, MYF(0),
1321                  "SUBQUERY in ROW in left expression of IN/ALL/ANY");
1322         DBUG_RETURN(1);
1323       }
1324       Item *element=args[0]->element_index(i);
1325       if (element->used_tables() || !element->const_item())
1326       {
1327 	((Item_cache *)cache->element_index(i))->
1328           set_used_tables(OUTER_REF_TABLE_BIT);
1329         cache->set_used_tables(OUTER_REF_TABLE_BIT);
1330       }
1331       else
1332 	((Item_cache *)cache->element_index(i))->set_used_tables(0);
1333     }
1334     used_tables_cache= args[0]->used_tables();
1335   }
1336   eval_not_null_tables(NULL);
1337   copy_with_sum_func(args[0]);
1338   with_param= args[0]->with_param || args[1]->with_param;
1339   with_field= args[0]->with_field;
1340   if ((const_item_cache= args[0]->const_item()))
1341   {
1342     cache->store(args[0]);
1343     cache->cache_value();
1344   }
1345   if (args[1]->is_fixed())
1346   {
1347     /* to avoid overriding is called to update left expression */
1348     used_tables_and_const_cache_join(args[1]);
1349     join_with_sum_func(args[1]);
1350   }
1351   DBUG_RETURN(0);
1352 }
1353 
1354 
fix_fields(THD * thd,Item ** ref)1355 bool Item_in_optimizer::fix_fields(THD *thd, Item **ref)
1356 {
1357   DBUG_ASSERT(fixed == 0);
1358   Item_subselect *sub= 0;
1359   uint col;
1360 
1361   /*
1362      MAX/MIN optimization can convert the subquery into
1363      expr + Item_singlerow_subselect
1364    */
1365   if (args[1]->type() == Item::SUBSELECT_ITEM)
1366     sub= (Item_subselect *)args[1];
1367 
1368   if (fix_left(thd))
1369     return TRUE;
1370   if (args[0]->maybe_null)
1371     maybe_null=1;
1372 
1373   if (args[1]->fix_fields_if_needed(thd, args + 1))
1374     return TRUE;
1375   if (!invisible_mode() &&
1376       ((sub && ((col= args[0]->cols()) != sub->engine->cols())) ||
1377        (!sub && (args[1]->cols() != (col= 1)))))
1378   {
1379     my_error(ER_OPERAND_COLUMNS, MYF(0), col);
1380     return TRUE;
1381   }
1382   if (args[1]->maybe_null)
1383     maybe_null=1;
1384   m_with_subquery= true;
1385   join_with_sum_func(args[1]);
1386   with_window_func= args[0]->with_window_func;
1387   // The subquery cannot have window functions aggregated in this select
1388   DBUG_ASSERT(!args[1]->with_window_func);
1389   with_field= with_field || args[1]->with_field;
1390   with_param= args[0]->with_param || args[1]->with_param;
1391   used_tables_and_const_cache_join(args[1]);
1392   fixed= 1;
1393   return FALSE;
1394 }
1395 
1396 /**
1397   Check if Item_in_optimizer should work as a pass-through item for its
1398   arguments.
1399 
1400   @note
1401    Item_in_optimizer should work as pass-through for
1402     - subqueries that were processed by ALL/ANY->MIN/MAX rewrite
1403     - subqueries that were originally EXISTS subqueries (and were coinverted by
1404       the EXISTS->IN rewrite)
1405 
1406    When Item_in_optimizer is not not working as a pass-through, it
1407     - caches its "left argument", args[0].
1408     - makes adjustments to subquery item's return value for proper NULL
1409       value handling
1410 */
1411 
invisible_mode()1412 bool Item_in_optimizer::invisible_mode()
1413 {
1414   /* MAX/MIN transformed or EXISTS->IN prepared => do nothing */
1415  return (args[1]->type() != Item::SUBSELECT_ITEM ||
1416          ((Item_subselect *)args[1])->substype() ==
1417          Item_subselect::EXISTS_SUBS);
1418 }
1419 
1420 
1421 /**
1422   Add an expression cache for this subquery if it is needed
1423 
1424   @param thd_arg         Thread handle
1425 
1426   @details
1427   The function checks whether an expression cache is needed for this item
1428   and if if so wraps the item into an item of the class
1429   Item_cache_wrapper with an appropriate expression cache set up there.
1430 
1431   @note
1432   used from Item::transform()
1433 
1434   @return
1435   new wrapper item if an expression cache is needed,
1436   this item - otherwise
1437 */
1438 
expr_cache_insert_transformer(THD * thd,uchar * unused)1439 Item *Item_in_optimizer::expr_cache_insert_transformer(THD *thd, uchar *unused)
1440 {
1441   DBUG_ENTER("Item_in_optimizer::expr_cache_insert_transformer");
1442   DBUG_ASSERT(fixed);
1443 
1444   if (invisible_mode())
1445     DBUG_RETURN(this);
1446 
1447   if (expr_cache)
1448     DBUG_RETURN(expr_cache);
1449 
1450   if (args[1]->expr_cache_is_needed(thd) &&
1451       (expr_cache= set_expr_cache(thd)))
1452     DBUG_RETURN(expr_cache);
1453 
1454   DBUG_RETURN(this);
1455 }
1456 
1457 
1458 
1459 /**
1460     Collect and add to the list cache parameters for this Item.
1461 
1462     @param parameters    The list where to add parameters
1463 */
1464 
get_cache_parameters(List<Item> & parameters)1465 void Item_in_optimizer::get_cache_parameters(List<Item> &parameters)
1466 {
1467   DBUG_ASSERT(fixed);
1468   /* Add left expression to the list of the parameters of the subquery */
1469   if (!invisible_mode())
1470   {
1471     if (args[0]->cols() == 1)
1472       parameters.add_unique(args[0], &cmp_items);
1473     else
1474     {
1475       for (uint i= 0; i < args[0]->cols(); i++)
1476       {
1477         parameters.add_unique(args[0]->element_index(i), &cmp_items);
1478       }
1479     }
1480   }
1481   args[1]->get_cache_parameters(parameters);
1482 }
1483 
1484 /**
1485    The implementation of optimized \<outer expression\> [NOT] IN \<subquery\>
1486    predicates. The implementation works as follows.
1487 
1488    For the current value of the outer expression
1489 
1490    - If it contains only NULL values, the original (before rewrite by the
1491      Item_in_subselect rewrite methods) inner subquery is non-correlated and
1492      was previously executed, there is no need to re-execute it, and the
1493      previous return value is returned.
1494 
1495    - If it contains NULL values, check if there is a partial match for the
1496      inner query block by evaluating it. For clarity we repeat here the
1497      transformation previously performed on the sub-query. The expression
1498 
1499      <tt>
1500      ( oc_1, ..., oc_n )
1501      \<in predicate\>
1502      ( SELECT ic_1, ..., ic_n
1503        FROM \<table\>
1504        WHERE \<inner where\>
1505      )
1506      </tt>
1507 
1508      was transformed into
1509 
1510      <tt>
1511      ( oc_1, ..., oc_n )
1512      \<in predicate\>
1513      ( SELECT ic_1, ..., ic_n
1514        FROM \<table\>
1515        WHERE \<inner where\> AND ... ( ic_k = oc_k OR ic_k IS NULL )
1516        HAVING ... NOT ic_k IS NULL
1517      )
1518      </tt>
1519 
1520      The evaluation will now proceed according to special rules set up
1521      elsewhere. These rules include:
1522 
1523      - The HAVING NOT \<inner column\> IS NULL conditions added by the
1524        aforementioned rewrite methods will detect whether they evaluated (and
1525        rejected) a NULL value and if so, will cause the subquery to evaluate
1526        to NULL.
1527 
1528      - The added WHERE and HAVING conditions are present only for those inner
1529        columns that correspond to outer column that are not NULL at the moment.
1530 
1531      - If there is an eligible index for executing the subquery, the special
1532        access method "Full scan on NULL key" is employed which ensures that
1533        the inner query will detect if there are NULL values resulting from the
1534        inner query. This access method will quietly resort to table scan if it
1535        needs to find NULL values as well.
1536 
1537      - Under these conditions, the sub-query need only be evaluated in order to
1538        find out whether it produced any rows.
1539 
1540        - If it did, we know that there was a partial match since there are
1541          NULL values in the outer row expression.
1542 
1543        - If it did not, the result is FALSE or UNKNOWN. If at least one of the
1544          HAVING sub-predicates rejected a NULL value corresponding to an outer
1545          non-NULL, and hence the inner query block returns UNKNOWN upon
1546          evaluation, there was a partial match and the result is UNKNOWN.
1547 
1548    - If it contains no NULL values, the call is forwarded to the inner query
1549      block.
1550 
1551      @see Item_in_subselect::val_bool()
1552      @see Item_is_not_null_test::val_int()
1553 */
1554 
val_int()1555 longlong Item_in_optimizer::val_int()
1556 {
1557   bool tmp;
1558   DBUG_ASSERT(fixed == 1);
1559   cache->store(args[0]);
1560   cache->cache_value();
1561   DBUG_ENTER(" Item_in_optimizer::val_int");
1562 
1563   if (invisible_mode())
1564   {
1565     longlong res= args[1]->val_int();
1566     null_value= args[1]->null_value;
1567     DBUG_PRINT("info", ("pass trough"));
1568     DBUG_RETURN(res);
1569   }
1570 
1571   if (cache->null_value_inside)
1572   {
1573      DBUG_PRINT("info", ("Left NULL..."));
1574     /*
1575       We're evaluating
1576       "<outer_value_list> [NOT] IN (SELECT <inner_value_list>...)"
1577       where one or more of the outer values is NULL.
1578     */
1579     if (((Item_in_subselect*)args[1])->is_top_level_item())
1580     {
1581       /*
1582         We're evaluating a top level item, e.g.
1583 	"<outer_value_list> IN (SELECT <inner_value_list>...)",
1584 	and in this case a NULL value in the outer_value_list means
1585         that the result shall be NULL/FALSE (makes no difference for
1586         top level items). The cached value is NULL, so just return
1587         NULL.
1588       */
1589       null_value= 1;
1590     }
1591     else
1592     {
1593       /*
1594 	We're evaluating an item where a NULL value in either the
1595         outer or inner value list does not automatically mean that we
1596         can return NULL/FALSE. An example of such a query is
1597         "<outer_value_list> NOT IN (SELECT <inner_value_list>...)"
1598         The result when there is at least one NULL value is: NULL if the
1599         SELECT evaluated over the non-NULL values produces at least
1600         one row, FALSE otherwise
1601       */
1602       Item_in_subselect *item_subs=(Item_in_subselect*)args[1];
1603       bool all_left_cols_null= true;
1604       const uint ncols= cache->cols();
1605 
1606       /*
1607         Turn off the predicates that are based on column compares for
1608         which the left part is currently NULL
1609       */
1610       for (uint i= 0; i < ncols; i++)
1611       {
1612         if (cache->element_index(i)->null_value)
1613           item_subs->set_cond_guard_var(i, FALSE);
1614         else
1615           all_left_cols_null= false;
1616       }
1617 
1618       if (!item_subs->is_correlated &&
1619           all_left_cols_null && result_for_null_param != UNKNOWN)
1620       {
1621         /*
1622            This is a non-correlated subquery, all values in the outer
1623            value list are NULL, and we have already evaluated the
1624            subquery for all NULL values: Return the same result we
1625            did last time without evaluating the subquery.
1626         */
1627         null_value= result_for_null_param;
1628       }
1629       else
1630       {
1631         /* The subquery has to be evaluated */
1632         (void) item_subs->val_bool_result();
1633         if (item_subs->engine->no_rows())
1634           null_value= item_subs->null_value;
1635         else
1636           null_value= TRUE;
1637         if (all_left_cols_null)
1638           result_for_null_param= null_value;
1639       }
1640 
1641       /* Turn all predicates back on */
1642       for (uint i= 0; i < ncols; i++)
1643         item_subs->set_cond_guard_var(i, TRUE);
1644     }
1645     DBUG_RETURN(0);
1646   }
1647   tmp= args[1]->val_bool_result();
1648   null_value= args[1]->null_value;
1649   DBUG_RETURN(tmp);
1650 }
1651 
1652 
keep_top_level_cache()1653 void Item_in_optimizer::keep_top_level_cache()
1654 {
1655   cache->keep_array();
1656   save_cache= 1;
1657 }
1658 
1659 
cleanup()1660 void Item_in_optimizer::cleanup()
1661 {
1662   DBUG_ENTER("Item_in_optimizer::cleanup");
1663   Item_bool_func::cleanup();
1664   if (!save_cache)
1665     cache= 0;
1666   expr_cache= 0;
1667   DBUG_VOID_RETURN;
1668 }
1669 
1670 
is_null()1671 bool Item_in_optimizer::is_null()
1672 {
1673   val_int();
1674   return null_value;
1675 }
1676 
1677 
1678 /**
1679   Transform an Item_in_optimizer and its arguments with a callback function.
1680 
1681   @param transformer the transformer callback function to be applied to the
1682          nodes of the tree of the object
1683   @param parameter to be passed to the transformer
1684 
1685   @detail
1686     Recursively transform the left and the right operand of this Item. The
1687     Right operand is an Item_in_subselect or its subclass. To avoid the
1688     creation of new Items, we use the fact the the left operand of the
1689     Item_in_subselect is the same as the one of 'this', so instead of
1690     transforming its operand, we just assign the left operand of the
1691     Item_in_subselect to be equal to the left operand of 'this'.
1692     The transformation is not applied further to the subquery operand
1693     if the IN predicate.
1694 
1695   @returns
1696     @retval pointer to the transformed item
1697     @retval NULL if an error occurred
1698 */
1699 
transform(THD * thd,Item_transformer transformer,uchar * argument)1700 Item *Item_in_optimizer::transform(THD *thd, Item_transformer transformer,
1701                                    uchar *argument)
1702 {
1703   Item *new_item;
1704 
1705   DBUG_ASSERT(fixed);
1706   DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
1707   DBUG_ASSERT(arg_count == 2);
1708 
1709   /* Transform the left IN operand. */
1710   new_item= (*args)->transform(thd, transformer, argument);
1711   if (!new_item)
1712     return 0;
1713   /*
1714     THD::change_item_tree() should be called only if the tree was
1715     really transformed, i.e. when a new item has been created.
1716     Otherwise we'll be allocating a lot of unnecessary memory for
1717     change records at each execution.
1718   */
1719   if ((*args) != new_item)
1720     thd->change_item_tree(args, new_item);
1721 
1722   if (invisible_mode())
1723   {
1724     /* MAX/MIN transformed => pass through */
1725     new_item= args[1]->transform(thd, transformer, argument);
1726     if (!new_item)
1727       return 0;
1728     if (args[1] != new_item)
1729       thd->change_item_tree(args + 1, new_item);
1730   }
1731   else
1732   {
1733     /*
1734       Transform the right IN operand which should be an Item_in_subselect or a
1735       subclass of it. The left operand of the IN must be the same as the left
1736       operand of this Item_in_optimizer, so in this case there is no further
1737       transformation, we only make both operands the same.
1738       TODO: is it the way it should be?
1739     */
1740     DBUG_ASSERT((args[1])->type() == Item::SUBSELECT_ITEM &&
1741                 (((Item_subselect*)(args[1]))->substype() ==
1742                  Item_subselect::IN_SUBS ||
1743                  ((Item_subselect*)(args[1]))->substype() ==
1744                  Item_subselect::ALL_SUBS ||
1745                  ((Item_subselect*)(args[1]))->substype() ==
1746                  Item_subselect::ANY_SUBS));
1747 
1748     Item_in_subselect *in_arg= (Item_in_subselect*)args[1];
1749     thd->change_item_tree(&in_arg->left_expr, args[0]);
1750   }
1751   return (this->*transformer)(thd, argument);
1752 }
1753 
1754 
is_expensive_processor(void * arg)1755 bool Item_in_optimizer::is_expensive_processor(void *arg)
1756 {
1757   DBUG_ASSERT(fixed);
1758   return args[0]->is_expensive_processor(arg) ||
1759          args[1]->is_expensive_processor(arg);
1760 }
1761 
1762 
is_expensive()1763 bool Item_in_optimizer::is_expensive()
1764 {
1765   DBUG_ASSERT(fixed);
1766   return args[0]->is_expensive() || args[1]->is_expensive();
1767 }
1768 
1769 
val_int()1770 longlong Item_func_eq::val_int()
1771 {
1772   DBUG_ASSERT(fixed == 1);
1773   int value= cmp.compare();
1774   return value == 0 ? 1 : 0;
1775 }
1776 
1777 
1778 /** Same as Item_func_eq, but NULL = NULL. */
1779 
fix_length_and_dec()1780 bool Item_func_equal::fix_length_and_dec()
1781 {
1782   bool rc= Item_bool_rowready_func2::fix_length_and_dec();
1783   maybe_null=null_value=0;
1784   return rc;
1785 }
1786 
val_int()1787 longlong Item_func_equal::val_int()
1788 {
1789   DBUG_ASSERT(fixed == 1);
1790   return cmp.compare();
1791 }
1792 
val_int()1793 longlong Item_func_ne::val_int()
1794 {
1795   DBUG_ASSERT(fixed == 1);
1796   int value= cmp.compare();
1797   return value != 0 && !null_value ? 1 : 0;
1798 }
1799 
1800 
val_int()1801 longlong Item_func_ge::val_int()
1802 {
1803   DBUG_ASSERT(fixed == 1);
1804   int value= cmp.compare();
1805   return value >= 0 ? 1 : 0;
1806 }
1807 
1808 
val_int()1809 longlong Item_func_gt::val_int()
1810 {
1811   DBUG_ASSERT(fixed == 1);
1812   int value= cmp.compare();
1813   return value > 0 ? 1 : 0;
1814 }
1815 
val_int()1816 longlong Item_func_le::val_int()
1817 {
1818   DBUG_ASSERT(fixed == 1);
1819   int value= cmp.compare();
1820   return value <= 0 && !null_value ? 1 : 0;
1821 }
1822 
1823 
val_int()1824 longlong Item_func_lt::val_int()
1825 {
1826   DBUG_ASSERT(fixed == 1);
1827   int value= cmp.compare();
1828   return value < 0 && !null_value ? 1 : 0;
1829 }
1830 
1831 
val_int()1832 longlong Item_func_strcmp::val_int()
1833 {
1834   DBUG_ASSERT(fixed == 1);
1835   String *a= args[0]->val_str(&value1);
1836   String *b= args[1]->val_str(&value2);
1837   if (!a || !b)
1838   {
1839     null_value=1;
1840     return 0;
1841   }
1842   int value= cmp_collation.sortcmp(a, b);
1843   null_value=0;
1844   return !value ? 0 : (value < 0 ? (longlong) -1 : (longlong) 1);
1845 }
1846 
1847 
eq(const Item * item,bool binary_cmp) const1848 bool Item_func_opt_neg::eq(const Item *item, bool binary_cmp) const
1849 {
1850   /* Assume we don't have rtti */
1851   if (this == item)
1852     return 1;
1853   if (item->type() != FUNC_ITEM)
1854     return 0;
1855   Item_func *item_func=(Item_func*) item;
1856   if (arg_count != item_func->argument_count() ||
1857       functype() != item_func->functype())
1858     return 0;
1859   if (negated != ((Item_func_opt_neg *) item_func)->negated)
1860     return 0;
1861   return Item_args::eq(item_func, binary_cmp);
1862 }
1863 
1864 
fix_fields(THD * thd,Item ** ref)1865 bool Item_func_interval::fix_fields(THD *thd, Item **ref)
1866 {
1867   if (Item_long_func::fix_fields(thd, ref))
1868     return true;
1869   for (uint i= 0 ; i < row->cols(); i++)
1870   {
1871     if (row->element_index(i)->check_cols(1))
1872       return true;
1873   }
1874   return false;
1875 }
1876 
1877 
fix_length_and_dec()1878 bool Item_func_interval::fix_length_and_dec()
1879 {
1880   uint rows= row->cols();
1881 
1882   use_decimal_comparison= ((row->element_index(0)->result_type() ==
1883                             DECIMAL_RESULT) ||
1884                            (row->element_index(0)->result_type() ==
1885                             INT_RESULT));
1886   if (rows > 8)
1887   {
1888     bool not_null_consts= TRUE;
1889 
1890     for (uint i= 1; not_null_consts && i < rows; i++)
1891     {
1892       Item *el= row->element_index(i);
1893       not_null_consts&= el->const_item() && !el->is_null();
1894     }
1895 
1896     if (not_null_consts)
1897     {
1898       intervals= (interval_range*) current_thd->alloc(sizeof(interval_range) *
1899                                                          (rows - 1));
1900       if (!intervals)
1901         return TRUE;
1902 
1903       if (use_decimal_comparison)
1904       {
1905         for (uint i= 1; i < rows; i++)
1906         {
1907           Item *el= row->element_index(i);
1908           interval_range *range= intervals + (i-1);
1909           if ((el->result_type() == DECIMAL_RESULT) ||
1910               (el->result_type() == INT_RESULT))
1911           {
1912             range->type= DECIMAL_RESULT;
1913             range->dec.init();
1914             my_decimal *dec= el->val_decimal(&range->dec);
1915             if (dec != &range->dec)
1916             {
1917               range->dec= *dec;
1918             }
1919           }
1920           else
1921           {
1922             range->type= REAL_RESULT;
1923             range->dbl= el->val_real();
1924           }
1925         }
1926       }
1927       else
1928       {
1929         for (uint i= 1; i < rows; i++)
1930         {
1931           intervals[i-1].dbl= row->element_index(i)->val_real();
1932         }
1933       }
1934     }
1935   }
1936   maybe_null= 0;
1937   max_length= 2;
1938   used_tables_and_const_cache_join(row);
1939   not_null_tables_cache= row->not_null_tables();
1940   join_with_sum_func(row);
1941   with_param= with_param || row->with_param;
1942   with_field= with_field || row->with_field;
1943   return FALSE;
1944 }
1945 
1946 
1947 /**
1948   Execute Item_func_interval().
1949 
1950   @note
1951     If we are doing a decimal comparison, we are evaluating the first
1952     item twice.
1953 
1954   @return
1955     - -1 if null value,
1956     - 0 if lower than lowest
1957     - 1 - arg_count-1 if between args[n] and args[n+1]
1958     - arg_count if higher than biggest argument
1959 */
1960 
val_int()1961 longlong Item_func_interval::val_int()
1962 {
1963   DBUG_ASSERT(fixed == 1);
1964   double value;
1965   my_decimal dec_buf, *dec= NULL;
1966   uint i;
1967 
1968   if (use_decimal_comparison)
1969   {
1970     dec= row->element_index(0)->val_decimal(&dec_buf);
1971     if (row->element_index(0)->null_value)
1972       return -1;
1973     my_decimal2double(E_DEC_FATAL_ERROR, dec, &value);
1974   }
1975   else
1976   {
1977     value= row->element_index(0)->val_real();
1978     if (row->element_index(0)->null_value)
1979       return -1;
1980   }
1981 
1982   if (intervals)
1983   {					// Use binary search to find interval
1984     uint start,end;
1985     start= 0;
1986     end=   row->cols()-2;
1987     while (start != end)
1988     {
1989       uint mid= (start + end + 1) / 2;
1990       interval_range *range= intervals + mid;
1991       my_bool cmp_result;
1992       /*
1993         The values in the range interval may have different types,
1994         Only do a decimal comparison if the first argument is a decimal
1995         and we are comparing against a decimal
1996       */
1997       if (dec && range->type == DECIMAL_RESULT)
1998         cmp_result= my_decimal_cmp(&range->dec, dec) <= 0;
1999       else
2000         cmp_result= (range->dbl <= value);
2001       if (cmp_result)
2002 	start= mid;
2003       else
2004 	end= mid - 1;
2005     }
2006     interval_range *range= intervals+start;
2007     return ((dec && range->type == DECIMAL_RESULT) ?
2008             my_decimal_cmp(dec, &range->dec) < 0 :
2009             value < range->dbl) ? 0 : start + 1;
2010   }
2011 
2012   for (i=1 ; i < row->cols() ; i++)
2013   {
2014     Item *el= row->element_index(i);
2015     if (use_decimal_comparison &&
2016         ((el->result_type() == DECIMAL_RESULT) ||
2017          (el->result_type() == INT_RESULT)))
2018     {
2019       VDec e_dec(el);
2020       /* Skip NULL ranges. */
2021       if (e_dec.is_null())
2022         continue;
2023       if (e_dec.cmp(dec) > 0)
2024         return i - 1;
2025     }
2026     else
2027     {
2028       double val= el->val_real();
2029       /* Skip NULL ranges. */
2030       if (el->null_value)
2031         continue;
2032       if (val > value)
2033         return i - 1;
2034     }
2035   }
2036   return i-1;
2037 }
2038 
2039 
2040 /**
2041   Perform context analysis of a BETWEEN item tree.
2042 
2043     This function performs context analysis (name resolution) and calculates
2044     various attributes of the item tree with Item_func_between as its root.
2045     The function saves in ref the pointer to the item or to a newly created
2046     item that is considered as a replacement for the original one.
2047 
2048   @param thd     reference to the global context of the query thread
2049   @param ref     pointer to Item* variable where pointer to resulting "fixed"
2050                  item is to be assigned
2051 
2052   @note
2053     Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
2054     a predicate/function level. Then it's easy to show that:
2055     @verbatim
2056       T0(e BETWEEN e1 AND e2)     = union(T1(e),T1(e1),T1(e2))
2057       T1(e BETWEEN e1 AND e2)     = union(T1(e),intersection(T1(e1),T1(e2)))
2058       T0(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
2059       T1(e NOT BETWEEN e1 AND e2) = union(T1(e),intersection(T1(e1),T1(e2)))
2060     @endverbatim
2061 
2062   @retval
2063     0   ok
2064   @retval
2065     1   got error
2066 */
2067 
2068 
eval_not_null_tables(void * opt_arg)2069 bool Item_func_between::eval_not_null_tables(void *opt_arg)
2070 {
2071   if (Item_func_opt_neg::eval_not_null_tables(NULL))
2072     return 1;
2073 
2074   /* not_null_tables_cache == union(T1(e),T1(e1),T1(e2)) */
2075   if (pred_level && !negated)
2076     return 0;
2077 
2078   /* not_null_tables_cache == union(T1(e), intersection(T1(e1),T1(e2))) */
2079   not_null_tables_cache= (args[0]->not_null_tables() |
2080                           (args[1]->not_null_tables() &
2081                            args[2]->not_null_tables()));
2082   return 0;
2083 }
2084 
2085 
count_sargable_conds(void * arg)2086 bool Item_func_between::count_sargable_conds(void *arg)
2087 {
2088   SELECT_LEX *sel= (SELECT_LEX *) arg;
2089   sel->cond_count++;
2090   sel->between_count++;
2091   return 0;
2092 }
2093 
2094 
fix_after_pullout(st_select_lex * new_parent,Item ** ref,bool merge)2095 void Item_func_between::fix_after_pullout(st_select_lex *new_parent,
2096                                           Item **ref, bool merge)
2097 {
2098   /* This will re-calculate attributes of the arguments */
2099   Item_func_opt_neg::fix_after_pullout(new_parent, ref, merge);
2100   /* Then, re-calculate not_null_tables_cache according to our special rules */
2101   eval_not_null_tables(NULL);
2102 }
2103 
fix_length_and_dec()2104 bool Item_func_between::fix_length_and_dec()
2105 {
2106   max_length= 1;
2107 
2108   /*
2109     As some compare functions are generated after sql_yacc,
2110     we have to check for out of memory conditions here
2111   */
2112   if (!args[0] || !args[1] || !args[2])
2113     return TRUE;
2114   if (m_comparator.aggregate_for_comparison(Item_func_between::func_name(),
2115                                             args, 3, false))
2116   {
2117     DBUG_ASSERT(current_thd->is_error());
2118     return TRUE;
2119   }
2120 
2121   return m_comparator.type_handler()->
2122     Item_func_between_fix_length_and_dec(this);
2123 }
2124 
2125 
fix_length_and_dec_numeric(THD * thd)2126 bool Item_func_between::fix_length_and_dec_numeric(THD *thd)
2127 {
2128   /* See the comment about the similar block in Item_bool_func2 */
2129   if (args[0]->real_item()->type() == FIELD_ITEM &&
2130       !thd->lex->is_ps_or_view_context_analysis())
2131   {
2132     Item_field *field_item= (Item_field*) (args[0]->real_item());
2133     if (field_item->field_type() ==  MYSQL_TYPE_LONGLONG ||
2134         field_item->field_type() ==  MYSQL_TYPE_YEAR)
2135     {
2136       const bool cvt_arg1= convert_const_to_int(thd, field_item, &args[1]);
2137       const bool cvt_arg2= convert_const_to_int(thd, field_item, &args[2]);
2138       if (cvt_arg1 && cvt_arg2)
2139       {
2140         // Works for all types
2141         m_comparator.set_handler(&type_handler_longlong);
2142       }
2143     }
2144   }
2145   return FALSE;
2146 }
2147 
2148 
fix_length_and_dec_temporal(THD * thd)2149 bool Item_func_between::fix_length_and_dec_temporal(THD *thd)
2150 {
2151   if (!thd->lex->is_ps_or_view_context_analysis())
2152   {
2153     for (uint i= 0; i < 3; i ++)
2154     {
2155       if (args[i]->const_item() &&
2156           args[i]->type_handler_for_comparison() != m_comparator.type_handler())
2157       {
2158         Item_cache *cache= m_comparator.type_handler()->Item_get_cache(thd, args[i]);
2159         if (!cache || cache->setup(thd, args[i]))
2160           return true;
2161         thd->change_item_tree(&args[i], cache);
2162       }
2163     }
2164   }
2165   return false;
2166 }
2167 
2168 
val_int_cmp_datetime()2169 longlong Item_func_between::val_int_cmp_datetime()
2170 {
2171   THD *thd= current_thd;
2172   longlong value= args[0]->val_datetime_packed(thd), a, b;
2173   if ((null_value= args[0]->null_value))
2174     return 0;
2175   a= args[1]->val_datetime_packed(thd);
2176   b= args[2]->val_datetime_packed(thd);
2177   return val_int_cmp_int_finalize(value, a, b);
2178 }
2179 
2180 
val_int_cmp_time()2181 longlong Item_func_between::val_int_cmp_time()
2182 {
2183   THD *thd= current_thd;
2184   longlong value= args[0]->val_time_packed(thd), a, b;
2185   if ((null_value= args[0]->null_value))
2186     return 0;
2187   a= args[1]->val_time_packed(thd);
2188   b= args[2]->val_time_packed(thd);
2189   return val_int_cmp_int_finalize(value, a, b);
2190 }
2191 
2192 
val_int_cmp_native()2193 longlong Item_func_between::val_int_cmp_native()
2194 {
2195   THD *thd= current_thd;
2196   const Type_handler *h= m_comparator.type_handler();
2197   NativeBuffer<STRING_BUFFER_USUAL_SIZE> value, a, b;
2198   if (val_native_with_conversion_from_item(thd, args[0], &value, h))
2199     return 0;
2200   bool ra= args[1]->val_native_with_conversion(thd, &a, h);
2201   bool rb= args[2]->val_native_with_conversion(thd, &b, h);
2202   if (!ra && !rb)
2203     return (longlong)
2204       ((h->cmp_native(value, a) >= 0 &&
2205         h->cmp_native(value, b) <= 0) != negated);
2206   if (ra && rb)
2207     null_value= true;
2208   else if (ra)
2209     null_value= h->cmp_native(value, b) <= 0;
2210   else
2211     null_value= h->cmp_native(value, a) >= 0;
2212   return (longlong) (!null_value && negated);
2213 }
2214 
2215 
val_int_cmp_string()2216 longlong Item_func_between::val_int_cmp_string()
2217 {
2218   String *value,*a,*b;
2219   value=args[0]->val_str(&value0);
2220   if ((null_value=args[0]->null_value))
2221     return 0;
2222   a= args[1]->val_str(&value1);
2223   b= args[2]->val_str(&value2);
2224   if (!args[1]->null_value && !args[2]->null_value)
2225     return (longlong) ((sortcmp(value,a,cmp_collation.collation) >= 0 &&
2226                         sortcmp(value,b,cmp_collation.collation) <= 0) !=
2227                        negated);
2228   if (args[1]->null_value && args[2]->null_value)
2229     null_value= true;
2230   else if (args[1]->null_value)
2231   {
2232     // Set to not null if false range.
2233     null_value= sortcmp(value,b,cmp_collation.collation) <= 0;
2234   }
2235   else
2236   {
2237     // Set to not null if false range.
2238     null_value= sortcmp(value,a,cmp_collation.collation) >= 0;
2239   }
2240   return (longlong) (!null_value && negated);
2241 }
2242 
2243 
val_int_cmp_int()2244 longlong Item_func_between::val_int_cmp_int()
2245 {
2246   Longlong_hybrid value= args[0]->to_longlong_hybrid();
2247   if ((null_value= args[0]->null_value))
2248     return 0;					/* purecov: inspected */
2249   Longlong_hybrid a= args[1]->to_longlong_hybrid();
2250   Longlong_hybrid b= args[2]->to_longlong_hybrid();
2251   if (!args[1]->null_value && !args[2]->null_value)
2252     return (longlong) ((value.cmp(a) >= 0 && value.cmp(b) <= 0) != negated);
2253   if (args[1]->null_value && args[2]->null_value)
2254     null_value= true;
2255   else if (args[1]->null_value)
2256     null_value= value.cmp(b) <= 0;              // not null if false range.
2257   else
2258     null_value= value.cmp(a) >= 0;
2259   return (longlong) (!null_value && negated);
2260 }
2261 
2262 
val_int_cmp_int_finalize(longlong value,longlong a,longlong b)2263 bool Item_func_between::val_int_cmp_int_finalize(longlong value,
2264                                                  longlong a,
2265                                                  longlong b)
2266 {
2267   if (!args[1]->null_value && !args[2]->null_value)
2268     return (longlong) ((value >= a && value <= b) != negated);
2269   if (args[1]->null_value && args[2]->null_value)
2270     null_value= true;
2271   else if (args[1]->null_value)
2272     null_value= value <= b;			// not null if false range.
2273   else
2274     null_value= value >= a;
2275   return (longlong) (!null_value && negated);
2276 }
2277 
2278 
val_int_cmp_decimal()2279 longlong Item_func_between::val_int_cmp_decimal()
2280 {
2281   VDec dec(args[0]);
2282   if ((null_value= dec.is_null()))
2283     return 0;					/* purecov: inspected */
2284   VDec a_dec(args[1]), b_dec(args[2]);
2285   if (!a_dec.is_null() && !b_dec.is_null())
2286     return (longlong) ((dec.cmp(a_dec) >= 0 &&
2287                         dec.cmp(b_dec) <= 0) != negated);
2288   if (a_dec.is_null() && b_dec.is_null())
2289     null_value= true;
2290   else if (a_dec.is_null())
2291     null_value= (dec.cmp(b_dec) <= 0);
2292   else
2293     null_value= (dec.cmp(a_dec) >= 0);
2294   return (longlong) (!null_value && negated);
2295 }
2296 
2297 
val_int_cmp_real()2298 longlong Item_func_between::val_int_cmp_real()
2299 {
2300   double value= args[0]->val_real(),a,b;
2301   if ((null_value=args[0]->null_value))
2302     return 0;					/* purecov: inspected */
2303   a= args[1]->val_real();
2304   b= args[2]->val_real();
2305   if (!args[1]->null_value && !args[2]->null_value)
2306     return (longlong) ((value >= a && value <= b) != negated);
2307   if (args[1]->null_value && args[2]->null_value)
2308     null_value= true;
2309   else if (args[1]->null_value)
2310   {
2311     null_value= value <= b;			// not null if false range.
2312   }
2313   else
2314   {
2315     null_value= value >= a;
2316   }
2317   return (longlong) (!null_value && negated);
2318 }
2319 
2320 
print(String * str,enum_query_type query_type)2321 void Item_func_between::print(String *str, enum_query_type query_type)
2322 {
2323   args[0]->print_parenthesised(str, query_type, higher_precedence());
2324   if (negated)
2325     str->append(STRING_WITH_LEN(" not"));
2326   str->append(STRING_WITH_LEN(" between "));
2327   args[1]->print_parenthesised(str, query_type, precedence());
2328   str->append(STRING_WITH_LEN(" and "));
2329   args[2]->print_parenthesised(str, query_type, precedence());
2330 }
2331 
2332 
2333 double
real_op()2334 Item_func_ifnull::real_op()
2335 {
2336   DBUG_ASSERT(fixed == 1);
2337   double value= args[0]->val_real();
2338   if (!args[0]->null_value)
2339   {
2340     null_value=0;
2341     return value;
2342   }
2343   value= args[1]->val_real();
2344   if ((null_value=args[1]->null_value))
2345     return 0.0;
2346   return value;
2347 }
2348 
2349 longlong
int_op()2350 Item_func_ifnull::int_op()
2351 {
2352   DBUG_ASSERT(fixed == 1);
2353   longlong value=args[0]->val_int();
2354   if (!args[0]->null_value)
2355   {
2356     null_value=0;
2357     return value;
2358   }
2359   value=args[1]->val_int();
2360   if ((null_value=args[1]->null_value))
2361     return 0;
2362   return value;
2363 }
2364 
2365 
decimal_op(my_decimal * decimal_value)2366 my_decimal *Item_func_ifnull::decimal_op(my_decimal *decimal_value)
2367 {
2368   DBUG_ASSERT(fixed == 1);
2369   my_decimal *value= args[0]->val_decimal(decimal_value);
2370   if (!args[0]->null_value)
2371   {
2372     null_value= 0;
2373     return value;
2374   }
2375   value= args[1]->val_decimal(decimal_value);
2376   if ((null_value= args[1]->null_value))
2377     return 0;
2378   return value;
2379 }
2380 
2381 
2382 String *
str_op(String * str)2383 Item_func_ifnull::str_op(String *str)
2384 {
2385   DBUG_ASSERT(fixed == 1);
2386   String *res  =args[0]->val_str(str);
2387   if (!args[0]->null_value)
2388   {
2389     null_value=0;
2390     res->set_charset(collation.collation);
2391     return res;
2392   }
2393   res=args[1]->val_str(str);
2394   if ((null_value=args[1]->null_value))
2395     return 0;
2396   res->set_charset(collation.collation);
2397   return res;
2398 }
2399 
2400 
native_op(THD * thd,Native * to)2401 bool Item_func_ifnull::native_op(THD *thd, Native *to)
2402 {
2403   DBUG_ASSERT(fixed == 1);
2404   if (!val_native_with_conversion_from_item(thd, args[0], to, type_handler()))
2405     return false;
2406   return val_native_with_conversion_from_item(thd, args[1], to, type_handler());
2407 }
2408 
2409 
date_op(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)2410 bool Item_func_ifnull::date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
2411 {
2412   DBUG_ASSERT(fixed == 1);
2413   for (uint i= 0; i < 2; i++)
2414   {
2415     Datetime_truncation_not_needed dt(thd, args[i],
2416                                       fuzzydate & ~TIME_FUZZY_DATES);
2417     if (!(dt.copy_to_mysql_time(ltime, mysql_timestamp_type())))
2418       return (null_value= false);
2419   }
2420   return (null_value= true);
2421 }
2422 
2423 
time_op(THD * thd,MYSQL_TIME * ltime)2424 bool Item_func_ifnull::time_op(THD *thd, MYSQL_TIME *ltime)
2425 {
2426   DBUG_ASSERT(fixed == 1);
2427   for (uint i= 0; i < 2; i++)
2428   {
2429     if (!Time(thd, args[i]).copy_to_mysql_time(ltime))
2430       return (null_value= false);
2431   }
2432   return (null_value= true);
2433 }
2434 
2435 
2436 /**
2437   Perform context analysis of an IF item tree.
2438 
2439     This function performs context analysis (name resolution) and calculates
2440     various attributes of the item tree with Item_func_if as its root.
2441     The function saves in ref the pointer to the item or to a newly created
2442     item that is considered as a replacement for the original one.
2443 
2444   @param thd     reference to the global context of the query thread
2445   @param ref     pointer to Item* variable where pointer to resulting "fixed"
2446                  item is to be assigned
2447 
2448   @note
2449     Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
2450     a predicate/function level. Then it's easy to show that:
2451     @verbatim
2452       T0(IF(e,e1,e2)  = T1(IF(e,e1,e2))
2453       T1(IF(e,e1,e2)) = intersection(T1(e1),T1(e2))
2454     @endverbatim
2455 
2456   @retval
2457     0   ok
2458   @retval
2459     1   got error
2460 */
2461 
2462 bool
fix_fields(THD * thd,Item ** ref)2463 Item_func_if::fix_fields(THD *thd, Item **ref)
2464 {
2465   DBUG_ASSERT(fixed == 0);
2466   args[0]->top_level_item();
2467 
2468   if (Item_func::fix_fields(thd, ref))
2469     return 1;
2470 
2471   return 0;
2472 }
2473 
2474 
2475 bool
eval_not_null_tables(void * opt_arg)2476 Item_func_if::eval_not_null_tables(void *opt_arg)
2477 {
2478   if (Item_func::eval_not_null_tables(NULL))
2479     return 1;
2480 
2481   not_null_tables_cache= (args[1]->not_null_tables() &
2482                           args[2]->not_null_tables());
2483 
2484   return 0;
2485 }
2486 
2487 
fix_after_pullout(st_select_lex * new_parent,Item ** ref,bool merge)2488 void Item_func_if::fix_after_pullout(st_select_lex *new_parent,
2489                                      Item **ref, bool merge)
2490 {
2491   /* This will re-calculate attributes of the arguments */
2492   Item_func::fix_after_pullout(new_parent, ref, merge);
2493   /* Then, re-calculate not_null_tables_cache according to our special rules */
2494   eval_not_null_tables(NULL);
2495 }
2496 
2497 
split_sum_func(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields,uint flags)2498 void Item_func_nullif::split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array,
2499                                       List<Item> &fields, uint flags)
2500 {
2501   if (m_cache)
2502   {
2503     flags|= SPLIT_SUM_SKIP_REGISTERED; // See Item_func::split_sum_func
2504     m_cache->split_sum_func2_example(thd, ref_pointer_array, fields, flags);
2505     args[1]->split_sum_func2(thd, ref_pointer_array, fields, &args[1], flags);
2506   }
2507   else
2508   {
2509     Item_func::split_sum_func(thd, ref_pointer_array, fields, flags);
2510   }
2511 }
2512 
2513 
walk(Item_processor processor,bool walk_subquery,void * arg)2514 bool Item_func_nullif::walk(Item_processor processor,
2515                             bool walk_subquery, void *arg)
2516 {
2517   /*
2518     No needs to iterate through args[2] when it's just a copy of args[0].
2519     See MDEV-9712 Performance degradation of nested NULLIF
2520   */
2521   uint tmp_count= arg_count == 2 || args[0] == args[2] ? 2 : 3;
2522   for (uint i= 0; i < tmp_count; i++)
2523   {
2524     if (args[i]->walk(processor, walk_subquery, arg))
2525       return true;
2526   }
2527   return (this->*processor)(arg);
2528 }
2529 
2530 
update_used_tables()2531 void Item_func_nullif::update_used_tables()
2532 {
2533   if (m_cache)
2534   {
2535     used_tables_and_const_cache_init();
2536     used_tables_and_const_cache_update_and_join(m_cache->get_example());
2537     used_tables_and_const_cache_update_and_join(arg_count, args);
2538   }
2539   else
2540   {
2541     /*
2542       MDEV-9712 Performance degradation of nested NULLIF
2543       No needs to iterate through args[2] when it's just a copy of args[0].
2544     */
2545     DBUG_ASSERT(arg_count == 3);
2546     used_tables_and_const_cache_init();
2547     used_tables_and_const_cache_update_and_join(args[0] == args[2] ? 2 : 3,
2548                                                 args);
2549   }
2550 }
2551 
2552 
2553 
2554 bool
fix_length_and_dec()2555 Item_func_nullif::fix_length_and_dec()
2556 {
2557   /*
2558     If this is the first invocation of fix_length_and_dec(), create the
2559     third argument as a copy of the first. This cannot be done before
2560     fix_fields(), because fix_fields() might replace items,
2561     for exampe NOT x --> x==0, or (SELECT 1) --> 1.
2562     See also class Item_func_nullif declaration.
2563   */
2564   if (arg_count == 2)
2565     args[arg_count++]= m_arg0 ? m_arg0 : args[0];
2566 
2567   THD *thd= current_thd;
2568   /*
2569     At prepared statement EXECUTE time, args[0] can already
2570     point to a different Item, created during PREPARE time fix_length_and_dec().
2571     For example, if character set conversion was needed, arguments can look
2572     like this:
2573 
2574       args[0]= > Item_func_conv_charset \
2575                                          l_expr
2576       args[2]= >------------------------/
2577 
2578     Otherwise (during PREPARE or convensional execution),
2579     args[0] and args[2] should still point to the same original l_expr.
2580   */
2581   DBUG_ASSERT(args[0] == args[2] || thd->stmt_arena->is_stmt_execute());
2582   if (args[0]->type() == SUM_FUNC_ITEM &&
2583       !thd->lex->is_ps_or_view_context_analysis())
2584   {
2585     /*
2586       NULLIF(l_expr, r_expr)
2587 
2588         is calculated in the way to return a result equal to:
2589 
2590       CASE WHEN l_expr = r_expr THEN NULL ELSE r_expr END.
2591 
2592       There's nothing special with r_expr, because it's referenced
2593       only by args[1] and nothing else.
2594 
2595       l_expr needs a special treatment, as it's referenced by both
2596       args[0] and args[2] initially.
2597 
2598       args[2] is used to return the value. Afrer all transformations
2599       (e.g. in fix_length_and_dec(), equal field propagation, etc)
2600       args[2] points to a an Item which preserves the exact data type and
2601       attributes (e.g. collation) of the original l_expr.
2602       It can point:
2603       - to the original l_expr
2604       - to an Item_cache pointing to l_expr
2605       - to a constant of the same data type with l_expr.
2606 
2607       args[0] is used for comparison. It can be replaced:
2608 
2609       - to Item_func_conv_charset by character set aggregation routines
2610       - to a constant Item by equal field propagation routines
2611         (in case of Item_field)
2612 
2613       The data type and/or the attributes of args[0] can differ from
2614       the data type and the attributes of the original l_expr, to make
2615       it comparable to args[1] (which points to r_expr or its replacement).
2616 
2617       For aggregate functions we have to wrap the original args[0]/args[2]
2618       into Item_cache (see MDEV-9181). In this case the Item_cache
2619       instance becomes the subject to character set conversion instead of
2620       the original args[0]/args[2], while the original args[0]/args[2] get
2621       hidden inside the cache.
2622 
2623       Some examples of what NULLIF can end up with after argument
2624       substitution (we don't mention args[1] in some cases for simplicity):
2625 
2626       1. l_expr is not an aggregate function:
2627 
2628         a. No conversion happened.
2629            args[0] and args[2] were not replaced to something else
2630            (i.e. neither by character set conversion, nor by propagation):
2631 
2632           args[1] > r_expr
2633           args[0] \
2634                     l_expr
2635           args[2] /
2636 
2637         b. Conversion of args[0] happened:
2638 
2639            CREATE OR REPLACE TABLE t1 (
2640              a CHAR(10) CHARACTER SET latin1,
2641              b CHAR(10) CHARACTER SET utf8);
2642            SELECT * FROM t1 WHERE NULLIF(a,b);
2643 
2644            args[1] > r_expr                          (Item_field for t1.b)
2645            args[0] > Item_func_conv_charset\
2646                                             l_expr   (Item_field for t1.a)
2647            args[2] > ----------------------/
2648 
2649         c. Conversion of args[1] happened:
2650 
2651           CREATE OR REPLACE TABLE t1 (
2652             a CHAR(10) CHARACTER SET utf8,
2653             b CHAR(10) CHARACTER SET latin1);
2654           SELECT * FROM t1 WHERE NULLIF(a,b);
2655 
2656           args[1] > Item_func_conv_charset -> r_expr (Item_field for t1.b)
2657           args[0] \
2658                    l_expr                            (Item_field for t1.a)
2659           args[2] /
2660 
2661         d. Conversion of only args[0] happened (by equal field proparation):
2662 
2663            CREATE OR REPLACE TABLE t1 (
2664              a CHAR(10),
2665              b CHAR(10));
2666            SELECT * FROM t1 WHERE NULLIF(a,b) AND a='a';
2667 
2668            args[1] > r_expr            (Item_field for t1.b)
2669            args[0] > Item_string('a')  (constant replacement for t1.a)
2670            args[2] > l_expr            (Item_field for t1.a)
2671 
2672         e. Conversion of both args[0] and args[2] happened
2673            (by equal field propagation):
2674 
2675            CREATE OR REPLACE TABLE t1 (a INT,b INT);
2676            SELECT * FROM t1 WHERE NULLIF(a,b) AND a=5;
2677 
2678            args[1] > r_expr         (Item_field for "b")
2679            args[0] \
2680                     Item_int (5)    (constant replacement for "a")
2681            args[2] /
2682 
2683       2. In case if l_expr is an aggregate function:
2684 
2685         a. No conversion happened:
2686 
2687           args[0] \
2688                    Item_cache > l_expr
2689           args[2] /
2690 
2691         b. Conversion of args[0] happened:
2692 
2693           args[0] > Item_func_conv_charset \
2694                                             Item_cache > l_expr
2695           args[2] >------------------------/
2696 
2697         c. Conversion of both args[0] and args[2] happened.
2698            (e.g. by equal expression propagation)
2699            TODO: check if it's possible (and add an example query if so).
2700     */
2701     m_cache= args[0]->cmp_type() == STRING_RESULT ?
2702              new (thd->mem_root) Item_cache_str_for_nullif(thd, args[0]) :
2703              args[0]->get_cache(thd);
2704     if (!m_cache)
2705       return TRUE;
2706     m_cache->setup(thd, args[0]);
2707     m_cache->store(args[0]);
2708     m_cache->set_used_tables(args[0]->used_tables());
2709     thd->change_item_tree(&args[0], m_cache);
2710     thd->change_item_tree(&args[2], m_cache);
2711   }
2712   set_handler(args[2]->type_handler());
2713   collation.set(args[2]->collation);
2714   decimals= args[2]->decimals;
2715   unsigned_flag= args[2]->unsigned_flag;
2716   fix_char_length(args[2]->max_char_length());
2717   maybe_null=1;
2718   m_arg0= args[0];
2719   if (setup_args_and_comparator(thd, &cmp))
2720     return TRUE;
2721   /*
2722     A special code for EXECUTE..PREPARE.
2723 
2724     If args[0] did not change, then we don't remember it, as it can point
2725     to a temporary Item object which will be destroyed between PREPARE
2726     and EXECUTE. EXECUTE time fix_length_and_dec() will correctly set args[2]
2727     from args[0] again.
2728 
2729     If args[0] changed, then it can be Item_func_conv_charset() for the
2730     original args[0], which was permanently installed during PREPARE time
2731     into the item tree as a wrapper for args[0], using change_item_tree(), i.e.
2732 
2733       NULLIF(latin1_field, 'a' COLLATE utf8_bin)
2734 
2735     was "rewritten" to:
2736 
2737       CASE WHEN CONVERT(latin1_field USING utf8) = 'a' COLLATE utf8_bin
2738         THEN NULL
2739         ELSE latin1_field
2740 
2741     - m_args0 points to Item_field corresponding to latin1_field
2742     - args[0] points to Item_func_conv_charset
2743     - args[0]->args[0] is equal to m_args0
2744     - args[1] points to Item_func_set_collation
2745     - args[2] points is eqial to m_args0
2746 
2747     In this case we remember and reuse m_arg0 during EXECUTE time as args[2].
2748 
2749     QQ: How to make sure that m_args0 does not point
2750     to something temporary which will be destroyed between PREPARE and EXECUTE.
2751     The condition below should probably be more strict and somehow check that:
2752     - change_item_tree() was called for the new args[0]
2753     - m_args0 is referenced from inside args[0], e.g. as a function argument,
2754       and therefore it is also something that won't be destroyed between
2755       PREPARE and EXECUTE.
2756     Any ideas?
2757   */
2758   if (args[0] == m_arg0)
2759     m_arg0= NULL;
2760   return FALSE;
2761 }
2762 
2763 
print(String * str,enum_query_type query_type)2764 void Item_func_nullif::print(String *str, enum_query_type query_type)
2765 {
2766   /*
2767     NULLIF(a,b) is implemented according to the SQL standard as a short for
2768     CASE WHEN a=b THEN NULL ELSE a END
2769 
2770     The constructor of Item_func_nullif sets args[0] and args[2] to the
2771     same item "a", and sets args[1] to "b".
2772 
2773     If "this" is a part of a WHERE or ON condition, then:
2774     - the left "a" is a subject to equal field propagation with ANY_SUBST.
2775     - the right "a" is a subject to equal field propagation with IDENTITY_SUBST.
2776     Therefore, after equal field propagation args[0] and args[2] can point
2777     to different items.
2778   */
2779   if ((query_type & QT_ITEM_ORIGINAL_FUNC_NULLIF) ||
2780       (arg_count == 2) ||
2781       (args[0] == args[2]))
2782   {
2783     /*
2784       If QT_ITEM_ORIGINAL_FUNC_NULLIF is requested,
2785       that means we want the original NULLIF() representation,
2786       e.g. when we are in:
2787         SHOW CREATE {VIEW|FUNCTION|PROCEDURE}
2788 
2789       The original representation is possible only if
2790       args[0] and args[2] still point to the same Item.
2791 
2792       The caller must never pass call print() with QT_ITEM_ORIGINAL_FUNC_NULLIF
2793       if an expression has undergone some optimization
2794       (e.g. equal field propagation done in optimize_cond()) already and
2795       NULLIF() potentially has two different representations of "a":
2796       - one "a" for comparison
2797       - another "a" for the returned value!
2798     */
2799     DBUG_ASSERT(arg_count == 2 ||
2800                 args[0] == args[2] || current_thd->lex->context_analysis_only);
2801     str->append(func_name());
2802     str->append('(');
2803     if (arg_count == 2)
2804       args[0]->print(str, query_type);
2805     else
2806       args[2]->print(str, query_type);
2807     str->append(',');
2808     args[1]->print(str, query_type);
2809     str->append(')');
2810   }
2811   else
2812   {
2813     /*
2814       args[0] and args[2] are different items.
2815       This is possible after WHERE optimization (equal fields propagation etc),
2816       e.g. in EXPLAIN EXTENDED or EXPLAIN FORMAT=JSON.
2817       As it's not possible to print as a function with 2 arguments any more,
2818       do it in the CASE style.
2819     */
2820     str->append(STRING_WITH_LEN("(case when "));
2821     args[0]->print(str, query_type);
2822     str->append(STRING_WITH_LEN(" = "));
2823     args[1]->print(str, query_type);
2824     str->append(STRING_WITH_LEN(" then NULL else "));
2825     args[2]->print(str, query_type);
2826     str->append(STRING_WITH_LEN(" end)"));
2827   }
2828 }
2829 
2830 
compare()2831 int Item_func_nullif::compare()
2832 {
2833   if (m_cache)
2834     m_cache->cache_value();
2835   return cmp.compare();
2836 }
2837 
2838 /**
2839   @note
2840   Note that we have to evaluate the first argument twice as the compare
2841   may have been done with a different type than return value
2842   @return
2843     NULL  if arguments are equal
2844   @return
2845     the first argument if not equal
2846 */
2847 
2848 double
real_op()2849 Item_func_nullif::real_op()
2850 {
2851   DBUG_ASSERT(fixed == 1);
2852   double value;
2853   if (!compare())
2854   {
2855     null_value=1;
2856     return 0.0;
2857   }
2858   value= args[2]->val_real();
2859   null_value= args[2]->null_value;
2860   return value;
2861 }
2862 
2863 longlong
int_op()2864 Item_func_nullif::int_op()
2865 {
2866   DBUG_ASSERT(fixed == 1);
2867   longlong value;
2868   if (!compare())
2869   {
2870     null_value=1;
2871     return 0;
2872   }
2873   value= args[2]->val_int();
2874   null_value= args[2]->null_value;
2875   return value;
2876 }
2877 
2878 String *
str_op(String * str)2879 Item_func_nullif::str_op(String *str)
2880 {
2881   DBUG_ASSERT(fixed == 1);
2882   String *res;
2883   if (!compare())
2884   {
2885     null_value=1;
2886     return 0;
2887   }
2888   res= args[2]->val_str(str);
2889   null_value= args[2]->null_value;
2890   return res;
2891 }
2892 
2893 
2894 my_decimal *
decimal_op(my_decimal * decimal_value)2895 Item_func_nullif::decimal_op(my_decimal * decimal_value)
2896 {
2897   DBUG_ASSERT(fixed == 1);
2898   my_decimal *res;
2899   if (!compare())
2900   {
2901     null_value=1;
2902     return 0;
2903   }
2904   res= args[2]->val_decimal(decimal_value);
2905   null_value= args[2]->null_value;
2906   return res;
2907 }
2908 
2909 
2910 bool
date_op(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)2911 Item_func_nullif::date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
2912 {
2913   DBUG_ASSERT(fixed == 1);
2914   if (!compare())
2915     return (null_value= true);
2916   Datetime_truncation_not_needed dt(thd, args[2], fuzzydate);
2917   return (null_value= dt.copy_to_mysql_time(ltime, mysql_timestamp_type()));
2918 }
2919 
2920 
2921 bool
time_op(THD * thd,MYSQL_TIME * ltime)2922 Item_func_nullif::time_op(THD *thd, MYSQL_TIME *ltime)
2923 {
2924   DBUG_ASSERT(fixed == 1);
2925   if (!compare())
2926     return (null_value= true);
2927   return (null_value= Time(thd, args[2]).copy_to_mysql_time(ltime));
2928 
2929 }
2930 
2931 
2932 bool
native_op(THD * thd,Native * to)2933 Item_func_nullif::native_op(THD *thd, Native *to)
2934 {
2935   DBUG_ASSERT(fixed == 1);
2936   if (!compare())
2937     return (null_value= true);
2938   return val_native_with_conversion_from_item(thd, args[2], to, type_handler());
2939 }
2940 
2941 
2942 bool
is_null()2943 Item_func_nullif::is_null()
2944 {
2945   return (null_value= (!compare() ? 1 : args[2]->is_null()));
2946 }
2947 
reorder_args(uint start)2948 void Item_func_case::reorder_args(uint start)
2949 {
2950   /*
2951     Reorder args, to have at first the optional CASE expression, then all WHEN
2952     expressions, then all THEN expressions. And the optional ELSE expression
2953     at the end.
2954 
2955     We reorder an even number of arguments, starting from start.
2956   */
2957   uint count = (arg_count - start) / 2;
2958   const size_t size= sizeof(Item*) * count * 2;
2959   Item **arg_buffer= (Item **)my_safe_alloca(size);
2960   memcpy(arg_buffer, &args[start], size);
2961   for (uint i= 0; i < count; i++)
2962   {
2963     args[start + i]= arg_buffer[i*2];
2964     args[start + i + count]= arg_buffer[i*2 + 1];
2965   }
2966   my_safe_afree(arg_buffer, size);
2967 }
2968 
2969 
2970 
2971 /**
2972     Find and return matching items for CASE or ELSE item if all compares
2973     are failed or NULL if ELSE item isn't defined.
2974 
2975   IMPLEMENTATION
2976     In order to do correct comparisons of the CASE expression (the expression
2977     between CASE and the first WHEN) with each WHEN expression several
2978     comparators are used. One for each result type. CASE expression can be
2979     evaluated up to # of different result types are used. To check whether
2980     the CASE expression already was evaluated for a particular result type
2981     a bit mapped variable value_added_map is used. Result types are mapped
2982     to it according to their int values i.e. STRING_RESULT is mapped to bit
2983     0, REAL_RESULT to bit 1, so on.
2984 
2985   @retval
2986     NULL  Nothing found and there is no ELSE expression defined
2987   @retval
2988     item  Found item or ELSE item if defined and all comparisons are
2989            failed
2990 */
2991 
find_item()2992 Item *Item_func_case_searched::find_item()
2993 {
2994   uint count= when_count();
2995   for (uint i= 0 ; i < count ; i++)
2996   {
2997     if (args[i]->val_bool())
2998       return args[i + count];
2999   }
3000   Item **pos= Item_func_case_searched::else_expr_addr();
3001   return pos ? pos[0] : 0;
3002 }
3003 
3004 
find_item()3005 Item *Item_func_case_simple::find_item()
3006 {
3007   /* Compare every WHEN argument with it and return the first match */
3008   uint idx;
3009   if (!Predicant_to_list_comparator::cmp(this, &idx, NULL))
3010     return args[idx + when_count()];
3011   Item **pos= Item_func_case_simple::else_expr_addr();
3012   return pos ? pos[0] : 0;
3013 }
3014 
3015 
find_item()3016 Item *Item_func_decode_oracle::find_item()
3017 {
3018   uint idx;
3019   if (!Predicant_to_list_comparator::cmp_nulls_equal(current_thd, this, &idx))
3020     return args[idx + when_count()];
3021   Item **pos= Item_func_decode_oracle::else_expr_addr();
3022   return pos ? pos[0] : 0;
3023 }
3024 
3025 
str_op(String * str)3026 String *Item_func_case::str_op(String *str)
3027 {
3028   DBUG_ASSERT(fixed == 1);
3029   String *res;
3030   Item *item= find_item();
3031 
3032   if (!item)
3033   {
3034     null_value=1;
3035     return 0;
3036   }
3037   null_value= 0;
3038   if (!(res=item->val_str(str)))
3039     null_value= 1;
3040   return res;
3041 }
3042 
3043 
int_op()3044 longlong Item_func_case::int_op()
3045 {
3046   DBUG_ASSERT(fixed == 1);
3047   Item *item= find_item();
3048   longlong res;
3049 
3050   if (!item)
3051   {
3052     null_value=1;
3053     return 0;
3054   }
3055   res=item->val_int();
3056   null_value=item->null_value;
3057   return res;
3058 }
3059 
real_op()3060 double Item_func_case::real_op()
3061 {
3062   DBUG_ASSERT(fixed == 1);
3063   Item *item= find_item();
3064   double res;
3065 
3066   if (!item)
3067   {
3068     null_value=1;
3069     return 0;
3070   }
3071   res= item->val_real();
3072   null_value=item->null_value;
3073   return res;
3074 }
3075 
3076 
decimal_op(my_decimal * decimal_value)3077 my_decimal *Item_func_case::decimal_op(my_decimal *decimal_value)
3078 {
3079   DBUG_ASSERT(fixed == 1);
3080   Item *item= find_item();
3081   my_decimal *res;
3082 
3083   if (!item)
3084   {
3085     null_value=1;
3086     return 0;
3087   }
3088 
3089   res= item->val_decimal(decimal_value);
3090   null_value= item->null_value;
3091   return res;
3092 }
3093 
3094 
date_op(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)3095 bool Item_func_case::date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
3096 {
3097   DBUG_ASSERT(fixed == 1);
3098   Item *item= find_item();
3099   if (!item)
3100     return (null_value= true);
3101   Datetime_truncation_not_needed dt(thd, item, fuzzydate);
3102   return (null_value= dt.copy_to_mysql_time(ltime, mysql_timestamp_type()));
3103 }
3104 
3105 
time_op(THD * thd,MYSQL_TIME * ltime)3106 bool Item_func_case::time_op(THD *thd, MYSQL_TIME *ltime)
3107 {
3108   DBUG_ASSERT(fixed == 1);
3109   Item *item= find_item();
3110   if (!item)
3111     return (null_value= true);
3112   return (null_value= Time(thd, item).copy_to_mysql_time(ltime));
3113 }
3114 
3115 
native_op(THD * thd,Native * to)3116 bool Item_func_case::native_op(THD *thd, Native *to)
3117 {
3118   DBUG_ASSERT(fixed == 1);
3119   Item *item= find_item();
3120   if (!item)
3121     return (null_value= true);
3122   return val_native_with_conversion_from_item(thd, item, to, type_handler());
3123 }
3124 
3125 
fix_fields(THD * thd,Item ** ref)3126 bool Item_func_case::fix_fields(THD *thd, Item **ref)
3127 {
3128   bool res= Item_func::fix_fields(thd, ref);
3129 
3130   Item **pos= else_expr_addr();
3131   if (!pos || pos[0]->maybe_null)
3132     maybe_null= 1;
3133   return res;
3134 }
3135 
3136 
3137 /**
3138   Check if (*place) and new_value points to different Items and call
3139   THD::change_item_tree() if needed.
3140 */
3141 
propagate_and_change_item_tree(THD * thd,Item ** place,COND_EQUAL * cond,const Item::Context & ctx)3142 static void propagate_and_change_item_tree(THD *thd, Item **place,
3143                                            COND_EQUAL *cond,
3144                                            const Item::Context &ctx)
3145 {
3146   Item *new_value= (*place)->propagate_equal_fields(thd, ctx, cond);
3147   if (new_value && *place != new_value)
3148     thd->change_item_tree(place, new_value);
3149 }
3150 
3151 
prepare_predicant_and_values(THD * thd,uint * found_types,bool nulls_equal)3152 bool Item_func_case_simple::prepare_predicant_and_values(THD *thd,
3153                                                          uint *found_types,
3154                                                          bool nulls_equal)
3155 {
3156   bool have_null= false;
3157   uint type_cnt;
3158   Type_handler_hybrid_field_type tmp;
3159   uint ncases= when_count();
3160   add_predicant(this, 0);
3161   for (uint i= 0 ; i < ncases; i++)
3162   {
3163     if (nulls_equal ?
3164         add_value("case..when", this, i + 1) :
3165         add_value_skip_null("case..when", this, i + 1, &have_null))
3166       return true;
3167   }
3168   all_values_added(&tmp, &type_cnt, &m_found_types);
3169 #ifndef DBUG_OFF
3170   Predicant_to_list_comparator::debug_print(thd);
3171 #endif
3172   return false;
3173 }
3174 
3175 
fix_length_and_dec()3176 bool Item_func_case_searched::fix_length_and_dec()
3177 {
3178   THD *thd= current_thd;
3179   return aggregate_then_and_else_arguments(thd, when_count());
3180 }
3181 
3182 
fix_length_and_dec()3183 bool Item_func_case_simple::fix_length_and_dec()
3184 {
3185   THD *thd= current_thd;
3186   return (aggregate_then_and_else_arguments(thd, when_count() + 1) ||
3187           aggregate_switch_and_when_arguments(thd, false));
3188 }
3189 
3190 
fix_length_and_dec()3191 bool Item_func_decode_oracle::fix_length_and_dec()
3192 {
3193   THD *thd= current_thd;
3194   return (aggregate_then_and_else_arguments(thd, when_count() + 1) ||
3195           aggregate_switch_and_when_arguments(thd, true));
3196 }
3197 
3198 
3199 /*
3200   Aggregate all THEN and ELSE expression types
3201   and collations when string result
3202 
3203   @param THD       - current thd
3204   @param start     - an element in args to start aggregating from
3205 */
aggregate_then_and_else_arguments(THD * thd,uint start)3206 bool Item_func_case::aggregate_then_and_else_arguments(THD *thd, uint start)
3207 {
3208   if (aggregate_for_result(func_name(), args + start, arg_count - start, true))
3209     return true;
3210 
3211   if (fix_attributes(args + start, arg_count - start))
3212     return true;
3213 
3214   return false;
3215 }
3216 
3217 
3218 /*
3219   Aggregate the predicant expression and all WHEN expression types
3220   and collations when string comparison
3221 */
aggregate_switch_and_when_arguments(THD * thd,bool nulls_eq)3222 bool Item_func_case_simple::aggregate_switch_and_when_arguments(THD *thd,
3223                                                                 bool nulls_eq)
3224 {
3225   uint ncases= when_count();
3226   m_found_types= 0;
3227   if (prepare_predicant_and_values(thd, &m_found_types, nulls_eq))
3228   {
3229     /*
3230       If Predicant_to_list_comparator() fails to prepare components,
3231       it must put an error into the diagnostics area. This is needed
3232       to make fix_fields() catches such errors.
3233     */
3234     DBUG_ASSERT(thd->is_error());
3235     return true;
3236   }
3237 
3238   if (!(m_found_types= collect_cmp_types(args, ncases + 1)))
3239     return true;
3240 
3241   if (m_found_types & (1U << STRING_RESULT))
3242   {
3243     /*
3244       If we'll do string comparison, we also need to aggregate
3245       character set and collation for first/WHEN items and
3246       install converters for some of them to cmp_collation when necessary.
3247       This is done because cmp_item compatators cannot compare
3248       strings in two different character sets.
3249       Some examples when we install converters:
3250 
3251       1. Converter installed for the first expression:
3252 
3253          CASE         latin1_item              WHEN utf16_item THEN ... END
3254 
3255       is replaced to:
3256 
3257          CASE CONVERT(latin1_item USING utf16) WHEN utf16_item THEN ... END
3258 
3259       2. Converter installed for the left WHEN item:
3260 
3261         CASE utf16_item WHEN         latin1_item              THEN ... END
3262 
3263       is replaced to:
3264 
3265          CASE utf16_item WHEN CONVERT(latin1_item USING utf16) THEN ... END
3266     */
3267     if (agg_arg_charsets_for_comparison(cmp_collation, args, ncases + 1))
3268       return true;
3269   }
3270 
3271   if (make_unique_cmp_items(thd, cmp_collation.collation))
3272     return true;
3273 
3274   return false;
3275 }
3276 
3277 
propagate_equal_fields(THD * thd,const Context & ctx,COND_EQUAL * cond)3278 Item* Item_func_case_simple::propagate_equal_fields(THD *thd,
3279                                                     const Context &ctx,
3280                                                     COND_EQUAL *cond)
3281 {
3282   const Type_handler *first_expr_cmp_handler;
3283 
3284   first_expr_cmp_handler= args[0]->type_handler_for_comparison();
3285   /*
3286     Cannot replace the CASE (the switch) argument if
3287     there are multiple comparison types were found, or found a single
3288     comparison type that is not equal to args[0]->cmp_type().
3289 
3290     - Example: multiple comparison types, can't propagate:
3291         WHERE CASE str_column
3292               WHEN 'string' THEN TRUE
3293               WHEN 1 THEN TRUE
3294               ELSE FALSE END;
3295 
3296     - Example: a single incompatible comparison type, can't propagate:
3297         WHERE CASE str_column
3298               WHEN DATE'2001-01-01' THEN TRUE
3299               ELSE FALSE END;
3300 
3301     - Example: a single incompatible comparison type, can't propagate:
3302         WHERE CASE str_column
3303               WHEN 1 THEN TRUE
3304               ELSE FALSE END;
3305 
3306     - Example: a single compatible comparison type, ok to propagate:
3307         WHERE CASE str_column
3308               WHEN 'str1' THEN TRUE
3309               WHEN 'str2' THEN TRUE
3310               ELSE FALSE END;
3311   */
3312   if (m_found_types == (1UL << first_expr_cmp_handler->cmp_type()))
3313     propagate_and_change_item_tree(thd, &args[0], cond,
3314       Context(ANY_SUBST, first_expr_cmp_handler, cmp_collation.collation));
3315 
3316   /*
3317     These arguments are in comparison.
3318     Allow invariants of the same value during propagation.
3319     Note, as we pass ANY_SUBST, none of the WHEN arguments will be
3320     replaced to zero-filled constants (only IDENTITY_SUBST allows this).
3321     Such a change for WHEN arguments would require rebuilding cmp_items.
3322   */
3323   uint i, count= when_count();
3324   for (i= 1; i <= count; i++)
3325   {
3326     Type_handler_hybrid_field_type tmp(first_expr_cmp_handler);
3327     if (!tmp.aggregate_for_comparison(args[i]->type_handler_for_comparison()))
3328       propagate_and_change_item_tree(thd, &args[i], cond,
3329         Context(ANY_SUBST, tmp.type_handler(), cmp_collation.collation));
3330   }
3331 
3332   // THEN and ELSE arguments (they are not in comparison)
3333   for (; i < arg_count; i++)
3334     propagate_and_change_item_tree(thd, &args[i], cond, Context_identity());
3335 
3336   return this;
3337 }
3338 
3339 
print_when_then_arguments(String * str,enum_query_type query_type,Item ** items,uint count)3340 inline void Item_func_case::print_when_then_arguments(String *str,
3341                                                       enum_query_type
3342                                                       query_type,
3343                                                       Item **items, uint count)
3344 {
3345   for (uint i= 0; i < count; i++)
3346   {
3347     str->append(STRING_WITH_LEN("when "));
3348     items[i]->print(str, query_type);
3349     str->append(STRING_WITH_LEN(" then "));
3350     items[i + count]->print(str, query_type);
3351     str->append(' ');
3352   }
3353 }
3354 
3355 
print_else_argument(String * str,enum_query_type query_type,Item * item)3356 inline void Item_func_case::print_else_argument(String *str,
3357                                                 enum_query_type query_type,
3358                                                 Item *item)
3359 {
3360   str->append(STRING_WITH_LEN("else "));
3361   item->print(str, query_type);
3362   str->append(' ');
3363 }
3364 
3365 
print(String * str,enum_query_type query_type)3366 void Item_func_case_searched::print(String *str, enum_query_type query_type)
3367 {
3368   Item **pos;
3369   str->append(STRING_WITH_LEN("case "));
3370   print_when_then_arguments(str, query_type, &args[0], when_count());
3371   if ((pos= Item_func_case_searched::else_expr_addr()))
3372     print_else_argument(str, query_type, pos[0]);
3373   str->append(STRING_WITH_LEN("end"));
3374 }
3375 
3376 
print(String * str,enum_query_type query_type)3377 void Item_func_case_simple::print(String *str, enum_query_type query_type)
3378 {
3379   Item **pos;
3380   str->append(STRING_WITH_LEN("case "));
3381   args[0]->print_parenthesised(str, query_type, precedence());
3382   str->append(' ');
3383   print_when_then_arguments(str, query_type, &args[1], when_count());
3384   if ((pos= Item_func_case_simple::else_expr_addr()))
3385     print_else_argument(str, query_type, pos[0]);
3386   str->append(STRING_WITH_LEN("end"));
3387 }
3388 
3389 
print(String * str,enum_query_type query_type)3390 void Item_func_decode_oracle::print(String *str, enum_query_type query_type)
3391 {
3392   str->append(func_name());
3393   str->append('(');
3394   args[0]->print(str, query_type);
3395   for (uint i= 1, count= when_count() ; i <= count; i++)
3396   {
3397     str->append(',');
3398     args[i]->print(str, query_type);
3399     str->append(',');
3400     args[i+count]->print(str, query_type);
3401   }
3402   Item **else_expr= Item_func_case_simple::else_expr_addr();
3403   if (else_expr)
3404   {
3405     str->append(',');
3406     (*else_expr)->print(str, query_type);
3407   }
3408   str->append(')');
3409 }
3410 
3411 
3412 /**
3413   Coalesce - return first not NULL argument.
3414 */
3415 
str_op(String * str)3416 String *Item_func_coalesce::str_op(String *str)
3417 {
3418   DBUG_ASSERT(fixed == 1);
3419   null_value=0;
3420   for (uint i=0 ; i < arg_count ; i++)
3421   {
3422     String *res;
3423     if ((res=args[i]->val_str(str)))
3424       return res;
3425   }
3426   null_value=1;
3427   return 0;
3428 }
3429 
int_op()3430 longlong Item_func_coalesce::int_op()
3431 {
3432   DBUG_ASSERT(fixed == 1);
3433   null_value=0;
3434   for (uint i=0 ; i < arg_count ; i++)
3435   {
3436     longlong res=args[i]->val_int();
3437     if (!args[i]->null_value)
3438       return res;
3439   }
3440   null_value=1;
3441   return 0;
3442 }
3443 
real_op()3444 double Item_func_coalesce::real_op()
3445 {
3446   DBUG_ASSERT(fixed == 1);
3447   null_value=0;
3448   for (uint i=0 ; i < arg_count ; i++)
3449   {
3450     double res= args[i]->val_real();
3451     if (!args[i]->null_value)
3452       return res;
3453   }
3454   null_value=1;
3455   return 0;
3456 }
3457 
3458 
date_op(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)3459 bool Item_func_coalesce::date_op(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
3460 {
3461   DBUG_ASSERT(fixed == 1);
3462   for (uint i= 0; i < arg_count; i++)
3463   {
3464     Datetime_truncation_not_needed dt(thd, args[i],
3465                                       fuzzydate & ~TIME_FUZZY_DATES);
3466     if (!dt.copy_to_mysql_time(ltime, mysql_timestamp_type()))
3467       return (null_value= false);
3468   }
3469   return (null_value= true);
3470 }
3471 
3472 
time_op(THD * thd,MYSQL_TIME * ltime)3473 bool Item_func_coalesce::time_op(THD *thd, MYSQL_TIME *ltime)
3474 {
3475   DBUG_ASSERT(fixed == 1);
3476   for (uint i= 0; i < arg_count; i++)
3477   {
3478     if (!Time(thd, args[i]).copy_to_mysql_time(ltime))
3479       return (null_value= false);
3480   }
3481   return (null_value= true);
3482 }
3483 
3484 
native_op(THD * thd,Native * to)3485 bool Item_func_coalesce::native_op(THD *thd, Native *to)
3486 {
3487   DBUG_ASSERT(fixed == 1);
3488   for (uint i= 0; i < arg_count; i++)
3489   {
3490     if (!val_native_with_conversion_from_item(thd, args[i], to, type_handler()))
3491       return false;
3492   }
3493   return (null_value= true);
3494 }
3495 
3496 
decimal_op(my_decimal * decimal_value)3497 my_decimal *Item_func_coalesce::decimal_op(my_decimal *decimal_value)
3498 {
3499   DBUG_ASSERT(fixed == 1);
3500   null_value= 0;
3501   for (uint i= 0; i < arg_count; i++)
3502   {
3503     my_decimal *res= args[i]->val_decimal(decimal_value);
3504     if (!args[i]->null_value)
3505       return res;
3506   }
3507   null_value=1;
3508   return 0;
3509 }
3510 
3511 
3512 /****************************************************************************
3513  Classes and function for the IN operator
3514 ****************************************************************************/
3515 
3516 /*
3517   Determine which of the signed longlong arguments is bigger
3518 
3519   SYNOPSIS
3520     cmp_longs()
3521       a_val     left argument
3522       b_val     right argument
3523 
3524   DESCRIPTION
3525     This function will compare two signed longlong arguments
3526     and will return -1, 0, or 1 if left argument is smaller than,
3527     equal to or greater than the right argument.
3528 
3529   RETURN VALUE
3530     -1          left argument is smaller than the right argument.
3531     0           left argument is equal to the right argument.
3532     1           left argument is greater than the right argument.
3533 */
cmp_longs(longlong a_val,longlong b_val)3534 static inline int cmp_longs (longlong a_val, longlong b_val)
3535 {
3536   return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3537 }
3538 
3539 
3540 /*
3541   Determine which of the unsigned longlong arguments is bigger
3542 
3543   SYNOPSIS
3544     cmp_ulongs()
3545       a_val     left argument
3546       b_val     right argument
3547 
3548   DESCRIPTION
3549     This function will compare two unsigned longlong arguments
3550     and will return -1, 0, or 1 if left argument is smaller than,
3551     equal to or greater than the right argument.
3552 
3553   RETURN VALUE
3554     -1          left argument is smaller than the right argument.
3555     0           left argument is equal to the right argument.
3556     1           left argument is greater than the right argument.
3557 */
cmp_ulongs(ulonglong a_val,ulonglong b_val)3558 static inline int cmp_ulongs (ulonglong a_val, ulonglong b_val)
3559 {
3560   return a_val < b_val ? -1 : a_val == b_val ? 0 : 1;
3561 }
3562 
3563 
3564 /*
3565   Compare two integers in IN value list format (packed_longlong)
3566 
3567   SYNOPSIS
3568     cmp_longlong()
3569       cmp_arg   an argument passed to the calling function (my_qsort2)
3570       a         left argument
3571       b         right argument
3572 
3573   DESCRIPTION
3574     This function will compare two integer arguments in the IN value list
3575     format and will return -1, 0, or 1 if left argument is smaller than,
3576     equal to or greater than the right argument.
3577     It's used in sorting the IN values list and finding an element in it.
3578     Depending on the signedness of the arguments cmp_longlong() will
3579     compare them as either signed (using cmp_longs()) or unsigned (using
3580     cmp_ulongs()).
3581 
3582   RETURN VALUE
3583     -1          left argument is smaller than the right argument.
3584     0           left argument is equal to the right argument.
3585     1           left argument is greater than the right argument.
3586 */
cmp_longlong(void * cmp_arg,in_longlong::packed_longlong * a,in_longlong::packed_longlong * b)3587 int cmp_longlong(void *cmp_arg,
3588                  in_longlong::packed_longlong *a,
3589                  in_longlong::packed_longlong *b)
3590 {
3591   if (a->unsigned_flag != b->unsigned_flag)
3592   {
3593     /*
3594       One of the args is unsigned and is too big to fit into the
3595       positive signed range. Report no match.
3596     */
3597     if ((a->unsigned_flag && ((ulonglong) a->val) > (ulonglong) LONGLONG_MAX)
3598         ||
3599         (b->unsigned_flag && ((ulonglong) b->val) > (ulonglong) LONGLONG_MAX))
3600       return a->unsigned_flag ? 1 : -1;
3601     /*
3602       Although the signedness differs both args can fit into the signed
3603       positive range. Make them signed and compare as usual.
3604     */
3605     return cmp_longs(a->val, b->val);
3606   }
3607   if (a->unsigned_flag)
3608     return cmp_ulongs((ulonglong) a->val, (ulonglong) b->val);
3609   return cmp_longs(a->val, b->val);
3610 }
3611 
cmp_double(void * cmp_arg,double * a,double * b)3612 static int cmp_double(void *cmp_arg, double *a,double *b)
3613 {
3614   return *a < *b ? -1 : *a == *b ? 0 : 1;
3615 }
3616 
cmp_row(void * cmp_arg,cmp_item_row * a,cmp_item_row * b)3617 static int cmp_row(void *cmp_arg, cmp_item_row *a, cmp_item_row *b)
3618 {
3619   return a->compare(b);
3620 }
3621 
3622 
cmp_decimal(void * cmp_arg,my_decimal * a,my_decimal * b)3623 static int cmp_decimal(void *cmp_arg, my_decimal *a, my_decimal *b)
3624 {
3625   /*
3626     We need call of fixing buffer pointer, because fast sort just copy
3627     decimal buffers in memory and pointers left pointing on old buffer place
3628   */
3629   a->fix_buffer_pointer();
3630   b->fix_buffer_pointer();
3631   return my_decimal_cmp(a, b);
3632 }
3633 
3634 
find(Item * item)3635 bool in_vector::find(Item *item)
3636 {
3637   uchar *result=get_value(item);
3638   if (!result || !used_count)
3639     return false;				// Null value
3640 
3641   uint start,end;
3642   start=0; end=used_count-1;
3643   while (start != end)
3644   {
3645     uint mid=(start+end+1)/2;
3646     int res;
3647     if ((res=(*compare)(collation, base+mid*size, result)) == 0)
3648       return true;
3649     if (res < 0)
3650       start=mid;
3651     else
3652       end=mid-1;
3653   }
3654   return ((*compare)(collation, base+start*size, result) == 0);
3655 }
3656 
in_string(THD * thd,uint elements,qsort2_cmp cmp_func,CHARSET_INFO * cs)3657 in_string::in_string(THD *thd, uint elements, qsort2_cmp cmp_func,
3658                      CHARSET_INFO *cs)
3659   :in_vector(thd, elements, sizeof(String), cmp_func, cs),
3660    tmp(buff, sizeof(buff), &my_charset_bin)
3661 {}
3662 
~in_string()3663 in_string::~in_string()
3664 {
3665   if (base)
3666   {
3667     // base was allocated on THD::mem_root => following is OK
3668     for (uint i=0 ; i < count ; i++)
3669       ((String*) base)[i].free();
3670   }
3671 }
3672 
set(uint pos,Item * item)3673 void in_string::set(uint pos,Item *item)
3674 {
3675   String *str=((String*) base)+pos;
3676   String *res=item->val_str(str);
3677   if (res && res != str)
3678   {
3679     if (res->uses_buffer_owned_by(str))
3680       res->copy();
3681     if (item->type() == Item::FUNC_ITEM)
3682       str->copy(*res);
3683     else
3684       *str= *res;
3685   }
3686   if (!str->charset())
3687   {
3688     CHARSET_INFO *cs;
3689     if (!(cs= item->collation.collation))
3690       cs= &my_charset_bin;		// Should never happen for STR items
3691     str->set_charset(cs);
3692   }
3693 }
3694 
3695 
get_value(Item * item)3696 uchar *in_string::get_value(Item *item)
3697 {
3698   return (uchar*) item->val_str(&tmp);
3699 }
3700 
create_item(THD * thd)3701 Item *in_string::create_item(THD *thd)
3702 {
3703   return new (thd->mem_root) Item_string_for_in_vector(thd, collation);
3704 }
3705 
3706 
in_row(THD * thd,uint elements,Item * item)3707 in_row::in_row(THD *thd, uint elements, Item * item)
3708 {
3709   base= (char*) new (thd->mem_root) cmp_item_row[count= elements];
3710   size= sizeof(cmp_item_row);
3711   compare= (qsort2_cmp) cmp_row;
3712   /*
3713     We need to reset these as otherwise we will call sort() with
3714     uninitialized (even if not used) elements
3715   */
3716   used_count= elements;
3717   collation= 0;
3718 }
3719 
~in_row()3720 in_row::~in_row()
3721 {
3722   if (base)
3723     delete [] (cmp_item_row*) base;
3724 }
3725 
get_value(Item * item)3726 uchar *in_row::get_value(Item *item)
3727 {
3728   tmp.store_value(item);
3729   if (item->is_null())
3730     return 0;
3731   return (uchar *)&tmp;
3732 }
3733 
set(uint pos,Item * item)3734 void in_row::set(uint pos, Item *item)
3735 {
3736   DBUG_ENTER("in_row::set");
3737   DBUG_PRINT("enter", ("pos: %u  item: %p", pos,item));
3738   ((cmp_item_row*) base)[pos].store_value_by_template(current_thd, &tmp, item);
3739   DBUG_VOID_RETURN;
3740 }
3741 
in_longlong(THD * thd,uint elements)3742 in_longlong::in_longlong(THD *thd, uint elements)
3743   :in_vector(thd, elements, sizeof(packed_longlong),
3744              (qsort2_cmp) cmp_longlong, 0)
3745 {}
3746 
set(uint pos,Item * item)3747 void in_longlong::set(uint pos,Item *item)
3748 {
3749   struct packed_longlong *buff= &((packed_longlong*) base)[pos];
3750 
3751   buff->val= item->val_int();
3752   buff->unsigned_flag= item->unsigned_flag;
3753 }
3754 
get_value(Item * item)3755 uchar *in_longlong::get_value(Item *item)
3756 {
3757   tmp.val= item->val_int();
3758   if (item->null_value)
3759     return 0;
3760   tmp.unsigned_flag= item->unsigned_flag;
3761   return (uchar*) &tmp;
3762 }
3763 
create_item(THD * thd)3764 Item *in_longlong::create_item(THD *thd)
3765 {
3766   /*
3767      We're created a signed INT, this may not be correct in
3768      general case (see BUG#19342).
3769   */
3770   return new (thd->mem_root) Item_int(thd, (longlong)0);
3771 }
3772 
3773 
cmp_timestamp(void * cmp_arg,Timestamp_or_zero_datetime * a,Timestamp_or_zero_datetime * b)3774 static int cmp_timestamp(void *cmp_arg,
3775                          Timestamp_or_zero_datetime *a,
3776                          Timestamp_or_zero_datetime *b)
3777 {
3778   return a->cmp(*b);
3779 }
3780 
3781 
in_timestamp(THD * thd,uint elements)3782 in_timestamp::in_timestamp(THD *thd, uint elements)
3783   :in_vector(thd, elements, sizeof(Value), (qsort2_cmp) cmp_timestamp, 0)
3784 {}
3785 
3786 
set(uint pos,Item * item)3787 void in_timestamp::set(uint pos, Item *item)
3788 {
3789   Timestamp_or_zero_datetime *buff= &((Timestamp_or_zero_datetime *) base)[pos];
3790   Timestamp_or_zero_datetime_native_null native(current_thd, item, true);
3791   if (native.is_null())
3792     *buff= Timestamp_or_zero_datetime();
3793   else
3794     *buff= Timestamp_or_zero_datetime(native);
3795 }
3796 
3797 
get_value(Item * item)3798 uchar *in_timestamp::get_value(Item *item)
3799 {
3800   Timestamp_or_zero_datetime_native_null native(current_thd, item, true);
3801   if (native.is_null())
3802     return 0;
3803   tmp= Timestamp_or_zero_datetime(native);
3804   return (uchar*) &tmp;
3805 }
3806 
3807 
create_item(THD * thd)3808 Item *in_timestamp::create_item(THD *thd)
3809 {
3810   return new (thd->mem_root) Item_timestamp_literal(thd);
3811 }
3812 
3813 
value_to_item(uint pos,Item * item)3814 void in_timestamp::value_to_item(uint pos, Item *item)
3815 {
3816   const Timestamp_or_zero_datetime &buff= (((Timestamp_or_zero_datetime*) base)[pos]);
3817   static_cast<Item_timestamp_literal*>(item)->set_value(buff);
3818 }
3819 
3820 
set(uint pos,Item * item)3821 void in_datetime::set(uint pos,Item *item)
3822 {
3823   struct packed_longlong *buff= &((packed_longlong*) base)[pos];
3824 
3825   buff->val= item->val_datetime_packed(current_thd);
3826   buff->unsigned_flag= 1L;
3827 }
3828 
set(uint pos,Item * item)3829 void in_time::set(uint pos,Item *item)
3830 {
3831   struct packed_longlong *buff= &((packed_longlong*) base)[pos];
3832 
3833   buff->val= item->val_time_packed(current_thd);
3834   buff->unsigned_flag= 1L;
3835 }
3836 
get_value(Item * item)3837 uchar *in_datetime::get_value(Item *item)
3838 {
3839   tmp.val= item->val_datetime_packed(current_thd);
3840   if (item->null_value)
3841     return 0;
3842   tmp.unsigned_flag= 1L;
3843   return (uchar*) &tmp;
3844 }
3845 
get_value(Item * item)3846 uchar *in_time::get_value(Item *item)
3847 {
3848   tmp.val= item->val_time_packed(current_thd);
3849   if (item->null_value)
3850     return 0;
3851   tmp.unsigned_flag= 1L;
3852   return (uchar*) &tmp;
3853 }
3854 
create_item(THD * thd)3855 Item *in_temporal::create_item(THD *thd)
3856 {
3857   return new (thd->mem_root) Item_datetime(thd);
3858 }
3859 
3860 
in_double(THD * thd,uint elements)3861 in_double::in_double(THD *thd, uint elements)
3862   :in_vector(thd, elements, sizeof(double), (qsort2_cmp) cmp_double, 0)
3863 {}
3864 
set(uint pos,Item * item)3865 void in_double::set(uint pos,Item *item)
3866 {
3867   ((double*) base)[pos]= item->val_real();
3868 }
3869 
get_value(Item * item)3870 uchar *in_double::get_value(Item *item)
3871 {
3872   tmp= item->val_real();
3873   if (item->null_value)
3874     return 0;					/* purecov: inspected */
3875   return (uchar*) &tmp;
3876 }
3877 
create_item(THD * thd)3878 Item *in_double::create_item(THD *thd)
3879 {
3880   return new (thd->mem_root) Item_float(thd, 0.0, 0);
3881 }
3882 
3883 
in_decimal(THD * thd,uint elements)3884 in_decimal::in_decimal(THD *thd, uint elements)
3885   :in_vector(thd, elements, sizeof(my_decimal), (qsort2_cmp) cmp_decimal, 0)
3886 {}
3887 
3888 
set(uint pos,Item * item)3889 void in_decimal::set(uint pos, Item *item)
3890 {
3891   /* as far as 'item' is constant, we can store reference on my_decimal */
3892   my_decimal *dec= ((my_decimal *)base) + pos;
3893   dec->len= DECIMAL_BUFF_LENGTH;
3894   dec->fix_buffer_pointer();
3895   my_decimal *res= item->val_decimal(dec);
3896   /* if item->val_decimal() is evaluated to NULL then res == 0 */
3897   if (!item->null_value && res != dec)
3898     my_decimal2decimal(res, dec);
3899 }
3900 
3901 
get_value(Item * item)3902 uchar *in_decimal::get_value(Item *item)
3903 {
3904   my_decimal *result= item->val_decimal(&val);
3905   if (item->null_value)
3906     return 0;
3907   return (uchar *)result;
3908 }
3909 
create_item(THD * thd)3910 Item *in_decimal::create_item(THD *thd)
3911 {
3912   return new (thd->mem_root) Item_decimal(thd, 0, FALSE);
3913 }
3914 
3915 
alloc_comparators(THD * thd,uint nargs)3916 bool Predicant_to_list_comparator::alloc_comparators(THD *thd, uint nargs)
3917 {
3918   size_t nbytes= sizeof(Predicant_to_value_comparator) * nargs;
3919   if (!(m_comparators= (Predicant_to_value_comparator *) thd->alloc(nbytes)))
3920     return true;
3921   memset(m_comparators, 0, nbytes);
3922   return false;
3923 }
3924 
3925 
add_value(const char * funcname,Item_args * args,uint value_index)3926 bool Predicant_to_list_comparator::add_value(const char *funcname,
3927                                              Item_args *args,
3928                                              uint value_index)
3929 {
3930   DBUG_ASSERT(m_predicant_index < args->argument_count());
3931   DBUG_ASSERT(value_index < args->argument_count());
3932   Type_handler_hybrid_field_type tmp;
3933   Item *tmpargs[2];
3934   tmpargs[0]= args->arguments()[m_predicant_index];
3935   tmpargs[1]= args->arguments()[value_index];
3936   if (tmp.aggregate_for_comparison(funcname, tmpargs, 2, true))
3937   {
3938     DBUG_ASSERT(current_thd->is_error());
3939     return true;
3940   }
3941   m_comparators[m_comparator_count].m_handler= tmp.type_handler();
3942   m_comparators[m_comparator_count].m_arg_index= value_index;
3943   m_comparator_count++;
3944   return false;
3945 }
3946 
3947 
add_value_skip_null(const char * funcname,Item_args * args,uint value_index,bool * nulls_found)3948 bool Predicant_to_list_comparator::add_value_skip_null(const char *funcname,
3949                                                        Item_args *args,
3950                                                        uint value_index,
3951                                                        bool *nulls_found)
3952 {
3953   /*
3954     Skip explicit NULL constant items.
3955     Using real_item() to correctly detect references to explicit NULLs
3956     in HAVING clause, e.g. in this example "b" is skipped:
3957       SELECT a,NULL AS b FROM t1 GROUP BY a HAVING 'A' IN (b,'A');
3958   */
3959   if (args->arguments()[value_index]->real_item()->type() == Item::NULL_ITEM)
3960   {
3961     *nulls_found= true;
3962     return false;
3963   }
3964   return add_value(funcname, args, value_index);
3965 }
3966 
3967 
3968 void Predicant_to_list_comparator::
detect_unique_handlers(Type_handler_hybrid_field_type * compatible,uint * unique_count,uint * found_types)3969        detect_unique_handlers(Type_handler_hybrid_field_type *compatible,
3970                               uint *unique_count,
3971                               uint *found_types)
3972 {
3973   *unique_count= 0;
3974   *found_types= 0;
3975   for (uint i= 0; i < m_comparator_count; i++)
3976   {
3977     uint idx;
3978     if (find_handler(&idx, m_comparators[i].m_handler, i))
3979     {
3980       m_comparators[i].m_handler_index= i; // New unique handler
3981       (*unique_count)++;
3982       (*found_types)|= 1U << m_comparators[i].m_handler->cmp_type();
3983       compatible->set_handler(m_comparators[i].m_handler);
3984     }
3985     else
3986     {
3987       m_comparators[i].m_handler_index= idx; // Non-unique handler
3988     }
3989   }
3990 }
3991 
3992 
make_unique_cmp_items(THD * thd,CHARSET_INFO * cs)3993 bool Predicant_to_list_comparator::make_unique_cmp_items(THD *thd,
3994                                                          CHARSET_INFO *cs)
3995 {
3996   for (uint i= 0; i < m_comparator_count; i++)
3997   {
3998     if (m_comparators[i].m_handler &&                   // Skip implicit NULLs
3999         m_comparators[i].m_handler_index == i && // Skip non-unuque
4000         !(m_comparators[i].m_cmp_item=
4001           m_comparators[i].m_handler->make_cmp_item(thd, cs)))
4002        return true;
4003   }
4004   return false;
4005 }
4006 
4007 
make_same()4008 cmp_item* cmp_item_sort_string::make_same()
4009 {
4010   return new cmp_item_sort_string_in_static(cmp_charset);
4011 }
4012 
make_same()4013 cmp_item* cmp_item_int::make_same()
4014 {
4015   return new cmp_item_int();
4016 }
4017 
make_same()4018 cmp_item* cmp_item_real::make_same()
4019 {
4020   return new cmp_item_real();
4021 }
4022 
make_same()4023 cmp_item* cmp_item_row::make_same()
4024 {
4025   return new cmp_item_row();
4026 }
4027 
4028 
~cmp_item_row()4029 cmp_item_row::~cmp_item_row()
4030 {
4031   DBUG_ENTER("~cmp_item_row");
4032   DBUG_PRINT("enter",("this: %p", this));
4033   if (comparators)
4034   {
4035     for (uint i= 0; i < n; i++)
4036     {
4037       if (comparators[i])
4038 	delete comparators[i];
4039     }
4040   }
4041   DBUG_VOID_RETURN;
4042 }
4043 
4044 
alloc_comparators(THD * thd,uint cols)4045 bool cmp_item_row::alloc_comparators(THD *thd, uint cols)
4046 {
4047   if (comparators)
4048   {
4049     DBUG_ASSERT(cols == n);
4050     return false;
4051   }
4052   return
4053     !(comparators= (cmp_item **) thd->calloc(sizeof(cmp_item *) * (n= cols)));
4054 }
4055 
4056 
store_value(Item * item)4057 void cmp_item_row::store_value(Item *item)
4058 {
4059   DBUG_ENTER("cmp_item_row::store_value");
4060   DBUG_ASSERT(comparators);
4061   DBUG_ASSERT(n == item->cols());
4062   item->bring_value();
4063   item->null_value= 0;
4064   for (uint i=0; i < n; i++)
4065   {
4066     DBUG_ASSERT(comparators[i]);
4067     comparators[i]->store_value(item->element_index(i));
4068     item->null_value|= item->element_index(i)->null_value;
4069   }
4070   DBUG_VOID_RETURN;
4071 }
4072 
4073 
store_value_by_template(THD * thd,cmp_item * t,Item * item)4074 void cmp_item_row::store_value_by_template(THD *thd, cmp_item *t, Item *item)
4075 {
4076   cmp_item_row *tmpl= (cmp_item_row*) t;
4077   if (tmpl->n != item->cols())
4078   {
4079     my_error(ER_OPERAND_COLUMNS, MYF(0), tmpl->n);
4080     return;
4081   }
4082   n= tmpl->n;
4083   if ((comparators= (cmp_item **) thd->alloc(sizeof(cmp_item *)*n)))
4084   {
4085     item->bring_value();
4086     item->null_value= 0;
4087     for (uint i=0; i < n; i++)
4088     {
4089       if (!(comparators[i]= tmpl->comparators[i]->make_same()))
4090 	break;					// new failed
4091       comparators[i]->store_value_by_template(thd, tmpl->comparators[i],
4092 					      item->element_index(i));
4093       item->null_value|= item->element_index(i)->null_value;
4094     }
4095   }
4096 }
4097 
4098 
cmp(Item * arg)4099 int cmp_item_row::cmp(Item *arg)
4100 {
4101   arg->null_value= 0;
4102   if (arg->cols() != n)
4103   {
4104     my_error(ER_OPERAND_COLUMNS, MYF(0), n);
4105     return 1;
4106   }
4107   bool was_null= 0;
4108   arg->bring_value();
4109   for (uint i=0; i < n; i++)
4110   {
4111     const int rc= comparators[i]->cmp(arg->element_index(i));
4112     switch (rc)
4113     {
4114     case UNKNOWN:
4115       was_null= true;
4116       break;
4117     case TRUE:
4118       return TRUE;
4119     case FALSE:
4120       break;                                    // elements #i are equal
4121     }
4122     arg->null_value|= arg->element_index(i)->null_value;
4123   }
4124   return was_null ? UNKNOWN : FALSE;
4125 }
4126 
4127 
compare(cmp_item * c)4128 int cmp_item_row::compare(cmp_item *c)
4129 {
4130   cmp_item_row *l_cmp= (cmp_item_row *) c;
4131   for (uint i=0; i < n; i++)
4132   {
4133     int res;
4134     if ((res= comparators[i]->compare(l_cmp->comparators[i])))
4135       return res;
4136   }
4137   return 0;
4138 }
4139 
4140 
store_value(Item * item)4141 void cmp_item_decimal::store_value(Item *item)
4142 {
4143   my_decimal *val= item->val_decimal(&value);
4144   /* val may be zero if item is nnull */
4145   if (val && val != &value)
4146     my_decimal2decimal(val, &value);
4147   m_null_value= item->null_value;
4148 }
4149 
4150 
cmp_not_null(const Value * val)4151 int cmp_item_decimal::cmp_not_null(const Value *val)
4152 {
4153   DBUG_ASSERT(!val->is_null());
4154   DBUG_ASSERT(val->is_decimal());
4155   return my_decimal_cmp(&value, &val->m_decimal);
4156 }
4157 
4158 
cmp(Item * arg)4159 int cmp_item_decimal::cmp(Item *arg)
4160 {
4161   VDec tmp(arg);
4162   return m_null_value || tmp.is_null() ? UNKNOWN : (tmp.cmp(&value) != 0);
4163 }
4164 
4165 
compare(cmp_item * arg)4166 int cmp_item_decimal::compare(cmp_item *arg)
4167 {
4168   cmp_item_decimal *l_cmp= (cmp_item_decimal*) arg;
4169   return my_decimal_cmp(&value, &l_cmp->value);
4170 }
4171 
4172 
make_same()4173 cmp_item* cmp_item_decimal::make_same()
4174 {
4175   return new cmp_item_decimal();
4176 }
4177 
4178 
cmp_not_null(const Value * val)4179 int cmp_item_datetime::cmp_not_null(const Value *val)
4180 {
4181   DBUG_ASSERT(!val->is_null());
4182   DBUG_ASSERT(val->is_temporal());
4183   return value != pack_time(&val->value.m_time);
4184 }
4185 
4186 
cmp(Item * arg)4187 int cmp_item_datetime::cmp(Item *arg)
4188 {
4189   const bool rc= value != arg->val_datetime_packed(current_thd);
4190   return (m_null_value || arg->null_value) ? UNKNOWN : rc;
4191 }
4192 
4193 
cmp_not_null(const Value * val)4194 int cmp_item_time::cmp_not_null(const Value *val)
4195 {
4196   DBUG_ASSERT(!val->is_null());
4197   DBUG_ASSERT(val->is_temporal());
4198   return value != pack_time(&val->value.m_time);
4199 }
4200 
4201 
cmp(Item * arg)4202 int cmp_item_time::cmp(Item *arg)
4203 {
4204   const bool rc= value != arg->val_time_packed(current_thd);
4205   return (m_null_value || arg->null_value) ? UNKNOWN : rc;
4206 }
4207 
4208 
compare(cmp_item * ci)4209 int cmp_item_temporal::compare(cmp_item *ci)
4210 {
4211   cmp_item_temporal *l_cmp= (cmp_item_temporal *)ci;
4212   return (value < l_cmp->value) ? -1 : ((value == l_cmp->value) ? 0 : 1);
4213 }
4214 
4215 
make_same()4216 cmp_item *cmp_item_datetime::make_same()
4217 {
4218   return new cmp_item_datetime();
4219 }
4220 
4221 
make_same()4222 cmp_item *cmp_item_time::make_same()
4223 {
4224   return new cmp_item_time();
4225 }
4226 
4227 
store_value(Item * item)4228 void cmp_item_timestamp::store_value(Item *item)
4229 {
4230   item->val_native_with_conversion(current_thd, &m_native,
4231                                    &type_handler_timestamp2);
4232   m_null_value= item->null_value;
4233 }
4234 
4235 
cmp_not_null(const Value * val)4236 int cmp_item_timestamp::cmp_not_null(const Value *val)
4237 {
4238   /*
4239     This method will be implemented when we add this syntax:
4240       SELECT TIMESTAMP WITH LOCAL TIME ZONE '2001-01-01 10:20:30'
4241     For now TIMESTAMP is compared to non-TIMESTAMP using DATETIME.
4242   */
4243   DBUG_ASSERT(0);
4244   return 0;
4245 }
4246 
4247 
cmp(Item * arg)4248 int cmp_item_timestamp::cmp(Item *arg)
4249 {
4250   THD *thd= current_thd;
4251   Timestamp_or_zero_datetime_native_null tmp(thd, arg, true);
4252   return m_null_value || tmp.is_null() ? UNKNOWN :
4253          type_handler_timestamp2.cmp_native(m_native, tmp) != 0;
4254 }
4255 
4256 
compare(cmp_item * arg)4257 int cmp_item_timestamp::compare(cmp_item *arg)
4258 {
4259   cmp_item_timestamp *tmp= static_cast<cmp_item_timestamp*>(arg);
4260   return type_handler_timestamp2.cmp_native(m_native, tmp->m_native);
4261 }
4262 
4263 
make_same()4264 cmp_item* cmp_item_timestamp::make_same()
4265 {
4266   return new cmp_item_timestamp();
4267 }
4268 
4269 
4270 
count_sargable_conds(void * arg)4271 bool Item_func_in::count_sargable_conds(void *arg)
4272 {
4273   ((SELECT_LEX*) arg)->cond_count++;
4274   return 0;
4275 }
4276 
4277 
list_contains_null()4278 bool Item_func_in::list_contains_null()
4279 {
4280   Item **arg,**arg_end;
4281   for (arg= args + 1, arg_end= args+arg_count; arg != arg_end ; arg++)
4282   {
4283     if ((*arg)->null_inside())
4284       return 1;
4285   }
4286   return 0;
4287 }
4288 
4289 
4290 /**
4291   Perform context analysis of an IN item tree.
4292 
4293     This function performs context analysis (name resolution) and calculates
4294     various attributes of the item tree with Item_func_in as its root.
4295     The function saves in ref the pointer to the item or to a newly created
4296     item that is considered as a replacement for the original one.
4297 
4298   @param thd     reference to the global context of the query thread
4299   @param ref     pointer to Item* variable where pointer to resulting "fixed"
4300                  item is to be assigned
4301 
4302   @note
4303     Let T0(e)/T1(e) be the value of not_null_tables(e) when e is used on
4304     a predicate/function level. Then it's easy to show that:
4305     @verbatim
4306       T0(e IN(e1,...,en))     = union(T1(e),intersection(T1(ei)))
4307       T1(e IN(e1,...,en))     = union(T1(e),intersection(T1(ei)))
4308       T0(e NOT IN(e1,...,en)) = union(T1(e),union(T1(ei)))
4309       T1(e NOT IN(e1,...,en)) = union(T1(e),intersection(T1(ei)))
4310     @endverbatim
4311 
4312   @retval
4313     0   ok
4314   @retval
4315     1   got error
4316 */
4317 
4318 bool
fix_fields(THD * thd,Item ** ref)4319 Item_func_in::fix_fields(THD *thd, Item **ref)
4320 {
4321 
4322   if (Item_func_opt_neg::fix_fields(thd, ref))
4323     return 1;
4324 
4325   return 0;
4326 }
4327 
4328 
4329 bool
eval_not_null_tables(void * opt_arg)4330 Item_func_in::eval_not_null_tables(void *opt_arg)
4331 {
4332   Item **arg, **arg_end;
4333 
4334   if (Item_func_opt_neg::eval_not_null_tables(NULL))
4335     return 1;
4336 
4337   /* not_null_tables_cache == union(T1(e),union(T1(ei))) */
4338   if (pred_level && negated)
4339     return 0;
4340 
4341   /* not_null_tables_cache = union(T1(e),intersection(T1(ei))) */
4342   not_null_tables_cache= ~(table_map) 0;
4343   for (arg= args + 1, arg_end= args + arg_count; arg != arg_end; arg++)
4344     not_null_tables_cache&= (*arg)->not_null_tables();
4345   not_null_tables_cache|= (*args)->not_null_tables();
4346   return 0;
4347 }
4348 
4349 
fix_after_pullout(st_select_lex * new_parent,Item ** ref,bool merge)4350 void Item_func_in::fix_after_pullout(st_select_lex *new_parent, Item **ref,
4351                                      bool merge)
4352 {
4353   /* This will re-calculate attributes of the arguments */
4354   Item_func_opt_neg::fix_after_pullout(new_parent, ref, merge);
4355   /* Then, re-calculate not_null_tables_cache according to our special rules */
4356   eval_not_null_tables(NULL);
4357 }
4358 
4359 
prepare_predicant_and_values(THD * thd,uint * found_types)4360 bool Item_func_in::prepare_predicant_and_values(THD *thd, uint *found_types)
4361 {
4362   uint type_cnt;
4363   have_null= false;
4364 
4365   add_predicant(this, 0);
4366   for (uint i= 1 ; i < arg_count; i++)
4367   {
4368     if (add_value_skip_null(Item_func_in::func_name(), this, i, &have_null))
4369       return true;
4370   }
4371   all_values_added(&m_comparator, &type_cnt, found_types);
4372   arg_types_compatible= type_cnt < 2;
4373 
4374 #ifndef DBUG_OFF
4375   Predicant_to_list_comparator::debug_print(thd);
4376 #endif
4377   return false;
4378 }
4379 
4380 
fix_length_and_dec()4381 bool Item_func_in::fix_length_and_dec()
4382 {
4383   THD *thd= current_thd;
4384   uint found_types;
4385   m_comparator.set_handler(type_handler_varchar.type_handler_for_comparison());
4386   max_length= 1;
4387 
4388   if (prepare_predicant_and_values(thd, &found_types))
4389   {
4390     DBUG_ASSERT(thd->is_error()); // Must set error
4391     return TRUE;
4392   }
4393 
4394   if (arg_types_compatible) // Bisection condition #1
4395   {
4396     if (m_comparator.type_handler()->
4397         Item_func_in_fix_comparator_compatible_types(thd, this))
4398       return TRUE;
4399   }
4400   else
4401   {
4402     DBUG_ASSERT(m_comparator.cmp_type() != ROW_RESULT);
4403     if ( fix_for_scalar_comparison_using_cmp_items(thd, found_types))
4404       return TRUE;
4405   }
4406 
4407   DBUG_EXECUTE_IF("Item_func_in",
4408                   push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4409                   ER_UNKNOWN_ERROR, "DBUG: types_compatible=%s bisect=%s",
4410                   arg_types_compatible ? "yes" : "no",
4411                   array != NULL ? "yes" : "no"););
4412   return FALSE;
4413 }
4414 
4415 
4416 /**
4417   Populate Item_func_in::array with constant not-NULL arguments and sort them.
4418 
4419   Sets "have_null" to true if some of the values appeared to be NULL.
4420   Note, explicit NULLs were found during prepare_predicant_and_values().
4421   So "have_null" can already be true before the fix_in_vector() call.
4422   Here we additionally catch implicit NULLs.
4423 */
fix_in_vector()4424 void Item_func_in::fix_in_vector()
4425 {
4426   DBUG_ASSERT(array);
4427   uint j=0;
4428   for (uint i=1 ; i < arg_count ; i++)
4429   {
4430     array->set(j,args[i]);
4431     if (!args[i]->null_value)
4432       j++; // include this cell in the array.
4433     else
4434     {
4435       /*
4436         We don't put NULL values in array, to avoid erronous matches in
4437         bisection.
4438       */
4439       have_null= 1;
4440     }
4441   }
4442   if ((array->used_count= j))
4443     array->sort();
4444 }
4445 
4446 
4447 /**
4448   Convert all items in <in value list> to INT.
4449 
4450   IN must compare INT columns and constants as int values (the same
4451   way as equality does).
4452   So we must check here if the column on the left and all the constant
4453   values on the right can be compared as integers and adjust the
4454   comparison type accordingly.
4455 
4456   See the comment about the similar block in Item_bool_func2
4457 */
value_list_convert_const_to_int(THD * thd)4458 bool Item_func_in::value_list_convert_const_to_int(THD *thd)
4459 {
4460   if (args[0]->real_item()->type() == FIELD_ITEM &&
4461       !thd->lex->is_view_context_analysis())
4462   {
4463     Item_field *field_item= (Item_field*) (args[0]->real_item());
4464     if (field_item->field_type() == MYSQL_TYPE_LONGLONG ||
4465         field_item->field_type() == MYSQL_TYPE_YEAR)
4466     {
4467       bool all_converted= true;
4468       Item **arg, **arg_end;
4469       for (arg=args+1, arg_end=args+arg_count; arg != arg_end ; arg++)
4470       {
4471           /*
4472             Explicit NULLs should not affect data cmp_type resolution:
4473             - we ignore NULLs when calling collect_cmp_type()
4474             - we ignore NULLs here
4475             So this expression:
4476               year_column IN (DATE'2001-01-01', NULL)
4477             switches from TIME_RESULT to INT_RESULT.
4478           */
4479           if (arg[0]->type() != Item::NULL_ITEM &&
4480               !convert_const_to_int(thd, field_item, &arg[0]))
4481            all_converted= false;
4482       }
4483       if (all_converted)
4484         m_comparator.set_handler(&type_handler_longlong);
4485     }
4486   }
4487   return thd->is_fatal_error; // Catch errrors in convert_const_to_int
4488 }
4489 
4490 
4491 bool cmp_item_row::
aggregate_row_elements_for_comparison(THD * thd,Type_handler_hybrid_field_type * cmp,Item_args * tmp,const char * funcname,uint col,uint level)4492       aggregate_row_elements_for_comparison(THD *thd,
4493                                             Type_handler_hybrid_field_type *cmp,
4494                                             Item_args *tmp,
4495                                             const char *funcname,
4496                                             uint col,
4497                                             uint level)
4498 {
4499   DBUG_EXECUTE_IF("cmp_item",
4500   {
4501     for (uint i= 0 ; i < tmp->argument_count(); i++)
4502     {
4503       Item *arg= tmp->arguments()[i];
4504       push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4505                           ER_UNKNOWN_ERROR, "DBUG: %s[%d,%d] handler=%s",
4506                           String_space(level).c_ptr(), col, i,
4507                           arg->type_handler()->name().ptr());
4508     }
4509   }
4510   );
4511   bool err= cmp->aggregate_for_comparison(funcname, tmp->arguments(),
4512                                           tmp->argument_count(), true);
4513   DBUG_EXECUTE_IF("cmp_item",
4514   {
4515     if (!err)
4516       push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4517                           ER_UNKNOWN_ERROR, "DBUG: %s=> handler=%s",
4518                           String_space(level).c_ptr(),
4519                           cmp->type_handler()->name().ptr());
4520   }
4521   );
4522   return err;
4523 }
4524 
4525 
prepare_comparators(THD * thd,const char * funcname,const Item_args * args,uint level)4526 bool cmp_item_row::prepare_comparators(THD *thd, const char *funcname,
4527                                        const Item_args *args, uint level)
4528 {
4529   DBUG_EXECUTE_IF("cmp_item",
4530                   push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4531                   ER_UNKNOWN_ERROR, "DBUG: %sROW(%d args) level=%d",
4532                   String_space(level).c_ptr(),
4533                   args->argument_count(), level););
4534   DBUG_ASSERT(args->argument_count() > 0);
4535   if (alloc_comparators(thd, args->arguments()[0]->cols()))
4536     return true;
4537   DBUG_ASSERT(n == args->arguments()[0]->cols());
4538   for (uint col= 0; col < n; col++)
4539   {
4540     Item_args tmp;
4541     Type_handler_hybrid_field_type cmp;
4542 
4543     if (tmp.alloc_and_extract_row_elements(thd, args, col) ||
4544         aggregate_row_elements_for_comparison(thd, &cmp, &tmp,
4545                                               funcname, col, level + 1))
4546       return true;
4547 
4548     /*
4549       There is a legacy bug (MDEV-11511) in the code below,
4550       which should be fixed eventually.
4551       When performing:
4552        (predicant0,predicant1) IN ((value00,value01),(value10,value11))
4553       It uses only the data type and the collation of the predicant
4554       elements only. It should be fixed to take into account the data type and
4555       the collation for all elements at the N-th positions of the
4556       predicate and all values:
4557       - predicate0, value00, value01
4558       - predicate1, value10, value11
4559     */
4560     Item *item0= args->arguments()[0]->element_index(col);
4561     CHARSET_INFO *collation= item0->collation.collation;
4562     if (!(comparators[col]= cmp.type_handler()->make_cmp_item(thd, collation)))
4563       return true;
4564     if (cmp.type_handler() == &type_handler_row)
4565     {
4566       // Prepare comparators for ROW elements recursively
4567       cmp_item_row *row= static_cast<cmp_item_row*>(comparators[col]);
4568       if (row->prepare_comparators(thd, funcname, &tmp, level + 1))
4569         return true;
4570     }
4571   }
4572   return false;
4573 }
4574 
4575 
fix_for_row_comparison_using_bisection(THD * thd)4576 bool Item_func_in::fix_for_row_comparison_using_bisection(THD *thd)
4577 {
4578   if (unlikely(!(array= new (thd->mem_root) in_row(thd, arg_count-1, 0))))
4579     return true;
4580   cmp_item_row *cmp= &((in_row*)array)->tmp;
4581   if (cmp->prepare_comparators(thd, func_name(), this, 0))
4582     return true;
4583   fix_in_vector();
4584   return false;
4585 }
4586 
4587 
4588 /**
4589   This method is called for scalar data types when bisection is not possible,
4590     for example:
4591   - Some of args[1..arg_count] are not constants.
4592   - args[1..arg_count] are constants, but pairs {args[0],args[1..arg_count]}
4593     are compared by different data types, e.g.:
4594       WHERE decimal_expr IN (1, 1e0)
4595     The pair {args[0],args[1]} is compared by type_handler_decimal.
4596     The pair {args[0],args[2]} is compared by type_handler_double.
4597 */
fix_for_scalar_comparison_using_cmp_items(THD * thd,uint found_types)4598 bool Item_func_in::fix_for_scalar_comparison_using_cmp_items(THD *thd,
4599                                                              uint found_types)
4600 {
4601   if (found_types & (1U << STRING_RESULT) &&
4602       agg_arg_charsets_for_comparison(cmp_collation, args, arg_count))
4603     return true;
4604   if (make_unique_cmp_items(thd, cmp_collation.collation))
4605     return true;
4606   return false;
4607 }
4608 
4609 
4610 /**
4611   This method is called for the ROW data type when bisection is not possible.
4612 */
fix_for_row_comparison_using_cmp_items(THD * thd)4613 bool Item_func_in::fix_for_row_comparison_using_cmp_items(THD *thd)
4614 {
4615   if (make_unique_cmp_items(thd, cmp_collation.collation))
4616     return true;
4617   DBUG_ASSERT(get_comparator_type_handler(0) == &type_handler_row);
4618   DBUG_ASSERT(get_comparator_cmp_item(0));
4619   cmp_item_row *cmp_row= (cmp_item_row*) get_comparator_cmp_item(0);
4620   return cmp_row->prepare_comparators(thd, func_name(), this, 0);
4621 }
4622 
4623 
print(String * str,enum_query_type query_type)4624 void Item_func_in::print(String *str, enum_query_type query_type)
4625 {
4626   args[0]->print_parenthesised(str, query_type, precedence());
4627   if (negated)
4628     str->append(STRING_WITH_LEN(" not"));
4629   str->append(STRING_WITH_LEN(" in ("));
4630   print_args(str, 1, query_type);
4631   str->append(STRING_WITH_LEN(")"));
4632 }
4633 
4634 
4635 /*
4636   Evaluate the function and return its value.
4637 
4638   SYNOPSIS
4639     val_int()
4640 
4641   DESCRIPTION
4642     Evaluate the function and return its value.
4643 
4644   IMPLEMENTATION
4645     If the array object is defined then the value of the function is
4646     calculated by means of this array.
4647     Otherwise several cmp_item objects are used in order to do correct
4648     comparison of left expression and an expression from the values list.
4649     One cmp_item object correspond to one used comparison type. Left
4650     expression can be evaluated up to number of different used comparison
4651     types. A bit mapped variable value_added_map is used to check whether
4652     the left expression already was evaluated for a particular result type.
4653     Result types are mapped to it according to their integer values i.e.
4654     STRING_RESULT is mapped to bit 0, REAL_RESULT to bit 1, so on.
4655 
4656   RETURN
4657     Value of the function
4658 */
4659 
val_int()4660 longlong Item_func_in::val_int()
4661 {
4662   DBUG_ASSERT(fixed == 1);
4663   if (array)
4664   {
4665     bool tmp=array->find(args[0]);
4666     /*
4667       NULL on left -> UNKNOWN.
4668       Found no match, and NULL on right -> UNKNOWN.
4669       NULL on right can never give a match, as it is not stored in
4670       array.
4671       See also the 'bisection_possible' variable in fix_length_and_dec().
4672     */
4673     null_value=args[0]->null_value || (!tmp && have_null);
4674     return (longlong) (!null_value && tmp != negated);
4675   }
4676 
4677   if ((null_value= args[0]->real_item()->type() == NULL_ITEM))
4678     return 0;
4679 
4680   null_value= have_null;
4681   uint idx;
4682   if (!Predicant_to_list_comparator::cmp(this, &idx, &null_value))
4683   {
4684     null_value= false;
4685     return (longlong) (!negated);
4686   }
4687   return (longlong) (!null_value && negated);
4688 }
4689 
4690 
mark_as_condition_AND_part(TABLE_LIST * embedding)4691 void Item_func_in::mark_as_condition_AND_part(TABLE_LIST *embedding)
4692 {
4693   THD *thd= current_thd;
4694 
4695   Query_arena *arena, backup;
4696   arena= thd->activate_stmt_arena_if_needed(&backup);
4697 
4698   if (to_be_transformed_into_in_subq(thd))
4699   {
4700     transform_into_subq= true;
4701     thd->lex->current_select->in_funcs.push_back(this, thd->mem_root);
4702   }
4703 
4704   if (arena)
4705     thd->restore_active_arena(arena, &backup);
4706 
4707   emb_on_expr_nest= embedding;
4708 }
4709 
4710 
val_int()4711 longlong Item_func_bit_or::val_int()
4712 {
4713   DBUG_ASSERT(fixed == 1);
4714   ulonglong arg1= (ulonglong) args[0]->val_int();
4715   if (args[0]->null_value)
4716   {
4717     null_value=1; /* purecov: inspected */
4718     return 0; /* purecov: inspected */
4719   }
4720   ulonglong arg2= (ulonglong) args[1]->val_int();
4721   if (args[1]->null_value)
4722   {
4723     null_value=1;
4724     return 0;
4725   }
4726   null_value=0;
4727   return (longlong) (arg1 | arg2);
4728 }
4729 
4730 
val_int()4731 longlong Item_func_bit_and::val_int()
4732 {
4733   DBUG_ASSERT(fixed == 1);
4734   ulonglong arg1= (ulonglong) args[0]->val_int();
4735   if (args[0]->null_value)
4736   {
4737     null_value=1; /* purecov: inspected */
4738     return 0; /* purecov: inspected */
4739   }
4740   ulonglong arg2= (ulonglong) args[1]->val_int();
4741   if (args[1]->null_value)
4742   {
4743     null_value=1; /* purecov: inspected */
4744     return 0; /* purecov: inspected */
4745   }
4746   null_value=0;
4747   return (longlong) (arg1 & arg2);
4748 }
4749 
Item_cond(THD * thd,Item_cond * item)4750 Item_cond::Item_cond(THD *thd, Item_cond *item)
4751   :Item_bool_func(thd, item),
4752    abort_on_null(item->abort_on_null),
4753    and_tables_cache(item->and_tables_cache)
4754 {
4755   /*
4756     item->list will be copied by copy_andor_arguments() call
4757   */
4758 }
4759 
4760 
Item_cond(THD * thd,Item * i1,Item * i2)4761 Item_cond::Item_cond(THD *thd, Item *i1, Item *i2):
4762   Item_bool_func(thd), abort_on_null(0)
4763 {
4764   list.push_back(i1, thd->mem_root);
4765   list.push_back(i2, thd->mem_root);
4766 }
4767 
4768 
copy_andor_structure(THD * thd)4769 Item *Item_cond_and::copy_andor_structure(THD *thd)
4770 {
4771   Item_cond_and *item;
4772   if ((item= new (thd->mem_root) Item_cond_and(thd, this)))
4773     item->copy_andor_arguments(thd, this);
4774   return item;
4775 }
4776 
4777 
copy_andor_arguments(THD * thd,Item_cond * item)4778 void Item_cond::copy_andor_arguments(THD *thd, Item_cond *item)
4779 {
4780   List_iterator_fast<Item> li(item->list);
4781   while (Item *it= li++)
4782     list.push_back(it->copy_andor_structure(thd), thd->mem_root);
4783 }
4784 
4785 
4786 bool
fix_fields(THD * thd,Item ** ref)4787 Item_cond::fix_fields(THD *thd, Item **ref)
4788 {
4789   DBUG_ASSERT(fixed == 0);
4790   List_iterator<Item> li(list);
4791   Item *item;
4792   uchar buff[sizeof(char*)];			// Max local vars in function
4793   bool is_and_cond= functype() == Item_func::COND_AND_FUNC;
4794   not_null_tables_cache= 0;
4795   used_tables_and_const_cache_init();
4796 
4797   /*
4798     and_table_cache is the value that Item_cond_or() returns for
4799     not_null_tables()
4800   */
4801   and_tables_cache= ~(table_map) 0;
4802 
4803   if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
4804     return TRUE;				// Fatal error flag is set!
4805   /*
4806     The following optimization reduces the depth of an AND-OR tree.
4807     E.g. a WHERE clause like
4808       F1 AND (F2 AND (F2 AND F4))
4809     is parsed into a tree with the same nested structure as defined
4810     by braces. This optimization will transform such tree into
4811       AND (F1, F2, F3, F4).
4812     Trees of OR items are flattened as well:
4813       ((F1 OR F2) OR (F3 OR F4))   =>   OR (F1, F2, F3, F4)
4814     Items for removed AND/OR levels will dangle until the death of the
4815     entire statement.
4816     The optimization is currently prepared statements and stored procedures
4817     friendly as it doesn't allocate any memory and its effects are durable
4818     (i.e. do not depend on PS/SP arguments).
4819   */
4820   while ((item=li++))
4821   {
4822     while (item->type() == Item::COND_ITEM &&
4823 	   ((Item_cond*) item)->functype() == functype() &&
4824            !((Item_cond*) item)->list.is_empty())
4825     {						// Identical function
4826       li.replace(((Item_cond*) item)->list);
4827       ((Item_cond*) item)->list.empty();
4828       item= *li.ref();				// new current item
4829     }
4830     if (abort_on_null)
4831       item->top_level_item();
4832 
4833     /*
4834       replace degraded condition:
4835         was:    <field>
4836         become: <field> = 1
4837     */
4838     Item::Type type= item->type();
4839     if (type == Item::FIELD_ITEM || type == Item::REF_ITEM)
4840     {
4841       Query_arena backup, *arena;
4842       Item *new_item;
4843       arena= thd->activate_stmt_arena_if_needed(&backup);
4844       if ((new_item= new (thd->mem_root) Item_func_ne(thd, item, new (thd->mem_root) Item_int(thd, 0, 1))))
4845         li.replace(item= new_item);
4846       if (arena)
4847         thd->restore_active_arena(arena, &backup);
4848     }
4849 
4850     if (item->fix_fields_if_needed_for_bool(thd, li.ref()))
4851       return TRUE; /* purecov: inspected */
4852     item= *li.ref(); // item can be substituted in fix_fields
4853     used_tables_cache|=     item->used_tables();
4854     if (item->const_item() && !item->with_param &&
4855         !item->is_expensive() && !cond_has_datetime_is_null(item))
4856     {
4857       if (item->eval_const_cond() == is_and_cond && top_level())
4858       {
4859         /*
4860           a. This is "... AND true_cond AND ..."
4861           In this case, true_cond  has no effect on cond_and->not_null_tables()
4862           b. This is "... OR false_cond/null cond OR ..."
4863           In this case, false_cond has no effect on cond_or->not_null_tables()
4864         */
4865       }
4866       else
4867       {
4868         /*
4869           a. This is "... AND false_cond/null_cond AND ..."
4870           The whole condition is FALSE/UNKNOWN.
4871           b. This is  "... OR const_cond OR ..."
4872           In this case, cond_or->not_null_tables()=0, because the condition
4873           const_cond might evaluate to true (regardless of whether some tables
4874           were NULL-complemented).
4875         */
4876         not_null_tables_cache= (table_map) 0;
4877         and_tables_cache= (table_map) 0;
4878       }
4879       if (thd->is_error())
4880         return TRUE;
4881     }
4882     else
4883     {
4884       table_map tmp_table_map= item->not_null_tables();
4885       not_null_tables_cache|= tmp_table_map;
4886       and_tables_cache&= tmp_table_map;
4887 
4888       const_item_cache= FALSE;
4889     }
4890 
4891     join_with_sum_func(item);
4892     with_param|=       item->with_param;
4893     with_field|=       item->with_field;
4894     m_with_subquery|=  item->with_subquery();
4895     with_window_func|= item->with_window_func;
4896     maybe_null|=       item->maybe_null;
4897   }
4898   if (fix_length_and_dec())
4899     return TRUE;
4900   fixed= 1;
4901   return FALSE;
4902 }
4903 
4904 
4905 bool
eval_not_null_tables(void * opt_arg)4906 Item_cond::eval_not_null_tables(void *opt_arg)
4907 {
4908   Item *item;
4909   bool is_and_cond= functype() == Item_func::COND_AND_FUNC;
4910   List_iterator<Item> li(list);
4911   not_null_tables_cache= (table_map) 0;
4912   and_tables_cache= ~(table_map) 0;
4913   while ((item=li++))
4914   {
4915     table_map tmp_table_map;
4916     if (item->const_item() && !item->with_param &&
4917         !item->is_expensive() && !cond_has_datetime_is_null(item))
4918     {
4919       if (item->eval_const_cond() == is_and_cond && top_level())
4920       {
4921         /*
4922           a. This is "... AND true_cond AND ..."
4923           In this case, true_cond  has no effect on cond_and->not_null_tables()
4924           b. This is "... OR false_cond/null cond OR ..."
4925           In this case, false_cond has no effect on cond_or->not_null_tables()
4926         */
4927       }
4928       else
4929       {
4930         /*
4931           a. This is "... AND false_cond/null_cond AND ..."
4932           The whole condition is FALSE/UNKNOWN.
4933           b. This is  "... OR const_cond OR ..."
4934           In this case, cond_or->not_null_tables()=0, because the condition
4935           const_cond might evaluate to true (regardless of whether some tables
4936           were NULL-complemented).
4937         */
4938         not_null_tables_cache= (table_map) 0;
4939         and_tables_cache= (table_map) 0;
4940       }
4941     }
4942     else
4943     {
4944       tmp_table_map= item->not_null_tables();
4945       not_null_tables_cache|= tmp_table_map;
4946       and_tables_cache&= tmp_table_map;
4947     }
4948   }
4949   return 0;
4950 }
4951 
4952 
fix_after_pullout(st_select_lex * new_parent,Item ** ref,bool merge)4953 void Item_cond::fix_after_pullout(st_select_lex *new_parent, Item **ref,
4954                                   bool merge)
4955 {
4956   List_iterator<Item> li(list);
4957   Item *item;
4958 
4959   used_tables_and_const_cache_init();
4960 
4961   and_tables_cache= ~(table_map) 0; // Here and below we do as fix_fields does
4962   not_null_tables_cache= 0;
4963 
4964   while ((item=li++))
4965   {
4966     table_map tmp_table_map;
4967     item->fix_after_pullout(new_parent, li.ref(), merge);
4968     item= *li.ref();
4969     used_tables_and_const_cache_join(item);
4970 
4971     if (item->const_item())
4972       and_tables_cache= (table_map) 0;
4973     else
4974     {
4975       tmp_table_map= item->not_null_tables();
4976       not_null_tables_cache|= tmp_table_map;
4977       and_tables_cache&= tmp_table_map;
4978       const_item_cache= FALSE;
4979     }
4980   }
4981 }
4982 
4983 
walk(Item_processor processor,bool walk_subquery,void * arg)4984 bool Item_cond::walk(Item_processor processor, bool walk_subquery, void *arg)
4985 {
4986   List_iterator_fast<Item> li(list);
4987   Item *item;
4988   while ((item= li++))
4989     if (item->walk(processor, walk_subquery, arg))
4990       return 1;
4991   return Item_func::walk(processor, walk_subquery, arg);
4992 }
4993 
4994 /**
4995   Transform an Item_cond object with a transformer callback function.
4996 
4997     The function recursively applies the transform method to each
4998      member item of the condition list.
4999     If the call of the method for a member item returns a new item
5000     the old item is substituted for a new one.
5001     After this the transformer is applied to the root node
5002     of the Item_cond object.
5003 
5004   @param transformer   the transformer callback function to be applied to
5005                        the nodes of the tree of the object
5006   @param arg           parameter to be passed to the transformer
5007 
5008   @return
5009     Item returned as the result of transformation of the root node
5010 */
5011 
transform(THD * thd,Item_transformer transformer,uchar * arg)5012 Item *Item_cond::transform(THD *thd, Item_transformer transformer, uchar *arg)
5013 {
5014   DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
5015 
5016   List_iterator<Item> li(list);
5017   Item *item;
5018   while ((item= li++))
5019   {
5020     Item *new_item= item->transform(thd, transformer, arg);
5021     if (!new_item)
5022       return 0;
5023 
5024     /*
5025       THD::change_item_tree() should be called only if the tree was
5026       really transformed, i.e. when a new item has been created.
5027       Otherwise we'll be allocating a lot of unnecessary memory for
5028       change records at each execution.
5029     */
5030     if (new_item != item)
5031       thd->change_item_tree(li.ref(), new_item);
5032   }
5033   return Item_func::transform(thd, transformer, arg);
5034 }
5035 
5036 
5037 /**
5038   Compile Item_cond object with a processor and a transformer
5039   callback functions.
5040 
5041     First the function applies the analyzer to the root node of
5042     the Item_func object. Then if the analyzer succeeeds (returns TRUE)
5043     the function recursively applies the compile method to member
5044     item of the condition list.
5045     If the call of the method for a member item returns a new item
5046     the old item is substituted for a new one.
5047     After this the transformer is applied to the root node
5048     of the Item_cond object.
5049 
5050   @param analyzer      the analyzer callback function to be applied to the
5051                        nodes of the tree of the object
5052   @param[in,out] arg_p parameter to be passed to the analyzer
5053   @param transformer   the transformer callback function to be applied to the
5054                        nodes of the tree of the object
5055   @param arg_t         parameter to be passed to the transformer
5056 
5057   @return
5058     Item returned as the result of transformation of the root node
5059 */
5060 
compile(THD * thd,Item_analyzer analyzer,uchar ** arg_p,Item_transformer transformer,uchar * arg_t)5061 Item *Item_cond::compile(THD *thd, Item_analyzer analyzer, uchar **arg_p,
5062                          Item_transformer transformer, uchar *arg_t)
5063 {
5064   if (!(this->*analyzer)(arg_p))
5065     return 0;
5066 
5067   List_iterator<Item> li(list);
5068   Item *item;
5069   while ((item= li++))
5070   {
5071     /*
5072       The same parameter value of arg_p must be passed
5073       to analyze any argument of the condition formula.
5074     */
5075     uchar *arg_v= *arg_p;
5076     Item *new_item= item->compile(thd, analyzer, &arg_v, transformer, arg_t);
5077     if (new_item && new_item != item)
5078       thd->change_item_tree(li.ref(), new_item);
5079   }
5080   return Item_func::transform(thd, transformer, arg_t);
5081 }
5082 
5083 
propagate_equal_fields(THD * thd,const Context & ctx,COND_EQUAL * cond)5084 Item *Item_cond::propagate_equal_fields(THD *thd,
5085                                         const Context &ctx,
5086                                         COND_EQUAL *cond)
5087 {
5088   DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
5089   DBUG_ASSERT(arg_count == 0);
5090   List_iterator<Item> li(list);
5091   while (li++)
5092   {
5093     /*
5094       The exact value of the last parameter to propagate_and_change_item_tree()
5095       is not important at this point. Item_func derivants will create and
5096       pass their own context to the arguments.
5097     */
5098     propagate_and_change_item_tree(thd, li.ref(), cond, Context_boolean());
5099   }
5100   return this;
5101 }
5102 
traverse_cond(Cond_traverser traverser,void * arg,traverse_order order)5103 void Item_cond::traverse_cond(Cond_traverser traverser,
5104                               void *arg, traverse_order order)
5105 {
5106   List_iterator<Item> li(list);
5107   Item *item;
5108 
5109   switch(order) {
5110   case(PREFIX):
5111     (*traverser)(this, arg);
5112     while ((item= li++))
5113     {
5114       item->traverse_cond(traverser, arg, order);
5115     }
5116     (*traverser)(NULL, arg);
5117     break;
5118   case(POSTFIX):
5119     while ((item= li++))
5120     {
5121       item->traverse_cond(traverser, arg, order);
5122     }
5123     (*traverser)(this, arg);
5124   }
5125 }
5126 
5127 /**
5128   Move SUM items out from item tree and replace with reference.
5129 
5130   The split is done to get an unique item for each SUM function
5131   so that we can easily find and calculate them.
5132   (Calculation done by update_sum_func() and copy_sum_funcs() in
5133   sql_select.cc)
5134 
5135   @param thd			Thread handler
5136   @param ref_pointer_array	Pointer to array of reference fields
5137   @param fields		All fields in select
5138 
5139   @note
5140     This function is run on all expression (SELECT list, WHERE, HAVING etc)
5141     that have or refer (HAVING) to a SUM expression.
5142 */
5143 
split_sum_func(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields,uint flags)5144 void Item_cond::split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array,
5145                                List<Item> &fields, uint flags)
5146 {
5147   List_iterator<Item> li(list);
5148   Item *item;
5149   while ((item= li++))
5150     item->split_sum_func2(thd, ref_pointer_array, fields, li.ref(),
5151                           flags | SPLIT_SUM_SKIP_REGISTERED);
5152 }
5153 
5154 
5155 table_map
used_tables() const5156 Item_cond::used_tables() const
5157 {						// This caches used_tables
5158   return used_tables_cache;
5159 }
5160 
5161 
print(String * str,enum_query_type query_type)5162 void Item_cond::print(String *str, enum_query_type query_type)
5163 {
5164   List_iterator_fast<Item> li(list);
5165   Item *item;
5166   if ((item=li++))
5167     item->print_parenthesised(str, query_type, precedence());
5168   while ((item=li++))
5169   {
5170     str->append(' ');
5171     str->append(func_name());
5172     str->append(' ');
5173     item->print_parenthesised(str, query_type, precedence());
5174   }
5175 }
5176 
5177 
neg_arguments(THD * thd)5178 void Item_cond::neg_arguments(THD *thd)
5179 {
5180   List_iterator<Item> li(list);
5181   Item *item;
5182   while ((item= li++))		/* Apply not transformation to the arguments */
5183   {
5184     Item *new_item= item->neg_transformer(thd);
5185     if (!new_item)
5186     {
5187       if (!(new_item= new (thd->mem_root) Item_func_not(thd, item)))
5188 	return;					// Fatal OEM error
5189     }
5190     (void) li.replace(new_item);
5191   }
5192 }
5193 
5194 
5195 /**
5196   @brief
5197     Building clone for Item_cond
5198 
5199   @param thd        thread handle
5200   @param mem_root   part of the memory for the clone
5201 
5202   @details
5203     This method gets copy of the current item and also
5204     build clones for its elements. For this elements
5205     build_copy is called again.
5206 
5207    @retval
5208      clone of the item
5209      0 if an error occurred
5210 */
5211 
build_clone(THD * thd)5212 Item *Item_cond::build_clone(THD *thd)
5213 {
5214   List_iterator_fast<Item> li(list);
5215   Item *item;
5216   Item_cond *copy= (Item_cond *) get_copy(thd);
5217   if (!copy)
5218     return 0;
5219   copy->list.empty();
5220   while ((item= li++))
5221   {
5222     Item *arg_clone= item->build_clone(thd);
5223     if (!arg_clone)
5224       return 0;
5225     if (copy->list.push_back(arg_clone, thd->mem_root))
5226       return 0;
5227   }
5228   return copy;
5229 }
5230 
5231 
excl_dep_on_table(table_map tab_map)5232 bool Item_cond::excl_dep_on_table(table_map tab_map)
5233 {
5234   if (used_tables() & OUTER_REF_TABLE_BIT)
5235     return false;
5236   if (!(used_tables() & ~tab_map))
5237     return true;
5238   List_iterator_fast<Item> li(list);
5239   Item *item;
5240   while ((item= li++))
5241   {
5242     if (!item->excl_dep_on_table(tab_map))
5243       return false;
5244   }
5245   return true;
5246 }
5247 
5248 
excl_dep_on_grouping_fields(st_select_lex * sel)5249 bool Item_cond::excl_dep_on_grouping_fields(st_select_lex *sel)
5250 {
5251   if (has_rand_bit())
5252     return false;
5253   List_iterator_fast<Item> li(list);
5254   Item *item;
5255   while ((item= li++))
5256   {
5257     if (!item->excl_dep_on_grouping_fields(sel))
5258       return false;
5259   }
5260   return true;
5261 }
5262 
5263 
mark_as_condition_AND_part(TABLE_LIST * embedding)5264 void Item_cond_and::mark_as_condition_AND_part(TABLE_LIST *embedding)
5265 {
5266   List_iterator<Item> li(list);
5267   Item *item;
5268   while ((item=li++))
5269   {
5270     item->mark_as_condition_AND_part(embedding);
5271   }
5272 }
5273 
5274 /**
5275   Evaluation of AND(expr, expr, expr ...).
5276 
5277   @note
5278     abort_if_null is set for AND expressions for which we don't care if the
5279     result is NULL or 0. This is set for:
5280     - WHERE clause
5281     - HAVING clause
5282     - IF(expression)
5283 
5284   @retval
5285     1  If all expressions are true
5286   @retval
5287     0  If all expressions are false or if we find a NULL expression and
5288        'abort_on_null' is set.
5289   @retval
5290     NULL if all expression are either 1 or NULL
5291 */
5292 
5293 
val_int()5294 longlong Item_cond_and::val_int()
5295 {
5296   DBUG_ASSERT(fixed == 1);
5297   List_iterator_fast<Item> li(list);
5298   Item *item;
5299   null_value= 0;
5300   while ((item=li++))
5301   {
5302     if (!item->val_bool())
5303     {
5304       if (abort_on_null || !(null_value= item->null_value))
5305 	return 0;				// return FALSE
5306     }
5307   }
5308   return null_value ? 0 : 1;
5309 }
5310 
5311 
val_int()5312 longlong Item_cond_or::val_int()
5313 {
5314   DBUG_ASSERT(fixed == 1);
5315   List_iterator_fast<Item> li(list);
5316   Item *item;
5317   null_value=0;
5318   while ((item=li++))
5319   {
5320     if (item->val_bool())
5321     {
5322       null_value=0;
5323       return 1;
5324     }
5325     if (item->null_value)
5326       null_value=1;
5327   }
5328   return 0;
5329 }
5330 
copy_andor_structure(THD * thd)5331 Item *Item_cond_or::copy_andor_structure(THD *thd)
5332 {
5333   Item_cond_or *item;
5334   if ((item= new (thd->mem_root) Item_cond_or(thd, this)))
5335     item->copy_andor_arguments(thd, this);
5336   return item;
5337 }
5338 
5339 
5340 /**
5341   Create an AND expression from two expressions.
5342 
5343   @param a	expression or NULL
5344   @param b    	expression.
5345   @param org_item	Don't modify a if a == *org_item.
5346                         If a == NULL, org_item is set to point at b,
5347                         to ensure that future calls will not modify b.
5348 
5349   @note
5350     This will not modify item pointed to by org_item or b
5351     The idea is that one can call this in a loop and create and
5352     'and' over all items without modifying any of the original items.
5353 
5354   @retval
5355     NULL	Error
5356   @retval
5357     Item
5358 */
5359 
and_expressions(THD * thd,Item * a,Item * b,Item ** org_item)5360 Item *and_expressions(THD *thd, Item *a, Item *b, Item **org_item)
5361 {
5362   if (!a)
5363     return (*org_item= (Item*) b);
5364   if (a == *org_item)
5365   {
5366     Item_cond *res;
5367     if ((res= new (thd->mem_root) Item_cond_and(thd, a, (Item*) b)))
5368     {
5369       res->used_tables_cache= a->used_tables() | b->used_tables();
5370       res->not_null_tables_cache= a->not_null_tables() | b->not_null_tables();
5371     }
5372     return res;
5373   }
5374   if (((Item_cond_and*) a)->add((Item*) b, thd->mem_root))
5375     return 0;
5376   ((Item_cond_and*) a)->used_tables_cache|= b->used_tables();
5377   ((Item_cond_and*) a)->not_null_tables_cache|= b->not_null_tables();
5378   return a;
5379 }
5380 
5381 
count_sargable_conds(void * arg)5382 bool Item_func_null_predicate::count_sargable_conds(void *arg)
5383 {
5384   ((SELECT_LEX*) arg)->cond_count++;
5385   return 0;
5386 }
5387 
5388 
val_int()5389 longlong Item_func_isnull::val_int()
5390 {
5391   DBUG_ASSERT(fixed == 1);
5392   if (const_item() && !args[0]->maybe_null)
5393     return 0;
5394   return args[0]->is_null() ? 1: 0;
5395 }
5396 
5397 
print(String * str,enum_query_type query_type)5398 void Item_func_isnull::print(String *str, enum_query_type query_type)
5399 {
5400   if (const_item() && !args[0]->maybe_null &&
5401       !(query_type & (QT_NO_DATA_EXPANSION | QT_VIEW_INTERNAL)))
5402     str->append("/*always not null*/ 1");
5403   else
5404     args[0]->print_parenthesised(str, query_type, precedence());
5405   str->append(STRING_WITH_LEN(" is null"));
5406 }
5407 
5408 
val_int()5409 longlong Item_is_not_null_test::val_int()
5410 {
5411   DBUG_ASSERT(fixed == 1);
5412   DBUG_ENTER("Item_is_not_null_test::val_int");
5413   if (const_item() && !args[0]->maybe_null)
5414     DBUG_RETURN(1);
5415   if (args[0]->is_null())
5416   {
5417     DBUG_PRINT("info", ("null"));
5418     owner->was_null|= 1;
5419     DBUG_RETURN(0);
5420   }
5421   else
5422     DBUG_RETURN(1);
5423 }
5424 
5425 /**
5426   Optimize case of not_null_column IS NULL.
5427 */
update_used_tables()5428 void Item_is_not_null_test::update_used_tables()
5429 {
5430   if (!args[0]->maybe_null)
5431     used_tables_cache= 0;			/* is always true */
5432   else
5433     args[0]->update_used_tables();
5434 }
5435 
5436 
val_int()5437 longlong Item_func_isnotnull::val_int()
5438 {
5439   DBUG_ASSERT(fixed == 1);
5440   return args[0]->is_null() ? 0 : 1;
5441 }
5442 
5443 
print(String * str,enum_query_type query_type)5444 void Item_func_isnotnull::print(String *str, enum_query_type query_type)
5445 {
5446   args[0]->print_parenthesised(str, query_type, precedence());
5447   str->append(STRING_WITH_LEN(" is not null"));
5448 }
5449 
5450 
count_sargable_conds(void * arg)5451 bool Item_bool_func2::count_sargable_conds(void *arg)
5452 {
5453   ((SELECT_LEX*) arg)->cond_count++;
5454   return 0;
5455 }
5456 
print(String * str,enum_query_type query_type)5457 void Item_func_like::print(String *str, enum_query_type query_type)
5458 {
5459   args[0]->print_parenthesised(str, query_type, precedence());
5460   str->append(' ');
5461   if (negated)
5462     str->append(STRING_WITH_LEN(" not "));
5463   str->append(func_name());
5464   str->append(' ');
5465   if (escape_used_in_parsing)
5466   {
5467     args[1]->print_parenthesised(str, query_type, precedence());
5468     str->append(STRING_WITH_LEN(" escape "));
5469     escape_item->print_parenthesised(str, query_type, higher_precedence());
5470   }
5471   else
5472     args[1]->print_parenthesised(str, query_type, higher_precedence());
5473 }
5474 
5475 
val_int()5476 longlong Item_func_like::val_int()
5477 {
5478   DBUG_ASSERT(fixed == 1);
5479   DBUG_ASSERT(escape != ESCAPE_NOT_INITIALIZED);
5480   String* res= args[0]->val_str(&cmp_value1);
5481   if (args[0]->null_value)
5482   {
5483     null_value=1;
5484     return 0;
5485   }
5486   String* res2= args[1]->val_str(&cmp_value2);
5487   if (args[1]->null_value)
5488   {
5489     null_value=1;
5490     return 0;
5491   }
5492   null_value=0;
5493   if (canDoTurboBM)
5494     return turboBM_matches(res->ptr(), res->length()) ? !negated : negated;
5495   return my_wildcmp(cmp_collation.collation,
5496 		    res->ptr(),res->ptr()+res->length(),
5497 		    res2->ptr(),res2->ptr()+res2->length(),
5498 		    escape,wild_one,wild_many) ? negated : !negated;
5499 }
5500 
5501 
5502 /**
5503   We can optimize a where if first character isn't a wildcard
5504 */
5505 
with_sargable_pattern() const5506 bool Item_func_like::with_sargable_pattern() const
5507 {
5508   if (negated)
5509     return false;
5510 
5511   if (!args[1]->const_item() || args[1]->is_expensive())
5512     return false;
5513 
5514   String* res2= args[1]->val_str((String *) &cmp_value2);
5515   if (!res2)
5516     return false;
5517 
5518   if (!res2->length()) // Can optimize empty wildcard: column LIKE ''
5519     return true;
5520 
5521   DBUG_ASSERT(res2->ptr());
5522   char first= res2->ptr()[0];
5523   return first != wild_many && first != wild_one;
5524 }
5525 
5526 
5527 /*
5528   subject LIKE pattern
5529   removes subject's dependency on PAD_CHAR_TO_FULL_LENGTH
5530   if pattern ends with the '%' wildcard.
5531 */
value_depends_on_sql_mode() const5532 Sql_mode_dependency Item_func_like::value_depends_on_sql_mode() const
5533 {
5534   if (!args[1]->value_depends_on_sql_mode_const_item())
5535     return Item_func::value_depends_on_sql_mode();
5536   StringBuffer<64> patternbuf;
5537   String *pattern= args[1]->val_str_ascii(&patternbuf);
5538   if (!pattern || !pattern->length())
5539     return Sql_mode_dependency();                  // Will return NULL or 0
5540   DBUG_ASSERT(pattern->charset()->mbminlen == 1);
5541   if (pattern->ptr()[pattern->length() - 1] != '%')
5542     return Item_func::value_depends_on_sql_mode();
5543   return ((args[0]->value_depends_on_sql_mode() |
5544            args[1]->value_depends_on_sql_mode()) &
5545           Sql_mode_dependency(~0, ~MODE_PAD_CHAR_TO_FULL_LENGTH)).
5546          soft_to_hard();
5547 }
5548 
5549 
get_mm_tree(RANGE_OPT_PARAM * param,Item ** cond_ptr)5550 SEL_TREE *Item_func_like::get_mm_tree(RANGE_OPT_PARAM *param, Item **cond_ptr)
5551 {
5552   MEM_ROOT *tmp_root= param->mem_root;
5553   param->thd->mem_root= param->old_root;
5554   bool sargable_pattern= with_sargable_pattern();
5555   param->thd->mem_root= tmp_root;
5556   return sargable_pattern ?
5557     Item_bool_func2::get_mm_tree(param, cond_ptr) :
5558     Item_func::get_mm_tree(param, cond_ptr);
5559 }
5560 
5561 
fix_escape_item(THD * thd,Item * escape_item,String * tmp_str,bool escape_used_in_parsing,CHARSET_INFO * cmp_cs,int * escape)5562 bool fix_escape_item(THD *thd, Item *escape_item, String *tmp_str,
5563                      bool escape_used_in_parsing, CHARSET_INFO *cmp_cs,
5564                      int *escape)
5565 {
5566   /*
5567     ESCAPE clause accepts only constant arguments and Item_param.
5568 
5569     Subqueries during context_analysis_only might decide they're
5570     const_during_execution, but not quite const yet, not evaluate-able.
5571     This is fine, as most of context_analysis_only modes will never
5572     reach val_int(), so we won't need the value.
5573     CONTEXT_ANALYSIS_ONLY_DERIVED being a notable exception here.
5574   */
5575   if (!escape_item->const_during_execution() ||
5576      (!escape_item->const_item() &&
5577       !(thd->lex->context_analysis_only & ~CONTEXT_ANALYSIS_ONLY_DERIVED)))
5578   {
5579     my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
5580     return TRUE;
5581   }
5582 
5583   IF_DBUG(*escape= ESCAPE_NOT_INITIALIZED,);
5584 
5585   if (escape_item->const_item())
5586   {
5587     /* If we are on execution stage */
5588     /* XXX is it safe to evaluate is_expensive() items here? */
5589     String *escape_str= escape_item->val_str(tmp_str);
5590     if (escape_str)
5591     {
5592       const char *escape_str_ptr= escape_str->ptr();
5593       if (escape_used_in_parsing && (
5594              (((thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
5595                 escape_str->numchars() != 1) ||
5596                escape_str->numchars() > 1)))
5597       {
5598         my_error(ER_WRONG_ARGUMENTS,MYF(0),"ESCAPE");
5599         return TRUE;
5600       }
5601 
5602       if (use_mb(cmp_cs))
5603       {
5604         CHARSET_INFO *cs= escape_str->charset();
5605         my_wc_t wc;
5606         int rc= cs->cset->mb_wc(cs, &wc,
5607                                 (const uchar*) escape_str_ptr,
5608                                 (const uchar*) escape_str_ptr +
5609                                 escape_str->length());
5610         *escape= (int) (rc > 0 ? wc : '\\');
5611       }
5612       else
5613       {
5614         /*
5615           In the case of 8bit character set, we pass native
5616           code instead of Unicode code as "escape" argument.
5617           Convert to "cs" if charset of escape differs.
5618         */
5619         uint32 unused;
5620         if (escape_str->needs_conversion(escape_str->length(),
5621                                          escape_str->charset(),cmp_cs,&unused))
5622         {
5623           char ch;
5624           uint errors;
5625           uint32 cnvlen= copy_and_convert(&ch, 1, cmp_cs, escape_str_ptr,
5626                                           escape_str->length(),
5627                                           escape_str->charset(), &errors);
5628           *escape= cnvlen ? ch : '\\';
5629         }
5630         else
5631           *escape= escape_str_ptr ? *escape_str_ptr : '\\';
5632       }
5633     }
5634     else
5635       *escape= '\\';
5636   }
5637 
5638   return FALSE;
5639 }
5640 
fix_fields(THD * thd,Item ** ref)5641 bool Item_func_like::fix_fields(THD *thd, Item **ref)
5642 {
5643   DBUG_ASSERT(fixed == 0);
5644   if (Item_bool_func2::fix_fields(thd, ref) ||
5645       escape_item->fix_fields_if_needed_for_scalar(thd, &escape_item) ||
5646       fix_escape_item(thd, escape_item, &cmp_value1, escape_used_in_parsing,
5647                       cmp_collation.collation, &escape))
5648     return TRUE;
5649 
5650   if (escape_item->const_item())
5651   {
5652     /*
5653       We could also do boyer-more for non-const items, but as we would have to
5654       recompute the tables for each row it's not worth it.
5655     */
5656     if (args[1]->const_item() && !use_strnxfrm(collation.collation) &&
5657         !args[1]->is_expensive())
5658     {
5659       String* res2= args[1]->val_str(&cmp_value2);
5660       if (!res2)
5661         return FALSE;				// Null argument
5662 
5663       const size_t len= res2->length();
5664 
5665       /*
5666         len must be > 2 ('%pattern%')
5667         heuristic: only do TurboBM for pattern_len > 2
5668       */
5669       if (len <= 2)
5670         return FALSE;
5671 
5672       const char*  first= res2->ptr();
5673       const char*  last=  first + len - 1;
5674 
5675       if (len > MIN_TURBOBM_PATTERN_LEN + 2 &&
5676           *first == wild_many &&
5677           *last  == wild_many)
5678       {
5679         const char* tmp = first + 1;
5680         for (; *tmp != wild_many && *tmp != wild_one && *tmp != escape; tmp++) ;
5681         canDoTurboBM = (tmp == last) && !use_mb(args[0]->collation.collation);
5682       }
5683       if (canDoTurboBM)
5684       {
5685         pattern_len = (int) len - 2;
5686         pattern     = thd->strmake(first + 1, pattern_len);
5687         DBUG_PRINT("info", ("Initializing pattern: '%s'", first));
5688         int *suff = (int*) thd->alloc((int) (sizeof(int)*
5689                                       ((pattern_len + 1)*2+
5690                                       alphabet_size)));
5691         bmGs      = suff + pattern_len + 1;
5692         bmBc      = bmGs + pattern_len + 1;
5693         turboBM_compute_good_suffix_shifts(suff);
5694         turboBM_compute_bad_character_shifts();
5695         DBUG_PRINT("info",("done"));
5696       }
5697       use_sampling= (len > 2 && (*first == wild_many || *first == wild_one));
5698     }
5699   }
5700   return FALSE;
5701 }
5702 
5703 
cleanup()5704 void Item_func_like::cleanup()
5705 {
5706   canDoTurboBM= FALSE;
5707   Item_bool_func2::cleanup();
5708 }
5709 
5710 
find_selective_predicates_list_processor(void * arg)5711 bool Item_func_like::find_selective_predicates_list_processor(void *arg)
5712 {
5713   find_selective_predicates_list_processor_data *data=
5714     (find_selective_predicates_list_processor_data *) arg;
5715   if (use_sampling && used_tables() == data->table->map)
5716   {
5717     THD *thd= data->table->in_use;
5718     COND_STATISTIC *stat;
5719     Item *arg0;
5720     if (!(stat= (COND_STATISTIC *) thd->alloc(sizeof(COND_STATISTIC))))
5721       return TRUE;
5722     stat->cond= this;
5723     arg0= args[0]->real_item();
5724     if (args[1]->const_item() && arg0->type() == FIELD_ITEM)
5725       stat->field_arg= ((Item_field *)arg0)->field;
5726     else
5727       stat->field_arg= NULL;
5728     data->list.push_back(stat, thd->mem_root);
5729   }
5730   return FALSE;
5731 }
5732 
5733 
default_regex_flags()5734 int Regexp_processor_pcre::default_regex_flags()
5735 {
5736   return default_regex_flags_pcre(current_thd);
5737 }
5738 
set_recursion_limit(THD * thd)5739 void Regexp_processor_pcre::set_recursion_limit(THD *thd)
5740 {
5741   long stack_used;
5742   DBUG_ASSERT(thd == current_thd);
5743   stack_used= available_stack_size(thd->thread_stack, &stack_used);
5744   m_pcre_extra.match_limit_recursion=
5745     (ulong)((my_thread_stack_size - STACK_MIN_SIZE - stack_used)/my_pcre_frame_size);
5746 }
5747 
5748 
5749 /**
5750   Convert string to lib_charset, if needed.
5751 */
convert_if_needed(String * str,String * converter)5752 String *Regexp_processor_pcre::convert_if_needed(String *str, String *converter)
5753 {
5754   if (m_conversion_is_needed)
5755   {
5756     uint dummy_errors;
5757     if (converter->copy(str->ptr(), str->length(), str->charset(),
5758                         m_library_charset, &dummy_errors))
5759       return NULL;
5760     str= converter;
5761   }
5762   return str;
5763 }
5764 
5765 
5766 /**
5767   @brief Compile regular expression.
5768 
5769   @param[in]    pattern        the pattern to compile from.
5770   @param[in]    send_error     send error message if any.
5771 
5772   @details Make necessary character set conversion then
5773   compile regular expression passed in the args[1].
5774 
5775   @retval    false  success.
5776   @retval    true   error occurred.
5777  */
5778 
compile(String * pattern,bool send_error)5779 bool Regexp_processor_pcre::compile(String *pattern, bool send_error)
5780 {
5781   const char *pcreErrorStr;
5782   int pcreErrorOffset;
5783 
5784   if (is_compiled())
5785   {
5786     if (!stringcmp(pattern, &m_prev_pattern))
5787       return false;
5788     cleanup();
5789     m_prev_pattern.copy(*pattern);
5790   }
5791 
5792   if (!(pattern= convert_if_needed(pattern, &pattern_converter)))
5793     return true;
5794 
5795   m_pcre= pcre_compile(pattern->c_ptr_safe(), m_library_flags,
5796                        &pcreErrorStr, &pcreErrorOffset, NULL);
5797 
5798   if (unlikely(m_pcre == NULL))
5799   {
5800     if (send_error)
5801     {
5802       char buff[MAX_FIELD_WIDTH];
5803       my_snprintf(buff, sizeof(buff), "%s at offset %d", pcreErrorStr, pcreErrorOffset);
5804       my_error(ER_REGEXP_ERROR, MYF(0), buff);
5805     }
5806     return true;
5807   }
5808   return false;
5809 }
5810 
5811 
compile(Item * item,bool send_error)5812 bool Regexp_processor_pcre::compile(Item *item, bool send_error)
5813 {
5814   char buff[MAX_FIELD_WIDTH];
5815   String tmp(buff, sizeof(buff), &my_charset_bin);
5816   String *pattern= item->val_str(&tmp);
5817   if (unlikely(item->null_value) || (unlikely(compile(pattern, send_error))))
5818     return true;
5819   return false;
5820 }
5821 
5822 
5823 /**
5824   Send a warning explaining an error code returned by pcre_exec().
5825 */
pcre_exec_warn(int rc) const5826 void Regexp_processor_pcre::pcre_exec_warn(int rc) const
5827 {
5828   char buf[64];
5829   const char *errmsg= NULL;
5830   THD *thd= current_thd;
5831 
5832   /*
5833     Make a descriptive message only for those pcre_exec() error codes
5834     that can actually happen in MariaDB.
5835   */
5836   switch (rc)
5837   {
5838   case PCRE_ERROR_NULL:
5839     errmsg= "pcre_exec: null argument passed";
5840     break;
5841   case PCRE_ERROR_BADOPTION:
5842     errmsg= "pcre_exec: bad option";
5843     break;
5844   case PCRE_ERROR_BADMAGIC:
5845     errmsg= "pcre_exec: bad magic - not a compiled regex";
5846     break;
5847   case PCRE_ERROR_UNKNOWN_OPCODE:
5848     errmsg= "pcre_exec: error in compiled regex";
5849     break;
5850   case PCRE_ERROR_NOMEMORY:
5851     errmsg= "pcre_exec: Out of memory";
5852     break;
5853   case PCRE_ERROR_NOSUBSTRING:
5854     errmsg= "pcre_exec: no substring";
5855     break;
5856   case PCRE_ERROR_MATCHLIMIT:
5857     errmsg= "pcre_exec: match limit exceeded";
5858     break;
5859   case PCRE_ERROR_CALLOUT:
5860     errmsg= "pcre_exec: callout error";
5861     break;
5862   case PCRE_ERROR_BADUTF8:
5863     errmsg= "pcre_exec: Invalid utf8 byte sequence in the subject string";
5864     break;
5865   case PCRE_ERROR_BADUTF8_OFFSET:
5866     errmsg= "pcre_exec: Started at invalid location within utf8 byte sequence";
5867     break;
5868   case PCRE_ERROR_PARTIAL:
5869     errmsg= "pcre_exec: partial match";
5870     break;
5871   case PCRE_ERROR_INTERNAL:
5872     errmsg= "pcre_exec: internal error";
5873     break;
5874   case PCRE_ERROR_BADCOUNT:
5875     errmsg= "pcre_exec: ovesize is negative";
5876     break;
5877   case PCRE_ERROR_RECURSIONLIMIT:
5878     my_snprintf(buf, sizeof(buf), "pcre_exec: recursion limit of %ld exceeded",
5879                 m_pcre_extra.match_limit_recursion);
5880     errmsg= buf;
5881     break;
5882   case PCRE_ERROR_BADNEWLINE:
5883     errmsg= "pcre_exec: bad newline options";
5884     break;
5885   case PCRE_ERROR_BADOFFSET:
5886     errmsg= "pcre_exec: start offset negative or greater than string length";
5887     break;
5888   case PCRE_ERROR_SHORTUTF8:
5889     errmsg= "pcre_exec: ended in middle of utf8 sequence";
5890     break;
5891   case PCRE_ERROR_JIT_STACKLIMIT:
5892     errmsg= "pcre_exec: insufficient stack memory for JIT compile";
5893     break;
5894   case PCRE_ERROR_RECURSELOOP:
5895     errmsg= "pcre_exec: Recursion loop detected";
5896     break;
5897   case PCRE_ERROR_BADMODE:
5898     errmsg= "pcre_exec: compiled pattern passed to wrong bit library function";
5899     break;
5900   case PCRE_ERROR_BADENDIANNESS:
5901     errmsg= "pcre_exec: compiled pattern passed to wrong endianness processor";
5902     break;
5903   case PCRE_ERROR_JIT_BADOPTION:
5904     errmsg= "pcre_exec: bad jit option";
5905     break;
5906   case PCRE_ERROR_BADLENGTH:
5907     errmsg= "pcre_exec: negative length";
5908     break;
5909   default:
5910     /*
5911       As other error codes should normally not happen,
5912       we just report the error code without textual description
5913       of the code.
5914     */
5915     my_snprintf(buf, sizeof(buf), "pcre_exec: Internal error (%d)", rc);
5916     errmsg= buf;
5917   }
5918   push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
5919                       ER_REGEXP_ERROR, ER_THD(thd, ER_REGEXP_ERROR), errmsg);
5920 }
5921 
5922 
5923 /**
5924   Call pcre_exec() and send a warning if pcre_exec() returned with an error.
5925 */
pcre_exec_with_warn(const pcre * code,const pcre_extra * extra,const char * subject,int length,int startoffset,int options,int * ovector,int ovecsize)5926 int Regexp_processor_pcre::pcre_exec_with_warn(const pcre *code,
5927                                                const pcre_extra *extra,
5928                                                const char *subject,
5929                                                int length, int startoffset,
5930                                                int options, int *ovector,
5931                                                int ovecsize)
5932 {
5933   int rc= pcre_exec(code, extra, subject, length,
5934                     startoffset, options, ovector, ovecsize);
5935   DBUG_EXECUTE_IF("pcre_exec_error_123", rc= -123;);
5936   if (unlikely(rc < PCRE_ERROR_NOMATCH))
5937     pcre_exec_warn(rc);
5938   return rc;
5939 }
5940 
5941 
exec(const char * str,size_t length,size_t offset)5942 bool Regexp_processor_pcre::exec(const char *str, size_t length, size_t offset)
5943 {
5944   m_pcre_exec_rc= pcre_exec_with_warn(m_pcre, &m_pcre_extra, str, (int)length, (int)offset, 0,
5945                                       m_SubStrVec, array_elements(m_SubStrVec));
5946   return false;
5947 }
5948 
5949 
exec(String * str,int offset,uint n_result_offsets_to_convert)5950 bool Regexp_processor_pcre::exec(String *str, int offset,
5951                                   uint n_result_offsets_to_convert)
5952 {
5953   if (!(str= convert_if_needed(str, &subject_converter)))
5954     return true;
5955   m_pcre_exec_rc= pcre_exec_with_warn(m_pcre, &m_pcre_extra,
5956                                       str->c_ptr_safe(), str->length(),
5957                                       offset, 0,
5958                                       m_SubStrVec, array_elements(m_SubStrVec));
5959   if (m_pcre_exec_rc > 0)
5960   {
5961     uint i;
5962     for (i= 0; i < n_result_offsets_to_convert; i++)
5963     {
5964       /*
5965         Convert byte offset into character offset.
5966       */
5967       m_SubStrVec[i]= (int) str->charset()->cset->numchars(str->charset(),
5968                                                            str->ptr(),
5969                                                            str->ptr() +
5970                                                            m_SubStrVec[i]);
5971     }
5972   }
5973   return false;
5974 }
5975 
5976 
exec(Item * item,int offset,uint n_result_offsets_to_convert)5977 bool Regexp_processor_pcre::exec(Item *item, int offset,
5978                                 uint n_result_offsets_to_convert)
5979 {
5980   char buff[MAX_FIELD_WIDTH];
5981   String tmp(buff,sizeof(buff),&my_charset_bin);
5982   String *res= item->val_str(&tmp);
5983   if (item->null_value)
5984     return true;
5985   return exec(res, offset, n_result_offsets_to_convert);
5986 }
5987 
5988 
fix_owner(Item_func * owner,Item * subject_arg,Item * pattern_arg)5989 void Regexp_processor_pcre::fix_owner(Item_func *owner,
5990                                       Item *subject_arg,
5991                                       Item *pattern_arg)
5992 {
5993   if (!is_compiled() && pattern_arg->const_item())
5994   {
5995     if (compile(pattern_arg, true))
5996     {
5997       owner->maybe_null= 1; // Will always return NULL
5998       return;
5999     }
6000     set_const(true);
6001     owner->maybe_null= subject_arg->maybe_null;
6002   }
6003   else
6004     owner->maybe_null= 1;
6005 }
6006 
6007 
fix_fields(THD * thd,Item ** ref)6008 bool Item_func_regex::fix_fields(THD *thd, Item **ref)
6009 {
6010   re.set_recursion_limit(thd);
6011   return Item_bool_func::fix_fields(thd, ref);
6012 }
6013 
6014 bool
fix_length_and_dec()6015 Item_func_regex::fix_length_and_dec()
6016 {
6017   if (Item_bool_func::fix_length_and_dec() ||
6018       agg_arg_charsets_for_comparison(cmp_collation, args, 2))
6019     return TRUE;
6020 
6021   re.init(cmp_collation.collation, 0);
6022   re.fix_owner(this, args[0], args[1]);
6023   return FALSE;
6024 }
6025 
6026 
val_int()6027 longlong Item_func_regex::val_int()
6028 {
6029   DBUG_ASSERT(fixed == 1);
6030   if ((null_value= re.recompile(args[1])))
6031     return 0;
6032 
6033   if ((null_value= re.exec(args[0], 0, 0)))
6034     return 0;
6035 
6036   return re.match();
6037 }
6038 
6039 
fix_fields(THD * thd,Item ** ref)6040 bool Item_func_regexp_instr::fix_fields(THD *thd, Item **ref)
6041 {
6042   re.set_recursion_limit(thd);
6043   return Item_int_func::fix_fields(thd, ref);
6044 }
6045 
6046 
6047 bool
fix_length_and_dec()6048 Item_func_regexp_instr::fix_length_and_dec()
6049 {
6050   if (agg_arg_charsets_for_comparison(cmp_collation, args, 2))
6051     return TRUE;
6052 
6053   re.init(cmp_collation.collation, 0);
6054   re.fix_owner(this, args[0], args[1]);
6055   max_length= MY_INT32_NUM_DECIMAL_DIGITS; // See also Item_func_locate
6056   return FALSE;
6057 }
6058 
6059 
val_int()6060 longlong Item_func_regexp_instr::val_int()
6061 {
6062   DBUG_ASSERT(fixed == 1);
6063   if ((null_value= re.recompile(args[1])))
6064     return 0;
6065 
6066   if ((null_value= re.exec(args[0], 0, 1)))
6067     return 0;
6068 
6069   return re.match() ? re.subpattern_start(0) + 1 : 0;
6070 }
6071 
6072 
6073 #ifdef LIKE_CMP_TOUPPER
6074 #define likeconv(cs,A) (uchar) (cs)->toupper(A)
6075 #else
6076 #define likeconv(cs,A) (uchar) (cs)->sort_order[(uchar) (A)]
6077 #endif
6078 
6079 
6080 /**
6081   Precomputation dependent only on pattern_len.
6082 */
6083 
turboBM_compute_suffixes(int * suff)6084 void Item_func_like::turboBM_compute_suffixes(int *suff)
6085 {
6086   const int   plm1 = pattern_len - 1;
6087   int            f = 0;
6088   int            g = plm1;
6089   int *const splm1 = suff + plm1;
6090   CHARSET_INFO	*cs= cmp_collation.collation;
6091 
6092   *splm1 = pattern_len;
6093 
6094   if (!cs->sort_order)
6095   {
6096     int i;
6097     for (i = pattern_len - 2; i >= 0; i--)
6098     {
6099       int tmp = *(splm1 + i - f);
6100       if (g < i && tmp < i - g)
6101 	suff[i] = tmp;
6102       else
6103       {
6104 	if (i < g)
6105 	  g = i; // g = MY_MIN(i, g)
6106 	f = i;
6107 	while (g >= 0 && pattern[g] == pattern[g + plm1 - f])
6108 	  g--;
6109 	suff[i] = f - g;
6110       }
6111     }
6112   }
6113   else
6114   {
6115     int i;
6116     for (i = pattern_len - 2; 0 <= i; --i)
6117     {
6118       int tmp = *(splm1 + i - f);
6119       if (g < i && tmp < i - g)
6120 	suff[i] = tmp;
6121       else
6122       {
6123 	if (i < g)
6124 	  g = i; // g = MY_MIN(i, g)
6125 	f = i;
6126 	while (g >= 0 &&
6127 	       likeconv(cs, pattern[g]) == likeconv(cs, pattern[g + plm1 - f]))
6128 	  g--;
6129 	suff[i] = f - g;
6130       }
6131     }
6132   }
6133 }
6134 
6135 
6136 /**
6137   Precomputation dependent only on pattern_len.
6138 */
6139 
turboBM_compute_good_suffix_shifts(int * suff)6140 void Item_func_like::turboBM_compute_good_suffix_shifts(int *suff)
6141 {
6142   turboBM_compute_suffixes(suff);
6143 
6144   int *end = bmGs + pattern_len;
6145   int *k;
6146   for (k = bmGs; k < end; k++)
6147     *k = pattern_len;
6148 
6149   int tmp;
6150   int i;
6151   int j          = 0;
6152   const int plm1 = pattern_len - 1;
6153   for (i = plm1; i > -1; i--)
6154   {
6155     if (suff[i] == i + 1)
6156     {
6157       for (tmp = plm1 - i; j < tmp; j++)
6158       {
6159 	int *tmp2 = bmGs + j;
6160 	if (*tmp2 == pattern_len)
6161 	  *tmp2 = tmp;
6162       }
6163     }
6164   }
6165 
6166   int *tmp2;
6167   for (tmp = plm1 - i; j < tmp; j++)
6168   {
6169     tmp2 = bmGs + j;
6170     if (*tmp2 == pattern_len)
6171       *tmp2 = tmp;
6172   }
6173 
6174   tmp2 = bmGs + plm1;
6175   for (i = 0; i <= pattern_len - 2; i++)
6176     *(tmp2 - suff[i]) = plm1 - i;
6177 }
6178 
6179 
6180 /**
6181    Precomputation dependent on pattern_len.
6182 */
6183 
turboBM_compute_bad_character_shifts()6184 void Item_func_like::turboBM_compute_bad_character_shifts()
6185 {
6186   int *i;
6187   int *end = bmBc + alphabet_size;
6188   int j;
6189   const int plm1 = pattern_len - 1;
6190   CHARSET_INFO	*cs= cmp_collation.collation;
6191 
6192   for (i = bmBc; i < end; i++)
6193     *i = pattern_len;
6194 
6195   if (!cs->sort_order)
6196   {
6197     for (j = 0; j < plm1; j++)
6198       bmBc[(uint) (uchar) pattern[j]] = plm1 - j;
6199   }
6200   else
6201   {
6202     for (j = 0; j < plm1; j++)
6203       bmBc[(uint) likeconv(cs,pattern[j])] = plm1 - j;
6204   }
6205 }
6206 
6207 
6208 /**
6209   Search for pattern in text.
6210 
6211   @return
6212     returns true/false for match/no match
6213 */
6214 
turboBM_matches(const char * text,int text_len) const6215 bool Item_func_like::turboBM_matches(const char* text, int text_len) const
6216 {
6217   int bcShift;
6218   int turboShift;
6219   int shift = pattern_len;
6220   int j     = 0;
6221   int u     = 0;
6222   CHARSET_INFO	*cs= cmp_collation.collation;
6223 
6224   const int plm1=  pattern_len - 1;
6225   const int tlmpl= text_len - pattern_len;
6226 
6227   /* Searching */
6228   if (!cs->sort_order)
6229   {
6230     while (j <= tlmpl)
6231     {
6232       int i= plm1;
6233       while (i >= 0 && pattern[i] == text[i + j])
6234       {
6235 	i--;
6236 	if (i == plm1 - shift)
6237 	  i-= u;
6238       }
6239       if (i < 0)
6240 	return 1;
6241 
6242       const int v= plm1 - i;
6243       turboShift = u - v;
6244       bcShift    = bmBc[(uint) (uchar) text[i + j]] - plm1 + i;
6245       shift      = MY_MAX(turboShift, bcShift);
6246       shift      = MY_MAX(shift, bmGs[i]);
6247       if (shift == bmGs[i])
6248 	u = MY_MIN(pattern_len - shift, v);
6249       else
6250       {
6251 	if (turboShift < bcShift)
6252 	  shift = MY_MAX(shift, u + 1);
6253 	u = 0;
6254       }
6255       j+= shift;
6256     }
6257     return 0;
6258   }
6259   else
6260   {
6261     while (j <= tlmpl)
6262     {
6263       int i= plm1;
6264       while (i >= 0 && likeconv(cs,pattern[i]) == likeconv(cs,text[i + j]))
6265       {
6266 	i--;
6267 	if (i == plm1 - shift)
6268 	  i-= u;
6269       }
6270       if (i < 0)
6271 	return 1;
6272 
6273       const int v= plm1 - i;
6274       turboShift = u - v;
6275       bcShift    = bmBc[(uint) likeconv(cs, text[i + j])] - plm1 + i;
6276       shift      = MY_MAX(turboShift, bcShift);
6277       shift      = MY_MAX(shift, bmGs[i]);
6278       if (shift == bmGs[i])
6279 	u = MY_MIN(pattern_len - shift, v);
6280       else
6281       {
6282 	if (turboShift < bcShift)
6283 	  shift = MY_MAX(shift, u + 1);
6284 	u = 0;
6285       }
6286       j+= shift;
6287     }
6288     return 0;
6289   }
6290 }
6291 
6292 
6293 /**
6294   Make a logical XOR of the arguments.
6295 
6296   If either operator is NULL, return NULL.
6297 
6298   @todo
6299     (low priority) Change this to be optimized as: @n
6300     A XOR B   ->  (A) == 1 AND (B) <> 1) OR (A <> 1 AND (B) == 1) @n
6301     To be able to do this, we would however first have to extend the MySQL
6302     range optimizer to handle OR better.
6303 
6304   @note
6305     As we don't do any index optimization on XOR this is not going to be
6306     very fast to use.
6307 */
6308 
val_int()6309 longlong Item_func_xor::val_int()
6310 {
6311   DBUG_ASSERT(fixed == 1);
6312   int result= 0;
6313   null_value= false;
6314   for (uint i= 0; i < arg_count; i++)
6315   {
6316     result^= (args[i]->val_int() != 0);
6317     if (args[i]->null_value)
6318     {
6319       null_value= true;
6320       return 0;
6321     }
6322   }
6323   return result;
6324 }
6325 
6326 /**
6327   Apply NOT transformation to the item and return a new one.
6328 
6329 
6330     Transform the item using next rules:
6331     @verbatim
6332        a AND b AND ...    -> NOT(a) OR NOT(b) OR ...
6333        a OR b OR ...      -> NOT(a) AND NOT(b) AND ...
6334        NOT(a)             -> a
6335        a = b              -> a != b
6336        a != b             -> a = b
6337        a < b              -> a >= b
6338        a >= b             -> a < b
6339        a > b              -> a <= b
6340        a <= b             -> a > b
6341        IS NULL(a)         -> IS NOT NULL(a)
6342        IS NOT NULL(a)     -> IS NULL(a)
6343     @endverbatim
6344 
6345   @param thd		thread handler
6346 
6347   @return
6348     New item or
6349     NULL if we cannot apply NOT transformation (see Item::neg_transformer()).
6350 */
6351 
neg_transformer(THD * thd)6352 Item *Item_func_not::neg_transformer(THD *thd)	/* NOT(x)  ->  x */
6353 {
6354   return args[0];
6355 }
6356 
6357 
fix_fields(THD * thd,Item ** ref)6358 bool Item_func_not::fix_fields(THD *thd, Item **ref)
6359 {
6360   args[0]->under_not(this);
6361   if (args[0]->type() == FIELD_ITEM)
6362   {
6363     /* replace  "NOT <field>" with "<field> == 0" */
6364     Query_arena backup, *arena;
6365     Item *new_item;
6366     bool rc= TRUE;
6367     arena= thd->activate_stmt_arena_if_needed(&backup);
6368     if ((new_item= new (thd->mem_root) Item_func_eq(thd, args[0], new (thd->mem_root) Item_int(thd, 0, 1))))
6369     {
6370       new_item->name= name;
6371       rc= (*ref= new_item)->fix_fields(thd, ref);
6372     }
6373     if (arena)
6374       thd->restore_active_arena(arena, &backup);
6375     return rc;
6376   }
6377   return Item_func::fix_fields(thd, ref);
6378 }
6379 
6380 
neg_transformer(THD * thd)6381 Item *Item_bool_rowready_func2::neg_transformer(THD *thd)
6382 {
6383   Item *item= negated_item(thd);
6384   return item;
6385 }
6386 
6387 /**
6388   XOR can be negated by negating one of the operands:
6389 
6390   NOT (a XOR b)  => (NOT a) XOR b
6391                  => a       XOR (NOT b)
6392 
6393   @param thd     Thread handle
6394   @return        New negated item
6395 */
neg_transformer(THD * thd)6396 Item *Item_func_xor::neg_transformer(THD *thd)
6397 {
6398   Item *neg_operand;
6399   Item_func_xor *new_item;
6400   if ((neg_operand= args[0]->neg_transformer(thd)))
6401     // args[0] has neg_tranformer
6402     new_item= new(thd->mem_root) Item_func_xor(thd, neg_operand, args[1]);
6403   else if ((neg_operand= args[1]->neg_transformer(thd)))
6404     // args[1] has neg_tranformer
6405     new_item= new(thd->mem_root) Item_func_xor(thd, args[0], neg_operand);
6406   else
6407   {
6408     neg_operand= new(thd->mem_root) Item_func_not(thd, args[0]);
6409     new_item= new(thd->mem_root) Item_func_xor(thd, neg_operand, args[1]);
6410   }
6411   return new_item;
6412 }
6413 
6414 
6415 /**
6416   a IS NULL  ->  a IS NOT NULL.
6417 */
neg_transformer(THD * thd)6418 Item *Item_func_isnull::neg_transformer(THD *thd)
6419 {
6420   Item *item= new (thd->mem_root) Item_func_isnotnull(thd, args[0]);
6421   return item;
6422 }
6423 
6424 
6425 /**
6426   a IS NOT NULL  ->  a IS NULL.
6427 */
neg_transformer(THD * thd)6428 Item *Item_func_isnotnull::neg_transformer(THD *thd)
6429 {
6430   Item *item= new (thd->mem_root) Item_func_isnull(thd, args[0]);
6431   return item;
6432 }
6433 
6434 
neg_transformer(THD * thd)6435 Item *Item_cond_and::neg_transformer(THD *thd)	/* NOT(a AND b AND ...)  -> */
6436 					/* NOT a OR NOT b OR ... */
6437 {
6438   neg_arguments(thd);
6439   Item *item= new (thd->mem_root) Item_cond_or(thd, list);
6440   return item;
6441 }
6442 
6443 
neg_transformer(THD * thd)6444 Item *Item_cond_or::neg_transformer(THD *thd)	/* NOT(a OR b OR ...)  -> */
6445 					/* NOT a AND NOT b AND ... */
6446 {
6447   neg_arguments(thd);
6448   Item *item= new (thd->mem_root) Item_cond_and(thd, list);
6449   return item;
6450 }
6451 
6452 
neg_transformer(THD * thd)6453 Item *Item_func_nop_all::neg_transformer(THD *thd)
6454 {
6455   /* "NOT (e $cmp$ ANY (SELECT ...)) -> e $rev_cmp$" ALL (SELECT ...) */
6456   Item_func_not_all *new_item= new (thd->mem_root) Item_func_not_all(thd, args[0]);
6457   Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
6458   allany->create_comp_func(FALSE);
6459   allany->all= !allany->all;
6460   allany->upper_item= new_item;
6461   return new_item;
6462 }
6463 
neg_transformer(THD * thd)6464 Item *Item_func_not_all::neg_transformer(THD *thd)
6465 {
6466   /* "NOT (e $cmp$ ALL (SELECT ...)) -> e $rev_cmp$" ANY (SELECT ...) */
6467   Item_func_nop_all *new_item= new (thd->mem_root) Item_func_nop_all(thd, args[0]);
6468   Item_allany_subselect *allany= (Item_allany_subselect*)args[0];
6469   allany->all= !allany->all;
6470   allany->create_comp_func(TRUE);
6471   allany->upper_item= new_item;
6472   return new_item;
6473 }
6474 
negated_item(THD * thd)6475 Item *Item_func_eq::negated_item(THD *thd) /* a = b  ->  a != b */
6476 {
6477   return new (thd->mem_root) Item_func_ne(thd, args[0], args[1]);
6478 }
6479 
6480 
negated_item(THD * thd)6481 Item *Item_func_ne::negated_item(THD *thd) /* a != b  ->  a = b */
6482 {
6483   return new (thd->mem_root) Item_func_eq(thd, args[0], args[1]);
6484 }
6485 
6486 
negated_item(THD * thd)6487 Item *Item_func_lt::negated_item(THD *thd) /* a < b  ->  a >= b */
6488 {
6489   return new (thd->mem_root) Item_func_ge(thd, args[0], args[1]);
6490 }
6491 
6492 
negated_item(THD * thd)6493 Item *Item_func_ge::negated_item(THD *thd) /* a >= b  ->  a < b */
6494 {
6495   return new (thd->mem_root) Item_func_lt(thd, args[0], args[1]);
6496 }
6497 
6498 
negated_item(THD * thd)6499 Item *Item_func_gt::negated_item(THD *thd) /* a > b  ->  a <= b */
6500 {
6501   return new (thd->mem_root) Item_func_le(thd, args[0], args[1]);
6502 }
6503 
6504 
negated_item(THD * thd)6505 Item *Item_func_le::negated_item(THD *thd) /* a <= b  ->  a > b */
6506 {
6507   return new (thd->mem_root) Item_func_gt(thd, args[0], args[1]);
6508 }
6509 
6510 /**
6511   just fake method, should never be called.
6512 */
negated_item(THD * thd)6513 Item *Item_bool_rowready_func2::negated_item(THD *thd)
6514 {
6515   DBUG_ASSERT(0);
6516   return 0;
6517 }
6518 
6519 
6520 /**
6521   Construct a minimal multiple equality item
6522 
6523   @param f1               the first equal item
6524   @param f2               the second equal item
6525   @param with_const_item  TRUE if the first item is constant
6526 
6527   @details
6528   The constructor builds a new item equal object for the equality f1=f2.
6529   One of the equal items can be constant. If this is the case it is passed
6530   always as the first parameter and the parameter with_const_item serves
6531   as an indicator of this case.
6532   Currently any non-constant parameter items must point to an item of the
6533   of the type Item_field or Item_direct_view_ref(Item_field).
6534 */
6535 
Item_equal(THD * thd,const Type_handler * handler,Item * f1,Item * f2,bool with_const_item)6536 Item_equal::Item_equal(THD *thd, const Type_handler *handler,
6537                        Item *f1, Item *f2, bool with_const_item):
6538   Item_bool_func(thd), eval_item(0), cond_false(0), cond_true(0),
6539   context_field(NULL), link_equal_fields(FALSE),
6540   m_compare_handler(handler),
6541   m_compare_collation(f2->collation.collation)
6542 {
6543   const_item_cache= 0;
6544   with_const= with_const_item;
6545   equal_items.push_back(f1, thd->mem_root);
6546   equal_items.push_back(f2, thd->mem_root);
6547   upper_levels= NULL;
6548 }
6549 
6550 
6551 /**
6552   Copy constructor for a multiple equality
6553 
6554   @param item_equal   source item for the constructor
6555 
6556   @details
6557   The function creates a copy of an Item_equal object.
6558   This constructor is used when an item belongs to a multiple equality
6559   of an upper level (an upper AND/OR level or an upper level of a nested
6560   outer join).
6561 */
6562 
Item_equal(THD * thd,Item_equal * item_equal)6563 Item_equal::Item_equal(THD *thd, Item_equal *item_equal):
6564   Item_bool_func(thd), eval_item(0), cond_false(0), cond_true(0),
6565   context_field(NULL), link_equal_fields(FALSE),
6566   m_compare_handler(item_equal->m_compare_handler),
6567   m_compare_collation(item_equal->m_compare_collation)
6568 {
6569   const_item_cache= 0;
6570   List_iterator_fast<Item> li(item_equal->equal_items);
6571   Item *item;
6572   while ((item= li++))
6573   {
6574     equal_items.push_back(item, thd->mem_root);
6575   }
6576   with_const= item_equal->with_const;
6577   cond_false= item_equal->cond_false;
6578   upper_levels= item_equal->upper_levels;
6579 }
6580 
6581 
6582 /**
6583   @brief
6584   Add a constant item to the Item_equal object
6585 
6586   @param[in]  c  the constant to add
6587   @param[in]  f  item from the list equal_items the item c is equal to
6588                  (this parameter is optional)
6589 
6590   @details
6591   The method adds the constant item c to the equal_items list. If the list
6592   doesn't have any constant item yet the item c is just put in the front
6593   the list. Otherwise the value of c is compared with the value of the
6594   constant item from equal_items. If they are not equal cond_false is set
6595   to TRUE. This serves as an indicator that this Item_equal is always FALSE.
6596 */
6597 
add_const(THD * thd,Item * c)6598 void Item_equal::add_const(THD *thd, Item *c)
6599 {
6600   if (cond_false)
6601     return;
6602   if (!with_const)
6603   {
6604     with_const= TRUE;
6605     equal_items.push_front(c, thd->mem_root);
6606     return;
6607   }
6608 
6609   /*
6610     Suppose we have an expression (with a string type field) like this:
6611       WHERE field=const1 AND field=const2 ...
6612 
6613     For all pairs field=constXXX we know that:
6614 
6615     - Item_func_eq::fix_length_and_dec() performed collation and character
6616     set aggregation and added character set converters when needed.
6617     Note, the case like:
6618       WHERE field=const1 COLLATE latin1_bin AND field=const2
6619     is not handled here, because the field would be replaced to
6620     Item_func_set_collation, which cannot get into Item_equal.
6621     So all constXXX that are handled by Item_equal
6622     already have compatible character sets with "field".
6623 
6624     - Also, Field_str::test_if_equality_guarantees_uniqueness() guarantees
6625     that the comparison collation of all equalities handled by Item_equal
6626     match the the collation of the field.
6627 
6628     Therefore, at Item_equal::add_const() time all constants constXXX
6629     should be directly comparable to each other without an additional
6630     character set conversion.
6631     It's safe to do val_str() for "const_item" and "c" and compare
6632     them according to the collation of the *field*.
6633 
6634     So in a script like this:
6635       CREATE TABLE t1 (a VARCHAR(10) COLLATE xxx);
6636       INSERT INTO t1 VALUES ('a'),('A');
6637       SELECT * FROM t1 WHERE a='a' AND a='A';
6638     Item_equal::add_const() effectively rewrites the condition to:
6639       SELECT * FROM t1 WHERE a='a' AND 'a' COLLATE xxx='A';
6640     and then to:
6641       SELECT * FROM t1 WHERE a='a'; // if the two constants were equal
6642                                     // e.g. in case of latin1_swedish_ci
6643     or to:
6644       SELECT * FROM t1 WHERE FALSE; // if the two constants were not equal
6645                                     // e.g. in case of latin1_bin
6646 
6647     Note, both "const_item" and "c" can return NULL, e.g.:
6648       SELECT * FROM t1 WHERE a=NULL    AND a='const';
6649       SELECT * FROM t1 WHERE a='const' AND a=NULL;
6650       SELECT * FROM t1 WHERE a='const' AND a=(SELECT MAX(a) FROM t2)
6651   */
6652 
6653   cond_false= !Item_equal::compare_type_handler()->Item_eq_value(thd, this, c,
6654                                                                  get_const());
6655   if (with_const && equal_items.elements == 1)
6656     cond_true= TRUE;
6657   if (cond_false || cond_true)
6658     const_item_cache= 1;
6659 }
6660 
6661 
6662 /**
6663   @brief
6664   Check whether a field is referred to in the multiple equality
6665 
6666   @param field   field whose occurrence is to be checked
6667 
6668   @details
6669   The function checks whether field is referred to by one of the
6670   items from the equal_items list.
6671 
6672   @retval
6673     1       if multiple equality contains a reference to field
6674   @retval
6675     0       otherwise
6676 */
6677 
contains(Field * field)6678 bool Item_equal::contains(Field *field)
6679 {
6680   Item_equal_fields_iterator it(*this);
6681   while (it++)
6682   {
6683     if (field->eq(it.get_curr_field()))
6684         return 1;
6685   }
6686   return 0;
6687 }
6688 
6689 
6690 /**
6691   @brief
6692   Join members of another Item_equal object
6693 
6694   @param item    multiple equality whose members are to be joined
6695 
6696   @details
6697   The function actually merges two multiple equalities. After this operation
6698   the Item_equal object additionally contains the field items of another item of
6699   the type Item_equal.
6700   If the optional constant items are not equal the cond_false flag is set to TRUE.
6701 
6702   @notes
6703   The function is called for any equality f1=f2 such that f1 and f2 are items
6704   of the type Item_field or Item_direct_view_ref(Item_field), and, f1->field is
6705   referred to in the list this->equal_items, while the list item->equal_items
6706   contains a reference to f2->field.
6707 */
6708 
merge(THD * thd,Item_equal * item)6709 void Item_equal::merge(THD *thd, Item_equal *item)
6710 {
6711   Item *c= item->get_const();
6712   if (c)
6713     item->equal_items.pop();
6714   equal_items.append(&item->equal_items);
6715   if (c)
6716   {
6717     /*
6718       The flag cond_false will be set to TRUE after this if
6719       the multiple equality already contains a constant and its
6720       value is not equal to the value of c.
6721     */
6722     add_const(thd, c);
6723   }
6724   cond_false|= item->cond_false;
6725 }
6726 
6727 
6728 /**
6729   @brief
6730   Merge members of another Item_equal object into this one
6731 
6732   @param item         multiple equality whose members are to be merged
6733   @param save_merged  keep the list of equalities in 'item' intact
6734                       (e.g. for other merges)
6735 
6736   @details
6737   If the Item_equal 'item' happens to have some elements of the list
6738   of equal items belonging to 'this' object then the function merges
6739   the equal items from 'item' into this list.
6740   If both lists contains constants and they are different then
6741   the value of the cond_false flag is set to TRUE.
6742 
6743   @retval
6744     1    the lists of equal items in 'item' and 'this' contain common elements
6745   @retval
6746     0    otherwise
6747 
6748   @notes
6749   The method 'merge' just joins the list of equal items belonging to 'item'
6750   to the list of equal items belonging to this object assuming that the lists
6751   are disjoint. It would be more correct to call the method 'join'.
6752   The method 'merge_into_with_check' really merges two lists of equal items if
6753   they have common members.
6754 */
6755 
merge_with_check(THD * thd,Item_equal * item,bool save_merged)6756 bool Item_equal::merge_with_check(THD *thd, Item_equal *item, bool save_merged)
6757 {
6758   bool intersected= FALSE;
6759   Item_equal_fields_iterator_slow fi(*item);
6760 
6761   while (fi++)
6762   {
6763     if (contains(fi.get_curr_field()))
6764     {
6765       intersected= TRUE;
6766       if (!save_merged)
6767         fi.remove();
6768     }
6769   }
6770   if (intersected)
6771   {
6772     if (!save_merged)
6773       merge(thd, item);
6774     else
6775     {
6776       Item *c= item->get_const();
6777       if (c)
6778         add_const(thd, c);
6779       if (!cond_false)
6780       {
6781         Item *item;
6782         fi.rewind();
6783         while ((item= fi++))
6784 	{
6785           if (!contains(fi.get_curr_field()))
6786             add(item, thd->mem_root);
6787         }
6788       }
6789     }
6790   }
6791   return intersected;
6792 }
6793 
6794 
6795 /**
6796   @brief
6797   Merge this object into a list of Item_equal objects
6798 
6799   @param list                 the list of Item_equal objects to merge into
6800   @param save_merged          keep the list of equalities in 'this' intact
6801                               (e.g. for other merges)
6802   @param only_intersected     do not merge if there are no common members
6803                               in any of Item_equal objects from the list
6804                               and this Item_equal
6805 
6806   @details
6807   If the list of equal items from 'this' object contains common members
6808   with the lists of equal items belonging to Item_equal objects from 'list'
6809   then all involved Item_equal objects e1,...,ek are merged into one
6810   Item equal that replaces e1,...,ek in the 'list'. Otherwise, in the case
6811   when the value of the parameter only_if_intersected is false, this
6812   Item_equal is joined to the 'list'.
6813 */
6814 
merge_into_list(THD * thd,List<Item_equal> * list,bool save_merged,bool only_intersected)6815 void Item_equal::merge_into_list(THD *thd, List<Item_equal> *list,
6816                                  bool save_merged,
6817                                  bool only_intersected)
6818 {
6819   Item_equal *item;
6820   List_iterator<Item_equal> it(*list);
6821   Item_equal *merge_into= NULL;
6822   while((item= it++))
6823   {
6824     if (!merge_into)
6825     {
6826       if (item->merge_with_check(thd, this, save_merged))
6827         merge_into= item;
6828     }
6829     else
6830     {
6831       if (merge_into->merge_with_check(thd, item, false))
6832         it.remove();
6833     }
6834   }
6835   if (!only_intersected && !merge_into)
6836     list->push_back(this, thd->mem_root);
6837 }
6838 
6839 
6840 /**
6841   @brief
6842   Order equal items of the  multiple equality according to a sorting criteria
6843 
6844   @param compare      function to compare items from the equal_items list
6845   @param arg          context extra parameter for the cmp function
6846 
6847   @details
6848   The function performs ordering of the items from the equal_items list
6849   according to the criteria determined by the cmp callback parameter.
6850   If cmp(item1,item2,arg)<0 than item1 must be placed after item2.
6851 
6852   @notes
6853   The function sorts equal items by the bubble sort algorithm.
6854   The list of field items is looked through and whenever two neighboring
6855   members follow in a wrong order they are swapped. This is performed
6856   again and again until we get all members in a right order.
6857 */
6858 
sort(Item_field_cmpfunc compare,void * arg)6859 void Item_equal::sort(Item_field_cmpfunc compare, void *arg)
6860 {
6861   bubble_sort<Item>(&equal_items, compare, arg);
6862 }
6863 
6864 
6865 /**
6866   @brief
6867   Check appearance of new constant items in the multiple equality object
6868 
6869   @details
6870   The function checks appearance of new constant items among the members
6871   of the equal_items list. Each new constant item is compared with
6872   the constant item from the list if there is any. If there is none the first
6873   new constant item is placed at the very beginning of the list and
6874   with_const is set to TRUE. If it happens that the compared constant items
6875   are unequal then the flag cond_false is set to TRUE.
6876 
6877   @notes
6878   Currently this function is called only after substitution of constant tables.
6879 */
6880 
update_const(THD * thd)6881 void Item_equal::update_const(THD *thd)
6882 {
6883   List_iterator<Item> it(equal_items);
6884   if (with_const)
6885     it++;
6886   Item *item;
6887   while ((item= it++))
6888   {
6889     if (item->const_item() && !item->is_expensive() &&
6890         /*
6891           Don't propagate constant status of outer-joined column.
6892           Such a constant status here is a result of:
6893             a) empty outer-joined table: in this case such a column has a
6894                value of NULL; but at the same time other arguments of
6895                Item_equal don't have to be NULLs and the value of the whole
6896                multiple equivalence expression doesn't have to be NULL or FALSE
6897                because of the outer join nature;
6898           or
6899             b) outer-joined table contains only 1 row: the result of
6900                this column is equal to a row field value *or* NULL.
6901           Both values are inacceptable as Item_equal constants.
6902         */
6903         !item->is_outer_field())
6904     {
6905       if (item == equal_items.head())
6906         with_const= TRUE;
6907       else
6908       {
6909         it.remove();
6910         add_const(thd, item);
6911       }
6912     }
6913   }
6914 }
6915 
6916 
6917 /**
6918   @brief
6919   Fix fields in a completely built multiple equality
6920 
6921   @param  thd     currently not used thread handle
6922   @param  ref     not used
6923 
6924   @details
6925   This function is called once the multiple equality has been built out of
6926   the WHERE/ON condition and no new members are expected to be added to the
6927   equal_items list anymore.
6928   As any implementation of the virtual fix_fields method the function
6929   calculates the cached values of not_null_tables_cache, used_tables_cache,
6930   const_item_cache and calls fix_length_and_dec().
6931   Additionally the function sets a reference to the Item_equal object in
6932   the non-constant items of the equal_items list unless such a reference has
6933   been already set.
6934 
6935   @notes
6936   Currently this function is called only in the function
6937   build_equal_items_for_cond.
6938 
6939   @retval
6940   FALSE   always
6941 */
6942 
fix_fields(THD * thd,Item ** ref)6943 bool Item_equal::fix_fields(THD *thd, Item **ref)
6944 {
6945   DBUG_ASSERT(fixed == 0);
6946   Item_equal_fields_iterator it(*this);
6947   Item *item;
6948   Field *first_equal_field= NULL;
6949   Field *last_equal_field= NULL;
6950   Field *prev_equal_field= NULL;
6951   not_null_tables_cache= used_tables_cache= 0;
6952   const_item_cache= 0;
6953   while ((item= it++))
6954   {
6955     table_map tmp_table_map;
6956     used_tables_cache|= item->used_tables();
6957     tmp_table_map= item->not_null_tables();
6958     not_null_tables_cache|= tmp_table_map;
6959     DBUG_ASSERT(!item->with_sum_func() && !item->with_subquery());
6960     if (item->maybe_null)
6961       maybe_null= 1;
6962     if (!item->get_item_equal())
6963       item->set_item_equal(this);
6964     if (link_equal_fields && item->real_item()->type() == FIELD_ITEM)
6965     {
6966       last_equal_field= ((Item_field *) (item->real_item()))->field;
6967       if (!prev_equal_field)
6968         first_equal_field= last_equal_field;
6969       else
6970         prev_equal_field->next_equal_field= last_equal_field;
6971       prev_equal_field= last_equal_field;
6972     }
6973   }
6974   if (prev_equal_field && last_equal_field != first_equal_field)
6975     last_equal_field->next_equal_field= first_equal_field;
6976   if (fix_length_and_dec())
6977     return TRUE;
6978   fixed= 1;
6979   return FALSE;
6980 }
6981 
6982 
6983 /**
6984   Update the value of the used table attribute and other attributes
6985  */
6986 
update_used_tables()6987 void Item_equal::update_used_tables()
6988 {
6989   not_null_tables_cache= used_tables_cache= 0;
6990   if ((const_item_cache= cond_false || cond_true))
6991     return;
6992   Item_equal_fields_iterator it(*this);
6993   Item *item;
6994   const_item_cache= 1;
6995   while ((item= it++))
6996   {
6997     item->update_used_tables();
6998     used_tables_cache|= item->used_tables();
6999     /* see commentary at Item_equal::update_const() */
7000     const_item_cache&= item->const_item() && !item->is_outer_field();
7001   }
7002 }
7003 
7004 
count_sargable_conds(void * arg)7005 bool Item_equal::count_sargable_conds(void *arg)
7006 {
7007   SELECT_LEX *sel= (SELECT_LEX *) arg;
7008   uint m= equal_items.elements;
7009   sel->cond_count+= m*(m-1);
7010   return 0;
7011 }
7012 
7013 
7014 /**
7015   @brief
7016   Evaluate multiple equality
7017 
7018   @details
7019   The function evaluate multiple equality to a boolean value.
7020   The function ignores non-constant items from the equal_items list.
7021   The function returns 1 if all constant items from the list are equal.
7022   It returns 0 if there are unequal constant items in the list or
7023   one of the constant items is evaluated to NULL.
7024 
7025   @notes
7026   Currently this function can be called only at the optimization
7027   stage after the constant table substitution, since all Item_equals
7028   are eliminated before the execution stage.
7029 
7030   @retval
7031      0     multiple equality is always FALSE or NULL
7032      1     otherwise
7033 */
7034 
val_int()7035 longlong Item_equal::val_int()
7036 {
7037   if (cond_false)
7038     return 0;
7039   if (cond_true)
7040     return 1;
7041   Item *item= get_const();
7042   Item_equal_fields_iterator it(*this);
7043   if (!item)
7044     item= it++;
7045   eval_item->store_value(item);
7046   if ((null_value= item->null_value))
7047     return 0;
7048   while ((item= it++))
7049   {
7050     Field *field= it.get_curr_field();
7051     /* Skip fields of tables that has not been read yet */
7052     if (!field->table->status || (field->table->status & STATUS_NULL_ROW))
7053     {
7054       const int rc= eval_item->cmp(item);
7055       if ((rc == TRUE) || (null_value= (rc == UNKNOWN)))
7056         return 0;
7057     }
7058   }
7059   return 1;
7060 }
7061 
7062 
fix_length_and_dec()7063 bool Item_equal::fix_length_and_dec()
7064 {
7065   Item *item= get_first(NO_PARTICULAR_TAB, NULL);
7066   const Type_handler *handler= item->type_handler();
7067   eval_item= handler->make_cmp_item(current_thd, item->collation.collation);
7068   return eval_item == NULL;
7069 }
7070 
7071 
walk(Item_processor processor,bool walk_subquery,void * arg)7072 bool Item_equal::walk(Item_processor processor, bool walk_subquery, void *arg)
7073 {
7074   Item *item;
7075   Item_equal_fields_iterator it(*this);
7076   while ((item= it++))
7077   {
7078     if (item->walk(processor, walk_subquery, arg))
7079       return 1;
7080   }
7081   return Item_func::walk(processor, walk_subquery, arg);
7082 }
7083 
7084 
transform(THD * thd,Item_transformer transformer,uchar * arg)7085 Item *Item_equal::transform(THD *thd, Item_transformer transformer, uchar *arg)
7086 {
7087   DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
7088 
7089   Item *item;
7090   Item_equal_fields_iterator it(*this);
7091   while ((item= it++))
7092   {
7093     Item *new_item= item->transform(thd, transformer, arg);
7094     if (!new_item)
7095       return 0;
7096 
7097     /*
7098       THD::change_item_tree() should be called only if the tree was
7099       really transformed, i.e. when a new item has been created.
7100       Otherwise we'll be allocating a lot of unnecessary memory for
7101       change records at each execution.
7102     */
7103     if (new_item != item)
7104       thd->change_item_tree((Item **) it.ref(), new_item);
7105   }
7106   return Item_func::transform(thd, transformer, arg);
7107 }
7108 
7109 
print(String * str,enum_query_type query_type)7110 void Item_equal::print(String *str, enum_query_type query_type)
7111 {
7112   if (cond_false)
7113   {
7114     str->append('0');
7115     return;
7116   }
7117   str->append(func_name());
7118   str->append('(');
7119   List_iterator_fast<Item> it(equal_items);
7120   Item *item;
7121   item= it++;
7122   item->print(str, query_type);
7123   while ((item= it++))
7124   {
7125     str->append(',');
7126     str->append(' ');
7127     item->print(str, query_type);
7128   }
7129   str->append(')');
7130 }
7131 
7132 
7133 /*
7134   @brief Get the first equal field of multiple equality.
7135   @param[in] field   the field to get equal field to
7136 
7137   @details Get the first field of multiple equality that is equal to the
7138   given field. In order to make semi-join materialization strategy work
7139   correctly we can't propagate equal fields from upper select to a
7140   materialized semi-join.
7141   Thus the fields is returned according to following rules:
7142 
7143   1) If the given field belongs to a semi-join then the first field in
7144      multiple equality which belong to the same semi-join is returned.
7145      Otherwise NULL is returned.
7146   2) If the given field doesn't belong to a semi-join then
7147      the first field in the multiple equality that doesn't belong to any
7148      semi-join is returned.
7149      If all fields in the equality are belong to semi-join(s) then NULL
7150      is returned.
7151   3) If no field is given then the first field in the multiple equality
7152      is returned without regarding whether it belongs to a semi-join or not.
7153 
7154   @retval Found first field in the multiple equality.
7155   @retval 0 if no field found.
7156 */
7157 
get_first(JOIN_TAB * context,Item * field_item)7158 Item* Item_equal::get_first(JOIN_TAB *context, Item *field_item)
7159 {
7160   Item_equal_fields_iterator it(*this);
7161   Item *item;
7162   if (!field_item)
7163     return (it++);
7164   Field *field= ((Item_field *) (field_item->real_item()))->field;
7165 
7166   /*
7167     Of all equal fields, return the first one we can use. Normally, this is the
7168     field which belongs to the table that is the first in the join order.
7169 
7170     There is one exception to this: When semi-join materialization strategy is
7171     used, and the given field belongs to a table within the semi-join nest, we
7172     must pick the first field in the semi-join nest.
7173 
7174     Example: suppose we have a join order:
7175 
7176        ot1 ot2  SJ-Mat(it1  it2  it3)  ot3
7177 
7178     and equality ot2.col = it1.col = it2.col
7179     If we're looking for best substitute for 'it2.col', we should pick it1.col
7180     and not ot2.col.
7181 
7182     eliminate_item_equal() also has code that deals with equality substitution
7183     in presence of SJM nests.
7184   */
7185 
7186   TABLE_LIST *emb_nest;
7187   if (context != NO_PARTICULAR_TAB)
7188     emb_nest= context->emb_sj_nest;
7189   else
7190     emb_nest= field->table->pos_in_table_list->embedding;
7191 
7192   if (emb_nest && emb_nest->sj_mat_info && emb_nest->sj_mat_info->is_used)
7193   {
7194     /*
7195       It's a field from an materialized semi-join. We can substitute it for
7196        - a constant item
7197        - a field from the same semi-join
7198        Find the first of such items:
7199     */
7200     while ((item= it++))
7201     {
7202       if (item->const_item() ||
7203           it.get_curr_field()->table->pos_in_table_list->embedding == emb_nest)
7204       {
7205         /*
7206           If we found given field then return NULL to avoid unnecessary
7207           substitution.
7208         */
7209         return (item != field_item) ? item : NULL;
7210       }
7211     }
7212   }
7213   else
7214   {
7215     /*
7216       The field is not in SJ-Materialization nest. We must return the first
7217       field in the join order. The field may be inside a semi-join nest, i.e
7218       a join order may look like this:
7219 
7220           SJ-Mat(it1  it2)  ot1  ot2
7221 
7222       where we're looking what to substitute ot2.col for. In this case we must
7223       still return it1.col, here's a proof why:
7224 
7225       First let's note that either it1.col or it2.col participates in
7226       subquery's IN-equality. It can't be otherwise, because materialization is
7227       only applicable to uncorrelated subqueries, so the only way we could
7228       infer "it1.col=ot1.col" is from the IN-equality. Ok, so IN-eqality has
7229       it1.col or it2.col on its inner side. it1.col is first such item in the
7230       join order, so it's not possible for SJ-Mat to be
7231       SJ-Materialization-lookup, it is SJ-Materialization-Scan. The scan part
7232       of this strategy will unpack value of it1.col=it2.col into it1.col
7233       (that's the first equal item inside the subquery), and we'll be able to
7234       get it from there. qed.
7235     */
7236 
7237     return equal_items.head();
7238   }
7239   // Shouldn't get here.
7240   DBUG_ASSERT(0);
7241   return NULL;
7242 }
7243 
7244 
val_int()7245 longlong Item_func_dyncol_check::val_int()
7246 {
7247   char buff[STRING_BUFFER_USUAL_SIZE];
7248   String tmp(buff, sizeof(buff), &my_charset_bin);
7249   DYNAMIC_COLUMN col;
7250   String *str;
7251   enum enum_dyncol_func_result rc;
7252 
7253   str= args[0]->val_str(&tmp);
7254   if (args[0]->null_value)
7255     goto null;
7256   col.length= str->length();
7257   /* We do not change the string, so could do this trick */
7258   col.str= (char *)str->ptr();
7259   rc= mariadb_dyncol_check(&col);
7260   if (rc < 0 && rc != ER_DYNCOL_FORMAT)
7261   {
7262     dynamic_column_error_message(rc);
7263     goto null;
7264   }
7265   null_value= FALSE;
7266   return rc == ER_DYNCOL_OK;
7267 
7268 null:
7269   null_value= TRUE;
7270   return 0;
7271 }
7272 
val_int()7273 longlong Item_func_dyncol_exists::val_int()
7274 {
7275   char buff[STRING_BUFFER_USUAL_SIZE], nmstrbuf[11];
7276   String tmp(buff, sizeof(buff), &my_charset_bin),
7277          nmbuf(nmstrbuf, sizeof(nmstrbuf), system_charset_info);
7278   DYNAMIC_COLUMN col;
7279   String *str;
7280   LEX_STRING buf, *name= NULL;
7281   ulonglong num= 0;
7282   enum enum_dyncol_func_result rc;
7283 
7284   if (args[1]->result_type() == INT_RESULT)
7285     num= args[1]->val_int();
7286   else
7287   {
7288     String *nm= args[1]->val_str(&nmbuf);
7289     if (!nm || args[1]->null_value)
7290     {
7291       null_value= 1;
7292       return 1;
7293     }
7294     if (my_charset_same(nm->charset(), DYNCOL_UTF))
7295     {
7296       buf.str= (char *) nm->ptr();
7297       buf.length= nm->length();
7298     }
7299     else
7300     {
7301       uint strlen= nm->length() * DYNCOL_UTF->mbmaxlen + 1;
7302       uint dummy_errors;
7303       buf.str= (char *) current_thd->alloc(strlen);
7304       if (buf.str)
7305       {
7306         buf.length=
7307           copy_and_convert(buf.str, strlen, DYNCOL_UTF,
7308                            nm->ptr(), nm->length(), nm->charset(),
7309                            &dummy_errors);
7310       }
7311       else
7312         buf.length= 0;
7313     }
7314     name= &buf;
7315   }
7316   str= args[0]->val_str(&tmp);
7317   if (args[0]->null_value || args[1]->null_value || num > UINT_MAX16)
7318     goto null;
7319   col.length= str->length();
7320   /* We do not change the string, so could do this trick */
7321   col.str= (char *)str->ptr();
7322   rc= ((name == NULL) ?
7323        mariadb_dyncol_exists_num(&col, (uint) num) :
7324        mariadb_dyncol_exists_named(&col, name));
7325   if (rc < 0)
7326   {
7327     dynamic_column_error_message(rc);
7328     goto null;
7329   }
7330   null_value= FALSE;
7331   return rc == ER_DYNCOL_YES;
7332 
7333 null:
7334   null_value= TRUE;
7335   return 0;
7336 }
7337 
7338 
create(THD * thd,Item * a,Item * b) const7339 Item_bool_rowready_func2 *Eq_creator::create(THD *thd, Item *a, Item *b) const
7340 {
7341   return new(thd->mem_root) Item_func_eq(thd, a, b);
7342 }
7343 
7344 
create_swap(THD * thd,Item * a,Item * b) const7345 Item_bool_rowready_func2* Eq_creator::create_swap(THD *thd, Item *a, Item *b) const
7346 {
7347   return new(thd->mem_root) Item_func_eq(thd, b, a);
7348 }
7349 
7350 
create(THD * thd,Item * a,Item * b) const7351 Item_bool_rowready_func2* Ne_creator::create(THD *thd, Item *a, Item *b) const
7352 {
7353   return new(thd->mem_root) Item_func_ne(thd, a, b);
7354 }
7355 
7356 
create_swap(THD * thd,Item * a,Item * b) const7357 Item_bool_rowready_func2* Ne_creator::create_swap(THD *thd, Item *a, Item *b) const
7358 {
7359   return new(thd->mem_root) Item_func_ne(thd, b, a);
7360 }
7361 
7362 
create(THD * thd,Item * a,Item * b) const7363 Item_bool_rowready_func2* Gt_creator::create(THD *thd, Item *a, Item *b) const
7364 {
7365   return new(thd->mem_root) Item_func_gt(thd, a, b);
7366 }
7367 
7368 
create_swap(THD * thd,Item * a,Item * b) const7369 Item_bool_rowready_func2* Gt_creator::create_swap(THD *thd, Item *a, Item *b) const
7370 {
7371   return new(thd->mem_root) Item_func_lt(thd, b, a);
7372 }
7373 
7374 
create(THD * thd,Item * a,Item * b) const7375 Item_bool_rowready_func2* Lt_creator::create(THD *thd, Item *a, Item *b) const
7376 {
7377   return new(thd->mem_root) Item_func_lt(thd, a, b);
7378 }
7379 
7380 
create_swap(THD * thd,Item * a,Item * b) const7381 Item_bool_rowready_func2* Lt_creator::create_swap(THD *thd, Item *a, Item *b) const
7382 {
7383   return new(thd->mem_root) Item_func_gt(thd, b, a);
7384 }
7385 
7386 
create(THD * thd,Item * a,Item * b) const7387 Item_bool_rowready_func2* Ge_creator::create(THD *thd, Item *a, Item *b) const
7388 {
7389   return new(thd->mem_root) Item_func_ge(thd, a, b);
7390 }
7391 
7392 
create_swap(THD * thd,Item * a,Item * b) const7393 Item_bool_rowready_func2* Ge_creator::create_swap(THD *thd, Item *a, Item *b) const
7394 {
7395   return new(thd->mem_root) Item_func_le(thd, b, a);
7396 }
7397 
7398 
create(THD * thd,Item * a,Item * b) const7399 Item_bool_rowready_func2* Le_creator::create(THD *thd, Item *a, Item *b) const
7400 {
7401   return new(thd->mem_root) Item_func_le(thd, a, b);
7402 }
7403 
7404 
create_swap(THD * thd,Item * a,Item * b) const7405 Item_bool_rowready_func2* Le_creator::create_swap(THD *thd, Item *a, Item *b) const
7406 {
7407   return new(thd->mem_root) Item_func_ge(thd, b, a);
7408 }
7409 
7410 
7411 bool
excl_dep_on_grouping_fields(st_select_lex * sel)7412 Item_equal::excl_dep_on_grouping_fields(st_select_lex *sel)
7413 {
7414   Item_equal_fields_iterator it(*this);
7415   Item *item;
7416 
7417   while ((item=it++))
7418   {
7419     if (item->excl_dep_on_grouping_fields(sel))
7420     {
7421       set_extraction_flag(FULL_EXTRACTION_FL);
7422       return true;
7423     }
7424   }
7425   return false;
7426 }
7427 
7428 
7429 /**
7430   @brief
7431     Transform multiple equality into list of equalities
7432 
7433   @param thd         the thread handle
7434   @param equalities  the list where created equalities are stored
7435   @param checker     the checker callback function to be applied to the nodes
7436                      of the tree of the object to check if multiple equality
7437                      elements can be used to create equalities
7438   @param arg         parameter to be passed to the checker
7439   @param clone_const true <=> clone the constant member if there is any
7440 
7441   @details
7442     How the method works on examples:
7443 
7444     Example 1:
7445     It takes MULT_EQ(x,a,b) and tries to create from its elements a set of
7446     equalities {(x=a),(x=b)}.
7447 
7448     Example 2:
7449     It takes MULT_EQ(1,a,b) and tries to create from its elements a set of
7450     equalities {(a=1),(a=b)}.
7451 
7452     How it is done:
7453 
7454     1. If there is a constant member c the first non-constant member x for
7455        which the function checker returns true is taken and an item for
7456        the equality x=c is created. When constructing the equality item
7457        the left part of the equality is always taken as a clone of x while
7458        the right part is taken as a clone of c only if clone_const == true.
7459 
7460     2. After this all equalities of the form x=a (where x designates the first
7461        non-constant member for which checker returns true and a is some other
7462        such member of the multiplle equality) are created. When constructing
7463        an equality item both its parts are taken as clones of x and a.
7464 
7465        Suppose in the examples above that for 'x', 'a', and 'b' the function
7466        checker returns true.
7467 
7468        Example 1:
7469          the equality (x=a) is built
7470          the equality (x=b) is built
7471 
7472        Example 2:
7473          the equality (a=1) is built
7474          the equality (a=b) is built
7475 
7476     3. As a result we get a set of equalities built with the elements of
7477        this multiple equality. They are saved in the equality list.
7478 
7479        Example 1:
7480        {(x=a),(x=b)}
7481 
7482        Example 2:
7483        {(a=1),(a=b)}
7484 
7485   @note
7486     This method is called for condition pushdown into materialized
7487     derived table/view, and IN subquery, and pushdown from HAVING into WHERE.
7488     When it is called for pushdown from HAVING the empty checker is passed.
7489     This is because in this case the elements of the multiple equality don't
7490     need to be  checked if they can be used to build equalities: either all
7491     equalities can be pushed or none of them can be pushed.
7492     When the function is called for pushdown from HAVING the value of the
7493     parameter clone_const is always false. In other cases it's always true.
7494 
7495   @retval true   if an error occurs
7496   @retval false  otherwise
7497 */
7498 
create_pushable_equalities(THD * thd,List<Item> * equalities,Pushdown_checker checker,uchar * arg,bool clone_const)7499 bool Item_equal::create_pushable_equalities(THD *thd,
7500                                             List<Item> *equalities,
7501                                             Pushdown_checker checker,
7502                                             uchar *arg,
7503                                             bool clone_const)
7504 {
7505   Item *item;
7506   Item *left_item= NULL;
7507   Item *right_item = get_const();
7508   Item_equal_fields_iterator it(*this);
7509 
7510   while ((item=it++))
7511   {
7512     left_item= item;
7513     if (checker && !((item->*checker) (arg)))
7514       continue;
7515     break;
7516   }
7517 
7518   if (!left_item)
7519     return false;
7520 
7521   if (right_item)
7522   {
7523     Item_func_eq *eq= 0;
7524     Item *left_item_clone= left_item->build_clone(thd);
7525     Item *right_item_clone= !clone_const ?
7526                             right_item : right_item->build_clone(thd);
7527     if (!left_item_clone || !right_item_clone)
7528       return true;
7529     eq= new (thd->mem_root) Item_func_eq(thd,
7530                                          left_item_clone,
7531                                          right_item_clone);
7532     if (!eq ||  equalities->push_back(eq, thd->mem_root))
7533       return true;
7534     if (!clone_const)
7535       right_item->set_extraction_flag(IMMUTABLE_FL);
7536   }
7537 
7538   while ((item=it++))
7539   {
7540     if (checker && !((item->*checker) (arg)))
7541       continue;
7542     Item_func_eq *eq= 0;
7543     Item *left_item_clone= left_item->build_clone(thd);
7544     Item *right_item_clone= item->build_clone(thd);
7545     if (!(left_item_clone && right_item_clone))
7546       return true;
7547     left_item_clone->set_item_equal(NULL);
7548     right_item_clone->set_item_equal(NULL);
7549     eq= new (thd->mem_root) Item_func_eq(thd,
7550                                          right_item_clone,
7551                                          left_item_clone);
7552     if (!eq || equalities->push_back(eq, thd->mem_root))
7553       return true;
7554   }
7555   return false;
7556 }
7557 
7558 
7559 /**
7560   Transform multiple equality into the AND condition of equalities.
7561 
7562   Example:
7563   MULT_EQ(x,a,b)
7564   =>
7565   (x=a) AND (x=b)
7566 
7567   Equalities are built in Item_equal::create_pushable_equalities() method
7568   using elements of this multiple equality. The result of this method is
7569   saved in an equality list.
7570   This method returns the condition where the elements of the equality list
7571   are anded.
7572 */
7573 
multiple_equality_transformer(THD * thd,uchar * arg)7574 Item *Item_equal::multiple_equality_transformer(THD *thd, uchar *arg)
7575 {
7576   List<Item> equalities;
7577   if (create_pushable_equalities(thd, &equalities, 0, 0, false))
7578     return 0;
7579 
7580   switch (equalities.elements)
7581   {
7582   case 0:
7583     return 0;
7584   case 1:
7585     return equalities.head();
7586     break;
7587   default:
7588     return new (thd->mem_root) Item_cond_and(thd, equalities);
7589     break;
7590   }
7591 }
7592