1 /* Copyright (c) 2000, 2021, Oracle and/or its affiliates.
2 
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License, version 2.0,
5    as published by the Free Software Foundation.
6 
7    This program is also distributed with certain software (including
8    but not limited to OpenSSL) that is licensed under separate terms,
9    as designated in a particular file or component or in included license
10    documentation.  The authors of MySQL hereby grant you an additional
11    permission to link the program and your derivative works with the
12    separately licensed software that they have included with MySQL.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License, version 2.0, for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
22 
23 /**
24   @file
25 
26   @brief
27   This file defines all numerical functions
28 */
29 
30 #include "item_func.h"
31 
32 #include "my_bit.h"              // my_count_bits
33 #include "auth_common.h"         // check_password_strength
34 #include "binlog.h"              // mysql_bin_log
35 #include "debug_sync.h"          // DEBUG_SYNC
36 #include "item_cmpfunc.h"        // get_datetime_value
37 #include "item_strfunc.h"        // Item_func_geohash
38 #include <mysql/service_thd_wait.h>
39 #include "parse_tree_helpers.h"  // PT_item_list
40 #include "rpl_mi.h"              // Master_info
41 #include "rpl_msr.h"             // channel_map
42 #include "rpl_rli.h"             // Relay_log_info
43 #include "sp.h"                  // sp_find_routine
44 #include "sp_head.h"             // sp_name
45 #include "sql_audit.h"           // audit_global_variable
46 #include "sql_base.h"            // Internal_error_handler_holder
47 #include "sql_class.h"           // THD
48 #include "sql_optimizer.h"       // JOIN
49 #include "sql_parse.h"           // check_stack_overrun
50 #include "sql_show.h"            // append_identifier
51 #include "sql_time.h"            // TIME_from_longlong_packed
52 #include "strfunc.h"             // find_type
53 #include "item_json_func.h"      // Item_func_json_quote
54 #include <cfloat>                // DBL_DIG
55 
56 using std::min;
57 using std::max;
58 
check_reserved_words(LEX_STRING * name)59 bool check_reserved_words(LEX_STRING *name)
60 {
61   if (!my_strcasecmp(system_charset_info, name->str, "GLOBAL") ||
62       !my_strcasecmp(system_charset_info, name->str, "LOCAL") ||
63       !my_strcasecmp(system_charset_info, name->str, "SESSION"))
64     return TRUE;
65   return FALSE;
66 }
67 
68 
69 /**
70   Evaluate a constant condition, represented by an Item tree
71 
72   @param      thd   Thread handler
73   @param      cond  The constant condition to evaluate
74   @param[out] value Returned value, either true or false
75 
76   @returns false if evaluation is successful, true otherwise
77 */
78 
eval_const_cond(THD * thd,Item * cond,bool * value)79 bool eval_const_cond(THD *thd, Item *cond, bool *value)
80 {
81   assert(cond->const_item());
82   *value= cond->val_int();
83   return thd->is_error();
84 }
85 
86 
87 /**
88    Test if the sum of arguments overflows the ulonglong range.
89 */
test_if_sum_overflows_ull(ulonglong arg1,ulonglong arg2)90 static inline bool test_if_sum_overflows_ull(ulonglong arg1, ulonglong arg2)
91 {
92   return ULLONG_MAX - arg1 < arg2;
93 }
94 
set_arguments(List<Item> & list,bool context_free)95 void Item_func::set_arguments(List<Item> &list, bool context_free)
96 {
97   allowed_arg_cols= 1;
98   arg_count=list.elements;
99   args= tmp_arg;                                // If 2 arguments
100   if (arg_count <= 2 || (args=(Item**) sql_alloc(sizeof(Item*)*arg_count)))
101   {
102     List_iterator_fast<Item> li(list);
103     Item *item;
104     Item **save_args= args;
105 
106     while ((item=li++))
107     {
108       *(save_args++)= item;
109       if (!context_free)
110         with_sum_func|= item->with_sum_func;
111     }
112   }
113   else
114     arg_count= 0; // OOM
115   list.empty();					// Fields are used
116 }
117 
Item_func(List<Item> & list)118 Item_func::Item_func(List<Item> &list)
119   :allowed_arg_cols(1)
120 {
121   set_arguments(list, false);
122 }
123 
124 
Item_func(const POS & pos,PT_item_list * opt_list)125 Item_func::Item_func(const POS &pos, PT_item_list *opt_list)
126   : super(pos), allowed_arg_cols(1)
127 {
128   if (opt_list == NULL)
129   {
130     args= tmp_arg;
131     arg_count= 0;
132   }
133   else
134     set_arguments(opt_list->value, true);
135 }
136 
Item_func(THD * thd,Item_func * item)137 Item_func::Item_func(THD *thd, Item_func *item)
138   :Item_result_field(thd, item),
139    const_item_cache(0),
140    allowed_arg_cols(item->allowed_arg_cols),
141    used_tables_cache(item->used_tables_cache),
142    not_null_tables_cache(item->not_null_tables_cache),
143    arg_count(item->arg_count)
144 {
145   if (arg_count)
146   {
147     if (arg_count <=2)
148       args= tmp_arg;
149     else
150     {
151       if (!(args=(Item**) thd->alloc(sizeof(Item*)*arg_count)))
152 	return;
153     }
154     memcpy((char*) args, (char*) item->args, sizeof(Item*)*arg_count);
155   }
156 }
157 
158 
itemize(Parse_context * pc,Item ** res)159 bool Item_func::itemize(Parse_context *pc, Item **res)
160 {
161   if (skip_itemize(res))
162     return false;
163   if (super::itemize(pc, res))
164     return true;
165   with_sum_func= 0;
166   const bool no_named_params= !may_have_named_parameters();
167   for (size_t i= 0; i < arg_count; i++)
168   {
169     with_sum_func|= args[i]->with_sum_func;
170     if (args[i]->itemize(pc, &args[i]))
171       return true;
172     if (no_named_params && !args[i]->item_name.is_autogenerated())
173     {
174       my_error(functype() == FUNC_SP ? ER_WRONG_PARAMETERS_TO_STORED_FCT
175                                      : ER_WRONG_PARAMETERS_TO_NATIVE_FCT,
176                MYF(0), func_name());
177       return true;
178     }
179   }
180   return false;
181 }
182 
183 
184 /*
185   Resolve references to table column for a function and its argument
186 
187   SYNOPSIS:
188   fix_fields()
189   thd		Thread object
190   ref		Pointer to where this object is used.  This reference
191 		is used if we want to replace this object with another
192 		one (for example in the summary functions).
193 
194   DESCRIPTION
195     Call fix_fields() for all arguments to the function.  The main intention
196     is to allow all Item_field() objects to setup pointers to the table fields.
197 
198     Sets as a side effect the following class variables:
199       maybe_null	Set if any argument may return NULL
200       with_sum_func	Set if any of the arguments contains a sum function
201       used_tables_cache Set to union of the tables used by arguments
202 
203       str_value.charset If this is a string function, set this to the
204 			character set for the first argument.
205 			If any argument is binary, this is set to binary
206 
207    If for any item any of the defaults are wrong, then this can
208    be fixed in the fix_length_and_dec() function that is called
209    after this one or by writing a specialized fix_fields() for the
210    item.
211 
212   RETURN VALUES
213   FALSE	ok
214   TRUE	Got error.  Stored with my_error().
215 */
216 
217 bool
fix_fields(THD * thd,Item ** ref)218 Item_func::fix_fields(THD *thd, Item **ref)
219 {
220   assert(fixed == 0 || basic_const_item());
221 
222   Item **arg,**arg_end;
223   uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
224 
225   /*
226     Semi-join flattening should only be performed for top-level
227     predicates. Disable it for predicates that live under an
228     Item_func.
229   */
230   Disable_semijoin_flattening DSF(thd->lex->current_select(), true);
231 
232   used_tables_cache= get_initial_pseudo_tables();
233   not_null_tables_cache= 0;
234   const_item_cache=1;
235 
236   /*
237     Use stack limit of STACK_MIN_SIZE * 2 since
238     on some platforms a recursive call to fix_fields
239     requires more than STACK_MIN_SIZE bytes (e.g. for
240     MIPS, it takes about 22kB to make one recursive
241     call to Item_func::fix_fields())
242   */
243   if (check_stack_overrun(thd, STACK_MIN_SIZE * 2, buff))
244     return TRUE;				// Fatal error if flag is set!
245   if (arg_count)
246   {						// Print purify happy
247     for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
248     {
249       if (fix_func_arg(thd, arg))
250         return true;
251     }
252   }
253   fix_length_and_dec();
254   if (thd->is_error()) // An error inside fix_length_and_dec occured
255     return TRUE;
256   fixed= 1;
257   return FALSE;
258 }
259 
260 
fix_func_arg(THD * thd,Item ** arg)261 bool Item_func::fix_func_arg(THD *thd, Item **arg)
262 {
263   if ((!(*arg)->fixed && (*arg)->fix_fields(thd, arg)))
264     return true;                                /* purecov: inspected */
265   Item *item= *arg;
266 
267   if (allowed_arg_cols)
268   {
269     if (item->check_cols(allowed_arg_cols))
270       return true;
271   }
272   else
273   {
274     /*  we have to fetch allowed_arg_cols from first argument */
275     assert(arg == args); // it is first argument
276     allowed_arg_cols= item->cols();
277     assert(allowed_arg_cols); // Can't be 0 any more
278   }
279 
280   maybe_null|=            item->maybe_null;
281   with_sum_func|=         item->with_sum_func;
282   used_tables_cache|=     item->used_tables();
283   not_null_tables_cache|= item->not_null_tables();
284   const_item_cache&=      item->const_item();
285   with_subselect|=        item->has_subquery();
286   with_stored_program|=   item->has_stored_program();
287   return false;
288 }
289 
fix_after_pullout(st_select_lex * parent_select,st_select_lex * removed_select)290 void Item_func::fix_after_pullout(st_select_lex *parent_select,
291                                   st_select_lex *removed_select)
292 {
293   if (const_item())
294   {
295     /*
296       Pulling out a const item changes nothing to it. Moreover, some items may
297       have decided that they're const by some other logic than the generic
298       one below, and we must preserve that decision.
299     */
300     return;
301   }
302 
303   Item **arg,**arg_end;
304 
305   used_tables_cache= get_initial_pseudo_tables();
306   not_null_tables_cache= 0;
307   const_item_cache=1;
308 
309   if (arg_count)
310   {
311     for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
312     {
313       Item *const item= *arg;
314       item->fix_after_pullout(parent_select, removed_select);
315 
316       used_tables_cache|=     item->used_tables();
317       not_null_tables_cache|= item->not_null_tables();
318       const_item_cache&=      item->const_item();
319     }
320   }
321 }
322 
323 
walk(Item_processor processor,enum_walk walk,uchar * argument)324 bool Item_func::walk(Item_processor processor, enum_walk walk, uchar *argument)
325 {
326   if ((walk & WALK_PREFIX) && (this->*processor)(argument))
327     return true;
328 
329   Item **arg, **arg_end;
330   for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
331   {
332     if ((*arg)->walk(processor, walk, argument))
333       return true;
334   }
335   return (walk & WALK_POSTFIX) && (this->*processor)(argument);
336 }
337 
traverse_cond(Cond_traverser traverser,void * argument,traverse_order order)338 void Item_func::traverse_cond(Cond_traverser traverser,
339                               void *argument, traverse_order order)
340 {
341   if (arg_count)
342   {
343     Item **arg,**arg_end;
344 
345     switch (order) {
346     case(PREFIX):
347       (*traverser)(this, argument);
348       for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
349       {
350 	(*arg)->traverse_cond(traverser, argument, order);
351       }
352       break;
353     case (POSTFIX):
354       for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
355       {
356 	(*arg)->traverse_cond(traverser, argument, order);
357       }
358       (*traverser)(this, argument);
359     }
360   }
361   else
362     (*traverser)(this, argument);
363 }
364 
365 
366 /**
367   Transform an Item_func object with a transformer callback function.
368 
369     The function recursively applies the transform method to each
370     argument of the Item_func node.
371     If the call of the method for an argument item returns a new item
372     the old item is substituted for a new one.
373     After this the transformer is applied to the root node
374     of the Item_func object.
375   @param transformer   the transformer callback function to be applied to
376                        the nodes of the tree of the object
377   @param argument      parameter to be passed to the transformer
378 
379   @return
380     Item returned as the result of transformation of the root node
381 */
382 
transform(Item_transformer transformer,uchar * argument)383 Item *Item_func::transform(Item_transformer transformer, uchar *argument)
384 {
385   assert(!current_thd->stmt_arena->is_stmt_prepare());
386 
387   if (arg_count)
388   {
389     Item **arg,**arg_end;
390     for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
391     {
392       Item *new_item= (*arg)->transform(transformer, argument);
393       if (!new_item)
394 	return 0;
395 
396       /*
397         THD::change_item_tree() should be called only if the tree was
398         really transformed, i.e. when a new item has been created.
399         Otherwise we'll be allocating a lot of unnecessary memory for
400         change records at each execution.
401       */
402       if (*arg != new_item)
403         current_thd->change_item_tree(arg, new_item);
404     }
405   }
406   return (this->*transformer)(argument);
407 }
408 
409 
410 /**
411   Compile Item_func object with a processor and a transformer
412   callback functions.
413 
414     First the function applies the analyzer to the root node of
415     the Item_func object. Then if the analizer succeeeds (returns TRUE)
416     the function recursively applies the compile method to each argument
417     of the Item_func node.
418     If the call of the method for an argument item returns a new item
419     the old item is substituted for a new one.
420     After this the transformer is applied to the root node
421     of the Item_func object.
422 
423   @param analyzer      the analyzer callback function to be applied to the
424                        nodes of the tree of the object
425   @param[in,out] arg_p parameter to be passed to the processor
426   @param transformer   the transformer callback function to be applied to the
427                        nodes of the tree of the object
428   @param arg_t         parameter to be passed to the transformer
429 
430   @return              Item returned as result of transformation of the node,
431                        the same item if no transformation applied, or NULL if
432                        transformation caused an error.
433 */
434 
compile(Item_analyzer analyzer,uchar ** arg_p,Item_transformer transformer,uchar * arg_t)435 Item *Item_func::compile(Item_analyzer analyzer, uchar **arg_p,
436                          Item_transformer transformer, uchar *arg_t)
437 {
438   if (!(this->*analyzer)(arg_p))
439     return this;
440   if (arg_count)
441   {
442     Item **arg,**arg_end;
443     for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
444     {
445       /*
446         The same parameter value of arg_p must be passed
447         to analyze any argument of the condition formula.
448       */
449       uchar *arg_v= *arg_p;
450       Item *new_item= (*arg)->compile(analyzer, &arg_v, transformer, arg_t);
451       if (new_item == NULL)
452         return NULL;
453       if (*arg != new_item)
454         current_thd->change_item_tree(arg, new_item);
455     }
456   }
457   return (this->*transformer)(arg_t);
458 }
459 
460 /**
461   See comments in Item_cmp_func::split_sum_func()
462 */
463 
split_sum_func(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields)464 void Item_func::split_sum_func(THD *thd, Ref_ptr_array ref_pointer_array,
465                                List<Item> &fields)
466 {
467   Item **arg, **arg_end;
468   for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
469     (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg, TRUE);
470 }
471 
472 
update_used_tables()473 void Item_func::update_used_tables()
474 {
475   used_tables_cache= get_initial_pseudo_tables();
476   const_item_cache=1;
477   with_subselect= false;
478   with_stored_program= false;
479   for (uint i=0 ; i < arg_count ; i++)
480   {
481     args[i]->update_used_tables();
482     used_tables_cache|=args[i]->used_tables();
483     const_item_cache&=args[i]->const_item();
484     with_subselect|= args[i]->has_subquery();
485     with_stored_program|= args[i]->has_stored_program();
486   }
487 }
488 
489 
fix_after_pullout(SELECT_LEX * parent_select,SELECT_LEX * removed_select)490 void Item_func_sp::fix_after_pullout(SELECT_LEX *parent_select,
491                                      SELECT_LEX *removed_select)
492 {
493   Item_func::fix_after_pullout(parent_select, removed_select);
494 
495   /*
496     Prevents function from being evaluated before it is locked.
497     @todo - make this dependent on READS SQL or MODIFIES SQL.
498             Due to a limitation in how functions are evaluated, we need to
499             ensure that we are in a prelocked mode even though the function
500             doesn't reference any tables.
501   */
502   used_tables_cache|= PARAM_TABLE_BIT;
503 }
504 
505 
used_tables() const506 table_map Item_func::used_tables() const
507 {
508   return used_tables_cache;
509 }
510 
511 
not_null_tables() const512 table_map Item_func::not_null_tables() const
513 {
514   return not_null_tables_cache;
515 }
516 
517 
print(String * str,enum_query_type query_type)518 void Item_func::print(String *str, enum_query_type query_type)
519 {
520   str->append(func_name());
521   str->append('(');
522   print_args(str, 0, query_type);
523   str->append(')');
524 }
525 
526 
print_args(String * str,uint from,enum_query_type query_type)527 void Item_func::print_args(String *str, uint from, enum_query_type query_type)
528 {
529   for (uint i=from ; i < arg_count ; i++)
530   {
531     if (i != from)
532       str->append(',');
533     args[i]->print(str, query_type);
534   }
535 }
536 
537 
print_op(String * str,enum_query_type query_type)538 void Item_func::print_op(String *str, enum_query_type query_type)
539 {
540   str->append('(');
541   for (uint i=0 ; i < arg_count-1 ; i++)
542   {
543     args[i]->print(str, query_type);
544     str->append(' ');
545     str->append(func_name());
546     str->append(' ');
547   }
548   args[arg_count-1]->print(str, query_type);
549   str->append(')');
550 }
551 
552 /// @note Please keep in sync with Item_sum::eq().
eq(const Item * item,bool binary_cmp) const553 bool Item_func::eq(const Item *item, bool binary_cmp) const
554 {
555   /* Assume we don't have rtti */
556   if (this == item)
557     return 1;
558   if (item->type() != FUNC_ITEM)
559     return 0;
560   Item_func *item_func=(Item_func*) item;
561   Item_func::Functype func_type;
562   if ((func_type= functype()) != item_func->functype() ||
563       arg_count != item_func->arg_count ||
564       (func_type != Item_func::FUNC_SP &&
565        func_name() != item_func->func_name()) ||
566       (func_type == Item_func::FUNC_SP &&
567        my_strcasecmp(system_charset_info, func_name(), item_func->func_name())))
568     return 0;
569   for (uint i=0; i < arg_count ; i++)
570     if (!args[i]->eq(item_func->args[i], binary_cmp))
571       return 0;
572   return 1;
573 }
574 
575 
tmp_table_field(TABLE * table)576 Field *Item_func::tmp_table_field(TABLE *table)
577 {
578   Field *field= NULL;
579 
580   switch (result_type()) {
581   case INT_RESULT:
582     if (max_char_length() > MY_INT32_NUM_DECIMAL_DIGITS)
583       field= new Field_longlong(max_char_length(), maybe_null, item_name.ptr(),
584                                 unsigned_flag);
585     else
586       field= new Field_long(max_char_length(), maybe_null, item_name.ptr(),
587                             unsigned_flag);
588     break;
589   case REAL_RESULT:
590     field= new Field_double(max_char_length(), maybe_null, item_name.ptr(), decimals);
591     break;
592   case STRING_RESULT:
593     return make_string_field(table);
594     break;
595   case DECIMAL_RESULT:
596     field= Field_new_decimal::create_from_item(this);
597     break;
598   case ROW_RESULT:
599   default:
600     // This case should never be chosen
601     assert(0);
602     field= 0;
603     break;
604   }
605   if (field)
606     field->init(table);
607   return field;
608 }
609 
610 
val_decimal(my_decimal * decimal_value)611 my_decimal *Item_func::val_decimal(my_decimal *decimal_value)
612 {
613   assert(fixed);
614   longlong nr= val_int();
615   if (null_value)
616     return 0; /* purecov: inspected */
617   int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
618   return decimal_value;
619 }
620 
621 
save_possibly_as_json(Field * field,bool no_conversions)622 type_conversion_status Item_func::save_possibly_as_json(Field *field,
623                                                         bool no_conversions)
624 {
625   if (field->type() == MYSQL_TYPE_JSON)
626   {
627     // Store the value in the JSON binary format.
628     Field_json *f= down_cast<Field_json *>(field);
629     Json_wrapper wr;
630     val_json(&wr);
631 
632     if (null_value)
633       return set_field_to_null(field);
634 
635     field->set_notnull();
636     return f->store_json(&wr);
637   }
638   else
639   {
640     // TODO Convert the JSON value to text.
641     return Item_func::save_in_field_inner(field, no_conversions);
642   }
643 }
644 
val_str(String * str)645 String *Item_real_func::val_str(String *str)
646 {
647   assert(fixed == 1);
648   double nr= val_real();
649   if (null_value)
650     return 0; /* purecov: inspected */
651   str->set_real(nr, decimals, collation.collation);
652   return str;
653 }
654 
655 
val_decimal(my_decimal * decimal_value)656 my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value)
657 {
658   assert(fixed);
659   double nr= val_real();
660   if (null_value)
661     return 0; /* purecov: inspected */
662   double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
663   return decimal_value;
664 }
665 
666 
fix_num_length_and_dec()667 void Item_func::fix_num_length_and_dec()
668 {
669   uint fl_length= 0;
670   decimals=0;
671   for (uint i=0 ; i < arg_count ; i++)
672   {
673     set_if_bigger(decimals,args[i]->decimals);
674     set_if_bigger(fl_length, args[i]->max_length);
675   }
676   max_length=float_length(decimals);
677   if (fl_length > max_length)
678   {
679     decimals= NOT_FIXED_DEC;
680     max_length= float_length(NOT_FIXED_DEC);
681   }
682 }
683 
684 
fix_num_length_and_dec()685 void Item_func_numhybrid::fix_num_length_and_dec()
686 {}
687 
688 
689 
690 /**
691   Count max_length and decimals for temporal functions.
692 
693   @param item    Argument array
694   @param nitems  Number of arguments in the array.
695 
696   @retval        False on success, true on error.
697 */
count_datetime_length(Item ** item,uint nitems)698 void Item_func::count_datetime_length(Item **item, uint nitems)
699 {
700   unsigned_flag= 0;
701   decimals= 0;
702   if (field_type() != MYSQL_TYPE_DATE)
703   {
704     for (uint i= 0; i < nitems; i++)
705       set_if_bigger(decimals,
706                     field_type() == MYSQL_TYPE_TIME ?
707                     item[i]->time_precision() : item[i]->datetime_precision());
708   }
709   set_if_smaller(decimals, DATETIME_MAX_DECIMALS);
710   uint len= decimals ? (decimals + 1) : 0;
711   switch (field_type())
712   {
713     case MYSQL_TYPE_DATETIME:
714     case MYSQL_TYPE_TIMESTAMP:
715       len+= MAX_DATETIME_WIDTH;
716       break;
717     case MYSQL_TYPE_DATE:
718     case MYSQL_TYPE_NEWDATE:
719       len+= MAX_DATE_WIDTH;
720       break;
721     case MYSQL_TYPE_TIME:
722       len+= MAX_TIME_WIDTH;
723       break;
724     default:
725       assert(0);
726   }
727   fix_char_length(len);
728 }
729 
730 /**
731   Set max_length/decimals of function if function is fixed point and
732   result length/precision depends on argument ones.
733 
734   @param item    Argument array.
735   @param nitems  Number of arguments in the array.
736 
737   This function doesn't set unsigned_flag. Call agg_result_type()
738   first to do that.
739 */
740 
count_decimal_length(Item ** item,uint nitems)741 void Item_func::count_decimal_length(Item **item, uint nitems)
742 {
743   int max_int_part= 0;
744   decimals= 0;
745   for (uint i=0 ; i < nitems ; i++)
746   {
747     set_if_bigger(decimals, item[i]->decimals);
748     set_if_bigger(max_int_part, item[i]->decimal_int_part());
749   }
750   int precision= min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
751   fix_char_length(my_decimal_precision_to_length_no_truncation(precision,
752                                                                decimals,
753                                                                unsigned_flag));
754 }
755 
756 /**
757   Set char_length to the maximum number of characters required by any
758   of this function's arguments.
759 
760   This function doesn't set unsigned_flag. Call agg_result_type()
761   first to do that.
762 */
763 
count_only_length(Item ** item,uint nitems)764 void Item_func::count_only_length(Item **item, uint nitems)
765 {
766   uint32 char_length= 0;
767   for (uint i= 0; i < nitems; i++)
768     set_if_bigger(char_length, item[i]->max_char_length());
769   fix_char_length(char_length);
770 }
771 
772 /**
773   Set max_length/decimals of function if function is floating point and
774   result length/precision depends on argument ones.
775 
776   @param item    Argument array.
777   @param nitems  Number of arguments in the array.
778 */
779 
count_real_length(Item ** item,uint nitems)780 void Item_func::count_real_length(Item **item, uint nitems)
781 {
782   uint32 length= 0;
783   decimals= 0;
784   max_length= 0;
785   for (uint i=0 ; i < nitems; i++)
786   {
787     if (decimals != NOT_FIXED_DEC)
788     {
789       set_if_bigger(decimals, item[i]->decimals);
790       set_if_bigger(length, (item[i]->max_length - item[i]->decimals));
791     }
792     set_if_bigger(max_length, item[i]->max_length);
793   }
794   if (decimals != NOT_FIXED_DEC)
795   {
796     max_length= length;
797     length+= decimals;
798     if (length < max_length)  // If previous operation gave overflow
799       max_length= UINT_MAX32;
800     else
801       max_length= length;
802   }
803 }
804 
805 /**
806   Calculate max_length and decimals for STRING_RESULT functions.
807 
808   @param field_type  Field type.
809   @param items       Argument array.
810   @param nitems      Number of arguments.
811 
812   @retval            False on success, true on error.
813 */
count_string_result_length(enum_field_types field_type,Item ** items,uint nitems)814 bool Item_func::count_string_result_length(enum_field_types field_type,
815                                            Item **items, uint nitems)
816 {
817   if (agg_arg_charsets_for_string_result(collation, items, nitems))
818     return true;
819   if (is_temporal_type(field_type))
820     count_datetime_length(items, nitems);
821   else
822   {
823     decimals= NOT_FIXED_DEC;
824     count_only_length(items, nitems);
825   }
826   return false;
827 }
828 
829 
signal_divide_by_null()830 void Item_func::signal_divide_by_null()
831 {
832   THD *thd= current_thd;
833   if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO)
834     push_warning(thd, Sql_condition::SL_WARNING, ER_DIVISION_BY_ZERO,
835                  ER(ER_DIVISION_BY_ZERO));
836   null_value= 1;
837 }
838 
839 
signal_invalid_argument_for_log()840 void Item_func::signal_invalid_argument_for_log()
841 {
842   THD *thd= current_thd;
843   push_warning(thd, Sql_condition::SL_WARNING,
844                ER_INVALID_ARGUMENT_FOR_LOGARITHM,
845                ER(ER_INVALID_ARGUMENT_FOR_LOGARITHM));
846   null_value= TRUE;
847 }
848 
849 
get_tmp_table_item(THD * thd)850 Item *Item_func::get_tmp_table_item(THD *thd)
851 {
852   if (!with_sum_func && !const_item())
853     return new Item_field(result_field);
854   return copy_or_same(thd);
855 }
856 
857 const Item_field*
contributes_to_filter(table_map read_tables,table_map filter_for_table,const MY_BITMAP * fields_to_ignore) const858 Item_func::contributes_to_filter(table_map read_tables,
859                                  table_map filter_for_table,
860                                  const MY_BITMAP *fields_to_ignore) const
861 {
862   assert((read_tables & filter_for_table) == 0);
863   /*
864     Multiple equality (Item_equal) should not call this function
865     because it would reject valid comparisons.
866   */
867   assert(functype() != MULT_EQUAL_FUNC);
868 
869    /*
870      To contribute to filering effect, the condition must refer to
871      exactly one unread table: the table filtering is currently
872      calculated for.
873    */
874    if ((used_tables() & ~read_tables) != filter_for_table)
875      return NULL;
876 
877   /*
878     Whether or not this Item_func has an operand that is a field in
879     'filter_for_table' that is not in 'fields_to_ignore'.
880   */
881   Item_field* usable_field= NULL;
882 
883   /*
884     Whether or not this Item_func has an operand that can be used as
885     available value. arg_count==1 for Items with implicit values like
886     "field IS NULL".
887   */
888   bool found_comparable= (arg_count == 1);
889 
890   for (uint i= 0; i < arg_count; i++)
891   {
892     const Item::Type arg_type= args[i]->real_item()->type();
893 
894     if (arg_type == Item::SUBSELECT_ITEM)
895     {
896       if (args[i]->const_item())
897       {
898         // Constant subquery, i.e., not a dependent subquery.
899         found_comparable= true;
900         continue;
901       }
902 
903       /*
904         This is either "fld OP <dependent_subquery>" or "fld BETWEEN X
905         and Y" where either X or Y is a dependent subquery. Filtering
906         effect should not be calculated for this item because the cost
907         of evaluating the dependent subquery is currently not
908         calculated and its accompanying filtering effect is too
909         uncertain. See WL#7384.
910       */
911       return NULL;
912     } // ... if subquery.
913 
914     const table_map used_tabs= args[i]->used_tables();
915 
916     if (arg_type == Item::FIELD_ITEM && (used_tabs == filter_for_table))
917     {
918       /*
919         The qualifying table of args[i] is filter_for_table. args[i]
920         may be a field or a reference to a field, e.g. through a
921         view.
922       */
923       Item_field *fld= static_cast<Item_field*>(args[i]->real_item());
924 
925       /*
926         Use args[i] as value if
927         1) this field shall be ignored, or
928         2) a usable field has already been found (meaning that
929         this is "filter_for_table.colX OP filter_for_table.colY").
930       */
931       if (bitmap_is_set(fields_to_ignore, fld->field->field_index) || // 1)
932           usable_field)                                               // 2)
933       {
934         found_comparable= true;
935         continue;
936       }
937 
938       /*
939         This field shall contribute to filtering effect if a
940         value is found for it
941       */
942       usable_field= fld;
943     } // if field.
944     else
945     {
946       /*
947         It's not a subquery. May be a function, a constant, an outer
948         reference, a field of another table...
949 
950         Already checked that this predicate does not refer to tables
951         later in the join sequence. Verify it:
952       */
953       assert(!(used_tabs & (~read_tables & ~filter_for_table)));
954       found_comparable= true;
955     }
956   }
957   return (found_comparable ? usable_field : NULL);
958 }
959 
960 /**
961   Return new Item_field if given expression matches GC
962 
963   @see substitute_gc()
964 
965   @param func           Expression to be replaced
966   @param fld            GCs field
967   @param type           Result type to match with Field
968 
969   @returns
970     item new Item_field for matched GC
971     NULL otherwise
972 */
973 
get_gc_for_expr(Item_func ** func,Field * fld,Item_result type)974 Item_field *get_gc_for_expr(Item_func **func, Field *fld, Item_result type)
975 {
976   Item_func *expr= down_cast<Item_func*>(fld->gcol_info->expr_item);
977 
978   /*
979     In the case where the generated column expression returns JSON and
980     the predicate compares the values as strings, it is not safe to
981     replace the expression with the generated column, since the
982     indexed string values will be double-quoted. The generated column
983     expression should use the JSON_UNQUOTE function to strip off the
984     double-quotes in order to get a usable index for looking up
985     strings. See also the comment below.
986   */
987   if (type == STRING_RESULT && expr->field_type() == MYSQL_TYPE_JSON)
988     return NULL;
989 
990   /*
991     Skip unquoting function. This is needed to address JSON string
992     comparison issue. All JSON_* functions return quoted strings. In
993     order to create usable index, GC column expression has to include
994     JSON_UNQUOTE function, e.g JSON_UNQUOTE(JSON_EXTRACT(..)).
995     Hence, the unquoting function in column expression have to be
996     skipped in order to correctly match GC expr to expr in
997     WHERE condition.  The exception is if user has explicitly used
998     JSON_UNQUOTE in WHERE condition.
999   */
1000   if (!strcmp(expr->func_name(),"json_unquote") &&
1001       strcmp((*func)->func_name(),"json_unquote"))
1002   {
1003     if (!expr->arguments()[0]->can_be_substituted_for_gc())
1004       return NULL;
1005     expr= down_cast<Item_func*>(expr->arguments()[0]);
1006   }
1007   assert(expr->can_be_substituted_for_gc());
1008 
1009   if (type == fld->result_type() && (*func)->eq(expr, false))
1010   {
1011     Item_field *field= new Item_field(fld);
1012     // Mark field for read
1013     fld->table->mark_column_used(fld->table->in_use, fld, MARK_COLUMNS_READ);
1014     return field;
1015   }
1016   return NULL;
1017 }
1018 
1019 
1020 /**
1021   Transformer function for GC substitution.
1022 
1023   @param arg  List of indexed GC field
1024 
1025   @return this item
1026 
1027   @details This function transforms the WHERE condition. It doesn't change
1028   'this' item but rather changes its arguments. It takes list of GC fields
1029   and checks whether arguments of 'this' item matches them and index over
1030   the GC field isn't disabled with hints. If so, it replaces
1031   the argument with newly created Item_field which uses the matched GC
1032   field. Following functions' arguments could be transformed:
1033   - EQ_FUNC, LT_FUNC, LE_FUNC, GE_FUNC, GT_FUNC
1034     - Left _or_ right argument if the opposite argument is a constant.
1035   - IN_FUNC, BETWEEN
1036     - Left argument if all other arguments are constant and of the same type.
1037 
1038   After transformation comparators are updated to take into account the new
1039   field.
1040 */
1041 
gc_subst_transformer(uchar * arg)1042 Item *Item_func::gc_subst_transformer(uchar *arg)
1043 {
1044   switch(functype()) {
1045   case EQ_FUNC:
1046   case LT_FUNC:
1047   case LE_FUNC:
1048   case GE_FUNC:
1049   case GT_FUNC:
1050   {
1051     Item_func **func= NULL;
1052     Item **val= NULL;
1053     List<Field> *gc_fields= (List<Field> *)arg;
1054     List_iterator<Field> li(*gc_fields);
1055     // Check if we can substitute a function with a GC
1056     if (args[0]->can_be_substituted_for_gc() && args[1]->const_item())
1057     {
1058       func= (Item_func**)args;
1059       val= args + 1;
1060     }
1061     else if (args[1]->can_be_substituted_for_gc() && args[0]->const_item())
1062     {
1063       func= (Item_func**)args + 1;
1064       val= args;
1065     }
1066     if (func)
1067     {
1068       Field *fld;
1069       while((fld= li++))
1070       {
1071         // Check whether field has usable keys
1072         key_map tkm= fld->part_of_key;
1073         tkm.intersect(fld->table->keys_in_use_for_query);
1074         Item_field *field;
1075 
1076         if (!tkm.is_clear_all() &&
1077             (field= get_gc_for_expr(func, fld, (*val)->result_type())))
1078         {
1079           // Matching expression is found, substutite arg with the new
1080           // field
1081           fld->table->in_use->change_item_tree(pointer_cast<Item**>(func),
1082                                                field);
1083           // Adjust comparator
1084           ((Item_bool_func2*)this)->set_cmp_func();
1085           break;
1086         }
1087       }
1088     }
1089     break;
1090   }
1091   case BETWEEN:
1092   case IN_FUNC:
1093   {
1094     List<Field> *gc_fields= (List<Field> *)arg;
1095     List_iterator<Field> li(*gc_fields);
1096     if (!args[0]->can_be_substituted_for_gc())
1097       break;
1098     Item_result type= args[1]->result_type();
1099     bool can_do_subst= args[1]->const_item();
1100     for (uint i= 2; i < arg_count && can_do_subst; i++)
1101       if (!args[i]->const_item() || args[i]->result_type() != type)
1102       {
1103         can_do_subst= false;
1104         break;
1105       }
1106     if (can_do_subst)
1107     {
1108       Field *fld;
1109       while ((fld= li++))
1110       {
1111         // Check whether field has usable keys
1112         key_map tkm= fld->part_of_key;
1113         tkm.intersect(fld->table->keys_in_use_for_query);
1114         Item_field *field;
1115 
1116         if (!tkm.is_clear_all() &&
1117             (field= get_gc_for_expr(pointer_cast<Item_func**>(args), fld,
1118                                     type)))
1119         {
1120           // Matching expression is found, substutite arg[0] with the new
1121           // field
1122           fld->table->in_use->change_item_tree(pointer_cast<Item**>(args),
1123                                                field);
1124           // Adjust comparators
1125           if (functype() == IN_FUNC)
1126             ((Item_func_in*)this)->cleanup_arrays();
1127           fix_length_and_dec();
1128           break;
1129         }
1130       }
1131     }
1132     break;
1133   }
1134   default:
1135     break;
1136   }
1137   return this;
1138 }
1139 
1140 
replace_argument(THD * thd,Item ** oldpp,Item * newp)1141 void Item_func::replace_argument(THD *thd, Item **oldpp, Item *newp)
1142 {
1143   thd->change_item_tree(oldpp, newp);
1144 }
1145 
1146 
val_real()1147 double Item_int_func::val_real()
1148 {
1149   assert(fixed == 1);
1150 
1151   return unsigned_flag ? (double) ((ulonglong) val_int()) : (double) val_int();
1152 }
1153 
1154 
val_str(String * str)1155 String *Item_int_func::val_str(String *str)
1156 {
1157   assert(fixed == 1);
1158   longlong nr=val_int();
1159   if (null_value)
1160     return 0;
1161   str->set_int(nr, unsigned_flag, collation.collation);
1162   return str;
1163 }
1164 
1165 
itemize(Parse_context * pc,Item ** res)1166 bool Item_func_connection_id::itemize(Parse_context *pc, Item **res)
1167 {
1168   if (skip_itemize(res))
1169     return false;
1170   if (super::itemize(pc, res))
1171     return true;
1172   pc->thd->lex->safe_to_cache_query= false;
1173   return false;
1174 }
1175 
1176 
fix_length_and_dec()1177 void Item_func_connection_id::fix_length_and_dec()
1178 {
1179   Item_int_func::fix_length_and_dec();
1180   unsigned_flag= 1;
1181 }
1182 
1183 
fix_fields(THD * thd,Item ** ref)1184 bool Item_func_connection_id::fix_fields(THD *thd, Item **ref)
1185 {
1186   if (Item_int_func::fix_fields(thd, ref))
1187     return TRUE;
1188   thd->thread_specific_used= TRUE;
1189   value= thd->variables.pseudo_thread_id;
1190   return FALSE;
1191 }
1192 
1193 
1194 /**
1195   Check arguments here to determine result's type for a numeric
1196   function of two arguments.
1197 */
1198 
find_num_type(void)1199 void Item_num_op::find_num_type(void)
1200 {
1201   DBUG_ENTER("Item_num_op::find_num_type");
1202   DBUG_PRINT("info", ("name %s", func_name()));
1203   assert(arg_count == 2);
1204   Item_result r0= args[0]->numeric_context_result_type();
1205   Item_result r1= args[1]->numeric_context_result_type();
1206 
1207   assert(r0 != STRING_RESULT && r1 != STRING_RESULT);
1208 
1209   if (r0 == REAL_RESULT || r1 == REAL_RESULT)
1210   {
1211     /*
1212       Since DATE/TIME/DATETIME data types return INT_RESULT/DECIMAL_RESULT
1213       type codes, we should never get to here when both fields are temporal.
1214     */
1215     assert(!args[0]->is_temporal() || !args[1]->is_temporal());
1216     count_real_length(args, arg_count);
1217     max_length= float_length(decimals);
1218     hybrid_type= REAL_RESULT;
1219   }
1220   else if (r0 == DECIMAL_RESULT || r1 == DECIMAL_RESULT)
1221   {
1222     hybrid_type= DECIMAL_RESULT;
1223     result_precision();
1224   }
1225   else
1226   {
1227     assert(r0 == INT_RESULT && r1 == INT_RESULT);
1228     decimals= 0;
1229     hybrid_type=INT_RESULT;
1230     result_precision();
1231   }
1232   DBUG_PRINT("info", ("Type: %s",
1233              (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
1234               hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
1235               hybrid_type == INT_RESULT ? "INT_RESULT" :
1236               "--ILLEGAL!!!--")));
1237   DBUG_VOID_RETURN;
1238 }
1239 
1240 
1241 /**
1242   Set result type for a numeric function of one argument
1243   (can be also used by a numeric function of many arguments, if the result
1244   type depends only on the first argument)
1245 */
1246 
find_num_type()1247 void Item_func_num1::find_num_type()
1248 {
1249   DBUG_ENTER("Item_func_num1::find_num_type");
1250   DBUG_PRINT("info", ("name %s", func_name()));
1251   switch (hybrid_type= args[0]->result_type()) {
1252   case INT_RESULT:
1253     unsigned_flag= args[0]->unsigned_flag;
1254     break;
1255   case STRING_RESULT:
1256   case REAL_RESULT:
1257     hybrid_type= REAL_RESULT;
1258     max_length= float_length(decimals);
1259     break;
1260   case DECIMAL_RESULT:
1261     break;
1262   default:
1263     assert(0);
1264   }
1265   DBUG_PRINT("info", ("Type: %s",
1266                       (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
1267                        hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
1268                        hybrid_type == INT_RESULT ? "INT_RESULT" :
1269                        "--ILLEGAL!!!--")));
1270   DBUG_VOID_RETURN;
1271 }
1272 
1273 
fix_num_length_and_dec()1274 void Item_func_num1::fix_num_length_and_dec()
1275 {
1276   decimals= args[0]->decimals;
1277   max_length= args[0]->max_length;
1278 }
1279 
1280 /*
1281   Reject geometry arguments, should be called in fix_length_and_dec for
1282   SQL functions/operators where geometries are not suitable as operands.
1283  */
reject_geometry_args(uint arg_count,Item ** args,Item_result_field * me)1284 void reject_geometry_args(uint arg_count, Item **args, Item_result_field *me)
1285 {
1286   /*
1287     We want to make sure the operands are not GEOMETRY strings because
1288     it's meaningless for them to participate in arithmetic and/or numerical
1289     calculations.
1290 
1291     When a variable holds a MySQL Geometry byte string, it is regarded as a
1292     string rather than a MYSQL_TYPE_GEOMETRY, so here we can't catch an illegal
1293     variable argument which was assigned with a geometry.
1294 
1295     Item::field_type() requires the item not be of ROW_RESULT, since a row
1296     isn't a field.
1297   */
1298   for (uint i= 0; i < arg_count; i++)
1299   {
1300     if (args[i]->result_type() != ROW_RESULT &&
1301         args[i]->field_type() == MYSQL_TYPE_GEOMETRY)
1302     {
1303       my_error(ER_WRONG_ARGUMENTS, MYF(0), me->func_name());
1304       break;
1305     }
1306   }
1307 
1308   return;
1309 }
1310 
1311 
1312 /**
1313   Go through the arguments of a function and check if any of them are
1314   JSON. If a JSON argument is found, raise a warning saying that this
1315   operation is not supported yet. This function is used to notify
1316   users that they are comparing JSON values using a mechanism that has
1317   not yet been updated to use the JSON comparator. JSON values are
1318   typically handled as strings in that case.
1319 
1320   @param arg_count  the number of arguments
1321   @param args       the arguments to go through looking for JSON values
1322   @param msg        the message that explains what is not supported
1323 */
unsupported_json_comparison(size_t arg_count,Item ** args,const char * msg)1324 void unsupported_json_comparison(size_t arg_count, Item **args, const char *msg)
1325 {
1326   for (size_t i= 0; i < arg_count; ++i)
1327   {
1328     if (args[i]->result_type() == STRING_RESULT &&
1329         args[i]->field_type() == MYSQL_TYPE_JSON)
1330     {
1331       push_warning_printf(current_thd, Sql_condition::SL_WARNING,
1332                           ER_NOT_SUPPORTED_YET,
1333                           ER_THD(current_thd, ER_NOT_SUPPORTED_YET),
1334                           msg);
1335       break;
1336     }
1337   }
1338 }
1339 
1340 
fix_length_and_dec()1341 void Item_func_numhybrid::fix_length_and_dec()
1342 {
1343   fix_num_length_and_dec();
1344   find_num_type();
1345   reject_geometry_args(arg_count, args, this);
1346 }
1347 
val_str(String * str)1348 String *Item_func_numhybrid::val_str(String *str)
1349 {
1350   assert(fixed == 1);
1351   switch (hybrid_type) {
1352   case DECIMAL_RESULT:
1353   {
1354     my_decimal decimal_value, *val;
1355     if (!(val= decimal_op(&decimal_value)))
1356       return 0;                                 // null is set
1357     my_decimal_round(E_DEC_FATAL_ERROR, val, decimals, FALSE, val);
1358     str->set_charset(collation.collation);
1359     my_decimal2string(E_DEC_FATAL_ERROR, val, 0, 0, 0, str);
1360     break;
1361   }
1362   case INT_RESULT:
1363   {
1364     longlong nr= int_op();
1365     if (null_value)
1366       return 0; /* purecov: inspected */
1367     str->set_int(nr, unsigned_flag, collation.collation);
1368     break;
1369   }
1370   case REAL_RESULT:
1371   {
1372     double nr= real_op();
1373     if (null_value)
1374       return 0; /* purecov: inspected */
1375     str->set_real(nr, decimals, collation.collation);
1376     break;
1377   }
1378   case STRING_RESULT:
1379     switch (field_type()) {
1380     case MYSQL_TYPE_DATETIME:
1381     case MYSQL_TYPE_TIMESTAMP:
1382       return val_string_from_datetime(str);
1383     case MYSQL_TYPE_DATE:
1384       return val_string_from_date(str);
1385     case MYSQL_TYPE_TIME:
1386       return val_string_from_time(str);
1387     default:
1388       break;
1389     }
1390     return str_op(&str_value);
1391   default:
1392     assert(0);
1393   }
1394   return str;
1395 }
1396 
1397 
val_real()1398 double Item_func_numhybrid::val_real()
1399 {
1400   assert(fixed == 1);
1401   switch (hybrid_type) {
1402   case DECIMAL_RESULT:
1403   {
1404     my_decimal decimal_value, *val;
1405     double result;
1406     if (!(val= decimal_op(&decimal_value)))
1407       return 0.0;                               // null is set
1408     my_decimal2double(E_DEC_FATAL_ERROR, val, &result);
1409     return result;
1410   }
1411   case INT_RESULT:
1412   {
1413     longlong result= int_op();
1414     return unsigned_flag ? (double) ((ulonglong) result) : (double) result;
1415   }
1416   case REAL_RESULT:
1417     return real_op();
1418   case STRING_RESULT:
1419   {
1420     switch (field_type())
1421     {
1422     case MYSQL_TYPE_TIME:
1423     case MYSQL_TYPE_DATE:
1424     case MYSQL_TYPE_DATETIME:
1425     case MYSQL_TYPE_TIMESTAMP:
1426       return val_real_from_decimal();
1427     default:
1428       break;
1429     }
1430     char *end_not_used;
1431     int err_not_used;
1432     String *res= str_op(&str_value);
1433     return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
1434 			     &end_not_used, &err_not_used) : 0.0);
1435   }
1436   default:
1437     assert(0);
1438   }
1439   return 0.0;
1440 }
1441 
1442 
val_int()1443 longlong Item_func_numhybrid::val_int()
1444 {
1445   assert(fixed == 1);
1446   switch (hybrid_type) {
1447   case DECIMAL_RESULT:
1448   {
1449     my_decimal decimal_value, *val;
1450     if (!(val= decimal_op(&decimal_value)))
1451       return 0;                                 // null is set
1452     longlong result;
1453     my_decimal2int(E_DEC_FATAL_ERROR, val, unsigned_flag, &result);
1454     return result;
1455   }
1456   case INT_RESULT:
1457     return int_op();
1458   case REAL_RESULT:
1459     return (longlong) rint(real_op());
1460   case STRING_RESULT:
1461   {
1462     switch (field_type())
1463     {
1464     case MYSQL_TYPE_DATE:
1465       return val_int_from_date();
1466     case MYSQL_TYPE_DATETIME:
1467     case MYSQL_TYPE_TIMESTAMP:
1468       return val_int_from_datetime();
1469     case MYSQL_TYPE_TIME:
1470       return val_int_from_time();
1471     default:
1472       break;
1473     }
1474     int err_not_used;
1475     String *res;
1476     if (!(res= str_op(&str_value)))
1477       return 0;
1478 
1479     char *end= (char*) res->ptr() + res->length();
1480     const CHARSET_INFO *cs= res->charset();
1481     return (*(cs->cset->strtoll10))(cs, res->ptr(), &end, &err_not_used);
1482   }
1483   default:
1484     assert(0);
1485   }
1486   return 0;
1487 }
1488 
1489 
val_decimal(my_decimal * decimal_value)1490 my_decimal *Item_func_numhybrid::val_decimal(my_decimal *decimal_value)
1491 {
1492   my_decimal *val= decimal_value;
1493   assert(fixed == 1);
1494   switch (hybrid_type) {
1495   case DECIMAL_RESULT:
1496     val= decimal_op(decimal_value);
1497     break;
1498   case INT_RESULT:
1499   {
1500     longlong result= int_op();
1501     int2my_decimal(E_DEC_FATAL_ERROR, result, unsigned_flag, decimal_value);
1502     break;
1503   }
1504   case REAL_RESULT:
1505   {
1506     double result= real_op();
1507     double2my_decimal(E_DEC_FATAL_ERROR, result, decimal_value);
1508     break;
1509   }
1510   case STRING_RESULT:
1511   {
1512     switch (field_type())
1513     {
1514     case MYSQL_TYPE_DATE:
1515     case MYSQL_TYPE_DATETIME:
1516     case MYSQL_TYPE_TIMESTAMP:
1517       return val_decimal_from_date(decimal_value);
1518     case MYSQL_TYPE_TIME:
1519       return val_decimal_from_time(decimal_value);
1520     default:
1521       break;
1522     }
1523     String *res;
1524     if (!(res= str_op(&str_value)))
1525       return NULL;
1526 
1527     str2my_decimal(E_DEC_FATAL_ERROR, (char*) res->ptr(),
1528                    res->length(), res->charset(), decimal_value);
1529     break;
1530   }
1531   case ROW_RESULT:
1532   default:
1533     assert(0);
1534   }
1535   return val;
1536 }
1537 
1538 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)1539 bool Item_func_numhybrid::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
1540 {
1541   assert(fixed == 1);
1542   switch (field_type())
1543   {
1544   case MYSQL_TYPE_DATE:
1545   case MYSQL_TYPE_DATETIME:
1546   case MYSQL_TYPE_TIMESTAMP:
1547     return date_op(ltime, fuzzydate);
1548   case MYSQL_TYPE_TIME:
1549     return get_date_from_time(ltime);
1550   default:
1551     return Item::get_date_from_non_temporal(ltime, fuzzydate);
1552   }
1553 }
1554 
1555 
get_time(MYSQL_TIME * ltime)1556 bool Item_func_numhybrid::get_time(MYSQL_TIME *ltime)
1557 {
1558   assert(fixed == 1);
1559   switch (field_type())
1560   {
1561   case MYSQL_TYPE_TIME:
1562     return time_op(ltime);
1563   case MYSQL_TYPE_DATE:
1564     return get_time_from_date(ltime);
1565   case MYSQL_TYPE_DATETIME:
1566   case MYSQL_TYPE_TIMESTAMP:
1567     return get_time_from_datetime(ltime);
1568   default:
1569     return Item::get_time_from_non_temporal(ltime);
1570   }
1571 }
1572 
1573 
print(String * str,enum_query_type query_type)1574 void Item_func_signed::print(String *str, enum_query_type query_type)
1575 {
1576   str->append(STRING_WITH_LEN("cast("));
1577   args[0]->print(str, query_type);
1578   str->append(STRING_WITH_LEN(" as signed)"));
1579 
1580 }
1581 
1582 
fix_length_and_dec()1583 void Item_func_signed::fix_length_and_dec()
1584 {
1585   fix_char_length(std::min<uint32>(args[0]->max_char_length(),
1586                                    MY_INT64_NUM_DECIMAL_DIGITS));
1587   reject_geometry_args(arg_count, args, this);
1588 }
1589 
1590 
val_int_from_str(int * error)1591 longlong Item_func_signed::val_int_from_str(int *error)
1592 {
1593   char buff[MAX_FIELD_WIDTH], *end, *start;
1594   size_t length;
1595   String tmp(buff,sizeof(buff), &my_charset_bin), *res;
1596   longlong value;
1597   const CHARSET_INFO *cs;
1598 
1599   /*
1600     For a string result, we must first get the string and then convert it
1601     to a longlong
1602   */
1603 
1604   if (!(res= args[0]->val_str(&tmp)))
1605   {
1606     null_value= 1;
1607     *error= 0;
1608     return 0;
1609   }
1610   null_value= 0;
1611   start= (char *)res->ptr();
1612   length= res->length();
1613   cs= res->charset();
1614 
1615   end= start + length;
1616   value= cs->cset->strtoll10(cs, start, &end, error);
1617   if (*error > 0 || end != start+ length)
1618   {
1619     ErrConvString err(res);
1620     push_warning_printf(current_thd, Sql_condition::SL_WARNING,
1621                         ER_TRUNCATED_WRONG_VALUE,
1622                         ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
1623                         err.ptr());
1624   }
1625   return value;
1626 }
1627 
1628 
val_int()1629 longlong Item_func_signed::val_int()
1630 {
1631   longlong value;
1632   int error;
1633 
1634   if (args[0]->cast_to_int_type() != STRING_RESULT ||
1635       args[0]->is_temporal())
1636   {
1637     value= args[0]->val_int();
1638     null_value= args[0]->null_value;
1639     return value;
1640   }
1641 
1642   value= val_int_from_str(&error);
1643   if (value < 0 && error == 0)
1644   {
1645     push_warning(current_thd, Sql_condition::SL_WARNING, ER_UNKNOWN_ERROR,
1646                  "Cast to signed converted positive out-of-range integer to "
1647                  "it's negative complement");
1648   }
1649   return value;
1650 }
1651 
1652 
print(String * str,enum_query_type query_type)1653 void Item_func_unsigned::print(String *str, enum_query_type query_type)
1654 {
1655   str->append(STRING_WITH_LEN("cast("));
1656   args[0]->print(str, query_type);
1657   str->append(STRING_WITH_LEN(" as unsigned)"));
1658 
1659 }
1660 
1661 
val_int()1662 longlong Item_func_unsigned::val_int()
1663 {
1664   longlong value;
1665   int error;
1666 
1667   if (args[0]->cast_to_int_type() == DECIMAL_RESULT)
1668   {
1669     my_decimal tmp, *dec= args[0]->val_decimal(&tmp);
1670     if (!(null_value= args[0]->null_value))
1671       my_decimal2int(E_DEC_FATAL_ERROR, dec, 1, &value);
1672     else
1673       value= 0;
1674     return value;
1675   }
1676   else if (args[0]->cast_to_int_type() != STRING_RESULT ||
1677            args[0]->is_temporal())
1678   {
1679     value= args[0]->val_int();
1680     null_value= args[0]->null_value;
1681     return value;
1682   }
1683 
1684   value= val_int_from_str(&error);
1685   if (error < 0)
1686     push_warning(current_thd, Sql_condition::SL_WARNING, ER_UNKNOWN_ERROR,
1687                  "Cast to unsigned converted negative integer to it's "
1688                  "positive complement");
1689   return value;
1690 }
1691 
1692 
val_str(String * str)1693 String *Item_decimal_typecast::val_str(String *str)
1694 {
1695   my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
1696   if (null_value)
1697     return NULL;
1698   my_decimal2string(E_DEC_FATAL_ERROR, tmp, 0, 0, 0, str);
1699   return str;
1700 }
1701 
1702 
val_real()1703 double Item_decimal_typecast::val_real()
1704 {
1705   my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
1706   double res;
1707   if (null_value)
1708     return 0.0;
1709   my_decimal2double(E_DEC_FATAL_ERROR, tmp, &res);
1710   return res;
1711 }
1712 
1713 
val_int()1714 longlong Item_decimal_typecast::val_int()
1715 {
1716   my_decimal tmp_buf, *tmp= val_decimal(&tmp_buf);
1717   longlong res;
1718   if (null_value)
1719     return 0;
1720   my_decimal2int(E_DEC_FATAL_ERROR, tmp, unsigned_flag, &res);
1721   return res;
1722 }
1723 
1724 
val_decimal(my_decimal * dec)1725 my_decimal *Item_decimal_typecast::val_decimal(my_decimal *dec)
1726 {
1727   my_decimal tmp_buf, *tmp= args[0]->val_decimal(&tmp_buf);
1728   bool sign;
1729   uint precision;
1730 
1731   if ((null_value= args[0]->null_value))
1732     return NULL;
1733   my_decimal_round(E_DEC_FATAL_ERROR, tmp, decimals, FALSE, dec);
1734   sign= dec->sign();
1735   if (unsigned_flag)
1736   {
1737     if (sign)
1738     {
1739       my_decimal_set_zero(dec);
1740       goto err;
1741     }
1742   }
1743   precision= my_decimal_length_to_precision(max_length,
1744                                             decimals, unsigned_flag);
1745   if (precision - decimals < (uint) my_decimal_intg(dec))
1746   {
1747     max_my_decimal(dec, precision, decimals);
1748     dec->sign(sign);
1749     goto err;
1750   }
1751   return dec;
1752 
1753 err:
1754   push_warning_printf(current_thd, Sql_condition::SL_WARNING,
1755                       ER_WARN_DATA_OUT_OF_RANGE,
1756                       ER(ER_WARN_DATA_OUT_OF_RANGE),
1757                       item_name.ptr(), 1L);
1758   return dec;
1759 }
1760 
1761 
print(String * str,enum_query_type query_type)1762 void Item_decimal_typecast::print(String *str, enum_query_type query_type)
1763 {
1764   char len_buf[20*3 + 1];
1765   char *end;
1766 
1767   uint precision= my_decimal_length_to_precision(max_length, decimals,
1768                                                  unsigned_flag);
1769   str->append(STRING_WITH_LEN("cast("));
1770   args[0]->print(str, query_type);
1771   str->append(STRING_WITH_LEN(" as decimal("));
1772 
1773   end=int10_to_str(precision, len_buf,10);
1774   str->append(len_buf, (uint32) (end - len_buf));
1775 
1776   str->append(',');
1777 
1778   end=int10_to_str(decimals, len_buf,10);
1779   str->append(len_buf, (uint32) (end - len_buf));
1780 
1781   str->append(')');
1782   str->append(')');
1783 }
1784 
1785 
real_op()1786 double Item_func_plus::real_op()
1787 {
1788   double value= args[0]->val_real() + args[1]->val_real();
1789   if ((null_value=args[0]->null_value || args[1]->null_value))
1790     return 0.0;
1791   return check_float_overflow(value);
1792 }
1793 
1794 
int_op()1795 longlong Item_func_plus::int_op()
1796 {
1797   longlong val0= args[0]->val_int();
1798   longlong val1= args[1]->val_int();
1799   longlong res= val0 + val1;
1800   bool     res_unsigned= FALSE;
1801 
1802   if ((null_value= args[0]->null_value || args[1]->null_value))
1803     return 0;
1804 
1805   /*
1806     First check whether the result can be represented as a
1807     (bool unsigned_flag, longlong value) pair, then check if it is compatible
1808     with this Item's unsigned_flag by calling check_integer_overflow().
1809   */
1810   if (args[0]->unsigned_flag)
1811   {
1812     if (args[1]->unsigned_flag || val1 >= 0)
1813     {
1814       if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) val1))
1815         goto err;
1816       res_unsigned= TRUE;
1817     }
1818     else
1819     {
1820       /* val1 is negative */
1821       if ((ulonglong) val0 > (ulonglong) LLONG_MAX)
1822         res_unsigned= TRUE;
1823     }
1824   }
1825   else
1826   {
1827     if (args[1]->unsigned_flag)
1828     {
1829       if (val0 >= 0)
1830       {
1831         if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) val1))
1832           goto err;
1833         res_unsigned= TRUE;
1834       }
1835       else
1836       {
1837         if ((ulonglong) val1 > (ulonglong) LLONG_MAX)
1838           res_unsigned= TRUE;
1839       }
1840     }
1841     else
1842     {
1843       if (val0 >=0 && val1 >= 0)
1844         res_unsigned= TRUE;
1845       else if (val0 < 0 && val1 < 0 && res >= 0)
1846         goto err;
1847     }
1848   }
1849   return check_integer_overflow(res, res_unsigned);
1850 
1851 err:
1852   return raise_integer_overflow();
1853 }
1854 
1855 
1856 /**
1857   Calculate plus of two decimals.
1858 
1859   @param decimal_value	Buffer that can be used to store result
1860 
1861   @retval
1862     0  Value was NULL;  In this case null_value is set
1863   @retval
1864     \# Value of operation as a decimal
1865 */
1866 
decimal_op(my_decimal * decimal_value)1867 my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value)
1868 {
1869   my_decimal value1, *val1;
1870   my_decimal value2, *val2;
1871   val1= args[0]->val_decimal(&value1);
1872   if ((null_value= args[0]->null_value))
1873     return 0;
1874   val2= args[1]->val_decimal(&value2);
1875   if (!(null_value= (args[1]->null_value ||
1876                      check_decimal_overflow(my_decimal_add(E_DEC_FATAL_ERROR &
1877                                                            ~E_DEC_OVERFLOW,
1878                                                            decimal_value,
1879                                                            val1, val2)) > 3)))
1880     return decimal_value;
1881   return 0;
1882 }
1883 
1884 /**
1885   Set precision of results for additive operations (+ and -)
1886 */
result_precision()1887 void Item_func_additive_op::result_precision()
1888 {
1889   decimals= max(args[0]->decimals, args[1]->decimals);
1890   int arg1_int= args[0]->decimal_precision() - args[0]->decimals;
1891   int arg2_int= args[1]->decimal_precision() - args[1]->decimals;
1892   int precision= max(arg1_int, arg2_int) + 1 + decimals;
1893 
1894   /* Integer operations keep unsigned_flag if one of arguments is unsigned */
1895   if (result_type() == INT_RESULT)
1896     unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
1897   else
1898     unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
1899   max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
1900                                                            unsigned_flag);
1901 }
1902 
1903 
1904 /**
1905   The following function is here to allow the user to force
1906   subtraction of UNSIGNED BIGINT to return negative values.
1907 */
1908 
fix_length_and_dec()1909 void Item_func_minus::fix_length_and_dec()
1910 {
1911   Item_num_op::fix_length_and_dec();
1912   if (unsigned_flag &&
1913       (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
1914     unsigned_flag=0;
1915 }
1916 
1917 
real_op()1918 double Item_func_minus::real_op()
1919 {
1920   double value= args[0]->val_real() - args[1]->val_real();
1921   if ((null_value=args[0]->null_value || args[1]->null_value))
1922     return 0.0;
1923   return check_float_overflow(value);
1924 }
1925 
1926 
int_op()1927 longlong Item_func_minus::int_op()
1928 {
1929   longlong val0= args[0]->val_int();
1930   longlong val1= args[1]->val_int();
1931   longlong res= val0 - val1;
1932   bool     res_unsigned= FALSE;
1933 
1934   if ((null_value= args[0]->null_value || args[1]->null_value))
1935     return 0;
1936 
1937   /*
1938     First check whether the result can be represented as a
1939     (bool unsigned_flag, longlong value) pair, then check if it is compatible
1940     with this Item's unsigned_flag by calling check_integer_overflow().
1941   */
1942   if (args[0]->unsigned_flag)
1943   {
1944     if (args[1]->unsigned_flag)
1945     {
1946       if ((ulonglong) val0 < (ulonglong) val1)
1947       {
1948         if (res >= 0)
1949           goto err;
1950       }
1951       else
1952         res_unsigned= TRUE;
1953     }
1954     else
1955     {
1956       if (val1 >= 0)
1957       {
1958         if ((ulonglong) val0 > (ulonglong) val1)
1959           res_unsigned= TRUE;
1960       }
1961       else
1962       {
1963         if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) -val1))
1964           goto err;
1965         res_unsigned= TRUE;
1966       }
1967     }
1968   }
1969   else
1970   {
1971     if (args[1]->unsigned_flag)
1972     {
1973       if ((ulonglong) (val0 - LLONG_MIN) < (ulonglong) val1)
1974         goto err;
1975     }
1976     else
1977     {
1978       if (val0 > 0 && val1 < 0)
1979         res_unsigned= TRUE;
1980       else if (val0 < 0 && val1 > 0 && res >= 0)
1981         goto err;
1982     }
1983   }
1984   return check_integer_overflow(res, res_unsigned);
1985 
1986 err:
1987   return raise_integer_overflow();
1988 }
1989 
1990 
1991 /**
1992   See Item_func_plus::decimal_op for comments.
1993 */
1994 
decimal_op(my_decimal * decimal_value)1995 my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value)
1996 {
1997   my_decimal value1, *val1;
1998   my_decimal value2, *val2;
1999 
2000   val1= args[0]->val_decimal(&value1);
2001   if ((null_value= args[0]->null_value))
2002     return 0;
2003   val2= args[1]->val_decimal(&value2);
2004   if (!(null_value= (args[1]->null_value ||
2005                      (check_decimal_overflow(my_decimal_sub(E_DEC_FATAL_ERROR &
2006                                                             ~E_DEC_OVERFLOW,
2007                                                             decimal_value, val1,
2008                                                             val2)) > 3))))
2009     return decimal_value;
2010   return 0;
2011 }
2012 
2013 
real_op()2014 double Item_func_mul::real_op()
2015 {
2016   assert(fixed == 1);
2017   double value= args[0]->val_real() * args[1]->val_real();
2018   if ((null_value=args[0]->null_value || args[1]->null_value))
2019     return 0.0;
2020   return check_float_overflow(value);
2021 }
2022 
2023 
int_op()2024 longlong Item_func_mul::int_op()
2025 {
2026   assert(fixed == 1);
2027   longlong a= args[0]->val_int();
2028   longlong b= args[1]->val_int();
2029   longlong res;
2030   ulonglong res0, res1;
2031   ulong a0, a1, b0, b1;
2032   bool     res_unsigned= FALSE;
2033   bool     a_negative= FALSE, b_negative= FALSE;
2034 
2035   if ((null_value= args[0]->null_value || args[1]->null_value))
2036     return 0;
2037 
2038   /*
2039     First check whether the result can be represented as a
2040     (bool unsigned_flag, longlong value) pair, then check if it is compatible
2041     with this Item's unsigned_flag by calling check_integer_overflow().
2042 
2043     Let a = a1 * 2^32 + a0 and b = b1 * 2^32 + b0. Then
2044     a * b = (a1 * 2^32 + a0) * (b1 * 2^32 + b0) = a1 * b1 * 2^64 +
2045             + (a1 * b0 + a0 * b1) * 2^32 + a0 * b0;
2046     We can determine if the above sum overflows the ulonglong range by
2047     sequentially checking the following conditions:
2048     1. If both a1 and b1 are non-zero.
2049     2. Otherwise, if (a1 * b0 + a0 * b1) is greater than ULONG_MAX.
2050     3. Otherwise, if (a1 * b0 + a0 * b1) * 2^32 + a0 * b0 is greater than
2051     ULLONG_MAX.
2052 
2053     Since we also have to take the unsigned_flag for a and b into account,
2054     it is easier to first work with absolute values and set the
2055     correct sign later.
2056   */
2057   if (!args[0]->unsigned_flag && a < 0)
2058   {
2059     a_negative= TRUE;
2060     a= -a;
2061   }
2062   if (!args[1]->unsigned_flag && b < 0)
2063   {
2064     b_negative= TRUE;
2065     b= -b;
2066   }
2067 
2068   a0= 0xFFFFFFFFUL & a;
2069   a1= ((ulonglong) a) >> 32;
2070   b0= 0xFFFFFFFFUL & b;
2071   b1= ((ulonglong) b) >> 32;
2072 
2073   if (a1 && b1)
2074     goto err;
2075 
2076   res1= (ulonglong) a1 * b0 + (ulonglong) a0 * b1;
2077   if (res1 > 0xFFFFFFFFUL)
2078     goto err;
2079 
2080   res1= res1 << 32;
2081   res0= (ulonglong) a0 * b0;
2082 
2083   if (test_if_sum_overflows_ull(res1, res0))
2084     goto err;
2085   res= res1 + res0;
2086 
2087   if (a_negative != b_negative)
2088   {
2089     if ((ulonglong) res > (ulonglong) LLONG_MIN + 1)
2090       goto err;
2091     res= -res;
2092   }
2093   else
2094     res_unsigned= TRUE;
2095 
2096   return check_integer_overflow(res, res_unsigned);
2097 
2098 err:
2099   return raise_integer_overflow();
2100 }
2101 
2102 
2103 /** See Item_func_plus::decimal_op for comments. */
2104 
decimal_op(my_decimal * decimal_value)2105 my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value)
2106 {
2107   my_decimal value1, *val1;
2108   my_decimal value2, *val2;
2109   val1= args[0]->val_decimal(&value1);
2110   if ((null_value= args[0]->null_value))
2111     return 0;
2112   val2= args[1]->val_decimal(&value2);
2113   if (!(null_value= (args[1]->null_value ||
2114                      (check_decimal_overflow(my_decimal_mul(E_DEC_FATAL_ERROR &
2115                                                             ~E_DEC_OVERFLOW,
2116                                                             decimal_value, val1,
2117                                                             val2)) > 3))))
2118     return decimal_value;
2119   return 0;
2120 }
2121 
2122 
result_precision()2123 void Item_func_mul::result_precision()
2124 {
2125   /* Integer operations keep unsigned_flag if one of arguments is unsigned */
2126   if (result_type() == INT_RESULT)
2127     unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
2128   else
2129     unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
2130   decimals= min(args[0]->decimals + args[1]->decimals, DECIMAL_MAX_SCALE);
2131   uint est_prec = args[0]->decimal_precision() + args[1]->decimal_precision();
2132   uint precision= min<uint>(est_prec, DECIMAL_MAX_PRECISION);
2133   max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
2134                                                            unsigned_flag);
2135 }
2136 
2137 
real_op()2138 double Item_func_div::real_op()
2139 {
2140   assert(fixed == 1);
2141   double value= args[0]->val_real();
2142   double val2= args[1]->val_real();
2143   if ((null_value= args[0]->null_value || args[1]->null_value))
2144     return 0.0;
2145   if (val2 == 0.0)
2146   {
2147     signal_divide_by_null();
2148     return 0.0;
2149   }
2150   return check_float_overflow(value/val2);
2151 }
2152 
2153 
decimal_op(my_decimal * decimal_value)2154 my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value)
2155 {
2156   my_decimal value1, *val1;
2157   my_decimal value2, *val2;
2158   int err;
2159 
2160   val1= args[0]->val_decimal(&value1);
2161   if ((null_value= args[0]->null_value))
2162     return 0;
2163   val2= args[1]->val_decimal(&value2);
2164   if ((null_value= args[1]->null_value))
2165     return 0;
2166   if ((err= check_decimal_overflow(my_decimal_div(E_DEC_FATAL_ERROR &
2167                                                   ~E_DEC_OVERFLOW &
2168                                                   ~E_DEC_DIV_ZERO,
2169                                                   decimal_value,
2170                                                   val1, val2,
2171                                                   prec_increment))) > 3)
2172   {
2173     if (err == E_DEC_DIV_ZERO)
2174       signal_divide_by_null();
2175     null_value= 1;
2176     return 0;
2177   }
2178   return decimal_value;
2179 }
2180 
2181 
result_precision()2182 void Item_func_div::result_precision()
2183 {
2184   uint precision= min<uint>(args[0]->decimal_precision() +
2185                             args[1]->decimals + prec_increment,
2186                             DECIMAL_MAX_PRECISION);
2187 
2188   if (result_type() == DECIMAL_RESULT)
2189     assert(precision > 0);
2190 
2191   /* Integer operations keep unsigned_flag if one of arguments is unsigned */
2192   if (result_type() == INT_RESULT)
2193     unsigned_flag= args[0]->unsigned_flag | args[1]->unsigned_flag;
2194   else
2195     unsigned_flag= args[0]->unsigned_flag & args[1]->unsigned_flag;
2196   decimals= min<uint>(args[0]->decimals + prec_increment, DECIMAL_MAX_SCALE);
2197   max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
2198                                                            unsigned_flag);
2199 }
2200 
2201 
fix_length_and_dec()2202 void Item_func_div::fix_length_and_dec()
2203 {
2204   DBUG_ENTER("Item_func_div::fix_length_and_dec");
2205   prec_increment= current_thd->variables.div_precincrement;
2206   Item_num_op::fix_length_and_dec();
2207   switch(hybrid_type) {
2208   case REAL_RESULT:
2209   {
2210     decimals=max(args[0]->decimals,args[1]->decimals)+prec_increment;
2211     set_if_smaller(decimals, NOT_FIXED_DEC);
2212     uint tmp=float_length(decimals);
2213     if (decimals == NOT_FIXED_DEC)
2214       max_length= tmp;
2215     else
2216     {
2217       max_length=args[0]->max_length - args[0]->decimals + decimals;
2218       set_if_smaller(max_length,tmp);
2219     }
2220     break;
2221   }
2222   case INT_RESULT:
2223     hybrid_type= DECIMAL_RESULT;
2224     DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
2225     result_precision();
2226     break;
2227   case DECIMAL_RESULT:
2228     result_precision();
2229     break;
2230   default:
2231     assert(0);
2232   }
2233   maybe_null= 1; // devision by zero
2234   DBUG_VOID_RETURN;
2235 }
2236 
2237 
2238 /* Integer division */
val_int()2239 longlong Item_func_int_div::val_int()
2240 {
2241   assert(fixed == 1);
2242 
2243   /*
2244     Perform division using DECIMAL math if either of the operands has a
2245     non-integer type
2246   */
2247   if (args[0]->result_type() != INT_RESULT ||
2248       args[1]->result_type() != INT_RESULT)
2249   {
2250     my_decimal tmp;
2251     my_decimal *val0p= args[0]->val_decimal(&tmp);
2252     if ((null_value= args[0]->null_value))
2253       return 0;
2254     my_decimal val0= *val0p;
2255 
2256     my_decimal *val1p= args[1]->val_decimal(&tmp);
2257     if ((null_value= args[1]->null_value))
2258       return 0;
2259     my_decimal val1= *val1p;
2260 
2261     int err;
2262     if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, &tmp,
2263                              &val0, &val1, 0)) > 3)
2264     {
2265       if (err == E_DEC_DIV_ZERO)
2266         signal_divide_by_null();
2267       return 0;
2268     }
2269 
2270     my_decimal truncated;
2271     const bool do_truncate= true;
2272     if (my_decimal_round(E_DEC_FATAL_ERROR, &tmp, 0, do_truncate, &truncated))
2273       assert(false);
2274 
2275     longlong res;
2276     if (my_decimal2int(E_DEC_FATAL_ERROR, &truncated, unsigned_flag, &res) &
2277         E_DEC_OVERFLOW)
2278       raise_integer_overflow();
2279     return res;
2280   }
2281 
2282   longlong val0=args[0]->val_int();
2283   longlong val1=args[1]->val_int();
2284   bool val0_negative, val1_negative, res_negative;
2285   ulonglong uval0, uval1, res;
2286   if ((null_value= (args[0]->null_value || args[1]->null_value)))
2287     return 0;
2288   if (val1 == 0)
2289   {
2290     signal_divide_by_null();
2291     return 0;
2292   }
2293 
2294   val0_negative= !args[0]->unsigned_flag && val0 < 0;
2295   val1_negative= !args[1]->unsigned_flag && val1 < 0;
2296   res_negative= val0_negative != val1_negative;
2297   uval0= (ulonglong) (val0_negative ? -val0 : val0);
2298   uval1= (ulonglong) (val1_negative ? -val1 : val1);
2299   res= uval0 / uval1;
2300   if (res_negative)
2301   {
2302     if (res > (ulonglong) LLONG_MAX)
2303       return raise_integer_overflow();
2304     res= (ulonglong) (-(longlong) res);
2305   }
2306   return check_integer_overflow(res, !res_negative);
2307 }
2308 
2309 
fix_length_and_dec()2310 void Item_func_int_div::fix_length_and_dec()
2311 {
2312   Item_result argtype= args[0]->result_type();
2313   /* use precision ony for the data type it is applicable for and valid */
2314   uint32 char_length= args[0]->max_char_length() -
2315                       (argtype == DECIMAL_RESULT || argtype == INT_RESULT ?
2316                        args[0]->decimals : 0);
2317   fix_char_length(char_length > MY_INT64_NUM_DECIMAL_DIGITS ?
2318                   MY_INT64_NUM_DECIMAL_DIGITS : char_length);
2319   maybe_null=1;
2320   unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
2321   reject_geometry_args(arg_count, args, this);
2322 }
2323 
2324 
int_op()2325 longlong Item_func_mod::int_op()
2326 {
2327   assert(fixed == 1);
2328   longlong val0= args[0]->val_int();
2329   longlong val1= args[1]->val_int();
2330   bool val0_negative, val1_negative;
2331   ulonglong uval0, uval1;
2332   ulonglong res;
2333 
2334   if ((null_value= args[0]->null_value || args[1]->null_value))
2335     return 0; /* purecov: inspected */
2336   if (val1 == 0)
2337   {
2338     signal_divide_by_null();
2339     return 0;
2340   }
2341 
2342   /*
2343     '%' is calculated by integer division internally. Since dividing
2344     LLONG_MIN by -1 generates SIGFPE, we calculate using unsigned values and
2345     then adjust the sign appropriately.
2346   */
2347   val0_negative= !args[0]->unsigned_flag && val0 < 0;
2348   val1_negative= !args[1]->unsigned_flag && val1 < 0;
2349   uval0= (ulonglong) (val0_negative ? -val0 : val0);
2350   uval1= (ulonglong) (val1_negative ? -val1 : val1);
2351   res= uval0 % uval1;
2352   return check_integer_overflow(val0_negative ? -(longlong) res : res,
2353                                 !val0_negative);
2354 }
2355 
real_op()2356 double Item_func_mod::real_op()
2357 {
2358   assert(fixed == 1);
2359   double value= args[0]->val_real();
2360   double val2=  args[1]->val_real();
2361   if ((null_value= args[0]->null_value || args[1]->null_value))
2362     return 0.0; /* purecov: inspected */
2363   if (val2 == 0.0)
2364   {
2365     signal_divide_by_null();
2366     return 0.0;
2367   }
2368   return fmod(value,val2);
2369 }
2370 
2371 
decimal_op(my_decimal * decimal_value)2372 my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value)
2373 {
2374   my_decimal value1, *val1;
2375   my_decimal value2, *val2;
2376 
2377   val1= args[0]->val_decimal(&value1);
2378   if ((null_value= args[0]->null_value))
2379     return 0;
2380   val2= args[1]->val_decimal(&value2);
2381   if ((null_value= args[1]->null_value))
2382     return 0;
2383   switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
2384                          val1, val2)) {
2385   case E_DEC_TRUNCATED:
2386   case E_DEC_OK:
2387     return decimal_value;
2388   case E_DEC_DIV_ZERO:
2389     signal_divide_by_null();
2390     // Fall through.
2391   default:
2392     null_value= 1;
2393     return 0;
2394   }
2395 }
2396 
2397 
result_precision()2398 void Item_func_mod::result_precision()
2399 {
2400   decimals= max(args[0]->decimals, args[1]->decimals);
2401   max_length= max(args[0]->max_length, args[1]->max_length);
2402   // Increase max_length if we have: signed % unsigned(precision == scale)
2403   if (!args[0]->unsigned_flag && args[1]->unsigned_flag &&
2404       args[0]->max_length <= args[1]->max_length &&
2405       args[1]->decimals == args[1]->decimal_precision())
2406   {
2407     max_length+= 1;
2408   }
2409 }
2410 
2411 
fix_length_and_dec()2412 void Item_func_mod::fix_length_and_dec()
2413 {
2414   Item_num_op::fix_length_and_dec();
2415   maybe_null= 1;
2416   unsigned_flag= args[0]->unsigned_flag;
2417 }
2418 
2419 
real_op()2420 double Item_func_neg::real_op()
2421 {
2422   double value= args[0]->val_real();
2423   null_value= args[0]->null_value;
2424   return -value;
2425 }
2426 
2427 
int_op()2428 longlong Item_func_neg::int_op()
2429 {
2430   longlong value= args[0]->val_int();
2431   if ((null_value= args[0]->null_value))
2432     return 0;
2433   if (args[0]->unsigned_flag &&
2434       (ulonglong) value > (ulonglong) LLONG_MAX + 1ULL)
2435     return raise_integer_overflow();
2436   // For some platforms we need special handling of LLONG_MIN to
2437   // guarantee overflow.
2438   if (value == LLONG_MIN &&
2439       !args[0]->unsigned_flag &&
2440       !unsigned_flag)
2441     return raise_integer_overflow();
2442   return check_integer_overflow(-value, !args[0]->unsigned_flag && value < 0);
2443 }
2444 
2445 
decimal_op(my_decimal * decimal_value)2446 my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value)
2447 {
2448   my_decimal val, *value= args[0]->val_decimal(&val);
2449   if (!(null_value= args[0]->null_value))
2450   {
2451     my_decimal2decimal(value, decimal_value);
2452     my_decimal_neg(decimal_value);
2453     return decimal_value;
2454   }
2455   return 0;
2456 }
2457 
2458 
fix_num_length_and_dec()2459 void Item_func_neg::fix_num_length_and_dec()
2460 {
2461   decimals= args[0]->decimals;
2462   /* 1 add because sign can appear */
2463   max_length= args[0]->max_length + 1;
2464 }
2465 
2466 
fix_length_and_dec()2467 void Item_func_neg::fix_length_and_dec()
2468 {
2469   DBUG_ENTER("Item_func_neg::fix_length_and_dec");
2470   Item_func_num1::fix_length_and_dec();
2471 
2472   /*
2473     If this is in integer context keep the context as integer if possible
2474     (This is how multiplication and other integer functions works)
2475     Use val() to get value as arg_type doesn't mean that item is
2476     Item_int or Item_real due to existence of Item_param.
2477   */
2478   if (hybrid_type == INT_RESULT && args[0]->const_item())
2479   {
2480     longlong val= args[0]->val_int();
2481     if ((ulonglong) val >= (ulonglong) LLONG_MIN &&
2482         ((ulonglong) val != (ulonglong) LLONG_MIN ||
2483           args[0]->type() != INT_ITEM))
2484     {
2485       /*
2486         Ensure that result is converted to DECIMAL, as longlong can't hold
2487         the negated number
2488       */
2489       hybrid_type= DECIMAL_RESULT;
2490       DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
2491     }
2492   }
2493   unsigned_flag= 0;
2494   DBUG_VOID_RETURN;
2495 }
2496 
2497 
real_op()2498 double Item_func_abs::real_op()
2499 {
2500   double value= args[0]->val_real();
2501   null_value= args[0]->null_value;
2502   return fabs(value);
2503 }
2504 
2505 
int_op()2506 longlong Item_func_abs::int_op()
2507 {
2508   longlong value= args[0]->val_int();
2509   if ((null_value= args[0]->null_value))
2510     return 0;
2511   if (unsigned_flag)
2512     return value;
2513   /* -LLONG_MIN = LLONG_MAX + 1 => outside of signed longlong range */
2514   if (value == LLONG_MIN)
2515     return raise_integer_overflow();
2516   return (value >= 0) ? value : -value;
2517 }
2518 
2519 
decimal_op(my_decimal * decimal_value)2520 my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value)
2521 {
2522   my_decimal val, *value= args[0]->val_decimal(&val);
2523   if (!(null_value= args[0]->null_value))
2524   {
2525     my_decimal2decimal(value, decimal_value);
2526     if (decimal_value->sign())
2527       my_decimal_neg(decimal_value);
2528     return decimal_value;
2529   }
2530   return 0;
2531 }
2532 
2533 
fix_length_and_dec()2534 void Item_func_abs::fix_length_and_dec()
2535 {
2536   Item_func_num1::fix_length_and_dec();
2537   unsigned_flag= args[0]->unsigned_flag;
2538 }
2539 
2540 
fix_length_and_dec()2541 void Item_func_latlongfromgeohash::fix_length_and_dec()
2542 {
2543   Item_real_func::fix_length_and_dec();
2544   unsigned_flag= FALSE;
2545 }
2546 
2547 
fix_fields(THD * thd,Item ** ref)2548 bool Item_func_latlongfromgeohash::fix_fields(THD *thd, Item **ref)
2549 {
2550   if (Item_real_func::fix_fields(thd, ref))
2551     return true;
2552 
2553   maybe_null= args[0]->maybe_null;
2554 
2555   if (!check_geohash_argument_valid_type(args[0]))
2556   {
2557     my_error(ER_INCORRECT_TYPE, MYF(0), "geohash", func_name());
2558     return true;
2559   }
2560 
2561   return false;
2562 }
2563 
2564 
2565 /**
2566   Checks if geohash arguments is of valid type
2567 
2568   We must enforce that input actually is text/char, since
2569   SELECT LongFromGeohash(0123) would give different (and wrong) result,
2570   as opposed to SELECT LongFromGeohash("0123").
2571 
2572   @param item Item to validate.
2573 
2574   @return false if validation failed. true if item is a valid type.
2575 */
2576 bool
check_geohash_argument_valid_type(Item * item)2577 Item_func_latlongfromgeohash::check_geohash_argument_valid_type(Item *item)
2578 {
2579   if (Item_func_geohash::is_item_null(item))
2580     return true;
2581 
2582   /*
2583     If charset is not binary and field_type() is BLOB,
2584     we have a TEXT column (which is allowed).
2585   */
2586   bool is_binary_charset= (item->collation.collation == &my_charset_bin);
2587   bool is_parameter_marker= (item->type() == PARAM_ITEM);
2588 
2589   switch (item->field_type())
2590   {
2591   case MYSQL_TYPE_VARCHAR:
2592   case MYSQL_TYPE_VAR_STRING:
2593   case MYSQL_TYPE_STRING:
2594   case MYSQL_TYPE_BLOB:
2595   case MYSQL_TYPE_TINY_BLOB:
2596   case MYSQL_TYPE_MEDIUM_BLOB:
2597   case MYSQL_TYPE_LONG_BLOB:
2598     return (!is_binary_charset || is_parameter_marker);
2599   default:
2600     return false;
2601   }
2602 }
2603 
2604 
2605 /**
2606   Decodes a geohash string into longitude and latitude.
2607 
2608   The results are rounded,  based on the length of input geohash. The function
2609   will stop evaluating when the error range, or "accuracy", has become 0.0 for
2610   both latitude and longitude since no more changes can happen after this.
2611 
2612   @param geohash The geohash to decode.
2613   @param upper_latitude Upper limit of returned latitude (normally 90.0).
2614   @param upper_latitude Lower limit of returned latitude (normally -90.0).
2615   @param upper_latitude Upper limit of returned longitude (normally 180.0).
2616   @param upper_latitude Lower limit of returned longitude (normally -180.0).
2617   @param[out] result_latitude Calculated latitude.
2618   @param[out] result_longitude Calculated longitude.
2619 
2620   @return false on success, true on failure (invalid geohash string).
2621 */
2622 bool
decode_geohash(String * geohash,double upper_latitude,double lower_latitude,double upper_longitude,double lower_longitude,double * result_latitude,double * result_longitude)2623 Item_func_latlongfromgeohash::decode_geohash(String *geohash,
2624                                              double upper_latitude,
2625                                              double lower_latitude,
2626                                              double upper_longitude,
2627                                              double lower_longitude,
2628                                              double *result_latitude,
2629                                              double *result_longitude)
2630 {
2631   double latitude_accuracy= (upper_latitude - lower_latitude) / 2.0;
2632   double longitude_accuracy= (upper_longitude - lower_longitude) / 2.0;
2633 
2634   double latitude_value= (upper_latitude + lower_latitude) / 2.0;
2635   double longitude_value= (upper_longitude + lower_longitude) / 2.0;
2636 
2637   uint number_of_bits_used= 0;
2638   uint input_length= geohash->length();
2639 
2640   for (uint i= 0;
2641        i < input_length && latitude_accuracy > 0.0 && longitude_accuracy > 0.0;
2642        i++)
2643   {
2644     char input_character= my_tolower(&my_charset_latin1, (*geohash)[i]);
2645 
2646     /*
2647      The following part will convert from character value to a
2648      contiguous value from 0 to 31, where "0" = 0, "1" = 1 ... "z" = 31.
2649      It will also detect characters that aren't allowed.
2650     */
2651     int converted_character;
2652     if (input_character >= '0' && input_character <= '9')
2653     {
2654       converted_character= input_character - '0';
2655     }
2656     else if (input_character >= 'b' && input_character <= 'z' &&
2657              input_character != 'i' &&
2658              input_character != 'l' &&
2659              input_character != 'o')
2660     {
2661       if (input_character > 'o')
2662         converted_character= input_character - ('b' - 10 + 3);
2663       else if (input_character > 'l')
2664         converted_character= input_character - ('b' - 10 + 2);
2665       else if (input_character > 'i')
2666         converted_character= input_character - ('b' - 10 + 1);
2667       else
2668         converted_character= input_character - ('b' - 10);
2669     }
2670     else
2671     {
2672       return true;
2673     }
2674 
2675     assert(converted_character >= 0 && converted_character <= 31);
2676 
2677     /*
2678      This loop decodes 5 bits of data. Every even bit (counting from 0) is
2679      used for longitude value, and odd bits are used for latitude value.
2680     */
2681     for (int bit_number= 4; bit_number >= 0; bit_number-= 1)
2682     {
2683       if (number_of_bits_used % 2 == 0)
2684       {
2685         longitude_accuracy/= 2.0;
2686 
2687         if (converted_character & (1 << bit_number))
2688           longitude_value+= longitude_accuracy;
2689         else
2690           longitude_value-= longitude_accuracy;
2691       }
2692       else
2693       {
2694         latitude_accuracy/= 2.0;
2695 
2696         if (converted_character & (1 << bit_number))
2697           latitude_value+= latitude_accuracy;
2698         else
2699           latitude_value-= latitude_accuracy;
2700       }
2701 
2702       number_of_bits_used++;
2703 
2704       assert(latitude_value >= lower_latitude &&
2705              latitude_value <= upper_latitude &&
2706              longitude_value >= lower_longitude &&
2707              longitude_value <= upper_longitude);
2708     }
2709   }
2710 
2711   *result_latitude= round_latlongitude(latitude_value,
2712                                        latitude_accuracy * 2.0,
2713                                        latitude_value - latitude_accuracy,
2714                                        latitude_value + latitude_accuracy);
2715   *result_longitude= round_latlongitude(longitude_value,
2716                                         longitude_accuracy * 2.0,
2717                                         longitude_value - longitude_accuracy,
2718                                         longitude_value + longitude_accuracy);
2719 
2720   /*
2721     Ensure that the rounded results are not ouside of the valid range. As
2722     written in the specification:
2723 
2724       Final rounding should be done carefully in a way that
2725                 min <= round(value) <= max
2726   */
2727   assert(latitude_value - latitude_accuracy <= *result_latitude);
2728   assert(*result_latitude <= latitude_value + latitude_accuracy);
2729 
2730   assert(longitude_value - longitude_accuracy <= *result_longitude);
2731   assert(*result_longitude <= longitude_value + longitude_accuracy);
2732 
2733   return false;
2734 }
2735 
2736 
2737 /**
2738   Rounds a latitude or longitude value.
2739 
2740   This will round a latitude or longitude value, based on error_range.
2741   The error_range is the difference between upper and lower lat/longitude
2742   (e.g upper value of 45.0 and a lower value of 22.5, gives an error range of
2743   22.5).
2744 
2745   The returned result will always be in the range [lower_limit, upper_limit]
2746 
2747   @param latlongitude The latitude or longitude to round.
2748   @param error_range The total error range of the calculated laglongitude.
2749   @param lower_limit Lower limit of the returned result.
2750   @param upper_limit Upper limit of the returned result.
2751 
2752   @return A rounded latitude or longitude.
2753 */
round_latlongitude(double latlongitude,double error_range,double lower_limit,double upper_limit)2754 double Item_func_latlongfromgeohash::round_latlongitude(double latlongitude,
2755                                                         double error_range,
2756                                                         double lower_limit,
2757                                                         double upper_limit)
2758 {
2759   // Ensure that we don't start with an impossible case to solve.
2760   assert(lower_limit <= latlongitude);
2761   assert(upper_limit >= latlongitude);
2762 
2763   if (error_range == 0.0)
2764   {
2765     return latlongitude;
2766   }
2767   else
2768   {
2769     uint number_of_decimals= 0;
2770     while (error_range <= 0.1 && number_of_decimals <= DBL_DIG)
2771     {
2772       number_of_decimals++;
2773       error_range*= 10.0;
2774     }
2775 
2776     double return_value;
2777     do
2778     {
2779       return_value= my_double_round(latlongitude, number_of_decimals, false,
2780                                     false);
2781       number_of_decimals++;
2782     } while ((lower_limit > return_value || return_value > upper_limit) &&
2783              number_of_decimals <= DBL_DIG);
2784 
2785     /*
2786       We may in some cases still be outside of the allowed range. If this is the
2787       case, return the input value (which we know for sure to be within the
2788       allowed range).
2789     */
2790     if (lower_limit > return_value || return_value > upper_limit)
2791       return_value= latlongitude;
2792 
2793     // Avoid printing signed zero.
2794     return return_value + 0.0;
2795   }
2796 }
2797 
2798 
2799 /**
2800   Decodes a geohash into longitude if start_on_even_bit == true, or latitude if
2801   start_on_even_bit == false. The output will be rounded based on the length
2802   of the geohash.
2803 */
val_real()2804 double Item_func_latlongfromgeohash::val_real()
2805 {
2806   assert(fixed == TRUE);
2807 
2808   String buf;
2809   String *input_value= args[0]->val_str_ascii(&buf);
2810 
2811   if ((null_value= args[0]->null_value))
2812     return 0.0;
2813 
2814   if (input_value->length() == 0)
2815   {
2816     my_error(ER_WRONG_VALUE_FOR_TYPE, MYF(0), "geohash",
2817              input_value->c_ptr_safe(), func_name());
2818     return error_real();
2819   }
2820 
2821   double latitude= 0.0;
2822   double longitude= 0.0;
2823   if (decode_geohash(input_value, upper_latitude, lower_latitude,
2824                      upper_longitude, lower_longitude, &latitude, &longitude))
2825   {
2826     my_error(ER_WRONG_VALUE_FOR_TYPE, MYF(0), "geohash",
2827              input_value->c_ptr_safe(), func_name());
2828     return error_real();
2829   }
2830 
2831   // Return longitude if start_on_even_bit == true. Otherwise, return latitude.
2832   if (start_on_even_bit)
2833     return longitude;
2834   return latitude;
2835 }
2836 
2837 
fix_length_and_dec()2838 void Item_dec_func::fix_length_and_dec()
2839 {
2840   decimals= NOT_FIXED_DEC;
2841   max_length= float_length(decimals);
2842   maybe_null= 1;
2843   reject_geometry_args(arg_count, args, this);
2844 }
2845 
2846 
2847 /** Gateway to natural LOG function. */
val_real()2848 double Item_func_ln::val_real()
2849 {
2850   assert(fixed == 1);
2851   double value= args[0]->val_real();
2852   if ((null_value= args[0]->null_value))
2853     return 0.0;
2854   if (value <= 0.0)
2855   {
2856     signal_invalid_argument_for_log();
2857     return 0.0;
2858   }
2859   return log(value);
2860 }
2861 
2862 
2863 /**
2864   Extended but so slower LOG function.
2865 
2866   We have to check if all values are > zero and first one is not one
2867   as these are the cases then result is not a number.
2868 */
val_real()2869 double Item_func_log::val_real()
2870 {
2871   assert(fixed == 1);
2872   double value= args[0]->val_real();
2873   if ((null_value= args[0]->null_value))
2874     return 0.0;
2875   if (value <= 0.0)
2876   {
2877     signal_invalid_argument_for_log();
2878     return 0.0;
2879   }
2880   if (arg_count == 2)
2881   {
2882     double value2= args[1]->val_real();
2883     if ((null_value= args[1]->null_value))
2884       return 0.0;
2885     if (value2 <= 0.0 || value == 1.0)
2886     {
2887       signal_invalid_argument_for_log();
2888       return 0.0;
2889     }
2890     return log(value2) / log(value);
2891   }
2892   return log(value);
2893 }
2894 
val_real()2895 double Item_func_log2::val_real()
2896 {
2897   assert(fixed == 1);
2898   double value= args[0]->val_real();
2899 
2900   if ((null_value=args[0]->null_value))
2901     return 0.0;
2902   if (value <= 0.0)
2903   {
2904     signal_invalid_argument_for_log();
2905     return 0.0;
2906   }
2907   return log(value) / M_LN2;
2908 }
2909 
val_real()2910 double Item_func_log10::val_real()
2911 {
2912   assert(fixed == 1);
2913   double value= args[0]->val_real();
2914   if ((null_value= args[0]->null_value))
2915     return 0.0;
2916   if (value <= 0.0)
2917   {
2918     signal_invalid_argument_for_log();
2919     return 0.0;
2920   }
2921   return log10(value);
2922 }
2923 
val_real()2924 double Item_func_exp::val_real()
2925 {
2926   assert(fixed == 1);
2927   double value= args[0]->val_real();
2928   if ((null_value=args[0]->null_value))
2929     return 0.0; /* purecov: inspected */
2930   return check_float_overflow(exp(value));
2931 }
2932 
val_real()2933 double Item_func_sqrt::val_real()
2934 {
2935   assert(fixed == 1);
2936   double value= args[0]->val_real();
2937   if ((null_value=(args[0]->null_value || value < 0)))
2938     return 0.0; /* purecov: inspected */
2939   return sqrt(value);
2940 }
2941 
val_real()2942 double Item_func_pow::val_real()
2943 {
2944   assert(fixed == 1);
2945   double value= args[0]->val_real();
2946   double val2= args[1]->val_real();
2947   if ((null_value=(args[0]->null_value || args[1]->null_value)))
2948     return 0.0; /* purecov: inspected */
2949   return check_float_overflow(pow(value,val2));
2950 }
2951 
2952 // Trigonometric functions
2953 
val_real()2954 double Item_func_acos::val_real()
2955 {
2956   assert(fixed == 1);
2957   /* One can use this to defer SELECT processing. */
2958   DEBUG_SYNC(current_thd, "before_acos_function");
2959   // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
2960   volatile double value= args[0]->val_real();
2961   if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
2962     return 0.0;
2963   return acos(value);
2964 }
2965 
val_real()2966 double Item_func_asin::val_real()
2967 {
2968   assert(fixed == 1);
2969   // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
2970   volatile double value= args[0]->val_real();
2971   if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
2972     return 0.0;
2973   return asin(value);
2974 }
2975 
val_real()2976 double Item_func_atan::val_real()
2977 {
2978   assert(fixed == 1);
2979   double value= args[0]->val_real();
2980   if ((null_value=args[0]->null_value))
2981     return 0.0;
2982   if (arg_count == 2)
2983   {
2984     double val2= args[1]->val_real();
2985     if ((null_value=args[1]->null_value))
2986       return 0.0;
2987     return check_float_overflow(atan2(value,val2));
2988   }
2989   return atan(value);
2990 }
2991 
val_real()2992 double Item_func_cos::val_real()
2993 {
2994   assert(fixed == 1);
2995   double value= args[0]->val_real();
2996   if ((null_value=args[0]->null_value))
2997     return 0.0;
2998   return cos(value);
2999 }
3000 
val_real()3001 double Item_func_sin::val_real()
3002 {
3003   assert(fixed == 1);
3004   double value= args[0]->val_real();
3005   if ((null_value=args[0]->null_value))
3006     return 0.0;
3007   return sin(value);
3008 }
3009 
val_real()3010 double Item_func_tan::val_real()
3011 {
3012   assert(fixed == 1);
3013   double value= args[0]->val_real();
3014   if ((null_value=args[0]->null_value))
3015     return 0.0;
3016   return check_float_overflow(tan(value));
3017 }
3018 
3019 
val_real()3020 double Item_func_cot::val_real()
3021 {
3022   assert(fixed == 1);
3023   double value= args[0]->val_real();
3024   if ((null_value=args[0]->null_value))
3025     return 0.0;
3026   return check_float_overflow(1.0 / tan(value));
3027 }
3028 
3029 
3030 // Shift-functions, same as << and >> in C/C++
3031 
3032 
val_int()3033 longlong Item_func_shift_left::val_int()
3034 {
3035   assert(fixed == 1);
3036   uint shift;
3037   ulonglong res= ((ulonglong) args[0]->val_int() <<
3038 		  (shift=(uint) args[1]->val_int()));
3039   if (args[0]->null_value || args[1]->null_value)
3040   {
3041     null_value=1;
3042     return 0;
3043   }
3044   null_value=0;
3045   return (shift < sizeof(longlong)*8 ? (longlong) res : 0LL);
3046 }
3047 
val_int()3048 longlong Item_func_shift_right::val_int()
3049 {
3050   assert(fixed == 1);
3051   uint shift;
3052   ulonglong res= (ulonglong) args[0]->val_int() >>
3053     (shift=(uint) args[1]->val_int());
3054   if (args[0]->null_value || args[1]->null_value)
3055   {
3056     null_value=1;
3057     return 0;
3058   }
3059   null_value=0;
3060   return (shift < sizeof(longlong)*8 ? (longlong) res : 0LL);
3061 }
3062 
3063 
val_int()3064 longlong Item_func_bit_neg::val_int()
3065 {
3066   assert(fixed == 1);
3067   ulonglong res= (ulonglong) args[0]->val_int();
3068   if ((null_value=args[0]->null_value))
3069     return 0;
3070   return ~res;
3071 }
3072 
3073 
3074 // Conversion functions
3075 
fix_length_and_dec()3076 void Item_func_integer::fix_length_and_dec()
3077 {
3078   max_length=args[0]->max_length - args[0]->decimals+1;
3079   uint tmp=float_length(decimals);
3080   set_if_smaller(max_length,tmp);
3081   decimals=0;
3082   reject_geometry_args(arg_count, args, this);
3083 }
3084 
fix_num_length_and_dec()3085 void Item_func_int_val::fix_num_length_and_dec()
3086 {
3087   ulonglong tmp_max_length= (ulonglong ) args[0]->max_length -
3088     (args[0]->decimals ? args[0]->decimals + 1 : 0) + 2;
3089   max_length= tmp_max_length > (ulonglong) 4294967295U ?
3090     (uint32) 4294967295U : (uint32) tmp_max_length;
3091   uint tmp= float_length(decimals);
3092   set_if_smaller(max_length,tmp);
3093   decimals= 0;
3094 }
3095 
3096 
find_num_type()3097 void Item_func_int_val::find_num_type()
3098 {
3099   DBUG_ENTER("Item_func_int_val::find_num_type");
3100   DBUG_PRINT("info", ("name %s", func_name()));
3101   switch(hybrid_type= args[0]->result_type())
3102   {
3103   case STRING_RESULT:
3104   case REAL_RESULT:
3105     hybrid_type= REAL_RESULT;
3106     max_length= float_length(decimals);
3107     break;
3108   case INT_RESULT:
3109   case DECIMAL_RESULT:
3110     /*
3111       -2 because in most high position can't be used any digit for longlong
3112       and one position for increasing value during operation
3113     */
3114     if ((args[0]->max_length - args[0]->decimals) >=
3115         (DECIMAL_LONGLONG_DIGITS - 2))
3116     {
3117       hybrid_type= DECIMAL_RESULT;
3118     }
3119     else
3120     {
3121       unsigned_flag= args[0]->unsigned_flag;
3122       hybrid_type= INT_RESULT;
3123     }
3124     break;
3125   default:
3126     assert(0);
3127   }
3128   DBUG_PRINT("info", ("Type: %s",
3129                       (hybrid_type == REAL_RESULT ? "REAL_RESULT" :
3130                        hybrid_type == DECIMAL_RESULT ? "DECIMAL_RESULT" :
3131                        hybrid_type == INT_RESULT ? "INT_RESULT" :
3132                        "--ILLEGAL!!!--")));
3133 
3134   DBUG_VOID_RETURN;
3135 }
3136 
3137 
int_op()3138 longlong Item_func_ceiling::int_op()
3139 {
3140   longlong result;
3141   switch (args[0]->result_type()) {
3142   case INT_RESULT:
3143     result= args[0]->val_int();
3144     null_value= args[0]->null_value;
3145     break;
3146   case DECIMAL_RESULT:
3147   {
3148     my_decimal dec_buf, *dec;
3149     if ((dec= Item_func_ceiling::decimal_op(&dec_buf)))
3150       my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
3151     else
3152       result= 0;
3153     break;
3154   }
3155   default:
3156     result= (longlong)Item_func_ceiling::real_op();
3157   };
3158   return result;
3159 }
3160 
3161 
real_op()3162 double Item_func_ceiling::real_op()
3163 {
3164   /*
3165     the volatile's for BUG #3051 to calm optimizer down (because of gcc's
3166     bug)
3167   */
3168   volatile double value= args[0]->val_real();
3169   null_value= args[0]->null_value;
3170   return ceil(value);
3171 }
3172 
3173 
decimal_op(my_decimal * decimal_value)3174 my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value)
3175 {
3176   my_decimal val, *value= args[0]->val_decimal(&val);
3177   if (!(null_value= (args[0]->null_value ||
3178                      my_decimal_ceiling(E_DEC_FATAL_ERROR, value,
3179                                         decimal_value) > 1)))
3180     return decimal_value;
3181   return 0;
3182 }
3183 
3184 
int_op()3185 longlong Item_func_floor::int_op()
3186 {
3187   longlong result;
3188   switch (args[0]->result_type()) {
3189   case INT_RESULT:
3190     result= args[0]->val_int();
3191     null_value= args[0]->null_value;
3192     break;
3193   case DECIMAL_RESULT:
3194   {
3195     my_decimal dec_buf, *dec;
3196     if ((dec= Item_func_floor::decimal_op(&dec_buf)))
3197       my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
3198     else
3199       result= 0;
3200     break;
3201   }
3202   default:
3203     result= (longlong)Item_func_floor::real_op();
3204   };
3205   return result;
3206 }
3207 
3208 
real_op()3209 double Item_func_floor::real_op()
3210 {
3211   /*
3212     the volatile's for BUG #3051 to calm optimizer down (because of gcc's
3213     bug)
3214   */
3215   volatile double value= args[0]->val_real();
3216   null_value= args[0]->null_value;
3217   return floor(value);
3218 }
3219 
3220 
decimal_op(my_decimal * decimal_value)3221 my_decimal *Item_func_floor::decimal_op(my_decimal *decimal_value)
3222 {
3223   my_decimal val, *value= args[0]->val_decimal(&val);
3224   if (!(null_value= (args[0]->null_value ||
3225                      my_decimal_floor(E_DEC_FATAL_ERROR, value,
3226                                       decimal_value) > 1)))
3227     return decimal_value;
3228   return 0;
3229 }
3230 
3231 
fix_length_and_dec()3232 void Item_func_round::fix_length_and_dec()
3233 {
3234   int      decimals_to_set;
3235   longlong val1;
3236   bool     val1_unsigned;
3237 
3238   unsigned_flag= args[0]->unsigned_flag;
3239   reject_geometry_args(arg_count, args, this);
3240 
3241   if (!args[1]->const_item())
3242   {
3243     decimals= args[0]->decimals;
3244     max_length= float_length(decimals);
3245     if (args[0]->result_type() == DECIMAL_RESULT)
3246     {
3247       max_length++;
3248       hybrid_type= DECIMAL_RESULT;
3249     }
3250     else
3251       hybrid_type= REAL_RESULT;
3252     return;
3253   }
3254 
3255   val1= args[1]->val_int();
3256   if ((null_value= args[1]->is_null()))
3257     return;
3258 
3259   val1_unsigned= args[1]->unsigned_flag;
3260   if (val1 < 0)
3261     decimals_to_set= val1_unsigned ? INT_MAX : 0;
3262   else
3263     decimals_to_set= (val1 > INT_MAX) ? INT_MAX : (int) val1;
3264 
3265   if (args[0]->decimals == NOT_FIXED_DEC)
3266   {
3267     decimals= min(decimals_to_set, NOT_FIXED_DEC);
3268     max_length= float_length(decimals);
3269     hybrid_type= REAL_RESULT;
3270     return;
3271   }
3272 
3273   switch (args[0]->result_type()) {
3274   case REAL_RESULT:
3275   case STRING_RESULT:
3276     hybrid_type= REAL_RESULT;
3277     decimals= min(decimals_to_set, NOT_FIXED_DEC);
3278     max_length= float_length(decimals);
3279     break;
3280   case INT_RESULT:
3281     if ((!decimals_to_set && truncate) || (args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS))
3282     {
3283       int length_can_increase= MY_TEST(!truncate && (val1 < 0) && !val1_unsigned);
3284       max_length= args[0]->max_length + length_can_increase;
3285       /* Here we can keep INT_RESULT */
3286       hybrid_type= INT_RESULT;
3287       decimals= 0;
3288       break;
3289     }
3290     /* fall through */
3291   case DECIMAL_RESULT:
3292   {
3293     hybrid_type= DECIMAL_RESULT;
3294     decimals_to_set= min(DECIMAL_MAX_SCALE, decimals_to_set);
3295     int decimals_delta= args[0]->decimals - decimals_to_set;
3296     int precision= args[0]->decimal_precision();
3297     int length_increase= ((decimals_delta <= 0) || truncate) ? 0:1;
3298 
3299     precision-= decimals_delta - length_increase;
3300     decimals= min(decimals_to_set, DECIMAL_MAX_SCALE);
3301     max_length= my_decimal_precision_to_length_no_truncation(precision,
3302                                                              decimals,
3303                                                              unsigned_flag);
3304     break;
3305   }
3306   default:
3307     assert(0); /* This result type isn't handled */
3308   }
3309 }
3310 
my_double_round(double value,longlong dec,bool dec_unsigned,bool truncate)3311 double my_double_round(double value, longlong dec, bool dec_unsigned,
3312                        bool truncate)
3313 {
3314   double tmp;
3315   bool dec_negative= (dec < 0) && !dec_unsigned;
3316   ulonglong abs_dec= dec_negative ? -dec : dec;
3317   /*
3318     tmp2 is here to avoid return the value with 80 bit precision
3319     This will fix that the test round(0.1,1) = round(0.1,1) is true
3320     Tagging with volatile is no guarantee, it may still be optimized away...
3321   */
3322   volatile double tmp2;
3323 
3324   tmp=(abs_dec < array_elements(log_10) ?
3325        log_10[abs_dec] : pow(10.0,(double) abs_dec));
3326 
3327   // Pre-compute these, to avoid optimizing away e.g. 'floor(v/tmp) * tmp'.
3328   volatile double value_div_tmp= value / tmp;
3329   volatile double value_mul_tmp= value * tmp;
3330 
3331   if (dec_negative && my_isinf(tmp))
3332     tmp2= 0.0;
3333   else if (!dec_negative &&
3334            (my_isinf(value_mul_tmp) || my_isnan(value_mul_tmp)))
3335     tmp2= value;
3336   else if (truncate)
3337   {
3338     if (value >= 0.0)
3339       tmp2= dec < 0 ? floor(value_div_tmp) * tmp : floor(value_mul_tmp) / tmp;
3340     else
3341       tmp2= dec < 0 ? ceil(value_div_tmp) * tmp : ceil(value_mul_tmp) / tmp;
3342   }
3343   else
3344     tmp2=dec < 0 ? rint(value_div_tmp) * tmp : rint(value_mul_tmp) / tmp;
3345 
3346   return tmp2;
3347 }
3348 
3349 
real_op()3350 double Item_func_round::real_op()
3351 {
3352   const double value= args[0]->val_real();
3353   const longlong decimal_places= args[1]->val_int();
3354 
3355   if (!(null_value= args[0]->null_value || args[1]->null_value))
3356     return my_double_round(value, decimal_places, args[1]->unsigned_flag,
3357                            truncate);
3358 
3359   return 0.0;
3360 }
3361 
3362 /*
3363   Rounds a given value to a power of 10 specified as the 'to' argument,
3364   avoiding overflows when the value is close to the ulonglong range boundary.
3365 */
3366 
my_unsigned_round(ulonglong value,ulonglong to)3367 static inline ulonglong my_unsigned_round(ulonglong value, ulonglong to)
3368 {
3369   ulonglong tmp= value / to * to;
3370   return (value - tmp < (to >> 1)) ? tmp : tmp + to;
3371 }
3372 
3373 
int_op()3374 longlong Item_func_round::int_op()
3375 {
3376   longlong value= args[0]->val_int();
3377   longlong dec= args[1]->val_int();
3378   decimals= 0;
3379   ulonglong abs_dec;
3380   if ((null_value= args[0]->null_value || args[1]->null_value))
3381     return 0;
3382   if ((dec >= 0) || args[1]->unsigned_flag)
3383     return value; // integer have not digits after point
3384 
3385   abs_dec= -dec;
3386   longlong tmp;
3387 
3388   if(abs_dec >= array_elements(log_10_int))
3389     return 0;
3390 
3391   tmp= log_10_int[abs_dec];
3392 
3393   if (truncate)
3394     value= (unsigned_flag) ?
3395       ((ulonglong) value / tmp) * tmp : (value / tmp) * tmp;
3396   else
3397     value= (unsigned_flag || value >= 0) ?
3398       my_unsigned_round((ulonglong) value, tmp) :
3399       -(longlong) my_unsigned_round((ulonglong) -value, tmp);
3400   return value;
3401 }
3402 
3403 
decimal_op(my_decimal * decimal_value)3404 my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value)
3405 {
3406   my_decimal val, *value= args[0]->val_decimal(&val);
3407   longlong dec= args[1]->val_int();
3408   if (dec >= 0 || args[1]->unsigned_flag)
3409     dec= min<ulonglong>(dec, decimals);
3410   else if (dec < INT_MIN)
3411     dec= INT_MIN;
3412 
3413   if (!(null_value= (args[0]->null_value || args[1]->null_value ||
3414                      my_decimal_round(E_DEC_FATAL_ERROR, value, (int) dec,
3415                                       truncate, decimal_value) > 1)))
3416     return decimal_value;
3417   return 0;
3418 }
3419 
3420 
itemize(Parse_context * pc,Item ** res)3421 bool Item_func_rand::itemize(Parse_context *pc, Item **res)
3422 {
3423   if (skip_itemize(res))
3424     return false;
3425   if (super::itemize(pc, res))
3426     return true;
3427   /*
3428     When RAND() is binlogged, the seed is binlogged too.  So the
3429     sequence of random numbers is the same on a replication slave as
3430     on the master.  However, if several RAND() values are inserted
3431     into a table, the order in which the rows are modified may differ
3432     between master and slave, because the order is undefined.  Hence,
3433     the statement is unsafe to log in statement format.
3434   */
3435   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
3436 
3437   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_RAND);
3438   return false;
3439 }
3440 
3441 
seed_random(Item * arg)3442 void Item_func_rand::seed_random(Item *arg)
3443 {
3444   /*
3445     TODO: do not do reinit 'rand' for every execute of PS/SP if
3446     args[0] is a constant.
3447   */
3448 #ifdef WITH_WSREP
3449   uint32 tmp;
3450   if (WSREP(current_thd))
3451   {
3452     if (current_thd->wsrep_exec_mode==REPL_RECV)
3453       tmp= current_thd->wsrep_rand;
3454     else
3455       tmp= current_thd->wsrep_rand= (uint32) arg->val_int();
3456   } else
3457          tmp= (uint32) arg->val_int();
3458 #else
3459   uint32 tmp= (uint32) arg->val_int();
3460 #endif
3461   randominit(rand, (uint32) (tmp*0x10001L+55555555L),
3462              (uint32) (tmp*0x10000001L));
3463 }
3464 
3465 
fix_length_and_dec()3466 void Item_func_rand::fix_length_and_dec()
3467 {
3468   Item_real_func::fix_length_and_dec();
3469   reject_geometry_args(arg_count, args, this);
3470 }
3471 
3472 
fix_fields(THD * thd,Item ** ref)3473 bool Item_func_rand::fix_fields(THD *thd,Item **ref)
3474 {
3475   if (Item_real_func::fix_fields(thd, ref))
3476     return TRUE;
3477 
3478   if (arg_count)
3479   {					// Only use argument once in query
3480     /*
3481       Allocate rand structure once: we must use thd->stmt_arena
3482       to create rand in proper mem_root if it's a prepared statement or
3483       stored procedure.
3484 
3485       No need to send a Rand log event if seed was given eg: RAND(seed),
3486       as it will be replicated in the query as such.
3487     */
3488     if (!rand && !(rand= (struct rand_struct*)
3489                    thd->stmt_arena->alloc(sizeof(*rand))))
3490       return TRUE;
3491   }
3492   else
3493   {
3494     /*
3495       Save the seed only the first time RAND() is used in the query
3496       Once events are forwarded rather than recreated,
3497       the following can be skipped if inside the slave thread
3498     */
3499     if (!thd->rand_used)
3500     {
3501       thd->rand_used= 1;
3502       thd->rand_saved_seed1= thd->rand.seed1;
3503       thd->rand_saved_seed2= thd->rand.seed2;
3504     }
3505     rand= &thd->rand;
3506   }
3507   return FALSE;
3508 }
3509 
3510 
val_real()3511 double Item_func_rand::val_real()
3512 {
3513   assert(fixed == 1);
3514   if (arg_count)
3515   {
3516     if (!args[0]->const_item())
3517       seed_random(args[0]);
3518     else if (first_eval)
3519     {
3520       /*
3521         Constantness of args[0] may be set during JOIN::optimize(), if arg[0]
3522         is a field item of "constant" table. Thus, we have to evaluate
3523         seed_random() for constant arg there but not at the fix_fields method.
3524       */
3525       first_eval= FALSE;
3526       seed_random(args[0]);
3527     }
3528   }
3529   return my_rnd(rand);
3530 }
3531 
3532 
fix_length_and_dec()3533 void Item_func_sign::fix_length_and_dec()
3534 {
3535   Item_int_func::fix_length_and_dec();
3536   reject_geometry_args(arg_count, args, this);
3537 }
3538 
3539 
val_int()3540 longlong Item_func_sign::val_int()
3541 {
3542   assert(fixed == 1);
3543   double value= args[0]->val_real();
3544   null_value=args[0]->null_value;
3545   return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
3546 }
3547 
3548 
fix_length_and_dec()3549 void Item_func_units::fix_length_and_dec()
3550 {
3551   decimals= NOT_FIXED_DEC;
3552   max_length= float_length(decimals);
3553   reject_geometry_args(arg_count, args, this);
3554 }
3555 
3556 
val_real()3557 double Item_func_units::val_real()
3558 {
3559   assert(fixed == 1);
3560   double value= args[0]->val_real();
3561   if ((null_value=args[0]->null_value))
3562     return 0;
3563   return check_float_overflow(value * mul + add);
3564 }
3565 
3566 
fix_length_and_dec()3567 void Item_func_min_max::fix_length_and_dec()
3568 {
3569   uint string_arg_count= 0;
3570   int max_int_part=0;
3571   bool datetime_found= FALSE;
3572   decimals=0;
3573   max_length=0;
3574   maybe_null=0;
3575   cmp_type= args[0]->temporal_with_date_as_number_result_type();
3576 
3577   for (uint i=0 ; i < arg_count ; i++)
3578   {
3579     set_if_bigger(max_length, args[i]->max_length);
3580     set_if_bigger(decimals, args[i]->decimals);
3581     set_if_bigger(max_int_part, args[i]->decimal_int_part());
3582     if (args[i]->maybe_null)
3583       maybe_null=1;
3584     cmp_type= item_cmp_type(cmp_type,
3585                             args[i]->temporal_with_date_as_number_result_type());
3586     if (args[i]->result_type() == STRING_RESULT)
3587      string_arg_count++;
3588     if (args[i]->result_type() != ROW_RESULT &&
3589         args[i]->is_temporal_with_date())
3590     {
3591       datetime_found= TRUE;
3592       if (!datetime_item || args[i]->field_type() == MYSQL_TYPE_DATETIME)
3593         datetime_item= args[i];
3594     }
3595   }
3596 
3597   if (string_arg_count == arg_count)
3598   {
3599     // We compare as strings only if all arguments were strings.
3600     agg_arg_charsets_for_string_result_with_comparison(collation,
3601                                                        args, arg_count);
3602     if (datetime_found)
3603     {
3604       compare_as_dates= TRUE;
3605       /*
3606         We should not do this:
3607           cached_field_type= datetime_item->field_type();
3608           count_datetime_length(args, arg_count);
3609         because compare_as_dates can be TRUE but
3610         result type can still be VARCHAR.
3611       */
3612     }
3613   }
3614   else if ((cmp_type == DECIMAL_RESULT) || (cmp_type == INT_RESULT))
3615   {
3616     collation.set_numeric();
3617     fix_char_length(my_decimal_precision_to_length_no_truncation(max_int_part +
3618                                                                  decimals,
3619                                                                  decimals,
3620                                                                  unsigned_flag));
3621   }
3622   else if (cmp_type == REAL_RESULT)
3623     fix_char_length(float_length(decimals));
3624   cached_field_type= agg_field_type(args, arg_count);
3625   /*
3626     LEAST and GREATEST convert JSON values to strings before they are
3627     compared, so their JSON nature is lost. Raise a warning to
3628     indicate to the users that the values are not compared using the
3629     JSON comparator, as they might expect. Also update the field type
3630     of the result to reflect that the result is a string.
3631   */
3632   unsupported_json_comparison(arg_count, args,
3633                               "comparison of JSON in the "
3634                               "LEAST and GREATEST operators");
3635   if (cached_field_type == MYSQL_TYPE_JSON)
3636     cached_field_type= MYSQL_TYPE_VARCHAR;
3637   reject_geometry_args(arg_count, args, this);
3638 }
3639 
3640 
3641 /*
3642   Compare item arguments in the DATETIME context.
3643 
3644   SYNOPSIS
3645     cmp_datetimes()
3646     value [out]   found least/greatest DATE/DATETIME value
3647 
3648   DESCRIPTION
3649     Compare item arguments as DATETIME values and return the index of the
3650     least/greatest argument in the arguments array.
3651     The correct integer DATE/DATETIME value of the found argument is
3652     stored to the value pointer, if latter is provided.
3653 
3654   RETURN
3655    0	If one of arguments is NULL or there was a execution error
3656    #	index of the least/greatest argument
3657 */
3658 
cmp_datetimes(longlong * value)3659 uint Item_func_min_max::cmp_datetimes(longlong *value)
3660 {
3661   longlong min_max= 0;
3662   uint min_max_idx= 0;
3663 
3664   for (uint i=0; i < arg_count ; i++)
3665   {
3666     Item **arg= args + i;
3667     bool is_null;
3668     THD *thd= current_thd;
3669     longlong res= get_datetime_value(thd, &arg, 0, datetime_item, &is_null);
3670 
3671     /* Check if we need to stop (because of error or KILL)  and stop the loop */
3672     if (thd->is_error())
3673     {
3674       null_value= 1;
3675       return 0;
3676     }
3677 
3678     if ((null_value= args[i]->null_value))
3679       return 0;
3680     if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0)
3681     {
3682       min_max= res;
3683       min_max_idx= i;
3684     }
3685   }
3686   if (value)
3687     *value= min_max;
3688   return min_max_idx;
3689 }
3690 
3691 
cmp_times(longlong * value)3692 uint Item_func_min_max::cmp_times(longlong *value)
3693 {
3694   longlong min_max= 0;
3695   uint min_max_idx= 0;
3696   for (uint i=0; i < arg_count ; i++)
3697   {
3698     longlong res= args[i]->val_time_temporal();
3699     if ((null_value= args[i]->null_value))
3700       return 0;
3701     if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0)
3702     {
3703       min_max= res;
3704       min_max_idx= i;
3705     }
3706   }
3707   if (value)
3708     *value= min_max;
3709   return min_max_idx;
3710 }
3711 
3712 
val_str(String * str)3713 String *Item_func_min_max::val_str(String *str)
3714 {
3715   assert(fixed == 1);
3716   if (compare_as_dates)
3717   {
3718     if (is_temporal())
3719     {
3720       /*
3721         In case of temporal data types, we always return
3722         string value according the format of the data type.
3723         For example, in case of LEAST(time_column, datetime_column)
3724         the result date type is DATETIME,
3725         so we return a 'YYYY-MM-DD hh:mm:ss' string even if time_column wins
3726         (conversion from TIME to DATETIME happens in this case).
3727       */
3728       longlong result;
3729       cmp_datetimes(&result);
3730       if (null_value)
3731         return 0;
3732       MYSQL_TIME ltime;
3733       TIME_from_longlong_packed(&ltime, field_type(), result);
3734       return (null_value= my_TIME_to_str(&ltime, str, decimals)) ?
3735              (String *) 0 : str;
3736     }
3737     else
3738     {
3739       /*
3740         In case of VARCHAR result type we just return val_str()
3741         value of the winning item AS IS, without conversion.
3742       */
3743       String *str_res;
3744       uint min_max_idx= cmp_datetimes(NULL);
3745       if (null_value)
3746         return 0;
3747       str_res= args[min_max_idx]->val_str(str);
3748       if (args[min_max_idx]->null_value)
3749       {
3750         // check if the call to val_str() above returns a NULL value
3751         null_value= 1;
3752         return NULL;
3753       }
3754       str_res->set_charset(collation.collation);
3755       return str_res;
3756     }
3757   }
3758 
3759   switch (cmp_type) {
3760   case INT_RESULT:
3761   {
3762     longlong nr=val_int();
3763     if (null_value)
3764       return 0;
3765     str->set_int(nr, unsigned_flag, collation.collation);
3766     return str;
3767   }
3768   case DECIMAL_RESULT:
3769   {
3770     my_decimal dec_buf, *dec_val= val_decimal(&dec_buf);
3771     if (null_value)
3772       return 0;
3773     my_decimal2string(E_DEC_FATAL_ERROR, dec_val, 0, 0, 0, str);
3774     return str;
3775   }
3776   case REAL_RESULT:
3777   {
3778     double nr= val_real();
3779     if (null_value)
3780       return 0; /* purecov: inspected */
3781     str->set_real(nr, decimals, collation.collation);
3782     return str;
3783   }
3784   case STRING_RESULT:
3785   {
3786     String *res= NULL;
3787     for (uint i=0; i < arg_count ; i++)
3788     {
3789       if (i == 0)
3790 	res=args[i]->val_str(str);
3791       else
3792       {
3793 	String *res2;
3794 	res2= args[i]->val_str(res == str ? &tmp_value : str);
3795 	if (res2)
3796 	{
3797 	  int cmp= sortcmp(res,res2,collation.collation);
3798 	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
3799 	    res=res2;
3800 	}
3801       }
3802       if ((null_value= args[i]->null_value))
3803         return 0;
3804     }
3805     res->set_charset(collation.collation);
3806     return res;
3807   }
3808   case ROW_RESULT:
3809   default:
3810     // This case should never be chosen
3811     assert(0);
3812     return 0;
3813   }
3814   return 0;					// Keep compiler happy
3815 }
3816 
3817 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)3818 bool Item_func_min_max::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
3819 {
3820   assert(fixed == 1);
3821   if (compare_as_dates)
3822   {
3823     longlong result;
3824     cmp_datetimes(&result);
3825     if (null_value)
3826       return true;
3827     TIME_from_longlong_packed(ltime, datetime_item->field_type(), result);
3828     int warnings;
3829     return check_date(ltime, non_zero_date(ltime), fuzzydate, &warnings);
3830   }
3831 
3832   switch (field_type())
3833   {
3834   case MYSQL_TYPE_TIME:
3835     return get_date_from_time(ltime);
3836   case MYSQL_TYPE_DATETIME:
3837   case MYSQL_TYPE_TIMESTAMP:
3838   case MYSQL_TYPE_DATE:
3839     assert(0); // Should have been processed in "compare_as_dates" block.
3840   default:
3841     return get_date_from_non_temporal(ltime, fuzzydate);
3842   }
3843 }
3844 
3845 
get_time(MYSQL_TIME * ltime)3846 bool Item_func_min_max::get_time(MYSQL_TIME *ltime)
3847 {
3848   assert(fixed == 1);
3849   if (compare_as_dates)
3850   {
3851     longlong result;
3852     cmp_datetimes(&result);
3853     if (null_value)
3854       return true;
3855     TIME_from_longlong_packed(ltime, datetime_item->field_type(), result);
3856     datetime_to_time(ltime);
3857     return false;
3858   }
3859 
3860   switch (field_type())
3861   {
3862   case MYSQL_TYPE_TIME:
3863     {
3864       longlong result;
3865       cmp_times(&result);
3866       if (null_value)
3867         return true;
3868       TIME_from_longlong_time_packed(ltime, result);
3869       return false;
3870     }
3871     break;
3872   case MYSQL_TYPE_DATE:
3873   case MYSQL_TYPE_TIMESTAMP:
3874   case MYSQL_TYPE_DATETIME:
3875     assert(0); // Should have been processed in "compare_as_dates" block.
3876   default:
3877     return get_time_from_non_temporal(ltime);
3878     break;
3879   }
3880 }
3881 
3882 
val_real()3883 double Item_func_min_max::val_real()
3884 {
3885   assert(fixed == 1);
3886   double value=0.0;
3887   if (compare_as_dates)
3888   {
3889     longlong result= 0;
3890     (void)cmp_datetimes(&result);
3891     return double_from_datetime_packed(datetime_item->field_type(), result);
3892   }
3893   for (uint i=0; i < arg_count ; i++)
3894   {
3895     if (i == 0)
3896       value= args[i]->val_real();
3897     else
3898     {
3899       double tmp= args[i]->val_real();
3900       if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
3901 	value=tmp;
3902     }
3903     if ((null_value= args[i]->null_value))
3904       break;
3905   }
3906   return value;
3907 }
3908 
3909 
val_int()3910 longlong Item_func_min_max::val_int()
3911 {
3912   assert(fixed == 1);
3913   longlong value=0;
3914   if (compare_as_dates)
3915   {
3916     longlong result= 0;
3917     (void)cmp_datetimes(&result);
3918     return longlong_from_datetime_packed(datetime_item->field_type(), result);
3919   }
3920   /*
3921     TS-TODO: val_str decides which type to use using cmp_type.
3922     val_int, val_decimal, val_real do not check cmp_type and
3923     decide data type according to the method type.
3924     This is probably not good:
3925 
3926 mysql> select least('11', '2'), least('11', '2')+0, concat(least(11,2));
3927 +------------------+--------------------+---------------------+
3928 | least('11', '2') | least('11', '2')+0 | concat(least(11,2)) |
3929 +------------------+--------------------+---------------------+
3930 | 11               |                  2 | 2                   |
3931 +------------------+--------------------+---------------------+
3932 1 row in set (0.00 sec)
3933 
3934     Should not the second column return 11?
3935     I.e. compare as strings and return '11', then convert to number.
3936   */
3937   for (uint i=0; i < arg_count ; i++)
3938   {
3939     if (i == 0)
3940       value=args[i]->val_int();
3941     else
3942     {
3943       longlong tmp=args[i]->val_int();
3944       if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
3945 	value=tmp;
3946     }
3947     if ((null_value= args[i]->null_value))
3948       break;
3949   }
3950   return value;
3951 }
3952 
3953 
val_decimal(my_decimal * dec)3954 my_decimal *Item_func_min_max::val_decimal(my_decimal *dec)
3955 {
3956   assert(fixed == 1);
3957   my_decimal tmp_buf, *tmp, *res= NULL;
3958 
3959   if (compare_as_dates)
3960   {
3961     longlong value= 0;
3962     (void)cmp_datetimes(&value);
3963     return my_decimal_from_datetime_packed(dec, datetime_item->field_type(),
3964                                            value);
3965   }
3966   for (uint i=0; i < arg_count ; i++)
3967   {
3968     if (i == 0)
3969       res= args[i]->val_decimal(dec);
3970     else
3971     {
3972       tmp= args[i]->val_decimal(&tmp_buf);      // Zero if NULL
3973       if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0)
3974       {
3975         if (tmp == &tmp_buf)
3976         {
3977           /* Move value out of tmp_buf as this will be reused on next loop */
3978           my_decimal2decimal(tmp, dec);
3979           res= dec;
3980         }
3981         else
3982           res= tmp;
3983       }
3984     }
3985     if ((null_value= args[i]->null_value))
3986     {
3987       res= 0;
3988       break;
3989     }
3990   }
3991 
3992   if (res)
3993   {
3994     /*
3995       Need this to make val_str() always return fixed
3996       number of fractional digits, according to "decimals".
3997     */
3998     my_decimal_round(E_DEC_FATAL_ERROR, res, decimals, false, res);
3999   }
4000   return res;
4001 }
4002 
val_real()4003 double Item_func_rollup_const::val_real()
4004 {
4005   assert(fixed == 1);
4006   double res= args[0]->val_real();
4007   if ((null_value= args[0]->null_value))
4008     return 0.0;
4009   return res;
4010 }
4011 
val_int()4012 longlong Item_func_rollup_const::val_int()
4013 {
4014   assert(fixed == 1);
4015   longlong res= args[0]->val_int();
4016   if ((null_value= args[0]->null_value))
4017     return 0;
4018   return res;
4019 }
4020 
val_str(String * str)4021 String *Item_func_rollup_const::val_str(String *str)
4022 {
4023   assert(fixed == 1);
4024   String *res= args[0]->val_str(str);
4025   if ((null_value= args[0]->null_value))
4026     return 0;
4027   return res;
4028 }
4029 
val_decimal(my_decimal * dec)4030 my_decimal *Item_func_rollup_const::val_decimal(my_decimal *dec)
4031 {
4032   assert(fixed == 1);
4033   my_decimal *res= args[0]->val_decimal(dec);
4034   if ((null_value= args[0]->null_value))
4035     return 0;
4036   return res;
4037 }
4038 
4039 
val_json(Json_wrapper * result)4040 bool Item_func_rollup_const::val_json(Json_wrapper *result)
4041 {
4042   assert(fixed == 1);
4043   bool res= args[0]->val_json(result);
4044   null_value= args[0]->null_value;
4045   return res;
4046 }
4047 
4048 
val_int()4049 longlong Item_func_length::val_int()
4050 {
4051   assert(fixed == 1);
4052   String *res=args[0]->val_str(&value);
4053   if (!res)
4054   {
4055     null_value=1;
4056     return 0; /* purecov: inspected */
4057   }
4058   null_value=0;
4059   return (longlong) res->length();
4060 }
4061 
4062 
val_int()4063 longlong Item_func_char_length::val_int()
4064 {
4065   assert(fixed == 1);
4066   String *res=args[0]->val_str(&value);
4067   if (!res)
4068   {
4069     null_value=1;
4070     return 0; /* purecov: inspected */
4071   }
4072   null_value=0;
4073   return (longlong) res->numchars();
4074 }
4075 
4076 
val_int()4077 longlong Item_func_coercibility::val_int()
4078 {
4079   assert(fixed == 1);
4080   null_value= 0;
4081   return (longlong) args[0]->collation.derivation;
4082 }
4083 
4084 
fix_length_and_dec()4085 void Item_func_locate::fix_length_and_dec()
4086 {
4087   max_length= MY_INT32_NUM_DECIMAL_DIGITS;
4088   agg_arg_charsets_for_comparison(cmp_collation, args, 2);
4089 }
4090 
4091 
val_int()4092 longlong Item_func_locate::val_int()
4093 {
4094   assert(fixed == 1);
4095   String *a=args[0]->val_str(&value1);
4096   String *b=args[1]->val_str(&value2);
4097   if (!a || !b)
4098   {
4099     null_value=1;
4100     return 0; /* purecov: inspected */
4101   }
4102   null_value=0;
4103   /* must be longlong to avoid truncation */
4104   longlong start=  0;
4105   longlong start0= 0;
4106   my_match_t match;
4107 
4108   if (arg_count == 3)
4109   {
4110     start0= start= args[2]->val_int() - 1;
4111 
4112     if ((start < 0) || (start > static_cast<longlong>(a->length())))
4113       return 0;
4114 
4115     /* start is now sufficiently valid to pass to charpos function */
4116     start= a->charpos((int) start);
4117 
4118     if (start + b->length() > a->length())
4119       return 0;
4120   }
4121 
4122   if (!b->length())				// Found empty string at start
4123     return start + 1;
4124 
4125   if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
4126                                             a->ptr()+start,
4127                                             (uint) (a->length()-start),
4128                                             b->ptr(), b->length(),
4129                                             &match, 1))
4130     return 0;
4131   return (longlong) match.mb_len + start0 + 1;
4132 }
4133 
4134 
print(String * str,enum_query_type query_type)4135 void Item_func_locate::print(String *str, enum_query_type query_type)
4136 {
4137   str->append(STRING_WITH_LEN("locate("));
4138   args[1]->print(str, query_type);
4139   str->append(',');
4140   args[0]->print(str, query_type);
4141   if (arg_count == 3)
4142   {
4143     str->append(',');
4144     args[2]->print(str, query_type);
4145   }
4146   str->append(')');
4147 }
4148 
4149 
val_int()4150 longlong Item_func_validate_password_strength::val_int()
4151 {
4152   char buff[STRING_BUFFER_USUAL_SIZE];
4153   String value(buff, sizeof(buff), system_charset_info);
4154   String *field= args[0]->val_str(&value);
4155   if ((null_value= args[0]->null_value) || field->length() == 0)
4156     return 0;
4157   return (my_calculate_password_strength(field->ptr(), field->length()));
4158 }
4159 
4160 
val_int()4161 longlong Item_func_field::val_int()
4162 {
4163   assert(fixed == 1);
4164 
4165   if (cmp_type == STRING_RESULT)
4166   {
4167     String *field;
4168     if (!(field= args[0]->val_str(&value)))
4169       return 0;
4170     for (uint i=1 ; i < arg_count ; i++)
4171     {
4172       String *tmp_value=args[i]->val_str(&tmp);
4173       if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
4174         return (longlong) (i);
4175     }
4176   }
4177   else if (cmp_type == INT_RESULT)
4178   {
4179     longlong val= args[0]->val_int();
4180     if (args[0]->null_value)
4181       return 0;
4182     for (uint i=1; i < arg_count ; i++)
4183     {
4184       if (val == args[i]->val_int() && !args[i]->null_value)
4185         return (longlong) (i);
4186     }
4187   }
4188   else if (cmp_type == DECIMAL_RESULT)
4189   {
4190     my_decimal dec_arg_buf, *dec_arg,
4191                dec_buf, *dec= args[0]->val_decimal(&dec_buf);
4192     if (args[0]->null_value)
4193       return 0;
4194     for (uint i=1; i < arg_count; i++)
4195     {
4196       dec_arg= args[i]->val_decimal(&dec_arg_buf);
4197       if (!args[i]->null_value && !my_decimal_cmp(dec_arg, dec))
4198         return (longlong) (i);
4199     }
4200   }
4201   else
4202   {
4203     double val= args[0]->val_real();
4204     if (args[0]->null_value)
4205       return 0;
4206     for (uint i=1; i < arg_count ; i++)
4207     {
4208       if (val == args[i]->val_real() && !args[i]->null_value)
4209         return (longlong) (i);
4210     }
4211   }
4212   return 0;
4213 }
4214 
4215 
fix_length_and_dec()4216 void Item_func_field::fix_length_and_dec()
4217 {
4218   maybe_null=0; max_length=3;
4219   cmp_type= args[0]->result_type();
4220   for (uint i=1; i < arg_count ; i++)
4221     cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
4222   if (cmp_type == STRING_RESULT)
4223     agg_arg_charsets_for_comparison(cmp_collation, args, arg_count);
4224 }
4225 
4226 
val_int()4227 longlong Item_func_ascii::val_int()
4228 {
4229   assert(fixed == 1);
4230   String *res=args[0]->val_str(&value);
4231   if (!res)
4232   {
4233     null_value=1;
4234     return 0;
4235   }
4236   null_value=0;
4237   return (longlong) (res->length() ? (uchar) (*res)[0] : (uchar) 0);
4238 }
4239 
val_int()4240 longlong Item_func_ord::val_int()
4241 {
4242   assert(fixed == 1);
4243   String *res=args[0]->val_str(&value);
4244   if (!res)
4245   {
4246     null_value=1;
4247     return 0;
4248   }
4249   null_value=0;
4250   if (!res->length()) return 0;
4251   if (use_mb(res->charset()))
4252   {
4253     const char *str=res->ptr();
4254     uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
4255     if (!l)
4256       return (longlong)((uchar) *str);
4257     while (l--)
4258       n=(n<<8)|(uint32)((uchar) *str++);
4259     return (longlong) n;
4260   }
4261   return (longlong) ((uchar) (*res)[0]);
4262 }
4263 
4264 	/* Search after a string in a string of strings separated by ',' */
4265 	/* Returns number of found type >= 1 or 0 if not found */
4266 	/* This optimizes searching in enums to bit testing! */
4267 
fix_length_and_dec()4268 void Item_func_find_in_set::fix_length_and_dec()
4269 {
4270   decimals=0;
4271   max_length=3;					// 1-999
4272   if (args[0]->const_item() && args[1]->type() == FIELD_ITEM)
4273   {
4274     Field *field= ((Item_field*) args[1])->field;
4275     if (field->real_type() == MYSQL_TYPE_SET)
4276     {
4277       String *find=args[0]->val_str(&value);
4278       if (find)
4279       {
4280         // find is not NULL pointer so args[0] is not a null-value
4281         assert(!args[0]->null_value);
4282 	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
4283 			      find->length(), 0);
4284 	enum_bit=0;
4285 	if (enum_value)
4286 	  enum_bit= 1LL << (enum_value-1);
4287       }
4288     }
4289   }
4290   agg_arg_charsets_for_comparison(cmp_collation, args, 2);
4291 }
4292 
4293 static const char separator=',';
4294 
val_int()4295 longlong Item_func_find_in_set::val_int()
4296 {
4297   assert(fixed == 1);
4298   if (enum_value)
4299   {
4300     // enum_value is set iff args[0]->const_item() in fix_length_and_dec().
4301     assert(args[0]->const_item());
4302 
4303     ulonglong tmp= (ulonglong) args[1]->val_int();
4304     null_value= args[1]->null_value;
4305     /*
4306       No need to check args[0]->null_value since enum_value is set iff
4307       args[0] is a non-null const item. Note: no assert on
4308       args[0]->null_value here because args[0] may have been replaced
4309       by an Item_cache on which val_int() has not been called. See
4310       BUG#11766317
4311     */
4312     if (!null_value)
4313     {
4314       if (tmp & enum_bit)
4315         return enum_value;
4316     }
4317     return 0L;
4318   }
4319 
4320   String *find=args[0]->val_str(&value);
4321   String *buffer=args[1]->val_str(&value2);
4322   if (!find || !buffer)
4323   {
4324     null_value=1;
4325     return 0; /* purecov: inspected */
4326   }
4327   null_value=0;
4328 
4329   if (buffer->length() >= find->length())
4330   {
4331     my_wc_t wc= 0;
4332     const CHARSET_INFO *cs= cmp_collation.collation;
4333     const char *str_begin= buffer->ptr();
4334     const char *str_end= buffer->ptr();
4335     const char *real_end= str_end+buffer->length();
4336     const uchar *find_str= (const uchar *) find->ptr();
4337     size_t find_str_len= find->length();
4338     int position= 0;
4339     while (1)
4340     {
4341       int symbol_len;
4342       if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end,
4343                                        (uchar*) real_end)) > 0)
4344       {
4345         const char *substr_end= str_end + symbol_len;
4346         bool is_last_item= (substr_end == real_end);
4347         bool is_separator= (wc == (my_wc_t) separator);
4348         if (is_separator || is_last_item)
4349         {
4350           position++;
4351           if (is_last_item && !is_separator)
4352             str_end= substr_end;
4353           if (!my_strnncoll(cs, (const uchar *) str_begin,
4354                             (uint) (str_end - str_begin),
4355                             find_str, find_str_len))
4356             return (longlong) position;
4357           else
4358             str_begin= substr_end;
4359         }
4360         str_end= substr_end;
4361       }
4362       else if (str_end - str_begin == 0 &&
4363                find_str_len == 0 &&
4364                wc == (my_wc_t) separator)
4365         return (longlong) ++position;
4366       else
4367         return 0LL;
4368     }
4369   }
4370   return 0;
4371 }
4372 
val_int()4373 longlong Item_func_bit_count::val_int()
4374 {
4375   assert(fixed == 1);
4376   ulonglong value= (ulonglong) args[0]->val_int();
4377   if ((null_value= args[0]->null_value))
4378     return 0; /* purecov: inspected */
4379   return (longlong) my_count_bits(value);
4380 }
4381 
4382 
4383 /****************************************************************************
4384 ** Functions to handle dynamic loadable functions
4385 ** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
4386 ** Rewritten by monty.
4387 ****************************************************************************/
4388 
4389 #ifdef HAVE_DLOPEN
4390 
cleanup()4391 void udf_handler::cleanup()
4392 {
4393   if (!not_original)
4394   {
4395     if (initialized)
4396     {
4397       if (u_d->func_deinit != NULL)
4398       {
4399         Udf_func_deinit deinit= u_d->func_deinit;
4400         (*deinit)(&initid);
4401       }
4402       free_udf(u_d);
4403       initialized= FALSE;
4404     }
4405     if (buffers)				// Because of bug in ecc
4406       delete [] buffers;
4407     buffers= 0;
4408   }
4409 }
4410 
4411 
4412 bool
fix_fields(THD * thd,Item_result_field * func,uint arg_count,Item ** arguments)4413 udf_handler::fix_fields(THD *thd, Item_result_field *func,
4414 			uint arg_count, Item **arguments)
4415 {
4416   uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
4417   DBUG_ENTER("Item_udf_func::fix_fields");
4418 
4419   if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
4420     DBUG_RETURN(TRUE);				// Fatal error flag is set!
4421 
4422   udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
4423 
4424   if (!tmp_udf)
4425   {
4426     my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str);
4427     DBUG_RETURN(TRUE);
4428   }
4429   u_d=tmp_udf;
4430   args=arguments;
4431 
4432   /* Fix all arguments */
4433   func->maybe_null=0;
4434   used_tables_cache=0;
4435   const_item_cache=1;
4436 
4437   if ((f_args.arg_count=arg_count))
4438   {
4439     if (!(f_args.arg_type= (Item_result*)
4440 	  sql_alloc(f_args.arg_count*sizeof(Item_result))))
4441 
4442     {
4443       free_udf(u_d);
4444       DBUG_RETURN(TRUE);
4445     }
4446     uint i;
4447     Item **arg,**arg_end;
4448     for (i=0, arg=arguments, arg_end=arguments+arg_count;
4449 	 arg != arg_end ;
4450 	 arg++,i++)
4451     {
4452       if (!(*arg)->fixed &&
4453           (*arg)->fix_fields(thd, arg))
4454 	DBUG_RETURN(1);
4455       // we can't assign 'item' before, because fix_fields() can change arg
4456       Item *item= *arg;
4457       if (item->check_cols(1))
4458 	DBUG_RETURN(TRUE);
4459       /*
4460 	TODO: We should think about this. It is not always
4461 	right way just to set an UDF result to return my_charset_bin
4462 	if one argument has binary sorting order.
4463 	The result collation should be calculated according to arguments
4464 	derivations in some cases and should not in other cases.
4465 	Moreover, some arguments can represent a numeric input
4466 	which doesn't effect the result character set and collation.
4467 	There is no a general rule for UDF. Everything depends on
4468         the particular user defined function.
4469       */
4470       if (item->collation.collation->state & MY_CS_BINSORT)
4471 	func->collation.set(&my_charset_bin);
4472       if (item->maybe_null)
4473 	func->maybe_null=1;
4474       func->with_sum_func= func->with_sum_func || item->with_sum_func;
4475       used_tables_cache|=item->used_tables();
4476       const_item_cache&=item->const_item();
4477       f_args.arg_type[i]=item->result_type();
4478     }
4479     //TODO: why all following memory is not allocated with 1 call of sql_alloc?
4480     if (!(buffers=new String[arg_count]) ||
4481 	!(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
4482 	!(f_args.lengths= (ulong*) sql_alloc(arg_count * sizeof(long))) ||
4483 	!(f_args.maybe_null= (char*) sql_alloc(arg_count * sizeof(char))) ||
4484 	!(num_buffer= (char*) sql_alloc(arg_count *
4485 					ALIGN_SIZE(sizeof(double)))) ||
4486 	!(f_args.attributes= (char**) sql_alloc(arg_count * sizeof(char *))) ||
4487 	!(f_args.attribute_lengths= (ulong*) sql_alloc(arg_count *
4488 						       sizeof(long))))
4489     {
4490       free_udf(u_d);
4491       DBUG_RETURN(TRUE);
4492     }
4493   }
4494   func->fix_length_and_dec();
4495   initid.max_length=func->max_length;
4496   initid.maybe_null=func->maybe_null;
4497   initid.const_item=const_item_cache;
4498   initid.decimals=func->decimals;
4499   initid.ptr=0;
4500 
4501   if (u_d->func_init)
4502   {
4503     char init_msg_buff[MYSQL_ERRMSG_SIZE];
4504     char *to=num_buffer;
4505     for (uint i=0; i < arg_count; i++)
4506     {
4507       /*
4508        For a constant argument i, args->args[i] points to the argument value.
4509        For non-constant, args->args[i] is NULL.
4510       */
4511       f_args.args[i]= NULL;         /* Non-const unless updated below. */
4512 
4513       f_args.lengths[i]= arguments[i]->max_length;
4514       f_args.maybe_null[i]= arguments[i]->maybe_null;
4515       f_args.attributes[i]= (char*) arguments[i]->item_name.ptr();
4516       f_args.attribute_lengths[i]= arguments[i]->item_name.length();
4517 
4518       if (arguments[i]->const_item())
4519       {
4520         switch (arguments[i]->result_type())
4521         {
4522         case STRING_RESULT:
4523         case DECIMAL_RESULT:
4524         {
4525           String *res= arguments[i]->val_str(&buffers[i]);
4526           if (arguments[i]->null_value)
4527             continue;
4528           f_args.args[i]= res->c_ptr_safe();
4529           f_args.lengths[i]= res->length();
4530           break;
4531         }
4532         case INT_RESULT:
4533           *((longlong*) to)= arguments[i]->val_int();
4534           if (arguments[i]->null_value)
4535             continue;
4536           f_args.args[i]= to;
4537           to+= ALIGN_SIZE(sizeof(longlong));
4538           break;
4539         case REAL_RESULT:
4540           *((double*) to)= arguments[i]->val_real();
4541           if (arguments[i]->null_value)
4542             continue;
4543           f_args.args[i]= to;
4544           to+= ALIGN_SIZE(sizeof(double));
4545           break;
4546         case ROW_RESULT:
4547         default:
4548           // This case should never be chosen
4549           assert(0);
4550           break;
4551         }
4552       }
4553     }
4554     Udf_func_init init= u_d->func_init;
4555     if ((error=(uchar) init(&initid, &f_args, init_msg_buff)))
4556     {
4557       my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
4558                u_d->name.str, init_msg_buff);
4559       free_udf(u_d);
4560       DBUG_RETURN(TRUE);
4561     }
4562     func->max_length= min<uint32>(initid.max_length, MAX_BLOB_WIDTH);
4563     func->maybe_null=initid.maybe_null;
4564     const_item_cache=initid.const_item;
4565     /*
4566       Keep used_tables_cache in sync with const_item_cache.
4567       See the comment in Item_udf_func::update_used tables.
4568     */
4569     if (!const_item_cache && !used_tables_cache)
4570       used_tables_cache= RAND_TABLE_BIT;
4571     func->decimals= min<uint>(initid.decimals, NOT_FIXED_DEC);
4572   }
4573   initialized=1;
4574   if (error)
4575   {
4576     my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
4577              u_d->name.str, ER(ER_UNKNOWN_ERROR));
4578     DBUG_RETURN(TRUE);
4579   }
4580   DBUG_RETURN(FALSE);
4581 }
4582 
4583 
get_arguments()4584 bool udf_handler::get_arguments()
4585 {
4586   if (error)
4587     return 1;					// Got an error earlier
4588   char *to= num_buffer;
4589   uint str_count=0;
4590   for (uint i=0; i < f_args.arg_count; i++)
4591   {
4592     f_args.args[i]=0;
4593     switch (f_args.arg_type[i]) {
4594     case STRING_RESULT:
4595     case DECIMAL_RESULT:
4596       {
4597 	String *res=args[i]->val_str(&buffers[str_count++]);
4598 	if (!(args[i]->null_value))
4599 	{
4600 	  f_args.args[i]=    res->c_ptr_safe();
4601 	  f_args.lengths[i]= res->length();
4602 	}
4603 	else
4604 	{
4605 	  f_args.lengths[i]= 0;
4606 	}
4607 	break;
4608       }
4609     case INT_RESULT:
4610       *((longlong*) to) = args[i]->val_int();
4611       if (!args[i]->null_value)
4612       {
4613 	f_args.args[i]=to;
4614 	to+= ALIGN_SIZE(sizeof(longlong));
4615       }
4616       break;
4617     case REAL_RESULT:
4618       *((double*) to)= args[i]->val_real();
4619       if (!args[i]->null_value)
4620       {
4621 	f_args.args[i]=to;
4622 	to+= ALIGN_SIZE(sizeof(double));
4623       }
4624       break;
4625     case ROW_RESULT:
4626     default:
4627       // This case should never be chosen
4628       assert(0);
4629       break;
4630     }
4631   }
4632   return 0;
4633 }
4634 
4635 /**
4636   @return
4637     (String*)NULL in case of NULL values
4638 */
val_str(String * str,String * save_str)4639 String *udf_handler::val_str(String *str,String *save_str)
4640 {
4641   uchar is_null_tmp=0;
4642   ulong res_length;
4643   DBUG_ENTER("udf_handler::val_str");
4644 
4645   if (get_arguments())
4646     DBUG_RETURN(0);
4647   char * (*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
4648     (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
4649     u_d->func;
4650 
4651   if ((res_length=str->alloced_length()) < MAX_FIELD_WIDTH)
4652   {						// This happens VERY seldom
4653     if (str->alloc(MAX_FIELD_WIDTH))
4654     {
4655       error=1;
4656       DBUG_RETURN(0);
4657     }
4658   }
4659   char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
4660 		 &is_null_tmp, &error);
4661   DBUG_PRINT("info", ("udf func returned, res_length: %lu", res_length));
4662   if (is_null_tmp || !res || error)		// The !res is for safety
4663   {
4664     DBUG_PRINT("info", ("Null or error"));
4665     DBUG_RETURN(0);
4666   }
4667   if (res == str->ptr())
4668   {
4669     str->length(res_length);
4670     DBUG_PRINT("exit", ("str: %*.s", (int) str->length(), str->ptr()));
4671     DBUG_RETURN(str);
4672   }
4673   save_str->set(res, res_length, str->charset());
4674   DBUG_PRINT("exit", ("save_str: %s", save_str->ptr()));
4675   DBUG_RETURN(save_str);
4676 }
4677 
4678 
4679 /*
4680   For the moment, UDF functions are returning DECIMAL values as strings
4681 */
4682 
val_decimal(my_bool * null_value,my_decimal * dec_buf)4683 my_decimal *udf_handler::val_decimal(my_bool *null_value, my_decimal *dec_buf)
4684 {
4685   char buf[DECIMAL_MAX_STR_LENGTH+1], *end;
4686   ulong res_length= DECIMAL_MAX_STR_LENGTH;
4687 
4688   if (get_arguments())
4689   {
4690     *null_value=1;
4691     return 0;
4692   }
4693   char *(*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
4694     (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
4695     u_d->func;
4696 
4697   char *res= func(&initid, &f_args, buf, &res_length, &is_null, &error);
4698   if (is_null || error)
4699   {
4700     *null_value= 1;
4701     return 0;
4702   }
4703   end= res+ res_length;
4704   str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end);
4705   return dec_buf;
4706 }
4707 
4708 
itemize(Parse_context * pc,Item ** res)4709 bool Item_udf_func::itemize(Parse_context *pc, Item **res)
4710 {
4711   if (skip_itemize(res))
4712     return false;
4713   if (super::itemize(pc, res))
4714     return true;
4715   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_UDF);
4716   pc->thd->lex->safe_to_cache_query= false;
4717   return false;
4718 }
4719 
4720 
cleanup()4721 void Item_udf_func::cleanup()
4722 {
4723   udf.cleanup();
4724   Item_func::cleanup();
4725 }
4726 
4727 
print(String * str,enum_query_type query_type)4728 void Item_udf_func::print(String *str, enum_query_type query_type)
4729 {
4730   str->append(func_name());
4731   str->append('(');
4732   for (uint i=0 ; i < arg_count ; i++)
4733   {
4734     if (i != 0)
4735       str->append(',');
4736     args[i]->print_item_w_name(str, query_type);
4737   }
4738   str->append(')');
4739 }
4740 
4741 
val_real()4742 double Item_func_udf_float::val_real()
4743 {
4744   assert(fixed == 1);
4745   DBUG_ENTER("Item_func_udf_float::val");
4746   DBUG_PRINT("info",("result_type: %d  arg_count: %d",
4747 		     args[0]->result_type(), arg_count));
4748   DBUG_RETURN(udf.val(&null_value));
4749 }
4750 
4751 
val_str(String * str)4752 String *Item_func_udf_float::val_str(String *str)
4753 {
4754   assert(fixed == 1);
4755   double nr= val_real();
4756   if (null_value)
4757     return 0;					/* purecov: inspected */
4758   str->set_real(nr,decimals,&my_charset_bin);
4759   return str;
4760 }
4761 
4762 
val_int()4763 longlong Item_func_udf_int::val_int()
4764 {
4765   assert(fixed == 1);
4766   DBUG_ENTER("Item_func_udf_int::val_int");
4767   DBUG_RETURN(udf.val_int(&null_value));
4768 }
4769 
4770 
val_str(String * str)4771 String *Item_func_udf_int::val_str(String *str)
4772 {
4773   assert(fixed == 1);
4774   longlong nr=val_int();
4775   if (null_value)
4776     return 0;
4777   str->set_int(nr, unsigned_flag, &my_charset_bin);
4778   return str;
4779 }
4780 
4781 
val_int()4782 longlong Item_func_udf_decimal::val_int()
4783 {
4784   my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
4785   longlong result;
4786   if (null_value)
4787     return 0;
4788   my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
4789   return result;
4790 }
4791 
4792 
val_real()4793 double Item_func_udf_decimal::val_real()
4794 {
4795   my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
4796   double result;
4797   if (null_value)
4798     return 0.0;
4799   my_decimal2double(E_DEC_FATAL_ERROR, dec, &result);
4800   return result;
4801 }
4802 
4803 
val_decimal(my_decimal * dec_buf)4804 my_decimal *Item_func_udf_decimal::val_decimal(my_decimal *dec_buf)
4805 {
4806   assert(fixed == 1);
4807   DBUG_ENTER("Item_func_udf_decimal::val_decimal");
4808   DBUG_PRINT("info",("result_type: %d  arg_count: %d",
4809                      args[0]->result_type(), arg_count));
4810 
4811   DBUG_RETURN(udf.val_decimal(&null_value, dec_buf));
4812 }
4813 
4814 
val_str(String * str)4815 String *Item_func_udf_decimal::val_str(String *str)
4816 {
4817   my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
4818   if (null_value)
4819     return 0;
4820   if (str->length() < DECIMAL_MAX_STR_LENGTH)
4821     str->length(DECIMAL_MAX_STR_LENGTH);
4822   my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
4823   my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, '0', str);
4824   return str;
4825 }
4826 
4827 
fix_length_and_dec()4828 void Item_func_udf_decimal::fix_length_and_dec()
4829 {
4830   fix_num_length_and_dec();
4831 }
4832 
4833 
4834 /* Default max_length is max argument length */
4835 
fix_length_and_dec()4836 void Item_func_udf_str::fix_length_and_dec()
4837 {
4838   DBUG_ENTER("Item_func_udf_str::fix_length_and_dec");
4839   max_length=0;
4840   for (uint i = 0; i < arg_count; i++)
4841     set_if_bigger(max_length,args[i]->max_length);
4842   DBUG_VOID_RETURN;
4843 }
4844 
val_str(String * str)4845 String *Item_func_udf_str::val_str(String *str)
4846 {
4847   assert(fixed == 1);
4848   String *res=udf.val_str(str,&str_value);
4849   null_value = !res;
4850   return res;
4851 }
4852 
~udf_handler()4853 udf_handler::~udf_handler()
4854 {
4855   /* Everything should be properly cleaned up by this moment. */
4856   assert(not_original || !(initialized || buffers));
4857 }
4858 
4859 #else
get_arguments()4860 bool udf_handler::get_arguments() { return 0; }
4861 #endif /* HAVE_DLOPEN */
4862 
4863 
itemize(Parse_context * pc,Item ** res)4864 bool Item_master_pos_wait::itemize(Parse_context *pc, Item **res)
4865 {
4866   if (skip_itemize(res))
4867     return false;
4868   if (super::itemize(pc, res))
4869     return true;
4870   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
4871   pc->thd->lex->safe_to_cache_query= false;
4872   return false;
4873 }
4874 
4875 
4876 /**
4877   Wait until we are at or past the given position in the master binlog
4878   on the slave.
4879 */
4880 
val_int()4881 longlong Item_master_pos_wait::val_int()
4882 {
4883   assert(fixed == 1);
4884   THD* thd = current_thd;
4885   String *log_name = args[0]->val_str(&value);
4886   int event_count= 0;
4887 
4888   null_value=0;
4889   if (thd->slave_thread || !log_name || !log_name->length())
4890   {
4891     null_value = 1;
4892     return 0;
4893   }
4894 #ifdef HAVE_REPLICATION
4895   Master_info *mi;
4896   longlong pos = (ulong)args[1]->val_int();
4897   double timeout = (arg_count >= 3) ? args[2]->val_real() : 0;
4898   if (timeout < 0)
4899   {
4900     if (thd->is_strict_mode())
4901     {
4902       my_error(ER_WRONG_ARGUMENTS, MYF(0), "MASTER_POS_WAIT.");
4903     }
4904     else
4905     {
4906       push_warning_printf(thd, Sql_condition::SL_WARNING,
4907                           ER_WRONG_ARGUMENTS,
4908                           ER(ER_WRONG_ARGUMENTS),
4909                           "MASTER_POS_WAIT.");
4910       null_value= 1;
4911     }
4912     return 0;
4913   }
4914 
4915   channel_map.rdlock();
4916 
4917   if (arg_count == 4)
4918   {
4919     String *channel_str;
4920     if(!(channel_str= args[3]->val_str(&value)))
4921     {
4922       null_value= 1;
4923       return 0;
4924     }
4925 
4926     mi= channel_map.get_mi(channel_str->ptr());
4927 
4928   }
4929   else
4930   {
4931     if (channel_map.get_num_instances() > 1)
4932     {
4933       mi = NULL;
4934       my_error(ER_SLAVE_MULTIPLE_CHANNELS_CMD, MYF(0));
4935     }
4936     else
4937       mi= channel_map.get_default_channel_mi();
4938   }
4939 
4940   if (mi != NULL)
4941     mi->inc_reference();
4942 
4943   channel_map.unlock();
4944 
4945   if (mi == NULL ||
4946       (event_count = mi->rli->wait_for_pos(thd, log_name, pos, timeout)) == -2)
4947   {
4948     null_value = 1;
4949     event_count=0;
4950   }
4951 
4952   if (mi != NULL)
4953     mi->dec_reference();
4954 #endif
4955   return event_count;
4956 }
4957 
itemize(Parse_context * pc,Item ** res)4958 bool Item_wait_for_executed_gtid_set::itemize(Parse_context *pc, Item **res)
4959 {
4960   if (skip_itemize(res))
4961     return false;
4962   if (super::itemize(pc, res))
4963     return true;
4964   /*
4965     It is unsafe because the return value depends on timing. If the timeout
4966     happens, the return value is different from the one in which the function
4967     returns with success.
4968   */
4969   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
4970   pc->thd->lex->safe_to_cache_query= false;
4971   return false;
4972 }
4973 
4974 /**
4975   Wait until the given gtid_set is found in the executed gtid_set independent
4976   of the slave threads.
4977 */
val_int()4978 longlong Item_wait_for_executed_gtid_set::val_int()
4979 {
4980   DBUG_ENTER("Item_wait_for_executed_gtid_set::val_int");
4981   assert(fixed == 1);
4982   THD* thd= current_thd;
4983   String *gtid_text= args[0]->val_str(&value);
4984 
4985   null_value= 0;
4986 
4987   if (gtid_text == NULL)
4988   {
4989     my_error(ER_MALFORMED_GTID_SET_SPECIFICATION, MYF(0), "NULL");
4990     DBUG_RETURN(0);
4991   }
4992 
4993   // Waiting for a GTID in a slave thread could cause the slave to
4994   // hang/deadlock.
4995   if (thd->slave_thread)
4996   {
4997     null_value= 1;
4998     DBUG_RETURN(0);
4999   }
5000 
5001   Gtid_set wait_for_gtid_set(global_sid_map, NULL);
5002 
5003   global_sid_lock->rdlock();
5004   if (get_gtid_mode(GTID_MODE_LOCK_SID) == GTID_MODE_OFF)
5005   {
5006     global_sid_lock->unlock();
5007     my_error(ER_GTID_MODE_OFF, MYF(0), "use WAIT_FOR_EXECUTED_GTID_SET");
5008     null_value= 1;
5009     DBUG_RETURN(0);
5010   }
5011 
5012   if (wait_for_gtid_set.add_gtid_text(gtid_text->c_ptr_safe()) !=
5013       RETURN_STATUS_OK)
5014   {
5015     global_sid_lock->unlock();
5016     // Error has already been generated.
5017     DBUG_RETURN(1);
5018   }
5019 
5020   // Cannot wait for a GTID that the thread owns since that would
5021   // immediately deadlock.
5022   if (thd->owned_gtid.sidno > 0 &&
5023       wait_for_gtid_set.contains_gtid(thd->owned_gtid))
5024   {
5025     char buf[Gtid::MAX_TEXT_LENGTH + 1];
5026     thd->owned_gtid.to_string(global_sid_map, buf);
5027     global_sid_lock->unlock();
5028     my_error(ER_CANT_WAIT_FOR_EXECUTED_GTID_SET_WHILE_OWNING_A_GTID, MYF(0),
5029              buf);
5030     DBUG_RETURN(0);
5031   }
5032 
5033   gtid_state->begin_gtid_wait(GTID_MODE_LOCK_SID);
5034 
5035   double timeout = (arg_count == 2) ? args[1]->val_real() : 0;
5036   if (timeout < 0)
5037   {
5038     if (thd->is_strict_mode())
5039     {
5040       my_error(ER_WRONG_ARGUMENTS, MYF(0), "WAIT_FOR_EXECUTED_GTID_SET.");
5041     }
5042     else
5043     {
5044       push_warning_printf(thd, Sql_condition::SL_WARNING,
5045                           ER_WRONG_ARGUMENTS,
5046                           ER(ER_WRONG_ARGUMENTS),
5047                           "WAIT_FOR_EXECUTED_GTID_SET.");
5048       null_value= 1;
5049     }
5050     gtid_state->end_gtid_wait();
5051     global_sid_lock->unlock();
5052     DBUG_RETURN(0);
5053   }
5054 
5055   bool result= gtid_state->wait_for_gtid_set(thd, &wait_for_gtid_set, timeout);
5056   global_sid_lock->unlock();
5057   gtid_state->end_gtid_wait();
5058 
5059   DBUG_RETURN(result);
5060 }
5061 
itemize(Parse_context * pc,Item ** res)5062 bool Item_master_gtid_set_wait::itemize(Parse_context *pc, Item **res)
5063 {
5064   if (skip_itemize(res))
5065     return false;
5066   if (super::itemize(pc, res))
5067     return true;
5068   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5069   pc->thd->lex->safe_to_cache_query= false;
5070   return false;
5071 }
5072 
5073 
val_int()5074 longlong Item_master_gtid_set_wait::val_int()
5075 {
5076   assert(fixed == 1);
5077   DBUG_ENTER("Item_master_gtid_set_wait::val_int");
5078   int event_count= 0;
5079 
5080   null_value=0;
5081 
5082 #if defined(HAVE_REPLICATION)
5083   String *gtid= args[0]->val_str(&value);
5084   THD* thd = current_thd;
5085   Master_info *mi= NULL;
5086   double timeout = (arg_count >= 2) ? args[1]->val_real() : 0;
5087   if (timeout < 0)
5088   {
5089     if (thd->is_strict_mode())
5090     {
5091       my_error(ER_WRONG_ARGUMENTS, MYF(0), "WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS.");
5092     }
5093     else
5094     {
5095       push_warning_printf(thd, Sql_condition::SL_WARNING,
5096                           ER_WRONG_ARGUMENTS,
5097                           ER(ER_WRONG_ARGUMENTS),
5098                           "WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS.");
5099       null_value= 1;
5100     }
5101     DBUG_RETURN(0);
5102   }
5103 
5104   if (thd->slave_thread || !gtid)
5105   {
5106     null_value = 1;
5107     DBUG_RETURN(0);
5108   }
5109 
5110   channel_map.rdlock();
5111 
5112   /* If replication channel is mentioned */
5113   if (arg_count == 3)
5114   {
5115     String *channel_str;
5116     if (!(channel_str= args[2]->val_str(&value)))
5117     {
5118       channel_map.unlock();
5119       null_value= 1;
5120       DBUG_RETURN(0);
5121     }
5122     mi= channel_map.get_mi(channel_str->ptr());
5123   }
5124   else
5125   {
5126     if (channel_map.get_num_instances() > 1)
5127     {
5128       channel_map.unlock();
5129       mi = NULL;
5130       my_error(ER_SLAVE_MULTIPLE_CHANNELS_CMD, MYF(0));
5131       DBUG_RETURN(0);
5132     }
5133     else
5134       mi= channel_map.get_default_channel_mi();
5135   }
5136 
5137   if (get_gtid_mode(GTID_MODE_LOCK_CHANNEL_MAP) == GTID_MODE_OFF)
5138   {
5139     null_value= 1;
5140     channel_map.unlock();
5141     DBUG_RETURN(0);
5142   }
5143   gtid_state->begin_gtid_wait(GTID_MODE_LOCK_CHANNEL_MAP);
5144 
5145   if (mi)
5146     mi->inc_reference();
5147 
5148   channel_map.unlock();
5149 
5150   if (mi && mi->rli)
5151   {
5152     event_count = mi->rli->wait_for_gtid_set(thd, gtid, timeout);
5153     if (event_count == -2)
5154     {
5155       null_value = 1;
5156       event_count=0;
5157     }
5158   }
5159   else
5160     /*
5161       Replication has not been set up, we should return NULL;
5162      */
5163     null_value = 1;
5164 
5165   if (mi != NULL)
5166     mi->dec_reference();
5167 #endif
5168 
5169   gtid_state->end_gtid_wait();
5170 
5171   DBUG_RETURN(event_count);
5172 }
5173 
5174 /**
5175   Return 1 if both arguments are Gtid_sets and the first is a subset
5176   of the second.  Generate an error if any of the arguments is not a
5177   Gtid_set.
5178 */
val_int()5179 longlong Item_func_gtid_subset::val_int()
5180 {
5181   DBUG_ENTER("Item_func_gtid_subset::val_int()");
5182   if (args[0]->null_value || args[1]->null_value)
5183   {
5184     null_value= true;
5185     DBUG_RETURN(0);
5186   }
5187   String *string1, *string2;
5188   const char *charp1, *charp2;
5189   int ret= 1;
5190   enum_return_status status;
5191   // get strings without lock
5192   if ((string1= args[0]->val_str(&buf1)) != NULL &&
5193       (charp1= string1->c_ptr_safe()) != NULL &&
5194       (string2= args[1]->val_str(&buf2)) != NULL &&
5195       (charp2= string2->c_ptr_safe()) != NULL)
5196   {
5197     Sid_map sid_map(NULL/*no rwlock*/);
5198     // compute sets while holding locks
5199     const Gtid_set sub_set(&sid_map, charp1, &status);
5200     if (status == RETURN_STATUS_OK)
5201     {
5202       const Gtid_set super_set(&sid_map, charp2, &status);
5203       if (status == RETURN_STATUS_OK)
5204         ret= sub_set.is_subset(&super_set) ? 1 : 0;
5205     }
5206   }
5207   DBUG_RETURN(ret);
5208 }
5209 
5210 
5211 /**
5212   Enables a session to wait on a condition until a timeout or a network
5213   disconnect occurs.
5214 
5215   @remark The connection is polled every m_interrupt_interval nanoseconds.
5216 */
5217 
5218 class Interruptible_wait
5219 {
5220   THD *m_thd;
5221   struct timespec m_abs_timeout;
5222   static const ulonglong m_interrupt_interval;
5223 
5224   public:
Interruptible_wait(THD * thd)5225     Interruptible_wait(THD *thd)
5226     : m_thd(thd) {}
5227 
~Interruptible_wait()5228     ~Interruptible_wait() {}
5229 
5230   public:
5231     /**
5232       Set the absolute timeout.
5233 
5234       @param timeout The amount of time in nanoseconds to wait
5235     */
set_timeout(ulonglong timeout)5236     void set_timeout(ulonglong timeout)
5237     {
5238       /*
5239         Calculate the absolute system time at the start so it can
5240         be controlled in slices. It relies on the fact that once
5241         the absolute time passes, the timed wait call will fail
5242         automatically with a timeout error.
5243       */
5244       set_timespec_nsec(&m_abs_timeout, timeout);
5245     }
5246 
5247     /** The timed wait. */
5248     int wait(mysql_cond_t *, mysql_mutex_t *);
5249 };
5250 
5251 
5252 /** Time to wait before polling the connection status. */
5253 const ulonglong Interruptible_wait::m_interrupt_interval= 5 * 1000000000ULL;
5254 
5255 
5256 /**
5257   Wait for a given condition to be signaled.
5258 
5259   @param cond   The condition variable to wait on.
5260   @param mutex  The associated mutex.
5261 
5262   @remark The absolute timeout is preserved across calls.
5263 
5264   @retval return value from mysql_cond_timedwait
5265 */
5266 
wait(mysql_cond_t * cond,mysql_mutex_t * mutex)5267 int Interruptible_wait::wait(mysql_cond_t *cond, mysql_mutex_t *mutex)
5268 {
5269   int error;
5270   struct timespec timeout;
5271 
5272   while (1)
5273   {
5274     /* Wait for a fixed interval. */
5275     set_timespec_nsec(&timeout, m_interrupt_interval);
5276 
5277     /* But only if not past the absolute timeout. */
5278     if (cmp_timespec(&timeout, &m_abs_timeout) > 0)
5279       timeout= m_abs_timeout;
5280 
5281     error= mysql_cond_timedwait(cond, mutex, &timeout);
5282     if (error == ETIMEDOUT || error == ETIME)
5283     {
5284       /* Return error if timed out or connection is broken. */
5285       if (!cmp_timespec(&timeout, &m_abs_timeout) || !m_thd->is_connected())
5286         break;
5287     }
5288     /* Otherwise, propagate status to the caller. */
5289     else
5290       break;
5291   }
5292 
5293   return error;
5294 }
5295 
5296 
5297 /*
5298   User-level locks implementation.
5299 */
5300 
5301 
5302 /**
5303   For locks with EXPLICIT duration, MDL returns a new ticket
5304   every time a lock is granted. This allows to implement recursive
5305   locks without extra allocation or additional data structures, such
5306   as below. However, if there are too many tickets in the same
5307   MDL_context, MDL_context::find_ticket() is getting too slow,
5308   since it's using a linear search.
5309   This is why a separate structure is allocated for a user
5310   level lock held by connection, and before requesting a new lock from MDL,
5311   GET_LOCK() checks thd->ull_hash if such lock is already granted,
5312   and if so, simply increments a reference counter.
5313 */
5314 
5315 struct User_level_lock
5316 {
5317   MDL_ticket *ticket;
5318   uint refs;
5319 };
5320 
5321 
5322 /** Extract a hash key from User_level_lock. */
5323 
ull_get_key(const uchar * ptr,size_t * length,my_bool not_used MY_ATTRIBUTE ((unused)))5324 uchar *ull_get_key(const uchar *ptr, size_t *length,
5325                    my_bool not_used MY_ATTRIBUTE((unused)))
5326 {
5327   const User_level_lock *ull = reinterpret_cast<const User_level_lock*>(ptr);
5328   const MDL_key *key = ull->ticket->get_key();
5329   *length= key->length();
5330   return const_cast<uchar*>(key->ptr());
5331 }
5332 
5333 
5334 /**
5335   Release all user level locks for this THD.
5336 */
5337 
mysql_ull_cleanup(THD * thd)5338 void mysql_ull_cleanup(THD *thd)
5339 {
5340   User_level_lock *ull;
5341   DBUG_ENTER("mysql_ull_cleanup");
5342 
5343   for (ulong i= 0; i < thd->ull_hash.records; i++)
5344   {
5345     ull= reinterpret_cast<User_level_lock*>(my_hash_element(&thd->ull_hash, i));
5346     thd->mdl_context.release_lock(ull->ticket);
5347     my_free(ull);
5348   }
5349 
5350   my_hash_free(&thd->ull_hash);
5351 
5352   DBUG_VOID_RETURN;
5353 }
5354 
5355 
5356 /**
5357   Set explicit duration for metadata locks corresponding to
5358   user level locks to protect them from being released at the end
5359   of transaction.
5360 */
5361 
mysql_ull_set_explicit_lock_duration(THD * thd)5362 void mysql_ull_set_explicit_lock_duration(THD *thd)
5363 {
5364   User_level_lock *ull;
5365   DBUG_ENTER("mysql_ull_set_explicit_lock_duration");
5366 
5367   for (ulong i= 0; i < thd->ull_hash.records; i++)
5368   {
5369     ull= reinterpret_cast<User_level_lock*>(my_hash_element(&thd->ull_hash, i));
5370     thd->mdl_context.set_lock_duration(ull->ticket, MDL_EXPLICIT);
5371   }
5372   DBUG_VOID_RETURN;
5373 }
5374 
5375 
5376 /**
5377   When MDL detects a lock wait timeout, it pushes an error into the statement
5378   diagnostics area. For GET_LOCK(), lock wait timeout is not an error, but a
5379   special return value (0). NULL is returned in case of error. Capture and
5380   suppress lock wait timeout.
5381   We also convert ER_LOCK_DEADLOCK error to ER_USER_LOCK_DEADLOCK error.
5382   The former means that implicit rollback of transaction has occurred
5383   which doesn't (and should not) happen when we get deadlock while waiting
5384   for user-level lock.
5385 */
5386 
5387 class User_level_lock_wait_error_handler: public Internal_error_handler
5388 {
5389 public:
User_level_lock_wait_error_handler()5390   User_level_lock_wait_error_handler()
5391     : m_lock_wait_timeout(false)
5392   { }
5393 
got_timeout() const5394   bool got_timeout() const { return m_lock_wait_timeout; }
5395 
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_severity_level * level,const char * msg)5396   virtual bool handle_condition(THD *thd,
5397                                 uint sql_errno,
5398                                 const char *sqlstate,
5399                                 Sql_condition::enum_severity_level *level,
5400                                 const char *msg)
5401   {
5402     if (sql_errno == ER_LOCK_WAIT_TIMEOUT)
5403     {
5404       m_lock_wait_timeout= true;
5405       return true;
5406     }
5407     else if (sql_errno == ER_LOCK_DEADLOCK)
5408     {
5409       my_error(ER_USER_LOCK_DEADLOCK, MYF(0));
5410       return true;
5411     }
5412 
5413     return false;
5414   }
5415 
5416 private:
5417   bool m_lock_wait_timeout;
5418 };
5419 
5420 
5421 class MDL_lock_get_owner_thread_id_visitor : public MDL_context_visitor
5422 {
5423 public:
MDL_lock_get_owner_thread_id_visitor()5424   MDL_lock_get_owner_thread_id_visitor()
5425     : m_owner_id(0)
5426   { }
5427 
visit_context(const MDL_context * ctx)5428   void visit_context(const MDL_context *ctx)
5429   {
5430     m_owner_id= ctx->get_owner()->get_thd()->thread_id();
5431   }
5432 
get_owner_id() const5433   my_thread_id get_owner_id() const { return m_owner_id; }
5434 
5435 private:
5436   my_thread_id m_owner_id;
5437 };
5438 
5439 
5440 /**
5441   Helper function which checks if user-level lock name is acceptable
5442   and converts it to system charset (utf8). Error is emitted if name
5443   is not acceptable. Name is also lowercased to ensure that user-level
5444   lock names are treated in case-insensitive fashion even though MDL
5445   subsystem which used by implementation does binary comparison of keys.
5446 
5447   @param buff      Buffer for lowercased name in system charset of
5448                    NAME_LEN + 1 bytes length.
5449   @param org_name  Original string passed as name parameter to
5450                    user-level lock function.
5451 
5452   @return True in case of error, false on success.
5453 */
5454 
check_and_convert_ull_name(char * buff,String * org_name)5455 static bool check_and_convert_ull_name(char *buff, String *org_name)
5456 {
5457   if (!org_name || !org_name->length())
5458   {
5459     my_error(ER_USER_LOCK_WRONG_NAME, MYF(0), (org_name ? "" : "NULL"));
5460     return true;
5461   }
5462 
5463   const char *well_formed_error_pos;
5464   const char *cannot_convert_error_pos;
5465   const char *from_end_pos;
5466   size_t bytes_copied;
5467 
5468   bytes_copied= well_formed_copy_nchars(system_charset_info,
5469                                         buff, NAME_LEN,
5470                                         org_name->charset(),
5471                                         org_name->ptr(), org_name->length(),
5472                                         NAME_CHAR_LEN,
5473                                         &well_formed_error_pos,
5474                                         &cannot_convert_error_pos,
5475                                         &from_end_pos);
5476 
5477   if (well_formed_error_pos || cannot_convert_error_pos ||
5478       from_end_pos < org_name->ptr() + org_name->length())
5479   {
5480     ErrConvString err(org_name);
5481     my_error(ER_USER_LOCK_WRONG_NAME, MYF(0), err.ptr());
5482     return true;
5483   }
5484 
5485   buff[bytes_copied]= '\0';
5486 
5487   my_casedn_str(system_charset_info, buff);
5488 
5489   return false;
5490 }
5491 
5492 
itemize(Parse_context * pc,Item ** res)5493 bool Item_func_get_lock::itemize(Parse_context *pc, Item **res)
5494 {
5495   if (skip_itemize(res))
5496     return false;
5497   if (super::itemize(pc, res))
5498     return true;
5499   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5500   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5501   return false;
5502 }
5503 
5504 
5505 /**
5506   Get a user level lock.
5507 
5508   @note Sets null_value to TRUE on error.
5509 
5510   @note This means that SQL-function GET_LOCK() returns:
5511         1    - if lock was acquired.
5512         0    - if lock was not acquired due to timeout.
5513         NULL - in case of error such as bad lock name, deadlock,
5514                thread being killed (also error is emitted).
5515 
5516   @retval
5517     1    : Got lock
5518   @retval
5519     0    : Timeout, error.
5520 */
5521 
val_int()5522 longlong Item_func_get_lock::val_int()
5523 {
5524   assert(fixed == 1);
5525   String *res= args[0]->val_str(&value);
5526   ulonglong timeout= args[1]->val_int();
5527   char name[NAME_LEN + 1];
5528   THD *thd= current_thd;
5529   User_level_lock *ull;
5530   DBUG_ENTER("Item_func_get_lock::val_int");
5531 
5532   null_value= TRUE;
5533   /*
5534     In slave thread no need to get locks, everything is serialized. Anyway
5535     there is no way to make GET_LOCK() work on slave like it did on master
5536     (i.e. make it return exactly the same value) because we don't have the
5537     same other concurrent threads environment. No matter what we return here,
5538     it's not guaranteed to be same as on master. So we always return 1.
5539   */
5540   if (thd->slave_thread)
5541   {
5542     null_value= FALSE;
5543     DBUG_RETURN(1);
5544   }
5545 
5546   if (check_and_convert_ull_name(name, res))
5547     DBUG_RETURN(0);
5548 
5549   DBUG_PRINT("info", ("lock %s, thd=%lu", name, (ulong) thd->real_id));
5550 
5551   /*
5552     Convert too big and negative timeout values to INT_MAX32.
5553     This gives robust, "infinite" wait on all platforms.
5554   */
5555   if (timeout > INT_MAX32)
5556     timeout= INT_MAX32;
5557 
5558   /* HASH entries are of type User_level_lock. */
5559   if (! my_hash_inited(&thd->ull_hash) &&
5560       my_hash_init(&thd->ull_hash, &my_charset_bin,
5561                    16 /* small hash */, 0, 0, ull_get_key, NULL, 0,
5562                    key_memory_User_level_lock))
5563   {
5564     DBUG_RETURN(0);
5565   }
5566 
5567   MDL_request ull_request;
5568   MDL_REQUEST_INIT(&ull_request, MDL_key::USER_LEVEL_LOCK, "",
5569                    name, MDL_EXCLUSIVE, MDL_EXPLICIT);
5570   MDL_key *ull_key= &ull_request.key;
5571 
5572   if ((ull= reinterpret_cast<User_level_lock*>
5573          (my_hash_search(&thd->ull_hash, ull_key->ptr(), ull_key->length()))))
5574   {
5575     /* Recursive lock. */
5576     ull->refs++;
5577     null_value= FALSE;
5578     DBUG_RETURN(1);
5579   }
5580 
5581   User_level_lock_wait_error_handler error_handler;
5582 
5583   thd->push_internal_handler(&error_handler);
5584   bool error= thd->mdl_context.acquire_lock(&ull_request,
5585                                             static_cast<ulong>(timeout));
5586   (void) thd->pop_internal_handler();
5587 
5588   if (error)
5589   {
5590     /*
5591       Return 0 in case of timeout and NULL in case of deadlock/other
5592       errors. In the latter case error (e.g. ER_USER_LOCK_DEADLOCK)
5593       will be reported as well.
5594     */
5595     if (error_handler.got_timeout())
5596       null_value= FALSE;
5597     DBUG_RETURN(0);
5598   }
5599 
5600   ull= reinterpret_cast<User_level_lock*>(my_malloc(key_memory_User_level_lock,
5601                                                     sizeof(User_level_lock),
5602                                                     MYF(0)));
5603 
5604   if (ull == NULL)
5605   {
5606     thd->mdl_context.release_lock(ull_request.ticket);
5607     DBUG_RETURN(0);
5608   }
5609 
5610   ull->ticket= ull_request.ticket;
5611   ull->refs= 1;
5612 
5613   if (my_hash_insert(&thd->ull_hash, reinterpret_cast<uchar*>(ull)))
5614   {
5615     thd->mdl_context.release_lock(ull_request.ticket);
5616     my_free(ull);
5617     DBUG_RETURN(0);
5618   }
5619 
5620   null_value= FALSE;
5621 
5622   DBUG_RETURN(1);
5623 }
5624 
5625 
itemize(Parse_context * pc,Item ** res)5626 bool Item_func_release_lock::itemize(Parse_context *pc, Item **res)
5627 {
5628   if (skip_itemize(res))
5629     return false;
5630   if (super::itemize(pc, res))
5631     return true;
5632   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5633   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5634   return false;
5635 }
5636 
5637 
5638 /**
5639   Release a user level lock.
5640 
5641   @note Sets null_value to TRUE on error/if no connection holds such lock.
5642 
5643   @note This means that SQL-function RELEASE_LOCK() returns:
5644         1    - if lock was held by this connection and was released.
5645         0    - if lock was held by some other connection (and was not released).
5646         NULL - if name of lock is bad or if it was not held by any connection
5647                (in the former case also error will be emitted),
5648 
5649   @return
5650     - 1 if lock released
5651     - 0 if lock wasn't held/error.
5652 */
5653 
val_int()5654 longlong Item_func_release_lock::val_int()
5655 {
5656   assert(fixed == 1);
5657   String *res= args[0]->val_str(&value);
5658   char name[NAME_LEN + 1];
5659   THD *thd= current_thd;
5660   DBUG_ENTER("Item_func_release_lock::val_int");
5661 
5662   null_value= TRUE;
5663 
5664   if (check_and_convert_ull_name(name, res))
5665     DBUG_RETURN(0);
5666 
5667   DBUG_PRINT("info", ("lock %s", name));
5668 
5669   MDL_key ull_key;
5670   ull_key.mdl_key_init(MDL_key::USER_LEVEL_LOCK, "", name);
5671 
5672   User_level_lock *ull;
5673 
5674   if (!(ull= reinterpret_cast<User_level_lock*>
5675           (my_hash_search(&thd->ull_hash, ull_key.ptr(), ull_key.length()))))
5676   {
5677     /*
5678       When RELEASE_LOCK() is called for lock which is not owned by the
5679       connection it should return 0 or NULL depending on whether lock
5680       is owned by any other connection or not.
5681     */
5682     MDL_lock_get_owner_thread_id_visitor get_owner_visitor;
5683 
5684     if (thd->mdl_context.find_lock_owner(&ull_key, &get_owner_visitor))
5685       DBUG_RETURN(0);
5686 
5687     null_value= get_owner_visitor.get_owner_id() == 0;
5688 
5689     DBUG_RETURN(0);
5690   }
5691   null_value= FALSE;
5692   if (--ull->refs == 0)
5693   {
5694     my_hash_delete(&thd->ull_hash, reinterpret_cast<uchar*>(ull));
5695     thd->mdl_context.release_lock(ull->ticket);
5696     my_free(ull);
5697   }
5698   DBUG_RETURN(1);
5699 }
5700 
5701 
itemize(Parse_context * pc,Item ** res)5702 bool Item_func_release_all_locks::itemize(Parse_context *pc, Item **res)
5703 {
5704   if (skip_itemize(res))
5705     return false;
5706   if (super::itemize(pc, res))
5707     return true;
5708   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5709   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5710   return false;
5711 }
5712 
5713 
5714 /**
5715   Release all user level lock held by connection.
5716 
5717   @return Number of locks released including recursive lock count.
5718 */
5719 
val_int()5720 longlong Item_func_release_all_locks::val_int()
5721 {
5722   assert(fixed == 1);
5723   THD *thd= current_thd;
5724   uint result= 0;
5725   User_level_lock *ull;
5726   DBUG_ENTER("Item_func_release_all_locks::val_int");
5727 
5728   if (my_hash_inited(&thd->ull_hash))
5729   {
5730     for (ulong i= 0; i < thd->ull_hash.records; i++)
5731     {
5732       ull= reinterpret_cast<User_level_lock*>(my_hash_element(&thd->ull_hash,
5733                                                               i));
5734       thd->mdl_context.release_lock(ull->ticket);
5735       result+= ull->refs;
5736       my_free(ull);
5737     }
5738     my_hash_reset(&thd->ull_hash);
5739   }
5740 
5741   DBUG_RETURN(result);
5742 }
5743 
5744 
itemize(Parse_context * pc,Item ** res)5745 bool Item_func_is_free_lock::itemize(Parse_context *pc, Item **res)
5746 {
5747   if (skip_itemize(res))
5748     return false;
5749   if (super::itemize(pc, res))
5750     return true;
5751   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5752   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5753   return false;
5754 }
5755 
5756 
5757 /**
5758   Check if user level lock is free.
5759 
5760   @note Sets null_value=TRUE on error.
5761 
5762   @note As result SQL-function IS_FREE_LOCK() returns:
5763         1    - if lock is free,
5764         0    - if lock is in use
5765         NULL - if lock name is bad or OOM (also error is emitted).
5766 
5767   @retval
5768     1		Available
5769   @retval
5770     0		Already taken, or error
5771 */
5772 
val_int()5773 longlong Item_func_is_free_lock::val_int()
5774 {
5775   assert(fixed == 1);
5776   String *res= args[0]->val_str(&value);
5777   char name[NAME_LEN + 1];
5778   THD *thd= current_thd;
5779 
5780   null_value= TRUE;
5781 
5782   if (check_and_convert_ull_name(name, res))
5783     return 0;
5784 
5785   MDL_key ull_key;
5786   ull_key.mdl_key_init(MDL_key::USER_LEVEL_LOCK, "", name);
5787 
5788   MDL_lock_get_owner_thread_id_visitor get_owner_visitor;
5789 
5790   if (thd->mdl_context.find_lock_owner(&ull_key, &get_owner_visitor))
5791     return 0;
5792 
5793   null_value= FALSE;
5794   return MY_TEST(get_owner_visitor.get_owner_id() == 0);
5795 }
5796 
5797 
itemize(Parse_context * pc,Item ** res)5798 bool Item_func_is_used_lock::itemize(Parse_context *pc, Item **res)
5799 {
5800   if (skip_itemize(res))
5801     return false;
5802   if (super::itemize(pc, res))
5803     return true;
5804   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5805   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5806   return false;
5807 }
5808 
5809 
5810 /**
5811   Check if user level lock is used and return connection id of owner.
5812 
5813   @note Sets null_value=TRUE if lock is free/on error.
5814 
5815   @note SQL-function IS_USED_LOCK() returns:
5816         #    - connection id of lock owner if lock is acquired.
5817         NULL - if lock is free or on error (in the latter case
5818                also error is emitted).
5819 
5820   @return Connection id of lock owner, 0 if lock is free/on error.
5821 */
5822 
val_int()5823 longlong Item_func_is_used_lock::val_int()
5824 {
5825   assert(fixed == 1);
5826   String *res= args[0]->val_str(&value);
5827   char name[NAME_LEN + 1];
5828   THD *thd= current_thd;
5829 
5830   null_value= TRUE;
5831 
5832   if (check_and_convert_ull_name(name, res))
5833     return 0;
5834 
5835   MDL_key ull_key;
5836   ull_key.mdl_key_init(MDL_key::USER_LEVEL_LOCK, "", name);
5837 
5838   MDL_lock_get_owner_thread_id_visitor get_owner_visitor;
5839 
5840   if (thd->mdl_context.find_lock_owner(&ull_key, &get_owner_visitor))
5841     return 0;
5842 
5843   my_thread_id thread_id= get_owner_visitor.get_owner_id();
5844   if (thread_id == 0)
5845     return 0;
5846 
5847   null_value= FALSE;
5848   return thread_id;
5849 }
5850 
5851 
itemize(Parse_context * pc,Item ** res)5852 bool Item_func_last_insert_id::itemize(Parse_context *pc, Item **res)
5853 {
5854   if (skip_itemize(res))
5855     return false;
5856   if (super::itemize(pc, res))
5857     return true;
5858   pc->thd->lex->safe_to_cache_query= false;
5859   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5860   return false;
5861 }
5862 
5863 
val_int()5864 longlong Item_func_last_insert_id::val_int()
5865 {
5866   THD *thd= current_thd;
5867   assert(fixed == 1);
5868   if (arg_count)
5869   {
5870     longlong value= args[0]->val_int();
5871     null_value= args[0]->null_value;
5872     /*
5873       LAST_INSERT_ID(X) must affect the client's mysql_insert_id() as
5874       documented in the manual. We don't want to touch
5875       first_successful_insert_id_in_cur_stmt because it would make
5876       LAST_INSERT_ID(X) take precedence over an generated auto_increment
5877       value for this row.
5878     */
5879     thd->arg_of_last_insert_id_function= TRUE;
5880     thd->first_successful_insert_id_in_prev_stmt= value;
5881     return value;
5882   }
5883   return
5884     static_cast<longlong>(thd->read_first_successful_insert_id_in_prev_stmt());
5885 }
5886 
5887 
itemize(Parse_context * pc,Item ** res)5888 bool Item_func_benchmark::itemize(Parse_context *pc, Item **res)
5889 {
5890   if (skip_itemize(res))
5891     return false;
5892   if (super::itemize(pc, res))
5893     return true;
5894   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5895   return false;
5896 }
5897 
5898 
5899 /* This function is just used to test speed of different functions */
5900 
val_int()5901 longlong Item_func_benchmark::val_int()
5902 {
5903   assert(fixed == 1);
5904   char buff[MAX_FIELD_WIDTH];
5905   String tmp(buff,sizeof(buff), &my_charset_bin);
5906   my_decimal tmp_decimal;
5907   THD *thd=current_thd;
5908   ulonglong loop_count;
5909 
5910   loop_count= (ulonglong) args[0]->val_int();
5911 
5912   if (args[0]->null_value ||
5913       (!args[0]->unsigned_flag && (((longlong) loop_count) < 0)))
5914   {
5915     if (!args[0]->null_value)
5916     {
5917       char buff[22];
5918       llstr(((longlong) loop_count), buff);
5919       push_warning_printf(current_thd, Sql_condition::SL_WARNING,
5920                           ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE),
5921                           "count", buff, "benchmark");
5922     }
5923 
5924     null_value= 1;
5925     return 0;
5926   }
5927 
5928   null_value=0;
5929   for (ulonglong loop=0 ; loop < loop_count && !thd->killed; loop++)
5930   {
5931     switch (args[1]->result_type()) {
5932     case REAL_RESULT:
5933       (void) args[1]->val_real();
5934       break;
5935     case INT_RESULT:
5936       (void) args[1]->val_int();
5937       break;
5938     case STRING_RESULT:
5939       (void) args[1]->val_str(&tmp);
5940       break;
5941     case DECIMAL_RESULT:
5942       (void) args[1]->val_decimal(&tmp_decimal);
5943       break;
5944     case ROW_RESULT:
5945     default:
5946       // This case should never be chosen
5947       assert(0);
5948       return 0;
5949     }
5950   }
5951   return 0;
5952 }
5953 
5954 
print(String * str,enum_query_type query_type)5955 void Item_func_benchmark::print(String *str, enum_query_type query_type)
5956 {
5957   str->append(STRING_WITH_LEN("benchmark("));
5958   args[0]->print(str, query_type);
5959   str->append(',');
5960   args[1]->print(str, query_type);
5961   str->append(')');
5962 }
5963 
5964 
5965 /**
5966   Lock which is used to implement interruptible wait for SLEEP() function.
5967 */
5968 
5969 mysql_mutex_t LOCK_item_func_sleep;
5970 
5971 
5972 #ifdef HAVE_PSI_INTERFACE
5973 static PSI_mutex_key key_LOCK_item_func_sleep;
5974 
5975 
5976 static PSI_mutex_info item_func_sleep_mutexes[]=
5977 {
5978   { &key_LOCK_item_func_sleep, "LOCK_item_func_sleep", PSI_FLAG_GLOBAL}
5979 };
5980 
5981 
init_item_func_sleep_psi_keys()5982 static void init_item_func_sleep_psi_keys()
5983 {
5984   int count;
5985 
5986   count= array_elements(item_func_sleep_mutexes);
5987   mysql_mutex_register("sql", item_func_sleep_mutexes, count);
5988 }
5989 #endif
5990 
5991 
5992 static bool item_func_sleep_inited= false;
5993 
5994 
item_func_sleep_init()5995 void item_func_sleep_init()
5996 {
5997 #ifdef HAVE_PSI_INTERFACE
5998   init_item_func_sleep_psi_keys();
5999 #endif
6000 
6001   mysql_mutex_init(key_LOCK_item_func_sleep, &LOCK_item_func_sleep, MY_MUTEX_INIT_SLOW);
6002   item_func_sleep_inited= true;
6003 }
6004 
6005 
item_func_sleep_free()6006 void item_func_sleep_free()
6007 {
6008   if (item_func_sleep_inited)
6009   {
6010     item_func_sleep_inited= false;
6011     mysql_mutex_destroy(&LOCK_item_func_sleep);
6012   }
6013 }
6014 
6015 
itemize(Parse_context * pc,Item ** res)6016 bool Item_func_sleep::itemize(Parse_context *pc, Item **res)
6017 {
6018   if (skip_itemize(res))
6019     return false;
6020   if (super::itemize(pc, res))
6021     return true;
6022   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
6023   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
6024   return false;
6025 }
6026 
6027 
6028 /** This function is just used to create tests with time gaps. */
6029 
val_int()6030 longlong Item_func_sleep::val_int()
6031 {
6032   THD *thd= current_thd;
6033   Interruptible_wait timed_cond(thd);
6034   mysql_cond_t cond;
6035   double timeout;
6036   int error;
6037 
6038   assert(fixed == 1);
6039 
6040   timeout= args[0]->val_real();
6041 
6042   /*
6043     Report error or warning depending on the value of SQL_MODE.
6044     If SQL is STRICT then report error, else report warning and continue
6045     execution.
6046   */
6047 
6048   if (args[0]->null_value || timeout < 0)
6049   {
6050     if (!thd->lex->is_ignore() && thd->is_strict_mode())
6051     {
6052       my_error(ER_WRONG_ARGUMENTS, MYF(0), "sleep.");
6053       return 0;
6054     }
6055     else
6056       push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
6057                           ER(ER_WRONG_ARGUMENTS), "sleep.");
6058   }
6059   /*
6060     On 64-bit OSX mysql_cond_timedwait() waits forever
6061     if passed abstime time has already been exceeded by
6062     the system time.
6063     When given a very short timeout (< 10 mcs) just return
6064     immediately.
6065     We assume that the lines between this test and the call
6066     to mysql_cond_timedwait() will be executed in less than 0.00001 sec.
6067   */
6068   if (timeout < 0.00001)
6069     return 0;
6070 
6071   timed_cond.set_timeout((ulonglong) (timeout * 1000000000.0));
6072 
6073   mysql_cond_init(key_item_func_sleep_cond, &cond);
6074   mysql_mutex_lock(&LOCK_item_func_sleep);
6075 
6076   thd->ENTER_COND(&cond, &LOCK_item_func_sleep, &stage_user_sleep, NULL);
6077 
6078   error= 0;
6079   thd_wait_begin(thd, THD_WAIT_SLEEP);
6080   while (!thd->killed)
6081   {
6082     error= timed_cond.wait(&cond, &LOCK_item_func_sleep);
6083     if (error == ETIMEDOUT || error == ETIME)
6084       break;
6085     error= 0;
6086   }
6087   thd_wait_end(thd);
6088   mysql_mutex_unlock(&LOCK_item_func_sleep);
6089   thd->EXIT_COND(NULL);
6090 
6091   mysql_cond_destroy(&cond);
6092 
6093   return MY_TEST(!error); 		// Return 1 killed
6094 }
6095 
6096 /*
6097   @param cs  character set; IF we are creating the user_var_entry,
6098              we give it this character set.
6099 */
get_variable(THD * thd,const Name_string & name,const CHARSET_INFO * cs)6100 static user_var_entry *get_variable(THD *thd, const Name_string &name,
6101                                     const CHARSET_INFO *cs)
6102 {
6103   user_var_entry *entry;
6104   HASH *hash= & thd->user_vars;
6105 
6106   /* Protects thd->user_vars. */
6107   mysql_mutex_assert_owner(&thd->LOCK_thd_data);
6108 
6109   if (!(entry= (user_var_entry*) my_hash_search(hash, (uchar*) name.ptr(),
6110                                                  name.length())) &&
6111         cs != NULL)
6112   {
6113     if (!my_hash_inited(hash))
6114       return 0;
6115     if (!(entry= user_var_entry::create(thd, name, cs)))
6116       return 0;
6117     if (my_hash_insert(hash,(uchar*) entry))
6118     {
6119       my_free(entry);
6120       return 0;
6121     }
6122   }
6123   return entry;
6124 }
6125 
6126 
cleanup()6127 void Item_func_set_user_var::cleanup()
6128 {
6129   Item_func::cleanup();
6130   entry= NULL;
6131 }
6132 
6133 
set_entry(THD * thd,bool create_if_not_exists)6134 bool Item_func_set_user_var::set_entry(THD *thd, bool create_if_not_exists)
6135 {
6136   if (entry && thd->thread_id() == entry_thread_id)
6137   {} // update entry->update_query_id for PS
6138   else
6139   {
6140     const CHARSET_INFO *cs=  create_if_not_exists ?
6141           (args[0]->collation.derivation == DERIVATION_NUMERIC ?
6142           default_charset() : args[0]->collation.collation) : NULL;
6143 
6144     /* Protects thd->user_vars. */
6145     mysql_mutex_lock(&thd->LOCK_thd_data);
6146     entry= get_variable(thd, name, cs);
6147     mysql_mutex_unlock(&thd->LOCK_thd_data);
6148 
6149     if (entry == NULL)
6150     {
6151       entry_thread_id= 0;
6152       return TRUE;
6153     }
6154     entry_thread_id= thd->thread_id();
6155   }
6156   /*
6157     Remember the last query which updated it, this way a query can later know
6158     if this variable is a constant item in the query (it is if update_query_id
6159     is different from query_id).
6160 
6161     If this object has delayed setting of non-constness, we delay this
6162     until Item_func_set-user_var::save_item_result().
6163   */
6164   if (!delayed_non_constness)
6165     entry->update_query_id= thd->query_id;
6166   return FALSE;
6167 }
6168 
6169 
6170 /*
6171   When a user variable is updated (in a SET command or a query like
6172   SELECT @a:= ).
6173 */
6174 
fix_fields(THD * thd,Item ** ref)6175 bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref)
6176 {
6177   assert(fixed == 0);
6178   /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
6179   if (Item_func::fix_fields(thd, ref) || set_entry(thd, TRUE))
6180     return TRUE;
6181 
6182   null_item= (args[0]->type() == NULL_ITEM);
6183 
6184   cached_result_type= args[0]->result_type();
6185   return FALSE;
6186 }
6187 
6188 
6189 void
fix_length_and_dec()6190 Item_func_set_user_var::fix_length_and_dec()
6191 {
6192   maybe_null=args[0]->maybe_null;
6193   decimals=args[0]->decimals;
6194   collation.set(DERIVATION_IMPLICIT);
6195   /*
6196      this sets the character set of the item immediately; rules for the
6197      character set of the variable ("entry" object) are different: if "entry"
6198      did not exist previously, set_entry () has created it and has set its
6199      character set; but if it existed previously, it keeps its previous
6200      character set, which may change only when we are sure that the assignment
6201      is to be executed, i.e. in user_var_entry::store ().
6202   */
6203   if (args[0]->collation.derivation == DERIVATION_NUMERIC)
6204     fix_length_and_charset(args[0]->max_char_length(), default_charset());
6205   else
6206   {
6207     fix_length_and_charset(args[0]->max_char_length(),
6208                            args[0]->collation.collation);
6209   }
6210   unsigned_flag= args[0]->unsigned_flag;
6211 }
6212 
6213 
mem_realloc(size_t length)6214 bool user_var_entry::mem_realloc(size_t length)
6215 {
6216   if (length <= extra_size)
6217   {
6218     /* Enough space to store value in value struct */
6219     free_value();
6220     m_ptr= internal_buffer_ptr();
6221   }
6222   else
6223   {
6224     /* Allocate an external buffer */
6225     if (m_length != length)
6226     {
6227       if (m_ptr == internal_buffer_ptr())
6228         m_ptr= 0;
6229       if (!(m_ptr= (char*) my_realloc(key_memory_user_var_entry_value,
6230                                       m_ptr, length,
6231                                       MYF(MY_ALLOW_ZERO_PTR | MY_WME |
6232                                       ME_FATALERROR))))
6233         return true;
6234     }
6235   }
6236   return false;
6237 }
6238 
6239 
6240 /**
6241   Set value to user variable.
6242   @param ptr            pointer to buffer with new value
6243   @param length         length of new value
6244   @param type           type of new value
6245 
6246   @retval  false   on success
6247   @retval  true    on allocation error
6248 
6249 */
store(const void * from,size_t length,Item_result type)6250 bool user_var_entry::store(const void *from, size_t length, Item_result type)
6251 {
6252   assert_locked();
6253 
6254   // Store strings with end \0
6255   if (mem_realloc(length + MY_TEST(type == STRING_RESULT)))
6256     return true;
6257   if (type == STRING_RESULT)
6258     m_ptr[length]= 0;     // Store end \0
6259 
6260   // Avoid memcpy of a my_decimal object, use copy CTOR instead.
6261   if (type == DECIMAL_RESULT)
6262   {
6263     assert(length == sizeof(my_decimal));
6264     const my_decimal* dec= static_cast<const my_decimal*>(from);
6265     dec->sanity_check();
6266     new (m_ptr) my_decimal(*dec);
6267   }
6268   else
6269     memcpy(m_ptr, from, length);
6270 
6271   m_length= length;
6272   m_type= type;
6273   return false;
6274 }
6275 
6276 
6277 /**
6278   Set value to user variable.
6279 
6280   @param ptr            pointer to buffer with new value
6281   @param length         length of new value
6282   @param type           type of new value
6283   @param cs             charset info for new value
6284   @param dv             derivation for new value
6285   @param unsigned_arg   indiates if a value of type INT_RESULT is unsigned
6286 
6287   @note Sets error and fatal error if allocation fails.
6288 
6289   @retval
6290     false   success
6291   @retval
6292     true    failure
6293 */
6294 
store(const void * ptr,size_t length,Item_result type,const CHARSET_INFO * cs,Derivation dv,bool unsigned_arg)6295 bool user_var_entry::store(const void *ptr, size_t length, Item_result type,
6296                            const CHARSET_INFO *cs, Derivation dv,
6297                            bool unsigned_arg)
6298 {
6299   assert_locked();
6300 
6301   if (store(ptr, length, type))
6302     return true;
6303   collation.set(cs, dv);
6304   unsigned_flag= unsigned_arg;
6305   return false;
6306 }
6307 
lock()6308 void user_var_entry::lock()
6309 {
6310   assert(m_owner != NULL);
6311   mysql_mutex_lock(&m_owner->LOCK_thd_data);
6312 }
6313 
unlock()6314 void user_var_entry::unlock()
6315 {
6316   assert(m_owner != NULL);
6317   mysql_mutex_unlock(&m_owner->LOCK_thd_data);
6318 }
6319 
6320 bool
update_hash(const void * ptr,uint length,Item_result res_type,const CHARSET_INFO * cs,Derivation dv,bool unsigned_arg)6321 Item_func_set_user_var::update_hash(const void *ptr, uint length,
6322                                     Item_result res_type,
6323                                     const CHARSET_INFO *cs, Derivation dv,
6324                                     bool unsigned_arg)
6325 {
6326   entry->lock();
6327 
6328   /*
6329     If we set a variable explicitely to NULL then keep the old
6330     result type of the variable
6331   */
6332   // args[0]->null_value could be outdated
6333   if (args[0]->type() == Item::FIELD_ITEM)
6334     null_value= ((Item_field*)args[0])->field->is_null();
6335   else
6336     null_value= args[0]->null_value;
6337 
6338   if (ptr == NULL)
6339   {
6340     assert(length == 0);
6341     null_value= true;
6342   }
6343 
6344   if (null_value && null_item)
6345     res_type= entry->type();                    // Don't change type of item
6346 
6347   if (null_value)
6348     entry->set_null_value(res_type);
6349   else if (entry->store(ptr, length, res_type, cs, dv, unsigned_arg))
6350   {
6351     entry->unlock();
6352     null_value= 1;
6353     return 1;
6354   }
6355   entry->unlock();
6356   return 0;
6357 }
6358 
6359 
6360 /** Get the value of a variable as a double. */
6361 
val_real(my_bool * null_value) const6362 double user_var_entry::val_real(my_bool *null_value) const
6363 {
6364   if ((*null_value= (m_ptr == 0)))
6365     return 0.0;
6366 
6367   switch (m_type) {
6368   case REAL_RESULT:
6369     return *(double*) m_ptr;
6370   case INT_RESULT:
6371     return (double) *(longlong*) m_ptr;
6372   case DECIMAL_RESULT:
6373   {
6374     double result;
6375     my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, &result);
6376     return result;
6377   }
6378   case STRING_RESULT:
6379     return my_atof(m_ptr);                    // This is null terminated
6380   case ROW_RESULT:
6381     assert(1);				// Impossible
6382     break;
6383   }
6384   return 0.0;					// Impossible
6385 }
6386 
6387 
6388 /** Get the value of a variable as an integer. */
6389 
val_int(my_bool * null_value) const6390 longlong user_var_entry::val_int(my_bool *null_value) const
6391 {
6392   if ((*null_value= (m_ptr == 0)))
6393     return 0LL;
6394 
6395   switch (m_type) {
6396   case REAL_RESULT:
6397     return (longlong) *(double*) m_ptr;
6398   case INT_RESULT:
6399     return *(longlong*) m_ptr;
6400   case DECIMAL_RESULT:
6401   {
6402     longlong result;
6403     my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, 0, &result);
6404     return result;
6405   }
6406   case STRING_RESULT:
6407   {
6408     int error;
6409     return my_strtoll10(m_ptr, (char**) 0, &error);// String is null terminated
6410   }
6411   case ROW_RESULT:
6412     assert(1);				// Impossible
6413     break;
6414   }
6415   return 0LL;					// Impossible
6416 }
6417 
6418 
6419 /** Get the value of a variable as a string. */
6420 
val_str(my_bool * null_value,String * str,uint decimals) const6421 String *user_var_entry::val_str(my_bool *null_value, String *str,
6422 				uint decimals) const
6423 {
6424   if ((*null_value= (m_ptr == 0)))
6425     return (String*) 0;
6426 
6427   switch (m_type) {
6428   case REAL_RESULT:
6429     str->set_real(*(double*) m_ptr, decimals, collation.collation);
6430     break;
6431   case INT_RESULT:
6432     if (!unsigned_flag)
6433       str->set(*(longlong*) m_ptr, collation.collation);
6434     else
6435       str->set(*(ulonglong*) m_ptr, collation.collation);
6436     break;
6437   case DECIMAL_RESULT:
6438     str_set_decimal((my_decimal *) m_ptr, str, collation.collation);
6439     break;
6440   case STRING_RESULT:
6441     if (str->copy(m_ptr, m_length, collation.collation))
6442       str= 0;					// EOM error
6443     break;
6444   case ROW_RESULT:
6445     assert(1);				// Impossible
6446     break;
6447   }
6448   return(str);
6449 }
6450 
6451 /** Get the value of a variable as a decimal. */
6452 
val_decimal(my_bool * null_value,my_decimal * val) const6453 my_decimal *user_var_entry::val_decimal(my_bool *null_value, my_decimal *val) const
6454 {
6455   if ((*null_value= (m_ptr == 0)))
6456     return 0;
6457 
6458   switch (m_type) {
6459   case REAL_RESULT:
6460     double2my_decimal(E_DEC_FATAL_ERROR, *(double*) m_ptr, val);
6461     break;
6462   case INT_RESULT:
6463     int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) m_ptr, 0, val);
6464     break;
6465   case DECIMAL_RESULT:
6466     my_decimal2decimal((my_decimal *) m_ptr, val);
6467     break;
6468   case STRING_RESULT:
6469     str2my_decimal(E_DEC_FATAL_ERROR, m_ptr, m_length,
6470                    collation.collation, val);
6471     break;
6472   case ROW_RESULT:
6473     assert(1);				// Impossible
6474     break;
6475   }
6476   return(val);
6477 }
6478 
6479 /**
6480   This functions is invoked on SET \@variable or
6481   \@variable:= expression.
6482 
6483   Evaluate (and check expression), store results.
6484 
6485   @note
6486     For now it always return OK. All problem with value evaluating
6487     will be caught by thd->is_error() check in sql_set_variables().
6488 
6489   @retval
6490     FALSE OK.
6491 */
6492 
6493 bool
check(bool use_result_field)6494 Item_func_set_user_var::check(bool use_result_field)
6495 {
6496   DBUG_ENTER("Item_func_set_user_var::check");
6497   if (use_result_field && !result_field)
6498     use_result_field= FALSE;
6499 
6500   switch (cached_result_type) {
6501   case REAL_RESULT:
6502   {
6503     save_result.vreal= use_result_field ? result_field->val_real() :
6504                         args[0]->val_real();
6505     break;
6506   }
6507   case INT_RESULT:
6508   {
6509     save_result.vint= use_result_field ? result_field->val_int() :
6510                        args[0]->val_int();
6511     unsigned_flag= use_result_field ? ((Field_num*)result_field)->unsigned_flag:
6512                     args[0]->unsigned_flag;
6513     break;
6514   }
6515   case STRING_RESULT:
6516   {
6517     save_result.vstr= use_result_field ? result_field->val_str(&value) :
6518                        args[0]->val_str(&value);
6519     break;
6520   }
6521   case DECIMAL_RESULT:
6522   {
6523     save_result.vdec= use_result_field ?
6524                        result_field->val_decimal(&decimal_buff) :
6525                        args[0]->val_decimal(&decimal_buff);
6526     break;
6527   }
6528   case ROW_RESULT:
6529   default:
6530     // This case should never be chosen
6531     assert(0);
6532     break;
6533   }
6534   DBUG_RETURN(FALSE);
6535 }
6536 
6537 
6538 /**
6539   @brief Evaluate and store item's result.
6540   This function is invoked on "SELECT ... INTO @var ...".
6541 
6542   @param    item    An item to get value from.
6543 */
6544 
save_item_result(Item * item)6545 void Item_func_set_user_var::save_item_result(Item *item)
6546 {
6547   DBUG_ENTER("Item_func_set_user_var::save_item_result");
6548 
6549   switch (cached_result_type) {
6550   case REAL_RESULT:
6551     save_result.vreal= item->val_result();
6552     break;
6553   case INT_RESULT:
6554     save_result.vint= item->val_int_result();
6555     unsigned_flag= item->unsigned_flag;
6556     break;
6557   case STRING_RESULT:
6558     save_result.vstr= item->str_result(&value);
6559     break;
6560   case DECIMAL_RESULT:
6561     save_result.vdec= item->val_decimal_result(&decimal_buff);
6562     break;
6563   case ROW_RESULT:
6564   default:
6565     // Should never happen
6566     assert(0);
6567     break;
6568   }
6569   /*
6570     Set the ID of the query that last updated this variable. This is
6571     usually set by Item_func_set_user_var::set_entry(), but if this
6572     item has delayed setting of non-constness, we must do it now.
6573    */
6574   if (delayed_non_constness)
6575     entry->update_query_id= current_thd->query_id;
6576   DBUG_VOID_RETURN;
6577 }
6578 
6579 
6580 /**
6581   This functions is invoked on
6582   SET \@variable or \@variable:= expression.
6583 
6584   @note
6585     We have to store the expression as such in the variable, independent of
6586     the value method used by the user
6587 
6588   @retval
6589     0	OK
6590   @retval
6591     1	EOM Error
6592 
6593 */
6594 
6595 bool
update()6596 Item_func_set_user_var::update()
6597 {
6598   bool res= 0;
6599   DBUG_ENTER("Item_func_set_user_var::update");
6600 
6601   switch (cached_result_type) {
6602   case REAL_RESULT:
6603   {
6604     res= update_hash(&save_result.vreal,sizeof(save_result.vreal),
6605 		     REAL_RESULT, default_charset(), DERIVATION_IMPLICIT, 0);
6606     break;
6607   }
6608   case INT_RESULT:
6609   {
6610     res= update_hash(&save_result.vint, sizeof(save_result.vint),
6611                      INT_RESULT, default_charset(), DERIVATION_IMPLICIT,
6612                      unsigned_flag);
6613     break;
6614   }
6615   case STRING_RESULT:
6616   {
6617     if (!save_result.vstr)					// Null value
6618       res= update_hash(NULL, 0, STRING_RESULT, &my_charset_bin,
6619 		       DERIVATION_IMPLICIT, 0);
6620     else
6621       res= update_hash(save_result.vstr->ptr(),
6622 		       save_result.vstr->length(), STRING_RESULT,
6623 		       save_result.vstr->charset(),
6624 		       DERIVATION_IMPLICIT, 0);
6625     break;
6626   }
6627   case DECIMAL_RESULT:
6628   {
6629     if (!save_result.vdec)					// Null value
6630       res= update_hash(NULL, 0, DECIMAL_RESULT, &my_charset_bin,
6631                        DERIVATION_IMPLICIT, false);
6632     else
6633       res= update_hash(save_result.vdec,
6634                        sizeof(my_decimal), DECIMAL_RESULT,
6635                        default_charset(), DERIVATION_IMPLICIT, 0);
6636     break;
6637   }
6638   case ROW_RESULT:
6639   default:
6640     // This case should never be chosen
6641     assert(0);
6642     break;
6643   }
6644   DBUG_RETURN(res);
6645 }
6646 
6647 
val_real()6648 double Item_func_set_user_var::val_real()
6649 {
6650   assert(fixed == 1);
6651   check(0);
6652   update();					// Store expression
6653   return entry->val_real(&null_value);
6654 }
6655 
val_int()6656 longlong Item_func_set_user_var::val_int()
6657 {
6658   assert(fixed == 1);
6659   check(0);
6660   update();					// Store expression
6661   return entry->val_int(&null_value);
6662 }
6663 
val_str(String * str)6664 String *Item_func_set_user_var::val_str(String *str)
6665 {
6666   assert(fixed == 1);
6667   check(0);
6668   update();					// Store expression
6669   return entry->val_str(&null_value, str, decimals);
6670 }
6671 
6672 
val_decimal(my_decimal * val)6673 my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val)
6674 {
6675   assert(fixed == 1);
6676   check(0);
6677   update();					// Store expression
6678   return entry->val_decimal(&null_value, val);
6679 }
6680 
6681 
val_result()6682 double Item_func_set_user_var::val_result()
6683 {
6684   assert(fixed == 1);
6685   check(TRUE);
6686   update();					// Store expression
6687   return entry->val_real(&null_value);
6688 }
6689 
val_int_result()6690 longlong Item_func_set_user_var::val_int_result()
6691 {
6692   assert(fixed == 1);
6693   check(TRUE);
6694   update();					// Store expression
6695   return entry->val_int(&null_value);
6696 }
6697 
val_bool_result()6698 bool Item_func_set_user_var::val_bool_result()
6699 {
6700   assert(fixed == 1);
6701   check(TRUE);
6702   update();					// Store expression
6703   return entry->val_int(&null_value) != 0;
6704 }
6705 
str_result(String * str)6706 String *Item_func_set_user_var::str_result(String *str)
6707 {
6708   assert(fixed == 1);
6709   check(TRUE);
6710   update();					// Store expression
6711   return entry->val_str(&null_value, str, decimals);
6712 }
6713 
6714 
val_decimal_result(my_decimal * val)6715 my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val)
6716 {
6717   assert(fixed == 1);
6718   check(TRUE);
6719   update();					// Store expression
6720   return entry->val_decimal(&null_value, val);
6721 }
6722 
6723 
is_null_result()6724 bool Item_func_set_user_var::is_null_result()
6725 {
6726   assert(fixed == 1);
6727   check(TRUE);
6728   update();					// Store expression
6729   return is_null();
6730 }
6731 
6732 // just the assignment, for use in "SET @a:=5" type self-prints
print_assignment(String * str,enum_query_type query_type)6733 void Item_func_set_user_var::print_assignment(String *str,
6734                                               enum_query_type query_type)
6735 {
6736   str->append(STRING_WITH_LEN("@"));
6737   str->append(name);
6738   str->append(STRING_WITH_LEN(":="));
6739   args[0]->print(str, query_type);
6740 }
6741 
6742 // parenthesize assignment for use in "EXPLAIN EXTENDED SELECT (@e:=80)+5"
print(String * str,enum_query_type query_type)6743 void Item_func_set_user_var::print(String *str, enum_query_type query_type)
6744 {
6745   str->append(STRING_WITH_LEN("("));
6746   print_assignment(str, query_type);
6747   str->append(STRING_WITH_LEN(")"));
6748 }
6749 
send(Protocol * protocol,String * str_arg)6750 bool Item_func_set_user_var::send(Protocol *protocol, String *str_arg)
6751 {
6752   if (result_field)
6753   {
6754     check(1);
6755     update();
6756     /*
6757       Workaround for metadata check in Protocol_text. Legacy Protocol_text
6758       is so well designed that it sends fields in text format, and functions'
6759       results in binary format. When this func tries to send its data as a
6760       field it breaks metadata asserts in the P_text.
6761       TODO This func have to be changed to avoid sending data as a field.
6762     */
6763     return result_field->send_binary(protocol);
6764   }
6765   return Item::send(protocol, str_arg);
6766 }
6767 
make_field(Send_field * tmp_field)6768 void Item_func_set_user_var::make_field(Send_field *tmp_field)
6769 {
6770   if (result_field)
6771   {
6772     result_field->make_field(tmp_field);
6773     assert(tmp_field->table_name != 0);
6774     if (Item::item_name.is_set())
6775       tmp_field->col_name=Item::item_name.ptr();    // Use user supplied name
6776   }
6777   else
6778     Item::make_field(tmp_field);
6779 }
6780 
6781 
6782 /*
6783   Save the value of a user variable into a field
6784 
6785   SYNOPSIS
6786     save_in_field()
6787       field           target field to save the value to
6788       no_conversion   flag indicating whether conversions are allowed
6789 
6790   DESCRIPTION
6791     Save the function value into a field and update the user variable
6792     accordingly. If a result field is defined and the target field doesn't
6793     coincide with it then the value from the result field will be used as
6794     the new value of the user variable.
6795 
6796     The reason to have this method rather than simply using the result
6797     field in the val_xxx() methods is that the value from the result field
6798     not always can be used when the result field is defined.
6799     Let's consider the following cases:
6800     1) when filling a tmp table the result field is defined but the value of it
6801     is undefined because it has to be produced yet. Thus we can't use it.
6802     2) on execution of an INSERT ... SELECT statement the save_in_field()
6803     function will be called to fill the data in the new record. If the SELECT
6804     part uses a tmp table then the result field is defined and should be
6805     used in order to get the correct result.
6806 
6807     The difference between the SET_USER_VAR function and regular functions
6808     like CONCAT is that the Item_func objects for the regular functions are
6809     replaced by Item_field objects after the values of these functions have
6810     been stored in a tmp table. Yet an object of the Item_field class cannot
6811     be used to update a user variable.
6812     Due to this we have to handle the result field in a special way here and
6813     in the Item_func_set_user_var::send() function.
6814 
6815   RETURN VALUES
6816     FALSE       Ok
6817     TRUE        Error
6818 */
6819 
6820 type_conversion_status
save_in_field(Field * field,bool no_conversions,bool can_use_result_field)6821 Item_func_set_user_var::save_in_field(Field *field, bool no_conversions,
6822                                       bool can_use_result_field)
6823 {
6824   bool use_result_field= (!can_use_result_field ? 0 :
6825                           (result_field && result_field != field));
6826   type_conversion_status error;
6827 
6828   /* Update the value of the user variable */
6829   check(use_result_field);
6830   update();
6831 
6832   if (result_type() == STRING_RESULT ||
6833       (result_type() == REAL_RESULT &&
6834       field->result_type() == STRING_RESULT))
6835   {
6836     String *result;
6837     const CHARSET_INFO *cs= collation.collation;
6838     char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
6839     str_value.set_quick(buff, sizeof(buff), cs);
6840     result= entry->val_str(&null_value, &str_value, decimals);
6841 
6842     if (null_value)
6843     {
6844       str_value.set_quick(0, 0, cs);
6845       return set_field_to_null_with_conversions(field, no_conversions);
6846     }
6847 
6848     /* NOTE: If null_value == FALSE, "result" must be not NULL.  */
6849 
6850     field->set_notnull();
6851     error=field->store(result->ptr(),result->length(),cs);
6852     str_value.set_quick(0, 0, cs);
6853   }
6854   else if (result_type() == REAL_RESULT)
6855   {
6856     double nr= entry->val_real(&null_value);
6857     if (null_value)
6858       return set_field_to_null(field);
6859     field->set_notnull();
6860     error=field->store(nr);
6861   }
6862   else if (result_type() == DECIMAL_RESULT)
6863   {
6864     my_decimal decimal_value;
6865     my_decimal *val= entry->val_decimal(&null_value, &decimal_value);
6866     if (null_value)
6867       return set_field_to_null(field);
6868     field->set_notnull();
6869     error=field->store_decimal(val);
6870   }
6871   else
6872   {
6873     longlong nr= entry->val_int(&null_value);
6874     if (null_value)
6875       return set_field_to_null_with_conversions(field, no_conversions);
6876     field->set_notnull();
6877     error=field->store(nr, unsigned_flag);
6878   }
6879   return error;
6880 }
6881 
6882 
6883 String *
val_str(String * str)6884 Item_func_get_user_var::val_str(String *str)
6885 {
6886   assert(fixed == 1);
6887   DBUG_ENTER("Item_func_get_user_var::val_str");
6888   if (!var_entry)
6889     DBUG_RETURN((String*) 0);			// No such variable
6890   String *res= var_entry->val_str(&null_value, str, decimals);
6891   DBUG_RETURN(res);
6892 }
6893 
6894 
val_real()6895 double Item_func_get_user_var::val_real()
6896 {
6897   assert(fixed == 1);
6898   if (!var_entry)
6899     return 0.0;					// No such variable
6900   return (var_entry->val_real(&null_value));
6901 }
6902 
6903 
val_decimal(my_decimal * dec)6904 my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec)
6905 {
6906   assert(fixed == 1);
6907   if (!var_entry)
6908     return 0;
6909   return var_entry->val_decimal(&null_value, dec);
6910 }
6911 
6912 
val_int()6913 longlong Item_func_get_user_var::val_int()
6914 {
6915   assert(fixed == 1);
6916   if (!var_entry)
6917     return 0LL;				// No such variable
6918   return (var_entry->val_int(&null_value));
6919 }
6920 
6921 
6922 /**
6923   Get variable by name and, if necessary, put the record of variable
6924   use into the binary log.
6925 
6926   When a user variable is invoked from an update query (INSERT, UPDATE etc),
6927   stores this variable and its value in thd->user_var_events, so that it can be
6928   written to the binlog (will be written just before the query is written, see
6929   log.cc).
6930 
6931   @param      thd        Current thread
6932   @param      name       Variable name
6933   @param[out] out_entry  variable structure or NULL. The pointer is set
6934                          regardless of whether function succeeded or not.
6935 
6936   @retval
6937     0  OK
6938   @retval
6939     1  Failed to put appropriate record into binary log
6940 
6941 */
6942 
6943 static int
get_var_with_binlog(THD * thd,enum_sql_command sql_command,Name_string & name,user_var_entry ** out_entry)6944 get_var_with_binlog(THD *thd, enum_sql_command sql_command,
6945                     Name_string &name, user_var_entry **out_entry)
6946 {
6947   BINLOG_USER_VAR_EVENT *user_var_event;
6948   user_var_entry *var_entry;
6949 
6950   /* Protects thd->user_vars. */
6951   mysql_mutex_lock(&thd->LOCK_thd_data);
6952   var_entry= get_variable(thd, name, NULL);
6953   mysql_mutex_unlock(&thd->LOCK_thd_data);
6954 
6955   /*
6956     Any reference to user-defined variable which is done from stored
6957     function or trigger affects their execution and the execution of the
6958     calling statement. We must log all such variables even if they are
6959     not involved in table-updating statements.
6960   */
6961   if (!(opt_bin_log &&
6962        (is_update_query(sql_command) || thd->in_sub_stmt)))
6963   {
6964     *out_entry= var_entry;
6965     return 0;
6966   }
6967 
6968   if (!var_entry)
6969   {
6970     /*
6971       If the variable does not exist, it's NULL, but we want to create it so
6972       that it gets into the binlog (if it didn't, the slave could be
6973       influenced by a variable of the same name previously set by another
6974       thread).
6975       We create it like if it had been explicitly set with SET before.
6976       The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'.
6977       sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION'
6978       in dispatch_command()). Instead of building a one-element list to pass to
6979       sql_set_variables(), we could instead manually call check() and update();
6980       this would save memory and time; but calling sql_set_variables() makes
6981       one unique place to maintain (sql_set_variables()).
6982 
6983       Manipulation with lex is necessary since free_underlaid_joins
6984       is going to release memory belonging to the main query.
6985     */
6986 
6987     List<set_var_base> tmp_var_list;
6988     LEX *sav_lex= thd->lex, lex_tmp;
6989     thd->lex= &lex_tmp;
6990     lex_start(thd);
6991     tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
6992                                                                        new Item_null(),
6993                                                                        false)));
6994     /* Create the variable */
6995     if (sql_set_variables(thd, &tmp_var_list))
6996     {
6997       thd->lex= sav_lex;
6998       goto err;
6999     }
7000     thd->lex= sav_lex;
7001     mysql_mutex_lock(&thd->LOCK_thd_data);
7002     var_entry= get_variable(thd, name, NULL);
7003     mysql_mutex_unlock(&thd->LOCK_thd_data);
7004 
7005     if (var_entry == NULL)
7006       goto err;
7007   }
7008   else if (var_entry->used_query_id == thd->query_id ||
7009            mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id))
7010   {
7011     /*
7012        If this variable was already stored in user_var_events by this query
7013        (because it's used in more than one place in the query), don't store
7014        it.
7015     */
7016     *out_entry= var_entry;
7017     return 0;
7018   }
7019 
7020   size_t size;
7021   /*
7022     First we need to store value of var_entry, when the next situation
7023     appears:
7024     > set @a:=1;
7025     > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
7026     We have to write to binlog value @a= 1.
7027 
7028     We allocate the user_var_event on user_var_events_alloc pool, not on
7029     the this-statement-execution pool because in SPs user_var_event objects
7030     may need to be valid after current [SP] statement execution pool is
7031     destroyed.
7032   */
7033   size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length();
7034   if (!(user_var_event= (BINLOG_USER_VAR_EVENT *)
7035         alloc_root(thd->user_var_events_alloc, size)))
7036     goto err;
7037 
7038   user_var_event->value= (char*) user_var_event +
7039     ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT));
7040   user_var_event->user_var_event= var_entry;
7041   user_var_event->type= var_entry->type();
7042   user_var_event->charset_number= var_entry->collation.collation->number;
7043   user_var_event->unsigned_flag= var_entry->unsigned_flag;
7044   if (!var_entry->ptr())
7045   {
7046     /* NULL value*/
7047     user_var_event->length= 0;
7048     user_var_event->value= 0;
7049   }
7050   else
7051   {
7052     // Avoid memcpy of a my_decimal object, use copy CTOR instead.
7053     user_var_event->length= var_entry->length();
7054     if (user_var_event->type == DECIMAL_RESULT)
7055     {
7056       assert(var_entry->length() == sizeof(my_decimal));
7057       const my_decimal* dec=
7058         static_cast<const my_decimal*>
7059         (static_cast<const void*>(var_entry->ptr()));
7060       dec->sanity_check();
7061       new (user_var_event->value) my_decimal(*dec);
7062     }
7063     else
7064       memcpy(user_var_event->value, var_entry->ptr(),
7065              var_entry->length());
7066   }
7067   /* Mark that this variable has been used by this query */
7068   var_entry->used_query_id= thd->query_id;
7069   if (thd->user_var_events.push_back(user_var_event))
7070     goto err;
7071 
7072   *out_entry= var_entry;
7073   return 0;
7074 
7075 err:
7076   *out_entry= var_entry;
7077   return 1;
7078 }
7079 
fix_length_and_dec()7080 void Item_func_get_user_var::fix_length_and_dec()
7081 {
7082   THD *thd=current_thd;
7083   int error;
7084   maybe_null=1;
7085   decimals=NOT_FIXED_DEC;
7086   max_length=MAX_BLOB_WIDTH;
7087 
7088   error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry);
7089 
7090   /*
7091     If the variable didn't exist it has been created as a STRING-type.
7092     'var_entry' is NULL only if there occurred an error during the call to
7093     get_var_with_binlog.
7094   */
7095   if (!error && var_entry)
7096   {
7097     m_cached_result_type= var_entry->type();
7098     unsigned_flag= var_entry->unsigned_flag;
7099     max_length= var_entry->length();
7100 
7101     collation.set(var_entry->collation);
7102     switch(m_cached_result_type) {
7103     case REAL_RESULT:
7104       fix_char_length(DBL_DIG + 8);
7105       break;
7106     case INT_RESULT:
7107       fix_char_length(MAX_BIGINT_WIDTH);
7108       decimals=0;
7109       break;
7110     case STRING_RESULT:
7111       max_length= MAX_BLOB_WIDTH - 1;
7112       break;
7113     case DECIMAL_RESULT:
7114       fix_char_length(DECIMAL_MAX_STR_LENGTH);
7115       decimals= DECIMAL_MAX_SCALE;
7116       break;
7117     case ROW_RESULT:                            // Keep compiler happy
7118     default:
7119       assert(0);
7120       break;
7121     }
7122   }
7123   else
7124   {
7125     collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
7126     null_value= 1;
7127     m_cached_result_type= STRING_RESULT;
7128     max_length= MAX_BLOB_WIDTH;
7129   }
7130 }
7131 
7132 
const_item() const7133 bool Item_func_get_user_var::const_item() const
7134 {
7135   return (!var_entry || current_thd->query_id != var_entry->update_query_id);
7136 }
7137 
7138 
result_type() const7139 enum Item_result Item_func_get_user_var::result_type() const
7140 {
7141   return m_cached_result_type;
7142 }
7143 
7144 
print(String * str,enum_query_type query_type)7145 void Item_func_get_user_var::print(String *str, enum_query_type query_type)
7146 {
7147   str->append(STRING_WITH_LEN("(@"));
7148   append_identifier(current_thd, str, name);
7149   str->append(')');
7150 }
7151 
7152 
eq(const Item * item,bool binary_cmp) const7153 bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
7154 {
7155   /* Assume we don't have rtti */
7156   if (this == item)
7157     return 1;					// Same item is same.
7158   /* Check if other type is also a get_user_var() object */
7159   if (item->type() != FUNC_ITEM ||
7160       ((Item_func*) item)->functype() != functype())
7161     return 0;
7162   Item_func_get_user_var *other=(Item_func_get_user_var*) item;
7163   return name.eq_bin(other->name);
7164 }
7165 
7166 
set_value(THD * thd,sp_rcontext *,Item ** it)7167 bool Item_func_get_user_var::set_value(THD *thd,
7168                                        sp_rcontext * /*ctx*/, Item **it)
7169 {
7170   Item_func_set_user_var *suv= new Item_func_set_user_var(name, *it, false);
7171   /*
7172     Item_func_set_user_var is not fixed after construction, call
7173     fix_fields().
7174   */
7175   return (!suv || suv->fix_fields(thd, it) || suv->check(0) || suv->update());
7176 }
7177 
7178 
fix_fields(THD * thd,Item ** ref)7179 bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref)
7180 {
7181   assert(fixed == 0);
7182   assert(thd->lex->exchange);
7183   /*
7184     Let us set the same collation which is used for loading
7185     of fields in LOAD DATA INFILE.
7186     (Since Item_user_var_as_out_param is used only there).
7187   */
7188   const CHARSET_INFO *cs= thd->lex->exchange->cs ?
7189     thd->lex->exchange->cs : thd->variables.collation_database;
7190 
7191   if (Item::fix_fields(thd, ref))
7192     return true;
7193 
7194   /* Protects thd->user_vars. */
7195   mysql_mutex_lock(&thd->LOCK_thd_data);
7196   entry= get_variable(thd, name, cs);
7197   if (entry != NULL)
7198   {
7199     entry->set_type(STRING_RESULT);
7200     entry->update_query_id= thd->query_id;
7201   }
7202   mysql_mutex_unlock(&thd->LOCK_thd_data);
7203 
7204   if (entry == NULL)
7205     return true;
7206 
7207   return false;
7208 }
7209 
7210 
set_null_value(const CHARSET_INFO * cs)7211 void Item_user_var_as_out_param::set_null_value(const CHARSET_INFO* cs)
7212 {
7213   entry->lock();
7214   entry->set_null_value(STRING_RESULT);
7215   entry->unlock();
7216 }
7217 
7218 
set_value(const char * str,size_t length,const CHARSET_INFO * cs)7219 void Item_user_var_as_out_param::set_value(const char *str, size_t length,
7220                                            const CHARSET_INFO* cs)
7221 {
7222   entry->lock();
7223   entry->store((void*) str, length, STRING_RESULT, cs,
7224                DERIVATION_IMPLICIT, 0 /* unsigned_arg */);
7225   entry->unlock();
7226 }
7227 
7228 
val_real()7229 double Item_user_var_as_out_param::val_real()
7230 {
7231   assert(0);
7232   return 0.0;
7233 }
7234 
7235 
val_int()7236 longlong Item_user_var_as_out_param::val_int()
7237 {
7238   assert(0);
7239   return 0;
7240 }
7241 
7242 
val_str(String * str)7243 String* Item_user_var_as_out_param::val_str(String *str)
7244 {
7245   assert(0);
7246   return 0;
7247 }
7248 
7249 
val_decimal(my_decimal * decimal_buffer)7250 my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer)
7251 {
7252   assert(0);
7253   return 0;
7254 }
7255 
7256 
print(String * str,enum_query_type query_type)7257 void Item_user_var_as_out_param::print(String *str, enum_query_type query_type)
7258 {
7259   str->append('@');
7260   append_identifier(current_thd, str, name);
7261 }
7262 
7263 
7264 Item_func_get_system_var::
Item_func_get_system_var(sys_var * var_arg,enum_var_type var_type_arg,LEX_STRING * component_arg,const char * name_arg,size_t name_len_arg)7265 Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg,
7266                        LEX_STRING *component_arg, const char *name_arg,
7267                        size_t name_len_arg)
7268   :var(NULL), var_type(var_type_arg), orig_var_type(var_type_arg),
7269   component(*component_arg), cache_present(0),
7270   var_tracker(var_arg)
7271 {
7272   /* copy() will allocate the name */
7273   item_name.copy(name_arg, (uint) name_len_arg);
7274 }
7275 
7276 
update_null_value()7277 void Item_func_get_system_var::update_null_value()
7278 {
7279   THD *thd= current_thd;
7280   int save_no_errors= thd->no_errors;
7281   thd->no_errors= TRUE;
7282   Item::update_null_value();
7283   thd->no_errors= save_no_errors;
7284 }
7285 
7286 
fix_length_and_dec()7287 void Item_func_get_system_var::fix_length_and_dec()
7288 {
7289   char *cptr;
7290   maybe_null= TRUE;
7291   max_length= 0;
7292 
7293   THD *const thd= current_thd;
7294 
7295   DEBUG_SYNC(current_thd, "after_error_checking");
7296 
7297   assert(var == NULL);
7298   var= var_tracker.bind_system_variable(thd);
7299   if (var == NULL)
7300     return;
7301 
7302   if (!var->check_scope(var_type))
7303   {
7304     if (var_type != OPT_DEFAULT)
7305     {
7306       my_error(ER_INCORRECT_GLOBAL_LOCAL_VAR, MYF(0),
7307                var->name.str, var_type == OPT_GLOBAL ? "SESSION" : "GLOBAL");
7308       return;
7309     }
7310     /* As there was no local variable, return the global value */
7311     var_type= OPT_GLOBAL;
7312   }
7313 
7314   switch (var->show_type())
7315   {
7316     case SHOW_LONG:
7317     case SHOW_INT:
7318     case SHOW_HA_ROWS:
7319     case SHOW_LONGLONG:
7320       unsigned_flag= TRUE;
7321       collation.set_numeric();
7322       fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS);
7323       decimals=0;
7324       break;
7325     case SHOW_SIGNED_LONG:
7326       unsigned_flag= FALSE;
7327       collation.set_numeric();
7328       fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS);
7329       decimals=0;
7330       break;
7331     case SHOW_CHAR:
7332     case SHOW_CHAR_PTR:
7333       mysql_mutex_lock(&LOCK_global_system_variables);
7334       cptr= var->show_type() == SHOW_CHAR ?
7335         (char*) var->value_ptr(thd, var_type, &component) :
7336         *(char**) var->value_ptr(thd, var_type, &component);
7337       if (cptr)
7338         max_length= system_charset_info->cset->numchars(system_charset_info,
7339                                                         cptr,
7340                                                         cptr + strlen(cptr));
7341       mysql_mutex_unlock(&LOCK_global_system_variables);
7342       collation.set(system_charset_info, DERIVATION_SYSCONST);
7343       max_length*= system_charset_info->mbmaxlen;
7344       decimals=NOT_FIXED_DEC;
7345       break;
7346     case SHOW_LEX_STRING:
7347       {
7348         mysql_mutex_lock(&LOCK_global_system_variables);
7349         LEX_STRING *ls= ((LEX_STRING*)var->value_ptr(thd, var_type, &component));
7350         max_length= system_charset_info->cset->numchars(system_charset_info,
7351                                                         ls->str,
7352                                                         ls->str + ls->length);
7353         mysql_mutex_unlock(&LOCK_global_system_variables);
7354         collation.set(system_charset_info, DERIVATION_SYSCONST);
7355         max_length*= system_charset_info->mbmaxlen;
7356         decimals=NOT_FIXED_DEC;
7357       }
7358       break;
7359     case SHOW_BOOL:
7360     case SHOW_MY_BOOL:
7361       unsigned_flag= FALSE;
7362       collation.set_numeric();
7363       fix_char_length(1);
7364       decimals=0;
7365       break;
7366     case SHOW_DOUBLE:
7367       unsigned_flag= FALSE;
7368       decimals= 6;
7369       collation.set_numeric();
7370       fix_char_length(DBL_DIG + 6);
7371       break;
7372     default:
7373       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7374       break;
7375   }
7376 }
7377 
7378 
print(String * str,enum_query_type query_type)7379 void Item_func_get_system_var::print(String *str, enum_query_type query_type)
7380 {
7381   str->append(item_name);
7382 }
7383 
7384 
result_type() const7385 enum Item_result Item_func_get_system_var::result_type() const
7386 {
7387   switch (var->show_type())
7388   {
7389     case SHOW_BOOL:
7390     case SHOW_MY_BOOL:
7391     case SHOW_INT:
7392     case SHOW_LONG:
7393     case SHOW_SIGNED_LONG:
7394     case SHOW_LONGLONG:
7395     case SHOW_HA_ROWS:
7396       return INT_RESULT;
7397     case SHOW_CHAR:
7398     case SHOW_CHAR_PTR:
7399     case SHOW_LEX_STRING:
7400       return STRING_RESULT;
7401     case SHOW_DOUBLE:
7402       return REAL_RESULT;
7403     default:
7404       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7405       return STRING_RESULT;                   // keep the compiler happy
7406   }
7407 }
7408 
7409 
field_type() const7410 enum_field_types Item_func_get_system_var::field_type() const
7411 {
7412   switch (var->show_type())
7413   {
7414     case SHOW_BOOL:
7415     case SHOW_MY_BOOL:
7416     case SHOW_INT:
7417     case SHOW_LONG:
7418     case SHOW_SIGNED_LONG:
7419     case SHOW_LONGLONG:
7420     case SHOW_HA_ROWS:
7421       return MYSQL_TYPE_LONGLONG;
7422     case SHOW_CHAR:
7423     case SHOW_CHAR_PTR:
7424     case SHOW_LEX_STRING:
7425       return MYSQL_TYPE_VARCHAR;
7426     case SHOW_DOUBLE:
7427       return MYSQL_TYPE_DOUBLE;
7428     default:
7429       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7430       return MYSQL_TYPE_VARCHAR;              // keep the compiler happy
7431   }
7432 }
7433 
7434 
7435 /*
7436   Uses var, var_type, component, cache_present, used_query_id, thd,
7437   cached_llval, null_value, cached_null_value
7438 */
7439 #define get_sys_var_safe(type) \
7440 do { \
7441   type value; \
7442   mysql_mutex_lock(&LOCK_global_system_variables); \
7443   value= *(type*) var->value_ptr(thd, var_type, &component); \
7444   mysql_mutex_unlock(&LOCK_global_system_variables); \
7445   cache_present |= GET_SYS_VAR_CACHE_LONG; \
7446   used_query_id= thd->query_id; \
7447   cached_llval= null_value ? 0 : (longlong) value; \
7448   cached_null_value= null_value; \
7449   return cached_llval; \
7450 } while (0)
7451 
7452 
val_int()7453 longlong Item_func_get_system_var::val_int()
7454 {
7455   THD *thd= current_thd;
7456 
7457   assert(var != NULL);
7458 
7459   if (cache_present && thd->query_id == used_query_id)
7460   {
7461     if (cache_present & GET_SYS_VAR_CACHE_LONG)
7462     {
7463       null_value= cached_null_value;
7464       return cached_llval;
7465     }
7466     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7467     {
7468       null_value= cached_null_value;
7469       cached_llval= (longlong) cached_dval;
7470       cache_present|= GET_SYS_VAR_CACHE_LONG;
7471       return cached_llval;
7472     }
7473     else if (cache_present & GET_SYS_VAR_CACHE_STRING)
7474     {
7475       null_value= cached_null_value;
7476       if (!null_value)
7477         cached_llval= longlong_from_string_with_check (cached_strval.charset(),
7478                                                        cached_strval.c_ptr(),
7479                                                        cached_strval.c_ptr() +
7480                                                        cached_strval.length());
7481       else
7482         cached_llval= 0;
7483       cache_present|= GET_SYS_VAR_CACHE_LONG;
7484       return cached_llval;
7485     }
7486   }
7487 
7488   switch (var->show_type())
7489   {
7490     case SHOW_INT:      get_sys_var_safe (uint);
7491     case SHOW_LONG:     get_sys_var_safe (ulong);
7492     case SHOW_SIGNED_LONG: get_sys_var_safe (long);
7493     case SHOW_LONGLONG: get_sys_var_safe (ulonglong);
7494     case SHOW_HA_ROWS:  get_sys_var_safe (ha_rows);
7495     case SHOW_BOOL:     get_sys_var_safe (bool);
7496     case SHOW_MY_BOOL:  get_sys_var_safe (my_bool);
7497     case SHOW_DOUBLE:
7498       {
7499         double dval= val_real();
7500 
7501         used_query_id= thd->query_id;
7502         cached_llval= (longlong) dval;
7503         cache_present|= GET_SYS_VAR_CACHE_LONG;
7504         return cached_llval;
7505       }
7506     case SHOW_CHAR:
7507     case SHOW_CHAR_PTR:
7508     case SHOW_LEX_STRING:
7509       {
7510         String *str_val= val_str(NULL);
7511         // Treat empty strings as NULL, like val_real() does.
7512         if (str_val && str_val->length())
7513           cached_llval= longlong_from_string_with_check (system_charset_info,
7514                                                           str_val->c_ptr(),
7515                                                           str_val->c_ptr() +
7516                                                           str_val->length());
7517         else
7518         {
7519           null_value= TRUE;
7520           cached_llval= 0;
7521         }
7522 
7523         cache_present|= GET_SYS_VAR_CACHE_LONG;
7524         return cached_llval;
7525       }
7526 
7527     default:
7528       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7529       return 0;                               // keep the compiler happy
7530   }
7531 }
7532 
7533 
val_str(String * str)7534 String* Item_func_get_system_var::val_str(String* str)
7535 {
7536   THD *thd= current_thd;
7537 
7538   assert(var != NULL);
7539 
7540   if (cache_present && thd->query_id == used_query_id)
7541   {
7542     if (cache_present & GET_SYS_VAR_CACHE_STRING)
7543     {
7544       null_value= cached_null_value;
7545       return null_value ? NULL : &cached_strval;
7546     }
7547     else if (cache_present & GET_SYS_VAR_CACHE_LONG)
7548     {
7549       null_value= cached_null_value;
7550       if (!null_value)
7551         cached_strval.set (cached_llval, collation.collation);
7552       cache_present|= GET_SYS_VAR_CACHE_STRING;
7553       return null_value ? NULL : &cached_strval;
7554     }
7555     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7556     {
7557       null_value= cached_null_value;
7558       if (!null_value)
7559         cached_strval.set_real (cached_dval, decimals, collation.collation);
7560       cache_present|= GET_SYS_VAR_CACHE_STRING;
7561       return null_value ? NULL : &cached_strval;
7562     }
7563   }
7564 
7565   str= &cached_strval;
7566   null_value= FALSE;
7567   switch (var->show_type())
7568   {
7569     case SHOW_CHAR:
7570     case SHOW_CHAR_PTR:
7571     case SHOW_LEX_STRING:
7572     {
7573       mysql_mutex_lock(&LOCK_global_system_variables);
7574       char *cptr= var->show_type() == SHOW_CHAR ?
7575         (char*) var->value_ptr(thd, var_type, &component) :
7576         *(char**) var->value_ptr(thd, var_type, &component);
7577       if (cptr)
7578       {
7579         size_t len= var->show_type() == SHOW_LEX_STRING ?
7580           ((LEX_STRING*)(var->value_ptr(thd, var_type, &component)))->length :
7581           strlen(cptr);
7582         if (str->copy(cptr, len, collation.collation))
7583         {
7584           null_value= TRUE;
7585           str= NULL;
7586         }
7587       }
7588       else
7589       {
7590         null_value= TRUE;
7591         str= NULL;
7592       }
7593       mysql_mutex_unlock(&LOCK_global_system_variables);
7594       break;
7595     }
7596 
7597     case SHOW_INT:
7598     case SHOW_LONG:
7599     case SHOW_SIGNED_LONG:
7600     case SHOW_LONGLONG:
7601     case SHOW_HA_ROWS:
7602     case SHOW_BOOL:
7603     case SHOW_MY_BOOL:
7604       str->set (val_int(), collation.collation);
7605       break;
7606     case SHOW_DOUBLE:
7607       str->set_real (val_real(), decimals, collation.collation);
7608       break;
7609 
7610     default:
7611       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7612       str= error_str();
7613       break;
7614   }
7615 
7616   cache_present|= GET_SYS_VAR_CACHE_STRING;
7617   used_query_id= thd->query_id;
7618   cached_null_value= null_value;
7619   return str;
7620 }
7621 
7622 
val_real()7623 double Item_func_get_system_var::val_real()
7624 {
7625   THD *thd= current_thd;
7626 
7627   assert(var != NULL);
7628 
7629   if (cache_present && thd->query_id == used_query_id)
7630   {
7631     if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7632     {
7633       null_value= cached_null_value;
7634       return cached_dval;
7635     }
7636     else if (cache_present & GET_SYS_VAR_CACHE_LONG)
7637     {
7638       null_value= cached_null_value;
7639       cached_dval= (double)cached_llval;
7640       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7641       return cached_dval;
7642     }
7643     else if (cache_present & GET_SYS_VAR_CACHE_STRING)
7644     {
7645       null_value= cached_null_value;
7646       if (!null_value)
7647         cached_dval= double_from_string_with_check (cached_strval.charset(),
7648                                                     cached_strval.c_ptr(),
7649                                                     cached_strval.c_ptr() +
7650                                                     cached_strval.length());
7651       else
7652         cached_dval= 0;
7653       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7654       return cached_dval;
7655     }
7656   }
7657 
7658   switch (var->show_type())
7659   {
7660     case SHOW_DOUBLE:
7661       mysql_mutex_lock(&LOCK_global_system_variables);
7662       cached_dval= *(double*) var->value_ptr(thd, var_type, &component);
7663       mysql_mutex_unlock(&LOCK_global_system_variables);
7664       used_query_id= thd->query_id;
7665       cached_null_value= null_value;
7666       if (null_value)
7667         cached_dval= 0;
7668       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7669       return cached_dval;
7670     case SHOW_CHAR:
7671     case SHOW_LEX_STRING:
7672     case SHOW_CHAR_PTR:
7673       {
7674         mysql_mutex_lock(&LOCK_global_system_variables);
7675         char *cptr= var->show_type() == SHOW_CHAR ?
7676           (char*) var->value_ptr(thd, var_type, &component) :
7677           *(char**) var->value_ptr(thd, var_type, &component);
7678         // Treat empty strings as NULL, like val_int() does.
7679         if (cptr && *cptr)
7680           cached_dval= double_from_string_with_check (system_charset_info,
7681                                                 cptr, cptr + strlen (cptr));
7682         else
7683         {
7684           null_value= TRUE;
7685           cached_dval= 0;
7686         }
7687         mysql_mutex_unlock(&LOCK_global_system_variables);
7688         used_query_id= thd->query_id;
7689         cached_null_value= null_value;
7690         cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7691         return cached_dval;
7692       }
7693     case SHOW_INT:
7694     case SHOW_LONG:
7695     case SHOW_SIGNED_LONG:
7696     case SHOW_LONGLONG:
7697     case SHOW_HA_ROWS:
7698     case SHOW_BOOL:
7699     case SHOW_MY_BOOL:
7700         cached_dval= (double) val_int();
7701         cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7702         used_query_id= thd->query_id;
7703         cached_null_value= null_value;
7704         return cached_dval;
7705     default:
7706       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7707       return 0;
7708   }
7709 }
7710 
7711 
eq(const Item * item,bool binary_cmp) const7712 bool Item_func_get_system_var::eq(const Item *item, bool binary_cmp) const
7713 {
7714   /* Assume we don't have rtti */
7715   if (this == item)
7716     return 1;					// Same item is same.
7717   /* Check if other type is also a get_user_var() object */
7718   if (item->type() != FUNC_ITEM ||
7719       ((Item_func*) item)->functype() != functype())
7720     return 0;
7721   Item_func_get_system_var *other=(Item_func_get_system_var*) item;
7722   return (var_tracker == other->var_tracker && var_type == other->var_type);
7723 }
7724 
7725 
cleanup()7726 void Item_func_get_system_var::cleanup()
7727 {
7728   Item_func::cleanup();
7729   cache_present= 0;
7730   var_type= orig_var_type;
7731   cached_strval.mem_free();
7732   var= NULL;
7733 }
7734 
7735 
itemize(Parse_context * pc,Item ** res)7736 bool Item_func_match::itemize(Parse_context *pc, Item **res)
7737 {
7738   if (skip_itemize(res))
7739     return false;
7740   if (super::itemize(pc, res) || against->itemize(pc, &against))
7741     return true;
7742   with_sum_func|= against->with_sum_func;
7743 
7744   pc->select->add_ftfunc_to_list(this);
7745   pc->thd->lex->set_using_match();
7746 
7747   switch (pc->select->parsing_place)
7748   {
7749     case CTX_WHERE:
7750     case CTX_ON:
7751       used_in_where_only= true;
7752       break;
7753     default:
7754       used_in_where_only= false;
7755   }
7756 
7757   return false;
7758 }
7759 
7760 
7761 /**
7762   Initialize searching within full-text index.
7763 
7764   @param thd    Thread handler
7765 
7766   @returns false if success, true if error
7767 */
7768 
init_search(THD * thd)7769 bool Item_func_match::init_search(THD *thd)
7770 {
7771   DBUG_ENTER("Item_func_match::init_search");
7772 
7773   /*
7774     We will skip execution if the item is not fixed
7775     with fix_field
7776   */
7777   if (!fixed)
7778     DBUG_RETURN(false);
7779 
7780   TABLE *const table= table_ref->table;
7781   /* Check if init_search() has been called before */
7782   if (ft_handler && !master)
7783   {
7784     /*
7785       We should reset ft_handler as it is cleaned up
7786       on destruction of FT_SELECT object
7787       (necessary in case of re-execution of subquery).
7788       TODO: FT_SELECT should not clean up ft_handler.
7789     */
7790     if (join_key)
7791       table->file->ft_handler= ft_handler;
7792     DBUG_RETURN(false);
7793   }
7794 
7795   if (key == NO_SUCH_KEY)
7796   {
7797     List<Item> fields;
7798     if (fields.push_back(new Item_string(" ",1, cmp_collation.collation)))
7799       DBUG_RETURN(true);
7800     for (uint i= 0; i < arg_count; i++)
7801       fields.push_back(args[i]);
7802     concat_ws=new Item_func_concat_ws(fields);
7803     if (concat_ws == NULL)
7804       DBUG_RETURN(true);
7805     /*
7806       Above function used only to get value and do not need fix_fields for it:
7807       Item_string - basic constant
7808       fields - fix_fields() was already called for this arguments
7809       Item_func_concat_ws - do not need fix_fields() to produce value
7810     */
7811     concat_ws->quick_fix_field();
7812   }
7813 
7814   if (master)
7815   {
7816     if (master->init_search(thd))
7817       DBUG_RETURN(true);
7818 
7819     ft_handler=master->ft_handler;
7820     DBUG_RETURN(false);
7821   }
7822 
7823   String *ft_tmp= 0;
7824 
7825   // MATCH ... AGAINST (NULL) is meaningless, but possible
7826   if (!(ft_tmp=key_item()->val_str(&value)))
7827   {
7828     ft_tmp= &value;
7829     value.set("",0,cmp_collation.collation);
7830   }
7831 
7832   if (ft_tmp->charset() != cmp_collation.collation)
7833   {
7834     uint dummy_errors;
7835     search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
7836                       cmp_collation.collation, &dummy_errors);
7837     ft_tmp= &search_value;
7838   }
7839 
7840   if (!table->is_created())
7841   {
7842      my_error(ER_NO_FT_MATERIALIZED_SUBQUERY, MYF(0));
7843      DBUG_RETURN(true);
7844   }
7845 
7846   assert(master == NULL);
7847   ft_handler= table->file->ft_init_ext_with_hints(key, ft_tmp, get_hints());
7848   if (thd->is_error())
7849     DBUG_RETURN(true);
7850 
7851   if (join_key)
7852     table->file->ft_handler=ft_handler;
7853 
7854   DBUG_RETURN(false);
7855 }
7856 
7857 
get_filtering_effect(table_map filter_for_table,table_map read_tables,const MY_BITMAP * fields_to_ignore,double rows_in_table)7858 float Item_func_match::get_filtering_effect(table_map filter_for_table,
7859                                             table_map read_tables,
7860                                             const MY_BITMAP *fields_to_ignore,
7861                                             double rows_in_table)
7862 {
7863   const Item_field* fld=
7864     contributes_to_filter(read_tables, filter_for_table, fields_to_ignore);
7865   if (!fld)
7866     return COND_FILTER_ALLPASS;
7867 
7868   /*
7869     MATCH () ... AGAINST" is similar to "LIKE '...'" which has the
7870     same selectivity as "col BETWEEN ...".
7871   */
7872   return fld->get_cond_filter_default_probability(rows_in_table,
7873                                                   COND_FILTER_BETWEEN);
7874 }
7875 
7876 
7877 /**
7878    Add field into table read set.
7879 
7880    @param field field to be added to the table read set.
7881 */
update_table_read_set(Field * field)7882 static void update_table_read_set(Field *field)
7883 {
7884   TABLE *table= field->table;
7885 
7886   if (!bitmap_fast_test_and_set(table->read_set, field->field_index))
7887     table->covering_keys.intersect(field->part_of_key);
7888 }
7889 
7890 
fix_fields(THD * thd,Item ** ref)7891 bool Item_func_match::fix_fields(THD *thd, Item **ref)
7892 {
7893   assert(fixed == 0);
7894   assert(arg_count > 0);
7895   Item *item= NULL;                        // Safe as arg_count is > 1
7896 
7897   maybe_null=1;
7898   join_key=0;
7899 
7900   /*
7901     const_item is assumed in quite a bit of places, so it would be difficult
7902     to remove;  If it would ever to be removed, this should include
7903     modifications to find_best and auto_close as complement to auto_init code
7904     above.
7905   */
7906   enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
7907   /*
7908     Since different engines require different columns for FTS index lookup
7909     we prevent updating of table read_set in argument's ::fix_fields().
7910   */
7911   thd->mark_used_columns= MARK_COLUMNS_NONE;
7912   if (Item_func::fix_fields(thd, ref) ||
7913       fix_func_arg(thd, &against) || !against->const_during_execution())
7914   {
7915     thd->mark_used_columns= save_mark_used_columns;
7916     my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
7917     return TRUE;
7918   }
7919   thd->mark_used_columns= save_mark_used_columns;
7920 
7921   bool allows_multi_table_search= true;
7922   const_item_cache=0;
7923   for (uint i= 0 ; i < arg_count ; i++)
7924   {
7925     item= args[i]= args[i]->real_item();
7926     if (item->type() != Item::FIELD_ITEM ||
7927         /* Cannot use FTS index with outer table field */
7928         (item->used_tables() & OUTER_REF_TABLE_BIT))
7929     {
7930       my_error(ER_WRONG_ARGUMENTS, MYF(0), "MATCH");
7931       return TRUE;
7932     }
7933     allows_multi_table_search &=
7934       allows_search_on_non_indexed_columns(((Item_field *)item)->field->table);
7935   }
7936 
7937   /*
7938     Check that all columns come from the same table.
7939     We've already checked that columns in MATCH are fields so
7940     PARAM_TABLE_BIT can only appear from AGAINST argument.
7941   */
7942   if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
7943     key=NO_SUCH_KEY;
7944 
7945   if (key == NO_SUCH_KEY && !allows_multi_table_search)
7946   {
7947     my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
7948     return TRUE;
7949   }
7950   table_ref= ((Item_field *)item)->table_ref;
7951 
7952   /*
7953     Here we make an assumption that if the engine supports
7954     fulltext extension(HA_CAN_FULLTEXT_EXT flag) then table
7955     can have FTS_DOC_ID column. Atm this is the only way
7956     to distinguish MyISAM and InnoDB engines.
7957     Generally table_ref should be available, but in case of
7958     a generated column's generation expression it's not. Thus
7959     we use field's table, at this moment it's already available.
7960   */
7961   TABLE *const table= table_ref ?
7962     table_ref->table :
7963     ((Item_field *)item)->field->table;
7964 
7965   if (!(table->file->ha_table_flags() & HA_CAN_FULLTEXT))
7966   {
7967     my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
7968     return 1;
7969   }
7970 
7971   if ((table->file->ha_table_flags() & HA_CAN_FULLTEXT_EXT))
7972   {
7973     Field *doc_id_field= table->fts_doc_id_field;
7974     /*
7975       Update read set with FTS_DOC_ID column so that indexes that have
7976       FTS_DOC_ID part can be considered as a covering index.
7977     */
7978     if (doc_id_field)
7979       update_table_read_set(doc_id_field);
7980     else
7981     {
7982       /* read_set needs to be updated for MATCH arguments */
7983       for (uint i= 0; i < arg_count; i++)
7984         update_table_read_set(((Item_field*)args[i])->field);
7985       /*
7986         Prevent index only accces by non-FTS index if table does not have
7987         FTS_DOC_ID column, find_relevance does not work properly without
7988         FTS_DOC_ID value. Decision for FTS index about index only access
7989         is made later by JOIN::fts_index_access() function.
7990       */
7991       table->covering_keys.clear_all();
7992     }
7993 
7994   }
7995   else
7996   {
7997     /*
7998       Since read_set is not updated for MATCH arguments
7999       it's necessary to update it here for MyISAM.
8000     */
8001     for (uint i= 0; i < arg_count; i++)
8002       update_table_read_set(((Item_field*)args[i])->field);
8003   }
8004 
8005   table->fulltext_searched=1;
8006 
8007   if (!master)
8008   {
8009     Prepared_stmt_arena_holder ps_arena_holder(thd);
8010     hints= new Ft_hints(flags);
8011     if (!hints)
8012     {
8013       my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
8014       return true;
8015     }
8016   }
8017   return agg_item_collations_for_comparison(cmp_collation, func_name(),
8018                                             args, arg_count, 0);
8019 }
8020 
fix_index()8021 bool Item_func_match::fix_index()
8022 {
8023   Item_field *item;
8024   TABLE *table;
8025   uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
8026   uint max_cnt=0, mkeys=0, i;
8027 
8028   if (!table_ref)
8029     goto err;
8030 
8031   /*
8032     We will skip execution if the item is not fixed
8033     with fix_field
8034   */
8035   if (!fixed)
8036   {
8037     if (allows_search_on_non_indexed_columns(table_ref->table))
8038       key= NO_SUCH_KEY;
8039 
8040     return false;
8041   }
8042   if (key == NO_SUCH_KEY)
8043     return 0;
8044 
8045   table= table_ref->table;
8046   for (keynr=0 ; keynr < table->s->keys ; keynr++)
8047   {
8048     if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
8049         (flags & FT_BOOL ? table->keys_in_use_for_query.is_set(keynr) :
8050                            table->s->keys_in_use.is_set(keynr)))
8051 
8052     {
8053       ft_to_key[fts]=keynr;
8054       ft_cnt[fts]=0;
8055       fts++;
8056     }
8057   }
8058 
8059   if (!fts)
8060     goto err;
8061 
8062   for (i= 0; i < arg_count; i++)
8063   {
8064     item=(Item_field*)args[i];
8065     for (keynr=0 ; keynr < fts ; keynr++)
8066     {
8067       KEY *ft_key=&table->key_info[ft_to_key[keynr]];
8068       uint key_parts=ft_key->user_defined_key_parts;
8069 
8070       for (uint part=0 ; part < key_parts ; part++)
8071       {
8072 	if (item->field->eq(ft_key->key_part[part].field))
8073 	  ft_cnt[keynr]++;
8074       }
8075     }
8076   }
8077 
8078   for (keynr=0 ; keynr < fts ; keynr++)
8079   {
8080     if (ft_cnt[keynr] > max_cnt)
8081     {
8082       mkeys=0;
8083       max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
8084       ft_to_key[mkeys]=ft_to_key[keynr];
8085       continue;
8086     }
8087     if (max_cnt && ft_cnt[keynr] == max_cnt)
8088     {
8089       mkeys++;
8090       ft_cnt[mkeys]=ft_cnt[keynr];
8091       ft_to_key[mkeys]=ft_to_key[keynr];
8092       continue;
8093     }
8094   }
8095 
8096   for (keynr=0 ; keynr <= mkeys ; keynr++)
8097   {
8098     // partial keys doesn't work
8099     if (max_cnt < arg_count ||
8100         max_cnt < table->key_info[ft_to_key[keynr]].user_defined_key_parts)
8101       continue;
8102 
8103     key=ft_to_key[keynr];
8104 
8105     return 0;
8106   }
8107 
8108 err:
8109   if (table_ref != 0 && allows_search_on_non_indexed_columns(table_ref->table))
8110   {
8111     key=NO_SUCH_KEY;
8112     return 0;
8113   }
8114   my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
8115              ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
8116   return 1;
8117 }
8118 
8119 
eq(const Item * item,bool binary_cmp) const8120 bool Item_func_match::eq(const Item *item, bool binary_cmp) const
8121 {
8122   /* We ignore FT_SORTED flag when checking for equality since result is
8123      equvialent regardless of sorting */
8124   if (item->type() != FUNC_ITEM ||
8125       ((Item_func*)item)->functype() != FT_FUNC ||
8126       (flags | FT_SORTED) != (((Item_func_match*)item)->flags | FT_SORTED))
8127     return 0;
8128 
8129   Item_func_match *ifm=(Item_func_match*) item;
8130 
8131   if (key == ifm->key && table_ref == ifm->table_ref &&
8132       key_item()->eq(ifm->key_item(), binary_cmp))
8133     return 1;
8134 
8135   return 0;
8136 }
8137 
8138 
val_real()8139 double Item_func_match::val_real()
8140 {
8141   assert(fixed == 1);
8142   DBUG_ENTER("Item_func_match::val");
8143   if (ft_handler == NULL)
8144     DBUG_RETURN(-1.0);
8145 
8146   TABLE *const table= table_ref->table;
8147   if (key != NO_SUCH_KEY && table->has_null_row()) // NULL row from outer join
8148     DBUG_RETURN(0.0);
8149 
8150   if (get_master()->join_key)
8151   {
8152     if (table->file->ft_handler)
8153       DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
8154     get_master()->join_key= 0;
8155   }
8156 
8157   if (key == NO_SUCH_KEY)
8158   {
8159     String *a= concat_ws->val_str(&value);
8160     if ((null_value= (a == 0)) || !a->length())
8161       DBUG_RETURN(0);
8162     DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
8163 				      (uchar *)a->ptr(), a->length()));
8164   }
8165   DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
8166                                                  table->record[0], 0));
8167 }
8168 
print(String * str,enum_query_type query_type)8169 void Item_func_match::print(String *str, enum_query_type query_type)
8170 {
8171   str->append(STRING_WITH_LEN("(match "));
8172   print_args(str, 0, query_type);
8173   str->append(STRING_WITH_LEN(" against ("));
8174   against->print(str, query_type);
8175   if (flags & FT_BOOL)
8176     str->append(STRING_WITH_LEN(" in boolean mode"));
8177   else if (flags & FT_EXPAND)
8178     str->append(STRING_WITH_LEN(" with query expansion"));
8179   str->append(STRING_WITH_LEN("))"));
8180 }
8181 
8182 
8183 /**
8184   Function sets FT hints(LIMIT, flags) depending on
8185   various join conditions.
8186 
8187   @param join     Pointer to JOIN object.
8188   @param ft_flag  FT flag value.
8189   @param ft_limit Limit value.
8190   @param no_cond  true if MATCH is not used in WHERE condition.
8191 */
8192 
set_hints(JOIN * join,uint ft_flag,ha_rows ft_limit,bool no_cond)8193 void Item_func_match::set_hints(JOIN *join, uint ft_flag,
8194                                 ha_rows ft_limit, bool no_cond)
8195 {
8196   assert(!master);
8197 
8198   if (!join)  // used for count() optimization
8199   {
8200     hints->set_hint_flag(ft_flag);
8201     return;
8202   }
8203 
8204   /* skip hints setting if there are aggregates(except of FT_NO_RANKING) */
8205   if (join->implicit_grouping || join->group_list || join->select_distinct)
8206   {
8207     /* 'No ranking' is possibe even if aggregates are present */
8208     if ((ft_flag & FT_NO_RANKING))
8209       hints->set_hint_flag(FT_NO_RANKING);
8210     return;
8211   }
8212 
8213   hints->set_hint_flag(ft_flag);
8214 
8215   /**
8216     Only one table is used, there is no aggregates,
8217     WHERE condition is a single MATCH expression
8218     (WHERE MATCH(..) or WHERE MATCH(..) [>=,>] value) or
8219     there is no WHERE condition.
8220   */
8221   if (join->primary_tables == 1 && (no_cond || is_simple_expression()))
8222     hints->set_hint_limit(ft_limit);
8223 }
8224 
8225 
val_int()8226 longlong Item_func_bit_xor::val_int()
8227 {
8228   assert(fixed == 1);
8229   ulonglong arg1= (ulonglong) args[0]->val_int();
8230   ulonglong arg2= (ulonglong) args[1]->val_int();
8231   if ((null_value= (args[0]->null_value || args[1]->null_value)))
8232     return 0;
8233   return (longlong) (arg1 ^ arg2);
8234 }
8235 
8236 
8237 /***************************************************************************
8238   System variables
8239 ****************************************************************************/
8240 
8241 /**
8242   @class Silence_deprecation_warnings
8243 
8244   @brief Disable deprecation warnings handler class
8245 */
8246 class Silence_deprecation_warnings : public Internal_error_handler
8247 {
8248 public:
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_severity_level * level,const char * msg)8249   virtual bool handle_condition(THD *thd,
8250                                 uint sql_errno,
8251                                 const char* sqlstate,
8252                                 Sql_condition::enum_severity_level *level,
8253                                 const char* msg)
8254   {
8255     return sql_errno == ER_WARN_DEPRECATED_SYNTAX;
8256   }
8257 };
8258 
8259 /**
8260   Return value of an system variable base[.name] as a constant item.
8261 
8262   @param pc                     Current parse context
8263   @param var_type               global / session
8264   @param name                   Name of base or system variable
8265   @param component              Component.
8266 
8267   @param unsafe                 If true and if the variable is written to a
8268                                 binlog then mark the statement as unsafe.
8269 
8270   @note
8271     If component.str = 0 then the variable name is in 'name'
8272 
8273   @return
8274     - 0  : error
8275     - #  : constant item
8276 */
8277 
8278 
get_system_var(Parse_context * pc,enum_var_type var_type,LEX_STRING name,LEX_STRING component,bool unsafe)8279 Item *get_system_var(Parse_context *pc,
8280                      enum_var_type var_type, LEX_STRING name,
8281                      LEX_STRING component, bool unsafe)
8282 {
8283   THD *thd= pc->thd;
8284   sys_var *var;
8285   LEX_STRING *base_name, *component_name;
8286 
8287   if (component.str)
8288   {
8289     base_name= &component;
8290     component_name= &name;
8291   }
8292   else
8293   {
8294     base_name= &name;
8295     component_name= &component;			// Empty string
8296   }
8297 
8298   if (!(var= find_sys_var(thd, base_name->str, base_name->length)))
8299     return 0;
8300   if (component.str)
8301   {
8302     if (!var->is_struct())
8303     {
8304       my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
8305       return 0;
8306     }
8307   }
8308   thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
8309 
8310   set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);
8311 
8312   var->do_deprecated_warning(thd);
8313 
8314   Item_func_get_system_var *item= new Item_func_get_system_var(var, var_type,
8315                                                                component_name,
8316                                                                NULL, 0);
8317   if (item == NULL)
8318     return NULL;  // OOM
8319 
8320   if (unsafe && !var->is_written_to_binlog(var_type))
8321     thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE);
8322 
8323 #ifndef EMBEDDED_LIBRARY
8324   if (var_type == OPT_GLOBAL && var->check_scope(OPT_GLOBAL))
8325   {
8326     String str;
8327     String *outStr;
8328     /* This object is just created for variable to string conversion.
8329        item object cannot be used after the conversion of the variable
8330        to string. It caches the data. */
8331     Item_func_get_system_var *si= new Item_func_get_system_var(var, var_type,
8332                                                                component_name,
8333                                                                NULL, 0);
8334 
8335     /* Disable deprecation warning during var to string conversion. */
8336     Silence_deprecation_warnings silencer;
8337     thd->push_internal_handler(&silencer);
8338 
8339     if (si)
8340       (void) si->fix_length_and_dec();
8341     outStr= si ? si->val_str(&str) : &str;
8342 
8343     thd->pop_internal_handler();
8344 
8345     if (mysql_audit_notify(thd, AUDIT_EVENT(MYSQL_AUDIT_GLOBAL_VARIABLE_GET),
8346                            var->name.str,
8347                            outStr ? outStr->ptr() : NULL,
8348                            outStr ? outStr->length() : 0))
8349       {
8350         return 0;
8351       }
8352   }
8353 #endif
8354 
8355   return item;
8356 }
8357 
8358 
itemize(Parse_context * pc,Item ** res)8359 bool Item_func_row_count::itemize(Parse_context *pc, Item **res)
8360 {
8361   if (skip_itemize(res))
8362     return false;
8363   if (super::itemize(pc, res))
8364     return true;
8365 
8366   LEX *lex= pc->thd->lex;
8367   lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8368   lex->safe_to_cache_query= 0;
8369   return false;
8370 }
8371 
val_int()8372 longlong Item_func_row_count::val_int()
8373 {
8374   assert(fixed == 1);
8375   THD *thd= current_thd;
8376 
8377   return thd->get_row_count_func();
8378 }
8379 
8380 
Item_func_sp(const POS & pos,const LEX_STRING & db_name,const LEX_STRING & fn_name,bool use_explicit_name,PT_item_list * opt_list)8381 Item_func_sp::Item_func_sp(const POS &pos,
8382                            const LEX_STRING &db_name,
8383                            const LEX_STRING &fn_name,
8384                            bool use_explicit_name,
8385                            PT_item_list *opt_list)
8386 : Item_func(pos, opt_list), m_sp(NULL), dummy_table(NULL), sp_result_field(NULL)
8387 {
8388   maybe_null= 1;
8389   with_stored_program= true;
8390   THD *thd= current_thd;
8391   m_name= new (thd->mem_root) sp_name(to_lex_cstring(db_name), fn_name,
8392                                       use_explicit_name);
8393 }
8394 
8395 
itemize(Parse_context * pc,Item ** res)8396 bool Item_func_sp::itemize(Parse_context *pc, Item **res)
8397 {
8398   if (skip_itemize(res))
8399     return false;
8400   if (super::itemize(pc, res))
8401     return true;
8402   if (m_name == NULL)
8403     return true; // OOM
8404 
8405   THD *thd= pc->thd;
8406   LEX *lex= thd->lex;
8407 
8408   context= lex->current_context();
8409   lex->safe_to_cache_query= false;
8410 
8411   if (m_name->m_db.str == NULL)
8412   {
8413     /* Cannot match the function since no database is selected */
8414     my_error(ER_NO_DB_ERROR, MYF(0));
8415     return true;
8416   }
8417 
8418   m_name->init_qname(thd);
8419   sp_add_used_routine(lex, thd, m_name, SP_TYPE_FUNCTION);
8420 
8421   dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE));
8422   if (dummy_table == NULL)
8423     return true;
8424   dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
8425 
8426   return false;
8427 }
8428 
8429 
8430 void
cleanup()8431 Item_func_sp::cleanup()
8432 {
8433   if (sp_result_field)
8434   {
8435     delete sp_result_field;
8436     sp_result_field= NULL;
8437   }
8438   m_sp= NULL;
8439   if (dummy_table != NULL)
8440     dummy_table->alias= NULL;
8441   Item_func::cleanup();
8442   tables_locked_cache= false;
8443   with_stored_program= true;
8444 }
8445 
8446 const char *
func_name() const8447 Item_func_sp::func_name() const
8448 {
8449   THD *thd= current_thd;
8450   /* Calculate length to avoid reallocation of string for sure */
8451   size_t len= (((m_name->m_explicit_name ? m_name->m_db.length : 0) +
8452                 m_name->m_name.length)*2 + //characters*quoting
8453                2 +                         // ` and `
8454                (m_name->m_explicit_name ?
8455                 3 : 0) +                   // '`', '`' and '.' for the db
8456                1 +                         // end of string
8457                ALIGN_SIZE(1));             // to avoid String reallocation
8458   String qname((char *)alloc_root(thd->mem_root, len), len,
8459                system_charset_info);
8460 
8461   qname.length(0);
8462   if (m_name->m_explicit_name)
8463   {
8464     append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length);
8465     qname.append('.');
8466   }
8467   append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length);
8468   return qname.ptr();
8469 }
8470 
8471 
get_initial_pseudo_tables() const8472 table_map Item_func_sp::get_initial_pseudo_tables() const
8473 {
8474   return m_sp->m_chistics->detistic ? 0 : RAND_TABLE_BIT;
8475 }
8476 
8477 
my_missing_function_error(const LEX_STRING & token,const char * func_name)8478 void my_missing_function_error(const LEX_STRING &token, const char *func_name)
8479 {
8480   if (token.length && is_lex_native_function (&token))
8481     my_error(ER_FUNC_INEXISTENT_NAME_COLLISION, MYF(0), func_name);
8482   else
8483     my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", func_name);
8484 }
8485 
8486 
8487 /**
8488   @brief Initialize the result field by creating a temporary dummy table
8489     and assign it to a newly created field object. Meta data used to
8490     create the field is fetched from the sp_head belonging to the stored
8491     proceedure found in the stored procedure functon cache.
8492 
8493   @note This function should be called from fix_fields to init the result
8494     field. It is some what related to Item_field.
8495 
8496   @see Item_field
8497 
8498   @param thd A pointer to the session and thread context.
8499 
8500   @return Function return error status.
8501   @retval TRUE is returned on an error
8502   @retval FALSE is returned on success.
8503 */
8504 
8505 bool
init_result_field(THD * thd)8506 Item_func_sp::init_result_field(THD *thd)
8507 {
8508   LEX_STRING empty_name= { C_STRING_WITH_LEN("") };
8509   TABLE_SHARE *share;
8510   DBUG_ENTER("Item_func_sp::init_result_field");
8511 
8512   assert(m_sp == NULL);
8513   assert(sp_result_field == NULL);
8514 
8515   Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8516     view_handler(thd, context->view_error_handler,
8517                  context->view_error_handler_arg);
8518   if (!(m_sp= sp_find_routine(thd, SP_TYPE_FUNCTION, m_name,
8519                                &thd->sp_func_cache, TRUE)))
8520   {
8521     my_missing_function_error (m_name->m_name, m_name->m_qname.str);
8522     DBUG_RETURN(TRUE);
8523   }
8524 
8525   /*
8526      A Field need to be attached to a Table.
8527      Below we "create" a dummy table by initializing
8528      the needed pointers.
8529    */
8530 
8531   share= dummy_table->s;
8532   dummy_table->alias = "";
8533   if (maybe_null)
8534     dummy_table->set_nullable();
8535   dummy_table->in_use= thd;
8536   dummy_table->copy_blobs= TRUE;
8537   share->table_cache_key = empty_name;
8538   share->table_name = empty_name;
8539 
8540   if (!(sp_result_field= m_sp->create_result_field(max_length, item_name.ptr(),
8541                                                    dummy_table)))
8542   {
8543    DBUG_RETURN(TRUE);
8544   }
8545 
8546   if (sp_result_field->pack_length() > sizeof(result_buf))
8547   {
8548     void *tmp;
8549     if (!(tmp= sql_alloc(sp_result_field->pack_length())))
8550       DBUG_RETURN(TRUE);
8551     sp_result_field->move_field((uchar*) tmp);
8552   }
8553   else
8554     sp_result_field->move_field(result_buf);
8555 
8556   sp_result_field->set_null_ptr((uchar *) &null_value, 1);
8557   DBUG_RETURN(FALSE);
8558 }
8559 
8560 
8561 /**
8562   @brief Initialize local members with values from the Field interface.
8563 
8564   @note called from Item::fix_fields.
8565 */
8566 
fix_length_and_dec()8567 void Item_func_sp::fix_length_and_dec()
8568 {
8569   DBUG_ENTER("Item_func_sp::fix_length_and_dec");
8570 
8571   assert(sp_result_field);
8572   decimals= sp_result_field->decimals();
8573   max_length= sp_result_field->field_length;
8574   collation.set(sp_result_field->charset());
8575   maybe_null= 1;
8576   unsigned_flag= MY_TEST(sp_result_field->flags & UNSIGNED_FLAG);
8577 
8578   DBUG_VOID_RETURN;
8579 }
8580 
8581 
val_json(Json_wrapper * result)8582 bool Item_func_sp::val_json(Json_wrapper *result)
8583 {
8584   if (sp_result_field->type() == MYSQL_TYPE_JSON)
8585   {
8586     if (execute())
8587     {
8588       return true;
8589     }
8590 
8591     Field_json *json_value= down_cast<Field_json *>(sp_result_field);
8592     return json_value->val_json(result);
8593   }
8594 
8595   /* purecov: begin deadcode */
8596   DBUG_ABORT();
8597   my_error(ER_INVALID_CAST_TO_JSON, MYF(0));
8598   return error_json();
8599   /* purecov: end */
8600 }
8601 
8602 
8603 type_conversion_status
save_in_field_inner(Field * field,bool no_conversions)8604 Item_func_sp::save_in_field_inner(Field *field, bool no_conversions)
8605 {
8606   return save_possibly_as_json(field, no_conversions);
8607 }
8608 
8609 
update_null_value()8610 void Item_func_sp::update_null_value()
8611 {
8612   /*
8613     This method is called when we try to check if the item value is NULL.
8614     We call Item_func_sp::execute() to get value of null_value attribute
8615     as a side effect of its execution.
8616     We ignore any error since update_null_value() doesn't return value.
8617     We used to delegate nullability check to Item::update_null_value as
8618     a result of a chain of function calls:
8619      Item_func_isnull::val_int --> Item_func::is_null -->
8620       Item::update_null_value -->Item_func_sp::val_int -->
8621         Field_varstring::val_int
8622     Such approach resulted in a call of push_warning_printf() in case
8623     if a stored program value couldn't be cast to integer (the case when
8624     for example there was a stored function that declared as returning
8625     varchar(1) and a function's implementation returned "Y" from its body).
8626   */
8627   execute();
8628 }
8629 
8630 
8631 /**
8632   @brief Execute function & store value in field.
8633 
8634   @return Function returns error status.
8635   @retval FALSE on success.
8636   @retval TRUE if an error occurred.
8637 */
8638 
8639 bool
execute()8640 Item_func_sp::execute()
8641 {
8642   THD *thd= current_thd;
8643 
8644   Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8645     view_handler(thd, context->view_error_handler,
8646                  context->view_error_handler_arg);
8647   /* Execute function and store the return value in the field. */
8648 
8649   if (execute_impl(thd))
8650   {
8651     null_value= 1;
8652     if (thd->killed)
8653       thd->send_kill_message();
8654     return TRUE;
8655   }
8656 
8657   /* Check that the field (the value) is not NULL. */
8658 
8659   null_value= sp_result_field->is_null();
8660 
8661   return null_value;
8662 }
8663 
8664 
8665 /**
8666    @brief Execute function and store the return value in the field.
8667 
8668    @note This function was intended to be the concrete implementation of
8669     the interface function execute. This was never realized.
8670 
8671    @return The error state.
8672    @retval FALSE on success
8673    @retval TRUE if an error occurred.
8674 */
8675 bool
execute_impl(THD * thd)8676 Item_func_sp::execute_impl(THD *thd)
8677 {
8678   bool err_status= TRUE;
8679   Sub_statement_state statement_state;
8680 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8681   Security_context *save_security_ctx= thd->security_context();
8682 #endif
8683   enum enum_sp_data_access access=
8684     (m_sp->m_chistics->daccess == SP_DEFAULT_ACCESS) ?
8685      SP_DEFAULT_ACCESS_MAPPING : m_sp->m_chistics->daccess;
8686 
8687   DBUG_ENTER("Item_func_sp::execute_impl");
8688 
8689 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8690   if (context->security_ctx)
8691   {
8692     /* Set view definer security context */
8693     thd->set_security_context(context->security_ctx);
8694   }
8695 #endif
8696   if (sp_check_access(thd))
8697     goto error;
8698 
8699   /*
8700     Throw an error if a non-deterministic function is called while
8701     statement-based replication (SBR) is active.
8702   */
8703 
8704   if (!m_sp->m_chistics->detistic && !trust_function_creators &&
8705       (access == SP_CONTAINS_SQL || access == SP_MODIFIES_SQL_DATA) &&
8706       (mysql_bin_log.is_open() &&
8707        thd->variables.binlog_format == BINLOG_FORMAT_STMT))
8708   {
8709     my_error(ER_BINLOG_UNSAFE_ROUTINE, MYF(0));
8710     goto error;
8711   }
8712   /*
8713     Disable the binlogging if this is not a SELECT statement. If this is a
8714     SELECT, leave binlogging on, so execute_function() code writes the
8715     function call into binlog.
8716   */
8717   thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION);
8718   err_status= m_sp->execute_function(thd, args, arg_count, sp_result_field);
8719   thd->restore_sub_statement_state(&statement_state);
8720 
8721 error:
8722 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8723   thd->set_security_context(save_security_ctx);
8724 #endif
8725 
8726   DBUG_RETURN(err_status);
8727 }
8728 
8729 
8730 void
make_field(Send_field * tmp_field)8731 Item_func_sp::make_field(Send_field *tmp_field)
8732 {
8733   DBUG_ENTER("Item_func_sp::make_field");
8734   assert(sp_result_field);
8735   sp_result_field->make_field(tmp_field);
8736   if (item_name.is_set())
8737     tmp_field->col_name= item_name.ptr();
8738   DBUG_VOID_RETURN;
8739 }
8740 
8741 
8742 enum enum_field_types
field_type() const8743 Item_func_sp::field_type() const
8744 {
8745   DBUG_ENTER("Item_func_sp::field_type");
8746   assert(sp_result_field);
8747   DBUG_RETURN(sp_result_field->type());
8748 }
8749 
8750 Item_result
result_type() const8751 Item_func_sp::result_type() const
8752 {
8753   DBUG_ENTER("Item_func_sp::result_type");
8754   DBUG_PRINT("info", ("m_sp = %p", (void *) m_sp));
8755   assert(sp_result_field);
8756   DBUG_RETURN(sp_result_field->result_type());
8757 }
8758 
8759 
itemize(Parse_context * pc,Item ** res)8760 bool Item_func_found_rows::itemize(Parse_context *pc, Item **res)
8761 {
8762   if (skip_itemize(res))
8763     return false;
8764   if (super::itemize(pc, res))
8765     return true;
8766   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8767   pc->thd->lex->safe_to_cache_query= false;
8768   return false;
8769 }
8770 
8771 
val_int()8772 longlong Item_func_found_rows::val_int()
8773 {
8774   assert(fixed == 1);
8775   return current_thd->found_rows();
8776 }
8777 
8778 
8779 Field *
tmp_table_field(TABLE * t_arg)8780 Item_func_sp::tmp_table_field(TABLE *t_arg)
8781 {
8782   DBUG_ENTER("Item_func_sp::tmp_table_field");
8783 
8784   assert(sp_result_field);
8785   DBUG_RETURN(sp_result_field);
8786 }
8787 
8788 
8789 /**
8790   @brief Checks if requested access to function can be granted to user.
8791     If function isn't found yet, it searches function first.
8792     If function can't be found or user don't have requested access
8793     error is raised.
8794 
8795   @param thd thread handler
8796 
8797   @return Indication if the access was granted or not.
8798   @retval FALSE Access is granted.
8799   @retval TRUE Requested access can't be granted or function doesn't exists.
8800 
8801 */
8802 
8803 bool
sp_check_access(THD * thd)8804 Item_func_sp::sp_check_access(THD *thd)
8805 {
8806   DBUG_ENTER("Item_func_sp::sp_check_access");
8807   assert(m_sp);
8808 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8809   if (check_routine_access(thd, EXECUTE_ACL,
8810 			   m_sp->m_db.str, m_sp->m_name.str, 0, FALSE))
8811     DBUG_RETURN(TRUE);
8812 #endif
8813 
8814   DBUG_RETURN(FALSE);
8815 }
8816 
8817 
8818 bool
fix_fields(THD * thd,Item ** ref)8819 Item_func_sp::fix_fields(THD *thd, Item **ref)
8820 {
8821   bool res;
8822 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8823   Security_context *save_security_ctx= thd->security_context();
8824 #endif
8825 
8826   DBUG_ENTER("Item_func_sp::fix_fields");
8827   assert(fixed == 0);
8828 
8829 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8830   /*
8831     Checking privileges to execute the function while creating view and
8832     executing the function of select.
8833    */
8834   if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) ||
8835       (thd->lex->sql_command == SQLCOM_CREATE_VIEW))
8836   {
8837     if (context->security_ctx)
8838     {
8839       /* Set view definer security context */
8840       thd->set_security_context(context->security_ctx);
8841     }
8842 
8843     /*
8844       Check whether user has execute privilege or not
8845      */
8846 
8847     Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8848       view_handler(thd, context->view_error_handler,
8849                    context->view_error_handler_arg);
8850 
8851     res= check_routine_access(thd, EXECUTE_ACL, m_name->m_db.str,
8852                               m_name->m_name.str, 0, FALSE);
8853     thd->set_security_context(save_security_ctx);
8854 
8855     if (res)
8856     {
8857       DBUG_RETURN(res);
8858     }
8859   }
8860 #endif
8861 
8862   /*
8863     We must call init_result_field before Item_func::fix_fields()
8864     to make m_sp and result_field members available to fix_length_and_dec(),
8865     which is called from Item_func::fix_fields().
8866   */
8867   res= init_result_field(thd);
8868 
8869   if (res)
8870     DBUG_RETURN(res);
8871 
8872   res= Item_func::fix_fields(thd, ref);
8873 
8874   /* These is reset/set by Item_func::fix_fields. */
8875   with_stored_program= true;
8876 
8877   if (res)
8878     DBUG_RETURN(res);
8879 
8880   if (thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)
8881   {
8882     /*
8883       Here we check privileges of the stored routine only during view
8884       creation, in order to validate the view.  A runtime check is
8885       perfomed in Item_func_sp::execute(), and this method is not
8886       called during context analysis.  Notice, that during view
8887       creation we do not infer into stored routine bodies and do not
8888       check privileges of its statements, which would probably be a
8889       good idea especially if the view has SQL SECURITY DEFINER and
8890       the used stored procedure has SQL SECURITY DEFINER.
8891     */
8892     res= sp_check_access(thd);
8893 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8894     /*
8895       Try to set and restore the security context to see whether it's valid
8896     */
8897     Security_context *save_secutiry_ctx;
8898     res= m_sp->set_security_ctx(thd, &save_secutiry_ctx);
8899     if (!res)
8900       m_sp->m_security_ctx.restore_security_context(thd, save_secutiry_ctx);
8901 
8902 #endif /* ! NO_EMBEDDED_ACCESS_CHECKS */
8903   }
8904 
8905   DBUG_RETURN(res);
8906 }
8907 
8908 
update_used_tables()8909 void Item_func_sp::update_used_tables()
8910 {
8911   Item_func::update_used_tables();
8912 
8913   /* This is reset by Item_func::update_used_tables(). */
8914   with_stored_program= true;
8915 }
8916 
8917 
8918 /*
8919   uuid_short handling.
8920 
8921   The short uuid is defined as a longlong that contains the following bytes:
8922 
8923   Bytes  Comment
8924   1      Server_id & 255
8925   4      Startup time of server in seconds
8926   3      Incrementor
8927 
8928   This means that an uuid is guaranteed to be unique
8929   even in a replication environment if the following holds:
8930 
8931   - The last byte of the server id is unique
8932   - If you between two shutdown of the server don't get more than
8933     an average of 2^24 = 16M calls to uuid_short() per second.
8934 */
8935 
8936 ulonglong uuid_value;
8937 
uuid_short_init()8938 void uuid_short_init()
8939 {
8940   uuid_value= ((((ulonglong) server_id) << 56) +
8941                (((ulonglong) server_start_time) << 24));
8942 }
8943 
8944 
itemize(Parse_context * pc,Item ** res)8945 bool Item_func_uuid_short::itemize(Parse_context *pc, Item **res)
8946 {
8947   if (skip_itemize(res))
8948     return false;
8949   if (super::itemize(pc, res))
8950     return true;
8951   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8952   pc->thd->lex->safe_to_cache_query= false;
8953   return false;
8954 }
8955 
8956 
val_int()8957 longlong Item_func_uuid_short::val_int()
8958 {
8959   ulonglong val;
8960   mysql_mutex_lock(&LOCK_uuid_generator);
8961   val= uuid_value++;
8962   mysql_mutex_unlock(&LOCK_uuid_generator);
8963   return (longlong) val;
8964 }
8965 
8966 
itemize(Parse_context * pc,Item ** res)8967 bool Item_func_version::itemize(Parse_context *pc, Item **res)
8968 {
8969   if (skip_itemize(res))
8970     return false;
8971   if (super::itemize(pc, res))
8972     return true;
8973   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8974   return false;
8975 }
8976 
8977