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   uint32 tmp= (uint32) arg->val_int();
3449   randominit(rand, (uint32) (tmp*0x10001L+55555555L),
3450              (uint32) (tmp*0x10000001L));
3451 }
3452 
3453 
fix_length_and_dec()3454 void Item_func_rand::fix_length_and_dec()
3455 {
3456   Item_real_func::fix_length_and_dec();
3457   reject_geometry_args(arg_count, args, this);
3458 }
3459 
3460 
fix_fields(THD * thd,Item ** ref)3461 bool Item_func_rand::fix_fields(THD *thd,Item **ref)
3462 {
3463   if (Item_real_func::fix_fields(thd, ref))
3464     return TRUE;
3465 
3466   if (arg_count)
3467   {					// Only use argument once in query
3468     /*
3469       Allocate rand structure once: we must use thd->stmt_arena
3470       to create rand in proper mem_root if it's a prepared statement or
3471       stored procedure.
3472 
3473       No need to send a Rand log event if seed was given eg: RAND(seed),
3474       as it will be replicated in the query as such.
3475     */
3476     if (!rand && !(rand= (struct rand_struct*)
3477                    thd->stmt_arena->alloc(sizeof(*rand))))
3478       return TRUE;
3479   }
3480   else
3481   {
3482     /*
3483       Save the seed only the first time RAND() is used in the query
3484       Once events are forwarded rather than recreated,
3485       the following can be skipped if inside the slave thread
3486     */
3487     if (!thd->rand_used)
3488     {
3489       thd->rand_used= 1;
3490       thd->rand_saved_seed1= thd->rand.seed1;
3491       thd->rand_saved_seed2= thd->rand.seed2;
3492     }
3493     rand= &thd->rand;
3494   }
3495   return FALSE;
3496 }
3497 
3498 
val_real()3499 double Item_func_rand::val_real()
3500 {
3501   assert(fixed == 1);
3502   if (arg_count)
3503   {
3504     if (!args[0]->const_item())
3505       seed_random(args[0]);
3506     else if (first_eval)
3507     {
3508       /*
3509         Constantness of args[0] may be set during JOIN::optimize(), if arg[0]
3510         is a field item of "constant" table. Thus, we have to evaluate
3511         seed_random() for constant arg there but not at the fix_fields method.
3512       */
3513       first_eval= FALSE;
3514       seed_random(args[0]);
3515     }
3516   }
3517   return my_rnd(rand);
3518 }
3519 
3520 
fix_length_and_dec()3521 void Item_func_sign::fix_length_and_dec()
3522 {
3523   Item_int_func::fix_length_and_dec();
3524   reject_geometry_args(arg_count, args, this);
3525 }
3526 
3527 
val_int()3528 longlong Item_func_sign::val_int()
3529 {
3530   assert(fixed == 1);
3531   double value= args[0]->val_real();
3532   null_value=args[0]->null_value;
3533   return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
3534 }
3535 
3536 
fix_length_and_dec()3537 void Item_func_units::fix_length_and_dec()
3538 {
3539   decimals= NOT_FIXED_DEC;
3540   max_length= float_length(decimals);
3541   reject_geometry_args(arg_count, args, this);
3542 }
3543 
3544 
val_real()3545 double Item_func_units::val_real()
3546 {
3547   assert(fixed == 1);
3548   double value= args[0]->val_real();
3549   if ((null_value=args[0]->null_value))
3550     return 0;
3551   return check_float_overflow(value * mul + add);
3552 }
3553 
3554 
fix_length_and_dec()3555 void Item_func_min_max::fix_length_and_dec()
3556 {
3557   uint string_arg_count= 0;
3558   int max_int_part=0;
3559   bool datetime_found= FALSE;
3560   decimals=0;
3561   max_length=0;
3562   maybe_null=0;
3563   cmp_type= args[0]->temporal_with_date_as_number_result_type();
3564 
3565   for (uint i=0 ; i < arg_count ; i++)
3566   {
3567     set_if_bigger(max_length, args[i]->max_length);
3568     set_if_bigger(decimals, args[i]->decimals);
3569     set_if_bigger(max_int_part, args[i]->decimal_int_part());
3570     if (args[i]->maybe_null)
3571       maybe_null=1;
3572     cmp_type= item_cmp_type(cmp_type,
3573                             args[i]->temporal_with_date_as_number_result_type());
3574     if (args[i]->result_type() == STRING_RESULT)
3575      string_arg_count++;
3576     if (args[i]->result_type() != ROW_RESULT &&
3577         args[i]->is_temporal_with_date())
3578     {
3579       datetime_found= TRUE;
3580       if (!datetime_item || args[i]->field_type() == MYSQL_TYPE_DATETIME)
3581         datetime_item= args[i];
3582     }
3583   }
3584 
3585   if (string_arg_count == arg_count)
3586   {
3587     // We compare as strings only if all arguments were strings.
3588     agg_arg_charsets_for_string_result_with_comparison(collation,
3589                                                        args, arg_count);
3590     if (datetime_found)
3591     {
3592       compare_as_dates= TRUE;
3593       /*
3594         We should not do this:
3595           cached_field_type= datetime_item->field_type();
3596           count_datetime_length(args, arg_count);
3597         because compare_as_dates can be TRUE but
3598         result type can still be VARCHAR.
3599       */
3600     }
3601   }
3602   else if ((cmp_type == DECIMAL_RESULT) || (cmp_type == INT_RESULT))
3603   {
3604     collation.set_numeric();
3605     fix_char_length(my_decimal_precision_to_length_no_truncation(max_int_part +
3606                                                                  decimals,
3607                                                                  decimals,
3608                                                                  unsigned_flag));
3609   }
3610   else if (cmp_type == REAL_RESULT)
3611     fix_char_length(float_length(decimals));
3612   cached_field_type= agg_field_type(args, arg_count);
3613   /*
3614     LEAST and GREATEST convert JSON values to strings before they are
3615     compared, so their JSON nature is lost. Raise a warning to
3616     indicate to the users that the values are not compared using the
3617     JSON comparator, as they might expect. Also update the field type
3618     of the result to reflect that the result is a string.
3619   */
3620   unsupported_json_comparison(arg_count, args,
3621                               "comparison of JSON in the "
3622                               "LEAST and GREATEST operators");
3623   if (cached_field_type == MYSQL_TYPE_JSON)
3624     cached_field_type= MYSQL_TYPE_VARCHAR;
3625   reject_geometry_args(arg_count, args, this);
3626 }
3627 
3628 
3629 /*
3630   Compare item arguments in the DATETIME context.
3631 
3632   SYNOPSIS
3633     cmp_datetimes()
3634     value [out]   found least/greatest DATE/DATETIME value
3635 
3636   DESCRIPTION
3637     Compare item arguments as DATETIME values and return the index of the
3638     least/greatest argument in the arguments array.
3639     The correct integer DATE/DATETIME value of the found argument is
3640     stored to the value pointer, if latter is provided.
3641 
3642   RETURN
3643    0	If one of arguments is NULL or there was a execution error
3644    #	index of the least/greatest argument
3645 */
3646 
cmp_datetimes(longlong * value)3647 uint Item_func_min_max::cmp_datetimes(longlong *value)
3648 {
3649   longlong min_max= 0;
3650   uint min_max_idx= 0;
3651 
3652   for (uint i=0; i < arg_count ; i++)
3653   {
3654     Item **arg= args + i;
3655     bool is_null;
3656     THD *thd= current_thd;
3657     longlong res= get_datetime_value(thd, &arg, 0, datetime_item, &is_null);
3658 
3659     /* Check if we need to stop (because of error or KILL)  and stop the loop */
3660     if (thd->is_error())
3661     {
3662       null_value= 1;
3663       return 0;
3664     }
3665 
3666     if ((null_value= args[i]->null_value))
3667       return 0;
3668     if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0)
3669     {
3670       min_max= res;
3671       min_max_idx= i;
3672     }
3673   }
3674   if (value)
3675     *value= min_max;
3676   return min_max_idx;
3677 }
3678 
3679 
cmp_times(longlong * value)3680 uint Item_func_min_max::cmp_times(longlong *value)
3681 {
3682   longlong min_max= 0;
3683   uint min_max_idx= 0;
3684   for (uint i=0; i < arg_count ; i++)
3685   {
3686     longlong res= args[i]->val_time_temporal();
3687     if ((null_value= args[i]->null_value))
3688       return 0;
3689     if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0)
3690     {
3691       min_max= res;
3692       min_max_idx= i;
3693     }
3694   }
3695   if (value)
3696     *value= min_max;
3697   return min_max_idx;
3698 }
3699 
3700 
val_str(String * str)3701 String *Item_func_min_max::val_str(String *str)
3702 {
3703   assert(fixed == 1);
3704   if (compare_as_dates)
3705   {
3706     if (is_temporal())
3707     {
3708       /*
3709         In case of temporal data types, we always return
3710         string value according the format of the data type.
3711         For example, in case of LEAST(time_column, datetime_column)
3712         the result date type is DATETIME,
3713         so we return a 'YYYY-MM-DD hh:mm:ss' string even if time_column wins
3714         (conversion from TIME to DATETIME happens in this case).
3715       */
3716       longlong result;
3717       cmp_datetimes(&result);
3718       if (null_value)
3719         return 0;
3720       MYSQL_TIME ltime;
3721       TIME_from_longlong_packed(&ltime, field_type(), result);
3722       return (null_value= my_TIME_to_str(&ltime, str, decimals)) ?
3723              (String *) 0 : str;
3724     }
3725     else
3726     {
3727       /*
3728         In case of VARCHAR result type we just return val_str()
3729         value of the winning item AS IS, without conversion.
3730       */
3731       String *str_res;
3732       uint min_max_idx= cmp_datetimes(NULL);
3733       if (null_value)
3734         return 0;
3735       str_res= args[min_max_idx]->val_str(str);
3736       if (args[min_max_idx]->null_value)
3737       {
3738         // check if the call to val_str() above returns a NULL value
3739         null_value= 1;
3740         return NULL;
3741       }
3742       str_res->set_charset(collation.collation);
3743       return str_res;
3744     }
3745   }
3746 
3747   switch (cmp_type) {
3748   case INT_RESULT:
3749   {
3750     longlong nr=val_int();
3751     if (null_value)
3752       return 0;
3753     str->set_int(nr, unsigned_flag, collation.collation);
3754     return str;
3755   }
3756   case DECIMAL_RESULT:
3757   {
3758     my_decimal dec_buf, *dec_val= val_decimal(&dec_buf);
3759     if (null_value)
3760       return 0;
3761     my_decimal2string(E_DEC_FATAL_ERROR, dec_val, 0, 0, 0, str);
3762     return str;
3763   }
3764   case REAL_RESULT:
3765   {
3766     double nr= val_real();
3767     if (null_value)
3768       return 0; /* purecov: inspected */
3769     str->set_real(nr, decimals, collation.collation);
3770     return str;
3771   }
3772   case STRING_RESULT:
3773   {
3774     String *res= NULL;
3775     for (uint i=0; i < arg_count ; i++)
3776     {
3777       if (i == 0)
3778 	res=args[i]->val_str(str);
3779       else
3780       {
3781 	String *res2;
3782 	res2= args[i]->val_str(res == str ? &tmp_value : str);
3783 	if (res2)
3784 	{
3785 	  int cmp= sortcmp(res,res2,collation.collation);
3786 	  if ((cmp_sign < 0 ? cmp : -cmp) < 0)
3787 	    res=res2;
3788 	}
3789       }
3790       if ((null_value= args[i]->null_value))
3791         return 0;
3792     }
3793     res->set_charset(collation.collation);
3794     return res;
3795   }
3796   case ROW_RESULT:
3797   default:
3798     // This case should never be chosen
3799     assert(0);
3800     return 0;
3801   }
3802   return 0;					// Keep compiler happy
3803 }
3804 
3805 
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)3806 bool Item_func_min_max::get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate)
3807 {
3808   assert(fixed == 1);
3809   if (compare_as_dates)
3810   {
3811     longlong result;
3812     cmp_datetimes(&result);
3813     if (null_value)
3814       return true;
3815     TIME_from_longlong_packed(ltime, datetime_item->field_type(), result);
3816     int warnings;
3817     return check_date(ltime, non_zero_date(ltime), fuzzydate, &warnings);
3818   }
3819 
3820   switch (field_type())
3821   {
3822   case MYSQL_TYPE_TIME:
3823     return get_date_from_time(ltime);
3824   case MYSQL_TYPE_DATETIME:
3825   case MYSQL_TYPE_TIMESTAMP:
3826   case MYSQL_TYPE_DATE:
3827     assert(0); // Should have been processed in "compare_as_dates" block.
3828   default:
3829     return get_date_from_non_temporal(ltime, fuzzydate);
3830   }
3831 }
3832 
3833 
get_time(MYSQL_TIME * ltime)3834 bool Item_func_min_max::get_time(MYSQL_TIME *ltime)
3835 {
3836   assert(fixed == 1);
3837   if (compare_as_dates)
3838   {
3839     longlong result;
3840     cmp_datetimes(&result);
3841     if (null_value)
3842       return true;
3843     TIME_from_longlong_packed(ltime, datetime_item->field_type(), result);
3844     datetime_to_time(ltime);
3845     return false;
3846   }
3847 
3848   switch (field_type())
3849   {
3850   case MYSQL_TYPE_TIME:
3851     {
3852       longlong result;
3853       cmp_times(&result);
3854       if (null_value)
3855         return true;
3856       TIME_from_longlong_time_packed(ltime, result);
3857       return false;
3858     }
3859     break;
3860   case MYSQL_TYPE_DATE:
3861   case MYSQL_TYPE_TIMESTAMP:
3862   case MYSQL_TYPE_DATETIME:
3863     assert(0); // Should have been processed in "compare_as_dates" block.
3864   default:
3865     return get_time_from_non_temporal(ltime);
3866     break;
3867   }
3868 }
3869 
3870 
val_real()3871 double Item_func_min_max::val_real()
3872 {
3873   assert(fixed == 1);
3874   double value=0.0;
3875   if (compare_as_dates)
3876   {
3877     longlong result= 0;
3878     (void)cmp_datetimes(&result);
3879     return double_from_datetime_packed(datetime_item->field_type(), result);
3880   }
3881   for (uint i=0; i < arg_count ; i++)
3882   {
3883     if (i == 0)
3884       value= args[i]->val_real();
3885     else
3886     {
3887       double tmp= args[i]->val_real();
3888       if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
3889 	value=tmp;
3890     }
3891     if ((null_value= args[i]->null_value))
3892       break;
3893   }
3894   return value;
3895 }
3896 
3897 
val_int()3898 longlong Item_func_min_max::val_int()
3899 {
3900   assert(fixed == 1);
3901   longlong value=0;
3902   if (compare_as_dates)
3903   {
3904     longlong result= 0;
3905     (void)cmp_datetimes(&result);
3906     return longlong_from_datetime_packed(datetime_item->field_type(), result);
3907   }
3908   /*
3909     TS-TODO: val_str decides which type to use using cmp_type.
3910     val_int, val_decimal, val_real do not check cmp_type and
3911     decide data type according to the method type.
3912     This is probably not good:
3913 
3914 mysql> select least('11', '2'), least('11', '2')+0, concat(least(11,2));
3915 +------------------+--------------------+---------------------+
3916 | least('11', '2') | least('11', '2')+0 | concat(least(11,2)) |
3917 +------------------+--------------------+---------------------+
3918 | 11               |                  2 | 2                   |
3919 +------------------+--------------------+---------------------+
3920 1 row in set (0.00 sec)
3921 
3922     Should not the second column return 11?
3923     I.e. compare as strings and return '11', then convert to number.
3924   */
3925   for (uint i=0; i < arg_count ; i++)
3926   {
3927     if (i == 0)
3928       value=args[i]->val_int();
3929     else
3930     {
3931       longlong tmp=args[i]->val_int();
3932       if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
3933 	value=tmp;
3934     }
3935     if ((null_value= args[i]->null_value))
3936       break;
3937   }
3938   return value;
3939 }
3940 
3941 
val_decimal(my_decimal * dec)3942 my_decimal *Item_func_min_max::val_decimal(my_decimal *dec)
3943 {
3944   assert(fixed == 1);
3945   my_decimal tmp_buf, *tmp, *res= NULL;
3946 
3947   if (compare_as_dates)
3948   {
3949     longlong value= 0;
3950     (void)cmp_datetimes(&value);
3951     return my_decimal_from_datetime_packed(dec, datetime_item->field_type(),
3952                                            value);
3953   }
3954   for (uint i=0; i < arg_count ; i++)
3955   {
3956     if (i == 0)
3957       res= args[i]->val_decimal(dec);
3958     else
3959     {
3960       tmp= args[i]->val_decimal(&tmp_buf);      // Zero if NULL
3961       if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0)
3962       {
3963         if (tmp == &tmp_buf)
3964         {
3965           /* Move value out of tmp_buf as this will be reused on next loop */
3966           my_decimal2decimal(tmp, dec);
3967           res= dec;
3968         }
3969         else
3970           res= tmp;
3971       }
3972     }
3973     if ((null_value= args[i]->null_value))
3974     {
3975       res= 0;
3976       break;
3977     }
3978   }
3979 
3980   if (res)
3981   {
3982     /*
3983       Need this to make val_str() always return fixed
3984       number of fractional digits, according to "decimals".
3985     */
3986     my_decimal_round(E_DEC_FATAL_ERROR, res, decimals, false, res);
3987   }
3988   return res;
3989 }
3990 
val_real()3991 double Item_func_rollup_const::val_real()
3992 {
3993   assert(fixed == 1);
3994   double res= args[0]->val_real();
3995   if ((null_value= args[0]->null_value))
3996     return 0.0;
3997   return res;
3998 }
3999 
val_int()4000 longlong Item_func_rollup_const::val_int()
4001 {
4002   assert(fixed == 1);
4003   longlong res= args[0]->val_int();
4004   if ((null_value= args[0]->null_value))
4005     return 0;
4006   return res;
4007 }
4008 
val_str(String * str)4009 String *Item_func_rollup_const::val_str(String *str)
4010 {
4011   assert(fixed == 1);
4012   String *res= args[0]->val_str(str);
4013   if ((null_value= args[0]->null_value))
4014     return 0;
4015   return res;
4016 }
4017 
val_decimal(my_decimal * dec)4018 my_decimal *Item_func_rollup_const::val_decimal(my_decimal *dec)
4019 {
4020   assert(fixed == 1);
4021   my_decimal *res= args[0]->val_decimal(dec);
4022   if ((null_value= args[0]->null_value))
4023     return 0;
4024   return res;
4025 }
4026 
4027 
val_json(Json_wrapper * result)4028 bool Item_func_rollup_const::val_json(Json_wrapper *result)
4029 {
4030   assert(fixed == 1);
4031   bool res= args[0]->val_json(result);
4032   null_value= args[0]->null_value;
4033   return res;
4034 }
4035 
4036 
val_int()4037 longlong Item_func_length::val_int()
4038 {
4039   assert(fixed == 1);
4040   String *res=args[0]->val_str(&value);
4041   if (!res)
4042   {
4043     null_value=1;
4044     return 0; /* purecov: inspected */
4045   }
4046   null_value=0;
4047   return (longlong) res->length();
4048 }
4049 
4050 
val_int()4051 longlong Item_func_char_length::val_int()
4052 {
4053   assert(fixed == 1);
4054   String *res=args[0]->val_str(&value);
4055   if (!res)
4056   {
4057     null_value=1;
4058     return 0; /* purecov: inspected */
4059   }
4060   null_value=0;
4061   return (longlong) res->numchars();
4062 }
4063 
4064 
val_int()4065 longlong Item_func_coercibility::val_int()
4066 {
4067   assert(fixed == 1);
4068   null_value= 0;
4069   return (longlong) args[0]->collation.derivation;
4070 }
4071 
4072 
fix_length_and_dec()4073 void Item_func_locate::fix_length_and_dec()
4074 {
4075   max_length= MY_INT32_NUM_DECIMAL_DIGITS;
4076   agg_arg_charsets_for_comparison(cmp_collation, args, 2);
4077 }
4078 
4079 
val_int()4080 longlong Item_func_locate::val_int()
4081 {
4082   assert(fixed == 1);
4083   String *a=args[0]->val_str(&value1);
4084   String *b=args[1]->val_str(&value2);
4085   if (!a || !b)
4086   {
4087     null_value=1;
4088     return 0; /* purecov: inspected */
4089   }
4090   null_value=0;
4091   /* must be longlong to avoid truncation */
4092   longlong start=  0;
4093   longlong start0= 0;
4094   my_match_t match;
4095 
4096   if (arg_count == 3)
4097   {
4098     start0= start= args[2]->val_int() - 1;
4099 
4100     if ((start < 0) || (start > static_cast<longlong>(a->length())))
4101       return 0;
4102 
4103     /* start is now sufficiently valid to pass to charpos function */
4104     start= a->charpos((int) start);
4105 
4106     if (start + b->length() > a->length())
4107       return 0;
4108   }
4109 
4110   if (!b->length())				// Found empty string at start
4111     return start + 1;
4112 
4113   if (!cmp_collation.collation->coll->instr(cmp_collation.collation,
4114                                             a->ptr()+start,
4115                                             (uint) (a->length()-start),
4116                                             b->ptr(), b->length(),
4117                                             &match, 1))
4118     return 0;
4119   return (longlong) match.mb_len + start0 + 1;
4120 }
4121 
4122 
print(String * str,enum_query_type query_type)4123 void Item_func_locate::print(String *str, enum_query_type query_type)
4124 {
4125   str->append(STRING_WITH_LEN("locate("));
4126   args[1]->print(str, query_type);
4127   str->append(',');
4128   args[0]->print(str, query_type);
4129   if (arg_count == 3)
4130   {
4131     str->append(',');
4132     args[2]->print(str, query_type);
4133   }
4134   str->append(')');
4135 }
4136 
4137 
val_int()4138 longlong Item_func_validate_password_strength::val_int()
4139 {
4140   char buff[STRING_BUFFER_USUAL_SIZE];
4141   String value(buff, sizeof(buff), system_charset_info);
4142   String *field= args[0]->val_str(&value);
4143   if ((null_value= args[0]->null_value) || field->length() == 0)
4144     return 0;
4145   return (my_calculate_password_strength(field->ptr(), field->length()));
4146 }
4147 
4148 
val_int()4149 longlong Item_func_field::val_int()
4150 {
4151   assert(fixed == 1);
4152 
4153   if (cmp_type == STRING_RESULT)
4154   {
4155     String *field;
4156     if (!(field= args[0]->val_str(&value)))
4157       return 0;
4158     for (uint i=1 ; i < arg_count ; i++)
4159     {
4160       String *tmp_value=args[i]->val_str(&tmp);
4161       if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
4162         return (longlong) (i);
4163     }
4164   }
4165   else if (cmp_type == INT_RESULT)
4166   {
4167     longlong val= args[0]->val_int();
4168     if (args[0]->null_value)
4169       return 0;
4170     for (uint i=1; i < arg_count ; i++)
4171     {
4172       if (val == args[i]->val_int() && !args[i]->null_value)
4173         return (longlong) (i);
4174     }
4175   }
4176   else if (cmp_type == DECIMAL_RESULT)
4177   {
4178     my_decimal dec_arg_buf, *dec_arg,
4179                dec_buf, *dec= args[0]->val_decimal(&dec_buf);
4180     if (args[0]->null_value)
4181       return 0;
4182     for (uint i=1; i < arg_count; i++)
4183     {
4184       dec_arg= args[i]->val_decimal(&dec_arg_buf);
4185       if (!args[i]->null_value && !my_decimal_cmp(dec_arg, dec))
4186         return (longlong) (i);
4187     }
4188   }
4189   else
4190   {
4191     double val= args[0]->val_real();
4192     if (args[0]->null_value)
4193       return 0;
4194     for (uint i=1; i < arg_count ; i++)
4195     {
4196       if (val == args[i]->val_real() && !args[i]->null_value)
4197         return (longlong) (i);
4198     }
4199   }
4200   return 0;
4201 }
4202 
4203 
fix_length_and_dec()4204 void Item_func_field::fix_length_and_dec()
4205 {
4206   maybe_null=0; max_length=3;
4207   cmp_type= args[0]->result_type();
4208   for (uint i=1; i < arg_count ; i++)
4209     cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
4210   if (cmp_type == STRING_RESULT)
4211     agg_arg_charsets_for_comparison(cmp_collation, args, arg_count);
4212 }
4213 
4214 
val_int()4215 longlong Item_func_ascii::val_int()
4216 {
4217   assert(fixed == 1);
4218   String *res=args[0]->val_str(&value);
4219   if (!res)
4220   {
4221     null_value=1;
4222     return 0;
4223   }
4224   null_value=0;
4225   return (longlong) (res->length() ? (uchar) (*res)[0] : (uchar) 0);
4226 }
4227 
val_int()4228 longlong Item_func_ord::val_int()
4229 {
4230   assert(fixed == 1);
4231   String *res=args[0]->val_str(&value);
4232   if (!res)
4233   {
4234     null_value=1;
4235     return 0;
4236   }
4237   null_value=0;
4238   if (!res->length()) return 0;
4239   if (use_mb(res->charset()))
4240   {
4241     const char *str=res->ptr();
4242     uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
4243     if (!l)
4244       return (longlong)((uchar) *str);
4245     while (l--)
4246       n=(n<<8)|(uint32)((uchar) *str++);
4247     return (longlong) n;
4248   }
4249   return (longlong) ((uchar) (*res)[0]);
4250 }
4251 
4252 	/* Search after a string in a string of strings separated by ',' */
4253 	/* Returns number of found type >= 1 or 0 if not found */
4254 	/* This optimizes searching in enums to bit testing! */
4255 
fix_length_and_dec()4256 void Item_func_find_in_set::fix_length_and_dec()
4257 {
4258   decimals=0;
4259   max_length=3;					// 1-999
4260   if (args[0]->const_item() && args[1]->type() == FIELD_ITEM)
4261   {
4262     Field *field= ((Item_field*) args[1])->field;
4263     if (field->real_type() == MYSQL_TYPE_SET)
4264     {
4265       String *find=args[0]->val_str(&value);
4266       if (find)
4267       {
4268         // find is not NULL pointer so args[0] is not a null-value
4269         assert(!args[0]->null_value);
4270 	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
4271 			      find->length(), 0);
4272 	enum_bit=0;
4273 	if (enum_value)
4274 	  enum_bit= 1LL << (enum_value-1);
4275       }
4276     }
4277   }
4278   agg_arg_charsets_for_comparison(cmp_collation, args, 2);
4279 }
4280 
4281 static const char separator=',';
4282 
val_int()4283 longlong Item_func_find_in_set::val_int()
4284 {
4285   assert(fixed == 1);
4286   if (enum_value)
4287   {
4288     // enum_value is set iff args[0]->const_item() in fix_length_and_dec().
4289     assert(args[0]->const_item());
4290 
4291     ulonglong tmp= (ulonglong) args[1]->val_int();
4292     null_value= args[1]->null_value;
4293     /*
4294       No need to check args[0]->null_value since enum_value is set iff
4295       args[0] is a non-null const item. Note: no assert on
4296       args[0]->null_value here because args[0] may have been replaced
4297       by an Item_cache on which val_int() has not been called. See
4298       BUG#11766317
4299     */
4300     if (!null_value)
4301     {
4302       if (tmp & enum_bit)
4303         return enum_value;
4304     }
4305     return 0L;
4306   }
4307 
4308   String *find=args[0]->val_str(&value);
4309   String *buffer=args[1]->val_str(&value2);
4310   if (!find || !buffer)
4311   {
4312     null_value=1;
4313     return 0; /* purecov: inspected */
4314   }
4315   null_value=0;
4316 
4317   if (buffer->length() >= find->length())
4318   {
4319     my_wc_t wc= 0;
4320     const CHARSET_INFO *cs= cmp_collation.collation;
4321     const char *str_begin= buffer->ptr();
4322     const char *str_end= buffer->ptr();
4323     const char *real_end= str_end+buffer->length();
4324     const uchar *find_str= (const uchar *) find->ptr();
4325     size_t find_str_len= find->length();
4326     int position= 0;
4327     while (1)
4328     {
4329       int symbol_len;
4330       if ((symbol_len= cs->cset->mb_wc(cs, &wc, (uchar*) str_end,
4331                                        (uchar*) real_end)) > 0)
4332       {
4333         const char *substr_end= str_end + symbol_len;
4334         bool is_last_item= (substr_end == real_end);
4335         bool is_separator= (wc == (my_wc_t) separator);
4336         if (is_separator || is_last_item)
4337         {
4338           position++;
4339           if (is_last_item && !is_separator)
4340             str_end= substr_end;
4341           if (!my_strnncoll(cs, (const uchar *) str_begin,
4342                             (uint) (str_end - str_begin),
4343                             find_str, find_str_len))
4344             return (longlong) position;
4345           else
4346             str_begin= substr_end;
4347         }
4348         str_end= substr_end;
4349       }
4350       else if (str_end - str_begin == 0 &&
4351                find_str_len == 0 &&
4352                wc == (my_wc_t) separator)
4353         return (longlong) ++position;
4354       else
4355         return 0LL;
4356     }
4357   }
4358   return 0;
4359 }
4360 
val_int()4361 longlong Item_func_bit_count::val_int()
4362 {
4363   assert(fixed == 1);
4364   ulonglong value= (ulonglong) args[0]->val_int();
4365   if ((null_value= args[0]->null_value))
4366     return 0; /* purecov: inspected */
4367   return (longlong) my_count_bits(value);
4368 }
4369 
4370 
4371 /****************************************************************************
4372 ** Functions to handle dynamic loadable functions
4373 ** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
4374 ** Rewritten by monty.
4375 ****************************************************************************/
4376 
4377 #ifdef HAVE_DLOPEN
4378 
cleanup()4379 void udf_handler::cleanup()
4380 {
4381   if (!not_original)
4382   {
4383     if (initialized)
4384     {
4385       if (u_d->func_deinit != NULL)
4386       {
4387         Udf_func_deinit deinit= u_d->func_deinit;
4388         (*deinit)(&initid);
4389       }
4390       free_udf(u_d);
4391       initialized= FALSE;
4392     }
4393     if (buffers)				// Because of bug in ecc
4394       delete [] buffers;
4395     buffers= 0;
4396   }
4397 }
4398 
4399 
4400 bool
fix_fields(THD * thd,Item_result_field * func,uint arg_count,Item ** arguments)4401 udf_handler::fix_fields(THD *thd, Item_result_field *func,
4402 			uint arg_count, Item **arguments)
4403 {
4404   uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
4405   DBUG_ENTER("Item_udf_func::fix_fields");
4406 
4407   if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
4408     DBUG_RETURN(TRUE);				// Fatal error flag is set!
4409 
4410   udf_func *tmp_udf=find_udf(u_d->name.str,(uint) u_d->name.length,1);
4411 
4412   if (!tmp_udf)
4413   {
4414     my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str);
4415     DBUG_RETURN(TRUE);
4416   }
4417   u_d=tmp_udf;
4418   args=arguments;
4419 
4420   /* Fix all arguments */
4421   func->maybe_null=0;
4422   used_tables_cache=0;
4423   const_item_cache=1;
4424 
4425   if ((f_args.arg_count=arg_count))
4426   {
4427     if (!(f_args.arg_type= (Item_result*)
4428 	  sql_alloc(f_args.arg_count*sizeof(Item_result))))
4429 
4430     {
4431       free_udf(u_d);
4432       DBUG_RETURN(TRUE);
4433     }
4434     uint i;
4435     Item **arg,**arg_end;
4436     for (i=0, arg=arguments, arg_end=arguments+arg_count;
4437 	 arg != arg_end ;
4438 	 arg++,i++)
4439     {
4440       if (!(*arg)->fixed &&
4441           (*arg)->fix_fields(thd, arg))
4442 	DBUG_RETURN(1);
4443       // we can't assign 'item' before, because fix_fields() can change arg
4444       Item *item= *arg;
4445       if (item->check_cols(1))
4446 	DBUG_RETURN(TRUE);
4447       /*
4448 	TODO: We should think about this. It is not always
4449 	right way just to set an UDF result to return my_charset_bin
4450 	if one argument has binary sorting order.
4451 	The result collation should be calculated according to arguments
4452 	derivations in some cases and should not in other cases.
4453 	Moreover, some arguments can represent a numeric input
4454 	which doesn't effect the result character set and collation.
4455 	There is no a general rule for UDF. Everything depends on
4456         the particular user defined function.
4457       */
4458       if (item->collation.collation->state & MY_CS_BINSORT)
4459 	func->collation.set(&my_charset_bin);
4460       if (item->maybe_null)
4461 	func->maybe_null=1;
4462       func->with_sum_func= func->with_sum_func || item->with_sum_func;
4463       used_tables_cache|=item->used_tables();
4464       const_item_cache&=item->const_item();
4465       f_args.arg_type[i]=item->result_type();
4466     }
4467     //TODO: why all following memory is not allocated with 1 call of sql_alloc?
4468     if (!(buffers=new String[arg_count]) ||
4469 	!(f_args.args= (char**) sql_alloc(arg_count * sizeof(char *))) ||
4470 	!(f_args.lengths= (ulong*) sql_alloc(arg_count * sizeof(long))) ||
4471 	!(f_args.maybe_null= (char*) sql_alloc(arg_count * sizeof(char))) ||
4472 	!(num_buffer= (char*) sql_alloc(arg_count *
4473 					ALIGN_SIZE(sizeof(double)))) ||
4474 	!(f_args.attributes= (char**) sql_alloc(arg_count * sizeof(char *))) ||
4475 	!(f_args.attribute_lengths= (ulong*) sql_alloc(arg_count *
4476 						       sizeof(long))))
4477     {
4478       free_udf(u_d);
4479       DBUG_RETURN(TRUE);
4480     }
4481   }
4482   func->fix_length_and_dec();
4483   initid.max_length=func->max_length;
4484   initid.maybe_null=func->maybe_null;
4485   initid.const_item=const_item_cache;
4486   initid.decimals=func->decimals;
4487   initid.ptr=0;
4488 
4489   if (u_d->func_init)
4490   {
4491     char init_msg_buff[MYSQL_ERRMSG_SIZE];
4492     char *to=num_buffer;
4493     for (uint i=0; i < arg_count; i++)
4494     {
4495       /*
4496        For a constant argument i, args->args[i] points to the argument value.
4497        For non-constant, args->args[i] is NULL.
4498       */
4499       f_args.args[i]= NULL;         /* Non-const unless updated below. */
4500 
4501       f_args.lengths[i]= arguments[i]->max_length;
4502       f_args.maybe_null[i]= arguments[i]->maybe_null;
4503       f_args.attributes[i]= (char*) arguments[i]->item_name.ptr();
4504       f_args.attribute_lengths[i]= arguments[i]->item_name.length();
4505 
4506       if (arguments[i]->const_item())
4507       {
4508         switch (arguments[i]->result_type())
4509         {
4510         case STRING_RESULT:
4511         case DECIMAL_RESULT:
4512         {
4513           String *res= arguments[i]->val_str(&buffers[i]);
4514           if (arguments[i]->null_value)
4515             continue;
4516           f_args.args[i]= res->c_ptr_safe();
4517           f_args.lengths[i]= res->length();
4518           break;
4519         }
4520         case INT_RESULT:
4521           *((longlong*) to)= arguments[i]->val_int();
4522           if (arguments[i]->null_value)
4523             continue;
4524           f_args.args[i]= to;
4525           to+= ALIGN_SIZE(sizeof(longlong));
4526           break;
4527         case REAL_RESULT:
4528           *((double*) to)= arguments[i]->val_real();
4529           if (arguments[i]->null_value)
4530             continue;
4531           f_args.args[i]= to;
4532           to+= ALIGN_SIZE(sizeof(double));
4533           break;
4534         case ROW_RESULT:
4535         default:
4536           // This case should never be chosen
4537           assert(0);
4538           break;
4539         }
4540       }
4541     }
4542     Udf_func_init init= u_d->func_init;
4543     if ((error=(uchar) init(&initid, &f_args, init_msg_buff)))
4544     {
4545       my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
4546                u_d->name.str, init_msg_buff);
4547       free_udf(u_d);
4548       DBUG_RETURN(TRUE);
4549     }
4550     func->max_length= min<uint32>(initid.max_length, MAX_BLOB_WIDTH);
4551     func->maybe_null=initid.maybe_null;
4552     const_item_cache=initid.const_item;
4553     /*
4554       Keep used_tables_cache in sync with const_item_cache.
4555       See the comment in Item_udf_func::update_used tables.
4556     */
4557     if (!const_item_cache && !used_tables_cache)
4558       used_tables_cache= RAND_TABLE_BIT;
4559     func->decimals= min<uint>(initid.decimals, NOT_FIXED_DEC);
4560   }
4561   initialized=1;
4562   if (error)
4563   {
4564     my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
4565              u_d->name.str, ER(ER_UNKNOWN_ERROR));
4566     DBUG_RETURN(TRUE);
4567   }
4568   DBUG_RETURN(FALSE);
4569 }
4570 
4571 
get_arguments()4572 bool udf_handler::get_arguments()
4573 {
4574   if (error)
4575     return 1;					// Got an error earlier
4576   char *to= num_buffer;
4577   uint str_count=0;
4578   for (uint i=0; i < f_args.arg_count; i++)
4579   {
4580     f_args.args[i]=0;
4581     switch (f_args.arg_type[i]) {
4582     case STRING_RESULT:
4583     case DECIMAL_RESULT:
4584       {
4585 	String *res=args[i]->val_str(&buffers[str_count++]);
4586 	if (!(args[i]->null_value))
4587 	{
4588 	  f_args.args[i]=    res->c_ptr_safe();
4589 	  f_args.lengths[i]= res->length();
4590 	}
4591 	else
4592 	{
4593 	  f_args.lengths[i]= 0;
4594 	}
4595 	break;
4596       }
4597     case INT_RESULT:
4598       *((longlong*) to) = args[i]->val_int();
4599       if (!args[i]->null_value)
4600       {
4601 	f_args.args[i]=to;
4602 	to+= ALIGN_SIZE(sizeof(longlong));
4603       }
4604       break;
4605     case REAL_RESULT:
4606       *((double*) to)= args[i]->val_real();
4607       if (!args[i]->null_value)
4608       {
4609 	f_args.args[i]=to;
4610 	to+= ALIGN_SIZE(sizeof(double));
4611       }
4612       break;
4613     case ROW_RESULT:
4614     default:
4615       // This case should never be chosen
4616       assert(0);
4617       break;
4618     }
4619   }
4620   return 0;
4621 }
4622 
4623 /**
4624   @return
4625     (String*)NULL in case of NULL values
4626 */
val_str(String * str,String * save_str)4627 String *udf_handler::val_str(String *str,String *save_str)
4628 {
4629   uchar is_null_tmp=0;
4630   ulong res_length;
4631   DBUG_ENTER("udf_handler::val_str");
4632 
4633   if (get_arguments())
4634     DBUG_RETURN(0);
4635   char * (*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
4636     (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
4637     u_d->func;
4638 
4639   if ((res_length=str->alloced_length()) < MAX_FIELD_WIDTH)
4640   {						// This happens VERY seldom
4641     if (str->alloc(MAX_FIELD_WIDTH))
4642     {
4643       error=1;
4644       DBUG_RETURN(0);
4645     }
4646   }
4647   char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
4648 		 &is_null_tmp, &error);
4649   DBUG_PRINT("info", ("udf func returned, res_length: %lu", res_length));
4650   if (is_null_tmp || !res || error)		// The !res is for safety
4651   {
4652     DBUG_PRINT("info", ("Null or error"));
4653     DBUG_RETURN(0);
4654   }
4655   if (res == str->ptr())
4656   {
4657     str->length(res_length);
4658     DBUG_PRINT("exit", ("str: %*.s", (int) str->length(), str->ptr()));
4659     DBUG_RETURN(str);
4660   }
4661   save_str->set(res, res_length, str->charset());
4662   DBUG_PRINT("exit", ("save_str: %s", save_str->ptr()));
4663   DBUG_RETURN(save_str);
4664 }
4665 
4666 
4667 /*
4668   For the moment, UDF functions are returning DECIMAL values as strings
4669 */
4670 
val_decimal(my_bool * null_value,my_decimal * dec_buf)4671 my_decimal *udf_handler::val_decimal(my_bool *null_value, my_decimal *dec_buf)
4672 {
4673   char buf[DECIMAL_MAX_STR_LENGTH+1], *end;
4674   ulong res_length= DECIMAL_MAX_STR_LENGTH;
4675 
4676   if (get_arguments())
4677   {
4678     *null_value=1;
4679     return 0;
4680   }
4681   char *(*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
4682     (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
4683     u_d->func;
4684 
4685   char *res= func(&initid, &f_args, buf, &res_length, &is_null, &error);
4686   if (is_null || error)
4687   {
4688     *null_value= 1;
4689     return 0;
4690   }
4691   end= res+ res_length;
4692   str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end);
4693   return dec_buf;
4694 }
4695 
4696 
itemize(Parse_context * pc,Item ** res)4697 bool Item_udf_func::itemize(Parse_context *pc, Item **res)
4698 {
4699   if (skip_itemize(res))
4700     return false;
4701   if (super::itemize(pc, res))
4702     return true;
4703   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_UDF);
4704   pc->thd->lex->safe_to_cache_query= false;
4705   return false;
4706 }
4707 
4708 
cleanup()4709 void Item_udf_func::cleanup()
4710 {
4711   udf.cleanup();
4712   Item_func::cleanup();
4713 }
4714 
4715 
print(String * str,enum_query_type query_type)4716 void Item_udf_func::print(String *str, enum_query_type query_type)
4717 {
4718   str->append(func_name());
4719   str->append('(');
4720   for (uint i=0 ; i < arg_count ; i++)
4721   {
4722     if (i != 0)
4723       str->append(',');
4724     args[i]->print_item_w_name(str, query_type);
4725   }
4726   str->append(')');
4727 }
4728 
4729 
val_real()4730 double Item_func_udf_float::val_real()
4731 {
4732   assert(fixed == 1);
4733   DBUG_ENTER("Item_func_udf_float::val");
4734   DBUG_PRINT("info",("result_type: %d  arg_count: %d",
4735 		     args[0]->result_type(), arg_count));
4736   DBUG_RETURN(udf.val(&null_value));
4737 }
4738 
4739 
val_str(String * str)4740 String *Item_func_udf_float::val_str(String *str)
4741 {
4742   assert(fixed == 1);
4743   double nr= val_real();
4744   if (null_value)
4745     return 0;					/* purecov: inspected */
4746   str->set_real(nr,decimals,&my_charset_bin);
4747   return str;
4748 }
4749 
4750 
val_int()4751 longlong Item_func_udf_int::val_int()
4752 {
4753   assert(fixed == 1);
4754   DBUG_ENTER("Item_func_udf_int::val_int");
4755   DBUG_RETURN(udf.val_int(&null_value));
4756 }
4757 
4758 
val_str(String * str)4759 String *Item_func_udf_int::val_str(String *str)
4760 {
4761   assert(fixed == 1);
4762   longlong nr=val_int();
4763   if (null_value)
4764     return 0;
4765   str->set_int(nr, unsigned_flag, &my_charset_bin);
4766   return str;
4767 }
4768 
4769 
val_int()4770 longlong Item_func_udf_decimal::val_int()
4771 {
4772   my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
4773   longlong result;
4774   if (null_value)
4775     return 0;
4776   my_decimal2int(E_DEC_FATAL_ERROR, dec, unsigned_flag, &result);
4777   return result;
4778 }
4779 
4780 
val_real()4781 double Item_func_udf_decimal::val_real()
4782 {
4783   my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
4784   double result;
4785   if (null_value)
4786     return 0.0;
4787   my_decimal2double(E_DEC_FATAL_ERROR, dec, &result);
4788   return result;
4789 }
4790 
4791 
val_decimal(my_decimal * dec_buf)4792 my_decimal *Item_func_udf_decimal::val_decimal(my_decimal *dec_buf)
4793 {
4794   assert(fixed == 1);
4795   DBUG_ENTER("Item_func_udf_decimal::val_decimal");
4796   DBUG_PRINT("info",("result_type: %d  arg_count: %d",
4797                      args[0]->result_type(), arg_count));
4798 
4799   DBUG_RETURN(udf.val_decimal(&null_value, dec_buf));
4800 }
4801 
4802 
val_str(String * str)4803 String *Item_func_udf_decimal::val_str(String *str)
4804 {
4805   my_decimal dec_buf, *dec= udf.val_decimal(&null_value, &dec_buf);
4806   if (null_value)
4807     return 0;
4808   if (str->length() < DECIMAL_MAX_STR_LENGTH)
4809     str->length(DECIMAL_MAX_STR_LENGTH);
4810   my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
4811   my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, '0', str);
4812   return str;
4813 }
4814 
4815 
fix_length_and_dec()4816 void Item_func_udf_decimal::fix_length_and_dec()
4817 {
4818   fix_num_length_and_dec();
4819 }
4820 
4821 
4822 /* Default max_length is max argument length */
4823 
fix_length_and_dec()4824 void Item_func_udf_str::fix_length_and_dec()
4825 {
4826   DBUG_ENTER("Item_func_udf_str::fix_length_and_dec");
4827   max_length=0;
4828   for (uint i = 0; i < arg_count; i++)
4829     set_if_bigger(max_length,args[i]->max_length);
4830   DBUG_VOID_RETURN;
4831 }
4832 
val_str(String * str)4833 String *Item_func_udf_str::val_str(String *str)
4834 {
4835   assert(fixed == 1);
4836   String *res=udf.val_str(str,&str_value);
4837   null_value = !res;
4838   return res;
4839 }
4840 
~udf_handler()4841 udf_handler::~udf_handler()
4842 {
4843   /* Everything should be properly cleaned up by this moment. */
4844   assert(not_original || !(initialized || buffers));
4845 }
4846 
4847 #else
get_arguments()4848 bool udf_handler::get_arguments() { return 0; }
4849 #endif /* HAVE_DLOPEN */
4850 
4851 
itemize(Parse_context * pc,Item ** res)4852 bool Item_master_pos_wait::itemize(Parse_context *pc, Item **res)
4853 {
4854   if (skip_itemize(res))
4855     return false;
4856   if (super::itemize(pc, res))
4857     return true;
4858   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
4859   pc->thd->lex->safe_to_cache_query= false;
4860   return false;
4861 }
4862 
4863 
4864 /**
4865   Wait until we are at or past the given position in the master binlog
4866   on the slave.
4867 */
4868 
val_int()4869 longlong Item_master_pos_wait::val_int()
4870 {
4871   assert(fixed == 1);
4872   THD* thd = current_thd;
4873   String *log_name = args[0]->val_str(&value);
4874   int event_count= 0;
4875 
4876   null_value=0;
4877   if (thd->slave_thread || !log_name || !log_name->length())
4878   {
4879     null_value = 1;
4880     return 0;
4881   }
4882 #ifdef HAVE_REPLICATION
4883   Master_info *mi;
4884   longlong pos = (ulong)args[1]->val_int();
4885   double timeout = (arg_count >= 3) ? args[2]->val_real() : 0;
4886   if (timeout < 0)
4887   {
4888     if (thd->is_strict_mode())
4889     {
4890       my_error(ER_WRONG_ARGUMENTS, MYF(0), "MASTER_POS_WAIT.");
4891     }
4892     else
4893     {
4894       push_warning_printf(thd, Sql_condition::SL_WARNING,
4895                           ER_WRONG_ARGUMENTS,
4896                           ER(ER_WRONG_ARGUMENTS),
4897                           "MASTER_POS_WAIT.");
4898       null_value= 1;
4899     }
4900     return 0;
4901   }
4902 
4903   channel_map.rdlock();
4904 
4905   if (arg_count == 4)
4906   {
4907     String *channel_str;
4908     if(!(channel_str= args[3]->val_str(&value)))
4909     {
4910       null_value= 1;
4911       return 0;
4912     }
4913 
4914     mi= channel_map.get_mi(channel_str->ptr());
4915 
4916   }
4917   else
4918   {
4919     if (channel_map.get_num_instances() > 1)
4920     {
4921       mi = NULL;
4922       my_error(ER_SLAVE_MULTIPLE_CHANNELS_CMD, MYF(0));
4923     }
4924     else
4925       mi= channel_map.get_default_channel_mi();
4926   }
4927 
4928   if (mi != NULL)
4929     mi->inc_reference();
4930 
4931   channel_map.unlock();
4932 
4933   if (mi == NULL ||
4934       (event_count = mi->rli->wait_for_pos(thd, log_name, pos, timeout)) == -2)
4935   {
4936     null_value = 1;
4937     event_count=0;
4938   }
4939 
4940   if (mi != NULL)
4941     mi->dec_reference();
4942 #endif
4943   return event_count;
4944 }
4945 
itemize(Parse_context * pc,Item ** res)4946 bool Item_wait_for_executed_gtid_set::itemize(Parse_context *pc, Item **res)
4947 {
4948   if (skip_itemize(res))
4949     return false;
4950   if (super::itemize(pc, res))
4951     return true;
4952   /*
4953     It is unsafe because the return value depends on timing. If the timeout
4954     happens, the return value is different from the one in which the function
4955     returns with success.
4956   */
4957   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
4958   pc->thd->lex->safe_to_cache_query= false;
4959   return false;
4960 }
4961 
4962 /**
4963   Wait until the given gtid_set is found in the executed gtid_set independent
4964   of the slave threads.
4965 */
val_int()4966 longlong Item_wait_for_executed_gtid_set::val_int()
4967 {
4968   DBUG_ENTER("Item_wait_for_executed_gtid_set::val_int");
4969   assert(fixed == 1);
4970   THD* thd= current_thd;
4971   String *gtid_text= args[0]->val_str(&value);
4972 
4973   null_value= 0;
4974 
4975   if (gtid_text == NULL)
4976   {
4977     my_error(ER_MALFORMED_GTID_SET_SPECIFICATION, MYF(0), "NULL");
4978     DBUG_RETURN(0);
4979   }
4980 
4981   // Waiting for a GTID in a slave thread could cause the slave to
4982   // hang/deadlock.
4983   if (thd->slave_thread)
4984   {
4985     null_value= 1;
4986     DBUG_RETURN(0);
4987   }
4988 
4989   Gtid_set wait_for_gtid_set(global_sid_map, NULL);
4990 
4991   global_sid_lock->rdlock();
4992   if (get_gtid_mode(GTID_MODE_LOCK_SID) == GTID_MODE_OFF)
4993   {
4994     global_sid_lock->unlock();
4995     my_error(ER_GTID_MODE_OFF, MYF(0), "use WAIT_FOR_EXECUTED_GTID_SET");
4996     null_value= 1;
4997     DBUG_RETURN(0);
4998   }
4999 
5000   if (wait_for_gtid_set.add_gtid_text(gtid_text->c_ptr_safe()) !=
5001       RETURN_STATUS_OK)
5002   {
5003     global_sid_lock->unlock();
5004     // Error has already been generated.
5005     DBUG_RETURN(1);
5006   }
5007 
5008   // Cannot wait for a GTID that the thread owns since that would
5009   // immediately deadlock.
5010   if (thd->owned_gtid.sidno > 0 &&
5011       wait_for_gtid_set.contains_gtid(thd->owned_gtid))
5012   {
5013     char buf[Gtid::MAX_TEXT_LENGTH + 1];
5014     thd->owned_gtid.to_string(global_sid_map, buf);
5015     global_sid_lock->unlock();
5016     my_error(ER_CANT_WAIT_FOR_EXECUTED_GTID_SET_WHILE_OWNING_A_GTID, MYF(0),
5017              buf);
5018     DBUG_RETURN(0);
5019   }
5020 
5021   gtid_state->begin_gtid_wait(GTID_MODE_LOCK_SID);
5022 
5023   double timeout = (arg_count == 2) ? args[1]->val_real() : 0;
5024   if (timeout < 0)
5025   {
5026     if (thd->is_strict_mode())
5027     {
5028       my_error(ER_WRONG_ARGUMENTS, MYF(0), "WAIT_FOR_EXECUTED_GTID_SET.");
5029     }
5030     else
5031     {
5032       push_warning_printf(thd, Sql_condition::SL_WARNING,
5033                           ER_WRONG_ARGUMENTS,
5034                           ER(ER_WRONG_ARGUMENTS),
5035                           "WAIT_FOR_EXECUTED_GTID_SET.");
5036       null_value= 1;
5037     }
5038     gtid_state->end_gtid_wait();
5039     global_sid_lock->unlock();
5040     DBUG_RETURN(0);
5041   }
5042 
5043   bool result= gtid_state->wait_for_gtid_set(thd, &wait_for_gtid_set, timeout);
5044   global_sid_lock->unlock();
5045   gtid_state->end_gtid_wait();
5046 
5047   DBUG_RETURN(result);
5048 }
5049 
itemize(Parse_context * pc,Item ** res)5050 bool Item_master_gtid_set_wait::itemize(Parse_context *pc, Item **res)
5051 {
5052   if (skip_itemize(res))
5053     return false;
5054   if (super::itemize(pc, res))
5055     return true;
5056   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5057   pc->thd->lex->safe_to_cache_query= false;
5058   return false;
5059 }
5060 
5061 
val_int()5062 longlong Item_master_gtid_set_wait::val_int()
5063 {
5064   assert(fixed == 1);
5065   DBUG_ENTER("Item_master_gtid_set_wait::val_int");
5066   int event_count= 0;
5067 
5068   null_value=0;
5069 
5070 #if defined(HAVE_REPLICATION)
5071   String *gtid= args[0]->val_str(&value);
5072   THD* thd = current_thd;
5073   Master_info *mi= NULL;
5074   double timeout = (arg_count >= 2) ? args[1]->val_real() : 0;
5075   if (timeout < 0)
5076   {
5077     if (thd->is_strict_mode())
5078     {
5079       my_error(ER_WRONG_ARGUMENTS, MYF(0), "WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS.");
5080     }
5081     else
5082     {
5083       push_warning_printf(thd, Sql_condition::SL_WARNING,
5084                           ER_WRONG_ARGUMENTS,
5085                           ER(ER_WRONG_ARGUMENTS),
5086                           "WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS.");
5087       null_value= 1;
5088     }
5089     DBUG_RETURN(0);
5090   }
5091 
5092   if (thd->slave_thread || !gtid)
5093   {
5094     null_value = 1;
5095     DBUG_RETURN(0);
5096   }
5097 
5098   channel_map.rdlock();
5099 
5100   /* If replication channel is mentioned */
5101   if (arg_count == 3)
5102   {
5103     String *channel_str;
5104     if (!(channel_str= args[2]->val_str(&value)))
5105     {
5106       channel_map.unlock();
5107       null_value= 1;
5108       DBUG_RETURN(0);
5109     }
5110     mi= channel_map.get_mi(channel_str->ptr());
5111   }
5112   else
5113   {
5114     if (channel_map.get_num_instances() > 1)
5115     {
5116       channel_map.unlock();
5117       mi = NULL;
5118       my_error(ER_SLAVE_MULTIPLE_CHANNELS_CMD, MYF(0));
5119       DBUG_RETURN(0);
5120     }
5121     else
5122       mi= channel_map.get_default_channel_mi();
5123   }
5124 
5125   if (get_gtid_mode(GTID_MODE_LOCK_CHANNEL_MAP) == GTID_MODE_OFF)
5126   {
5127     null_value= 1;
5128     channel_map.unlock();
5129     DBUG_RETURN(0);
5130   }
5131   gtid_state->begin_gtid_wait(GTID_MODE_LOCK_CHANNEL_MAP);
5132 
5133   if (mi)
5134     mi->inc_reference();
5135 
5136   channel_map.unlock();
5137 
5138   if (mi && mi->rli)
5139   {
5140     event_count = mi->rli->wait_for_gtid_set(thd, gtid, timeout);
5141     if (event_count == -2)
5142     {
5143       null_value = 1;
5144       event_count=0;
5145     }
5146   }
5147   else
5148     /*
5149       Replication has not been set up, we should return NULL;
5150      */
5151     null_value = 1;
5152 
5153   if (mi != NULL)
5154     mi->dec_reference();
5155 #endif
5156 
5157   gtid_state->end_gtid_wait();
5158 
5159   DBUG_RETURN(event_count);
5160 }
5161 
5162 /**
5163   Return 1 if both arguments are Gtid_sets and the first is a subset
5164   of the second.  Generate an error if any of the arguments is not a
5165   Gtid_set.
5166 */
val_int()5167 longlong Item_func_gtid_subset::val_int()
5168 {
5169   DBUG_ENTER("Item_func_gtid_subset::val_int()");
5170   if (args[0]->null_value || args[1]->null_value)
5171   {
5172     null_value= true;
5173     DBUG_RETURN(0);
5174   }
5175   String *string1, *string2;
5176   const char *charp1, *charp2;
5177   int ret= 1;
5178   enum_return_status status;
5179   // get strings without lock
5180   if ((string1= args[0]->val_str(&buf1)) != NULL &&
5181       (charp1= string1->c_ptr_safe()) != NULL &&
5182       (string2= args[1]->val_str(&buf2)) != NULL &&
5183       (charp2= string2->c_ptr_safe()) != NULL)
5184   {
5185     Sid_map sid_map(NULL/*no rwlock*/);
5186     // compute sets while holding locks
5187     const Gtid_set sub_set(&sid_map, charp1, &status);
5188     if (status == RETURN_STATUS_OK)
5189     {
5190       const Gtid_set super_set(&sid_map, charp2, &status);
5191       if (status == RETURN_STATUS_OK)
5192         ret= sub_set.is_subset(&super_set) ? 1 : 0;
5193     }
5194   }
5195   DBUG_RETURN(ret);
5196 }
5197 
5198 
5199 /**
5200   Enables a session to wait on a condition until a timeout or a network
5201   disconnect occurs.
5202 
5203   @remark The connection is polled every m_interrupt_interval nanoseconds.
5204 */
5205 
5206 class Interruptible_wait
5207 {
5208   THD *m_thd;
5209   struct timespec m_abs_timeout;
5210   static const ulonglong m_interrupt_interval;
5211 
5212   public:
Interruptible_wait(THD * thd)5213     Interruptible_wait(THD *thd)
5214     : m_thd(thd) {}
5215 
~Interruptible_wait()5216     ~Interruptible_wait() {}
5217 
5218   public:
5219     /**
5220       Set the absolute timeout.
5221 
5222       @param timeout The amount of time in nanoseconds to wait
5223     */
set_timeout(ulonglong timeout)5224     void set_timeout(ulonglong timeout)
5225     {
5226       /*
5227         Calculate the absolute system time at the start so it can
5228         be controlled in slices. It relies on the fact that once
5229         the absolute time passes, the timed wait call will fail
5230         automatically with a timeout error.
5231       */
5232       set_timespec_nsec(&m_abs_timeout, timeout);
5233     }
5234 
5235     /** The timed wait. */
5236     int wait(mysql_cond_t *, mysql_mutex_t *);
5237 };
5238 
5239 
5240 /** Time to wait before polling the connection status. */
5241 const ulonglong Interruptible_wait::m_interrupt_interval= 5 * 1000000000ULL;
5242 
5243 
5244 /**
5245   Wait for a given condition to be signaled.
5246 
5247   @param cond   The condition variable to wait on.
5248   @param mutex  The associated mutex.
5249 
5250   @remark The absolute timeout is preserved across calls.
5251 
5252   @retval return value from mysql_cond_timedwait
5253 */
5254 
wait(mysql_cond_t * cond,mysql_mutex_t * mutex)5255 int Interruptible_wait::wait(mysql_cond_t *cond, mysql_mutex_t *mutex)
5256 {
5257   int error;
5258   struct timespec timeout;
5259 
5260   while (1)
5261   {
5262     /* Wait for a fixed interval. */
5263     set_timespec_nsec(&timeout, m_interrupt_interval);
5264 
5265     /* But only if not past the absolute timeout. */
5266     if (cmp_timespec(&timeout, &m_abs_timeout) > 0)
5267       timeout= m_abs_timeout;
5268 
5269     error= mysql_cond_timedwait(cond, mutex, &timeout);
5270     if (error == ETIMEDOUT || error == ETIME)
5271     {
5272       /* Return error if timed out or connection is broken. */
5273       if (!cmp_timespec(&timeout, &m_abs_timeout) || !m_thd->is_connected())
5274         break;
5275     }
5276     /* Otherwise, propagate status to the caller. */
5277     else
5278       break;
5279   }
5280 
5281   return error;
5282 }
5283 
5284 
5285 /*
5286   User-level locks implementation.
5287 */
5288 
5289 
5290 /**
5291   For locks with EXPLICIT duration, MDL returns a new ticket
5292   every time a lock is granted. This allows to implement recursive
5293   locks without extra allocation or additional data structures, such
5294   as below. However, if there are too many tickets in the same
5295   MDL_context, MDL_context::find_ticket() is getting too slow,
5296   since it's using a linear search.
5297   This is why a separate structure is allocated for a user
5298   level lock held by connection, and before requesting a new lock from MDL,
5299   GET_LOCK() checks thd->ull_hash if such lock is already granted,
5300   and if so, simply increments a reference counter.
5301 */
5302 
5303 struct User_level_lock
5304 {
5305   MDL_ticket *ticket;
5306   uint refs;
5307 };
5308 
5309 
5310 /** Extract a hash key from User_level_lock. */
5311 
ull_get_key(const uchar * ptr,size_t * length,my_bool not_used MY_ATTRIBUTE ((unused)))5312 uchar *ull_get_key(const uchar *ptr, size_t *length,
5313                    my_bool not_used MY_ATTRIBUTE((unused)))
5314 {
5315   const User_level_lock *ull = reinterpret_cast<const User_level_lock*>(ptr);
5316   const MDL_key *key = ull->ticket->get_key();
5317   *length= key->length();
5318   return const_cast<uchar*>(key->ptr());
5319 }
5320 
5321 
5322 /**
5323   Release all user level locks for this THD.
5324 */
5325 
mysql_ull_cleanup(THD * thd)5326 void mysql_ull_cleanup(THD *thd)
5327 {
5328   User_level_lock *ull;
5329   DBUG_ENTER("mysql_ull_cleanup");
5330 
5331   for (ulong i= 0; i < thd->ull_hash.records; i++)
5332   {
5333     ull= reinterpret_cast<User_level_lock*>(my_hash_element(&thd->ull_hash, i));
5334     thd->mdl_context.release_lock(ull->ticket);
5335     my_free(ull);
5336   }
5337 
5338   my_hash_free(&thd->ull_hash);
5339 
5340   DBUG_VOID_RETURN;
5341 }
5342 
5343 
5344 /**
5345   Set explicit duration for metadata locks corresponding to
5346   user level locks to protect them from being released at the end
5347   of transaction.
5348 */
5349 
mysql_ull_set_explicit_lock_duration(THD * thd)5350 void mysql_ull_set_explicit_lock_duration(THD *thd)
5351 {
5352   User_level_lock *ull;
5353   DBUG_ENTER("mysql_ull_set_explicit_lock_duration");
5354 
5355   for (ulong i= 0; i < thd->ull_hash.records; i++)
5356   {
5357     ull= reinterpret_cast<User_level_lock*>(my_hash_element(&thd->ull_hash, i));
5358     thd->mdl_context.set_lock_duration(ull->ticket, MDL_EXPLICIT);
5359   }
5360   DBUG_VOID_RETURN;
5361 }
5362 
5363 
5364 /**
5365   When MDL detects a lock wait timeout, it pushes an error into the statement
5366   diagnostics area. For GET_LOCK(), lock wait timeout is not an error, but a
5367   special return value (0). NULL is returned in case of error. Capture and
5368   suppress lock wait timeout.
5369   We also convert ER_LOCK_DEADLOCK error to ER_USER_LOCK_DEADLOCK error.
5370   The former means that implicit rollback of transaction has occurred
5371   which doesn't (and should not) happen when we get deadlock while waiting
5372   for user-level lock.
5373 */
5374 
5375 class User_level_lock_wait_error_handler: public Internal_error_handler
5376 {
5377 public:
User_level_lock_wait_error_handler()5378   User_level_lock_wait_error_handler()
5379     : m_lock_wait_timeout(false)
5380   { }
5381 
got_timeout() const5382   bool got_timeout() const { return m_lock_wait_timeout; }
5383 
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_severity_level * level,const char * msg)5384   virtual bool handle_condition(THD *thd,
5385                                 uint sql_errno,
5386                                 const char *sqlstate,
5387                                 Sql_condition::enum_severity_level *level,
5388                                 const char *msg)
5389   {
5390     if (sql_errno == ER_LOCK_WAIT_TIMEOUT)
5391     {
5392       m_lock_wait_timeout= true;
5393       return true;
5394     }
5395     else if (sql_errno == ER_LOCK_DEADLOCK)
5396     {
5397       my_error(ER_USER_LOCK_DEADLOCK, MYF(0));
5398       return true;
5399     }
5400 
5401     return false;
5402   }
5403 
5404 private:
5405   bool m_lock_wait_timeout;
5406 };
5407 
5408 
5409 class MDL_lock_get_owner_thread_id_visitor : public MDL_context_visitor
5410 {
5411 public:
MDL_lock_get_owner_thread_id_visitor()5412   MDL_lock_get_owner_thread_id_visitor()
5413     : m_owner_id(0)
5414   { }
5415 
visit_context(const MDL_context * ctx)5416   void visit_context(const MDL_context *ctx)
5417   {
5418     m_owner_id= ctx->get_owner()->get_thd()->thread_id();
5419   }
5420 
get_owner_id() const5421   my_thread_id get_owner_id() const { return m_owner_id; }
5422 
5423 private:
5424   my_thread_id m_owner_id;
5425 };
5426 
5427 
5428 /**
5429   Helper function which checks if user-level lock name is acceptable
5430   and converts it to system charset (utf8). Error is emitted if name
5431   is not acceptable. Name is also lowercased to ensure that user-level
5432   lock names are treated in case-insensitive fashion even though MDL
5433   subsystem which used by implementation does binary comparison of keys.
5434 
5435   @param buff      Buffer for lowercased name in system charset of
5436                    NAME_LEN + 1 bytes length.
5437   @param org_name  Original string passed as name parameter to
5438                    user-level lock function.
5439 
5440   @return True in case of error, false on success.
5441 */
5442 
check_and_convert_ull_name(char * buff,String * org_name)5443 static bool check_and_convert_ull_name(char *buff, String *org_name)
5444 {
5445   if (!org_name || !org_name->length())
5446   {
5447     my_error(ER_USER_LOCK_WRONG_NAME, MYF(0), (org_name ? "" : "NULL"));
5448     return true;
5449   }
5450 
5451   const char *well_formed_error_pos;
5452   const char *cannot_convert_error_pos;
5453   const char *from_end_pos;
5454   size_t bytes_copied;
5455 
5456   bytes_copied= well_formed_copy_nchars(system_charset_info,
5457                                         buff, NAME_LEN,
5458                                         org_name->charset(),
5459                                         org_name->ptr(), org_name->length(),
5460                                         NAME_CHAR_LEN,
5461                                         &well_formed_error_pos,
5462                                         &cannot_convert_error_pos,
5463                                         &from_end_pos);
5464 
5465   if (well_formed_error_pos || cannot_convert_error_pos ||
5466       from_end_pos < org_name->ptr() + org_name->length())
5467   {
5468     ErrConvString err(org_name);
5469     my_error(ER_USER_LOCK_WRONG_NAME, MYF(0), err.ptr());
5470     return true;
5471   }
5472 
5473   buff[bytes_copied]= '\0';
5474 
5475   my_casedn_str(system_charset_info, buff);
5476 
5477   return false;
5478 }
5479 
5480 
itemize(Parse_context * pc,Item ** res)5481 bool Item_func_get_lock::itemize(Parse_context *pc, Item **res)
5482 {
5483   if (skip_itemize(res))
5484     return false;
5485   if (super::itemize(pc, res))
5486     return true;
5487   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5488   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5489   return false;
5490 }
5491 
5492 
5493 /**
5494   Get a user level lock.
5495 
5496   @note Sets null_value to TRUE on error.
5497 
5498   @note This means that SQL-function GET_LOCK() returns:
5499         1    - if lock was acquired.
5500         0    - if lock was not acquired due to timeout.
5501         NULL - in case of error such as bad lock name, deadlock,
5502                thread being killed (also error is emitted).
5503 
5504   @retval
5505     1    : Got lock
5506   @retval
5507     0    : Timeout, error.
5508 */
5509 
val_int()5510 longlong Item_func_get_lock::val_int()
5511 {
5512   assert(fixed == 1);
5513   String *res= args[0]->val_str(&value);
5514   ulonglong timeout= args[1]->val_int();
5515   char name[NAME_LEN + 1];
5516   THD *thd= current_thd;
5517   User_level_lock *ull;
5518   DBUG_ENTER("Item_func_get_lock::val_int");
5519 
5520   null_value= TRUE;
5521   /*
5522     In slave thread no need to get locks, everything is serialized. Anyway
5523     there is no way to make GET_LOCK() work on slave like it did on master
5524     (i.e. make it return exactly the same value) because we don't have the
5525     same other concurrent threads environment. No matter what we return here,
5526     it's not guaranteed to be same as on master. So we always return 1.
5527   */
5528   if (thd->slave_thread)
5529   {
5530     null_value= FALSE;
5531     DBUG_RETURN(1);
5532   }
5533 
5534   if (check_and_convert_ull_name(name, res))
5535     DBUG_RETURN(0);
5536 
5537   DBUG_PRINT("info", ("lock %s, thd=%lu", name, (ulong) thd->real_id));
5538 
5539   /*
5540     Convert too big and negative timeout values to INT_MAX32.
5541     This gives robust, "infinite" wait on all platforms.
5542   */
5543   if (timeout > INT_MAX32)
5544     timeout= INT_MAX32;
5545 
5546   /* HASH entries are of type User_level_lock. */
5547   if (! my_hash_inited(&thd->ull_hash) &&
5548       my_hash_init(&thd->ull_hash, &my_charset_bin,
5549                    16 /* small hash */, 0, 0, ull_get_key, NULL, 0,
5550                    key_memory_User_level_lock))
5551   {
5552     DBUG_RETURN(0);
5553   }
5554 
5555   MDL_request ull_request;
5556   MDL_REQUEST_INIT(&ull_request, MDL_key::USER_LEVEL_LOCK, "",
5557                    name, MDL_EXCLUSIVE, MDL_EXPLICIT);
5558   MDL_key *ull_key= &ull_request.key;
5559 
5560   if ((ull= reinterpret_cast<User_level_lock*>
5561          (my_hash_search(&thd->ull_hash, ull_key->ptr(), ull_key->length()))))
5562   {
5563     /* Recursive lock. */
5564     ull->refs++;
5565     null_value= FALSE;
5566     DBUG_RETURN(1);
5567   }
5568 
5569   User_level_lock_wait_error_handler error_handler;
5570 
5571   thd->push_internal_handler(&error_handler);
5572   bool error= thd->mdl_context.acquire_lock(&ull_request,
5573                                             static_cast<ulong>(timeout));
5574   (void) thd->pop_internal_handler();
5575 
5576   if (error)
5577   {
5578     /*
5579       Return 0 in case of timeout and NULL in case of deadlock/other
5580       errors. In the latter case error (e.g. ER_USER_LOCK_DEADLOCK)
5581       will be reported as well.
5582     */
5583     if (error_handler.got_timeout())
5584       null_value= FALSE;
5585     DBUG_RETURN(0);
5586   }
5587 
5588   ull= reinterpret_cast<User_level_lock*>(my_malloc(key_memory_User_level_lock,
5589                                                     sizeof(User_level_lock),
5590                                                     MYF(0)));
5591 
5592   if (ull == NULL)
5593   {
5594     thd->mdl_context.release_lock(ull_request.ticket);
5595     DBUG_RETURN(0);
5596   }
5597 
5598   ull->ticket= ull_request.ticket;
5599   ull->refs= 1;
5600 
5601   if (my_hash_insert(&thd->ull_hash, reinterpret_cast<uchar*>(ull)))
5602   {
5603     thd->mdl_context.release_lock(ull_request.ticket);
5604     my_free(ull);
5605     DBUG_RETURN(0);
5606   }
5607 
5608   null_value= FALSE;
5609 
5610   DBUG_RETURN(1);
5611 }
5612 
5613 
itemize(Parse_context * pc,Item ** res)5614 bool Item_func_release_lock::itemize(Parse_context *pc, Item **res)
5615 {
5616   if (skip_itemize(res))
5617     return false;
5618   if (super::itemize(pc, res))
5619     return true;
5620   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5621   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5622   return false;
5623 }
5624 
5625 
5626 /**
5627   Release a user level lock.
5628 
5629   @note Sets null_value to TRUE on error/if no connection holds such lock.
5630 
5631   @note This means that SQL-function RELEASE_LOCK() returns:
5632         1    - if lock was held by this connection and was released.
5633         0    - if lock was held by some other connection (and was not released).
5634         NULL - if name of lock is bad or if it was not held by any connection
5635                (in the former case also error will be emitted),
5636 
5637   @return
5638     - 1 if lock released
5639     - 0 if lock wasn't held/error.
5640 */
5641 
val_int()5642 longlong Item_func_release_lock::val_int()
5643 {
5644   assert(fixed == 1);
5645   String *res= args[0]->val_str(&value);
5646   char name[NAME_LEN + 1];
5647   THD *thd= current_thd;
5648   DBUG_ENTER("Item_func_release_lock::val_int");
5649 
5650   null_value= TRUE;
5651 
5652   if (check_and_convert_ull_name(name, res))
5653     DBUG_RETURN(0);
5654 
5655   DBUG_PRINT("info", ("lock %s", name));
5656 
5657   MDL_key ull_key;
5658   ull_key.mdl_key_init(MDL_key::USER_LEVEL_LOCK, "", name);
5659 
5660   User_level_lock *ull;
5661 
5662   if (!(ull= reinterpret_cast<User_level_lock*>
5663           (my_hash_search(&thd->ull_hash, ull_key.ptr(), ull_key.length()))))
5664   {
5665     /*
5666       When RELEASE_LOCK() is called for lock which is not owned by the
5667       connection it should return 0 or NULL depending on whether lock
5668       is owned by any other connection or not.
5669     */
5670     MDL_lock_get_owner_thread_id_visitor get_owner_visitor;
5671 
5672     if (thd->mdl_context.find_lock_owner(&ull_key, &get_owner_visitor))
5673       DBUG_RETURN(0);
5674 
5675     null_value= get_owner_visitor.get_owner_id() == 0;
5676 
5677     DBUG_RETURN(0);
5678   }
5679   null_value= FALSE;
5680   if (--ull->refs == 0)
5681   {
5682     my_hash_delete(&thd->ull_hash, reinterpret_cast<uchar*>(ull));
5683     thd->mdl_context.release_lock(ull->ticket);
5684     my_free(ull);
5685   }
5686   DBUG_RETURN(1);
5687 }
5688 
5689 
itemize(Parse_context * pc,Item ** res)5690 bool Item_func_release_all_locks::itemize(Parse_context *pc, Item **res)
5691 {
5692   if (skip_itemize(res))
5693     return false;
5694   if (super::itemize(pc, res))
5695     return true;
5696   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5697   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5698   return false;
5699 }
5700 
5701 
5702 /**
5703   Release all user level lock held by connection.
5704 
5705   @return Number of locks released including recursive lock count.
5706 */
5707 
val_int()5708 longlong Item_func_release_all_locks::val_int()
5709 {
5710   assert(fixed == 1);
5711   THD *thd= current_thd;
5712   uint result= 0;
5713   User_level_lock *ull;
5714   DBUG_ENTER("Item_func_release_all_locks::val_int");
5715 
5716   if (my_hash_inited(&thd->ull_hash))
5717   {
5718     for (ulong i= 0; i < thd->ull_hash.records; i++)
5719     {
5720       ull= reinterpret_cast<User_level_lock*>(my_hash_element(&thd->ull_hash,
5721                                                               i));
5722       thd->mdl_context.release_lock(ull->ticket);
5723       result+= ull->refs;
5724       my_free(ull);
5725     }
5726     my_hash_reset(&thd->ull_hash);
5727   }
5728 
5729   DBUG_RETURN(result);
5730 }
5731 
5732 
itemize(Parse_context * pc,Item ** res)5733 bool Item_func_is_free_lock::itemize(Parse_context *pc, Item **res)
5734 {
5735   if (skip_itemize(res))
5736     return false;
5737   if (super::itemize(pc, res))
5738     return true;
5739   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5740   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5741   return false;
5742 }
5743 
5744 
5745 /**
5746   Check if user level lock is free.
5747 
5748   @note Sets null_value=TRUE on error.
5749 
5750   @note As result SQL-function IS_FREE_LOCK() returns:
5751         1    - if lock is free,
5752         0    - if lock is in use
5753         NULL - if lock name is bad or OOM (also error is emitted).
5754 
5755   @retval
5756     1		Available
5757   @retval
5758     0		Already taken, or error
5759 */
5760 
val_int()5761 longlong Item_func_is_free_lock::val_int()
5762 {
5763   assert(fixed == 1);
5764   String *res= args[0]->val_str(&value);
5765   char name[NAME_LEN + 1];
5766   THD *thd= current_thd;
5767 
5768   null_value= TRUE;
5769 
5770   if (check_and_convert_ull_name(name, res))
5771     return 0;
5772 
5773   MDL_key ull_key;
5774   ull_key.mdl_key_init(MDL_key::USER_LEVEL_LOCK, "", name);
5775 
5776   MDL_lock_get_owner_thread_id_visitor get_owner_visitor;
5777 
5778   if (thd->mdl_context.find_lock_owner(&ull_key, &get_owner_visitor))
5779     return 0;
5780 
5781   null_value= FALSE;
5782   return MY_TEST(get_owner_visitor.get_owner_id() == 0);
5783 }
5784 
5785 
itemize(Parse_context * pc,Item ** res)5786 bool Item_func_is_used_lock::itemize(Parse_context *pc, Item **res)
5787 {
5788   if (skip_itemize(res))
5789     return false;
5790   if (super::itemize(pc, res))
5791     return true;
5792   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
5793   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5794   return false;
5795 }
5796 
5797 
5798 /**
5799   Check if user level lock is used and return connection id of owner.
5800 
5801   @note Sets null_value=TRUE if lock is free/on error.
5802 
5803   @note SQL-function IS_USED_LOCK() returns:
5804         #    - connection id of lock owner if lock is acquired.
5805         NULL - if lock is free or on error (in the latter case
5806                also error is emitted).
5807 
5808   @return Connection id of lock owner, 0 if lock is free/on error.
5809 */
5810 
val_int()5811 longlong Item_func_is_used_lock::val_int()
5812 {
5813   assert(fixed == 1);
5814   String *res= args[0]->val_str(&value);
5815   char name[NAME_LEN + 1];
5816   THD *thd= current_thd;
5817 
5818   null_value= TRUE;
5819 
5820   if (check_and_convert_ull_name(name, res))
5821     return 0;
5822 
5823   MDL_key ull_key;
5824   ull_key.mdl_key_init(MDL_key::USER_LEVEL_LOCK, "", name);
5825 
5826   MDL_lock_get_owner_thread_id_visitor get_owner_visitor;
5827 
5828   if (thd->mdl_context.find_lock_owner(&ull_key, &get_owner_visitor))
5829     return 0;
5830 
5831   my_thread_id thread_id= get_owner_visitor.get_owner_id();
5832   if (thread_id == 0)
5833     return 0;
5834 
5835   null_value= FALSE;
5836   return thread_id;
5837 }
5838 
5839 
itemize(Parse_context * pc,Item ** res)5840 bool Item_func_last_insert_id::itemize(Parse_context *pc, Item **res)
5841 {
5842   if (skip_itemize(res))
5843     return false;
5844   if (super::itemize(pc, res))
5845     return true;
5846   pc->thd->lex->safe_to_cache_query= false;
5847   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5848   return false;
5849 }
5850 
5851 
val_int()5852 longlong Item_func_last_insert_id::val_int()
5853 {
5854   THD *thd= current_thd;
5855   assert(fixed == 1);
5856   if (arg_count)
5857   {
5858     longlong value= args[0]->val_int();
5859     null_value= args[0]->null_value;
5860     /*
5861       LAST_INSERT_ID(X) must affect the client's mysql_insert_id() as
5862       documented in the manual. We don't want to touch
5863       first_successful_insert_id_in_cur_stmt because it would make
5864       LAST_INSERT_ID(X) take precedence over an generated auto_increment
5865       value for this row.
5866     */
5867     thd->arg_of_last_insert_id_function= TRUE;
5868     thd->first_successful_insert_id_in_prev_stmt= value;
5869     return value;
5870   }
5871   return
5872     static_cast<longlong>(thd->read_first_successful_insert_id_in_prev_stmt());
5873 }
5874 
5875 
itemize(Parse_context * pc,Item ** res)5876 bool Item_func_benchmark::itemize(Parse_context *pc, Item **res)
5877 {
5878   if (skip_itemize(res))
5879     return false;
5880   if (super::itemize(pc, res))
5881     return true;
5882   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
5883   return false;
5884 }
5885 
5886 
5887 /* This function is just used to test speed of different functions */
5888 
val_int()5889 longlong Item_func_benchmark::val_int()
5890 {
5891   assert(fixed == 1);
5892   char buff[MAX_FIELD_WIDTH];
5893   String tmp(buff,sizeof(buff), &my_charset_bin);
5894   my_decimal tmp_decimal;
5895   THD *thd=current_thd;
5896   ulonglong loop_count;
5897 
5898   loop_count= (ulonglong) args[0]->val_int();
5899 
5900   if (args[0]->null_value ||
5901       (!args[0]->unsigned_flag && (((longlong) loop_count) < 0)))
5902   {
5903     if (!args[0]->null_value)
5904     {
5905       char buff[22];
5906       llstr(((longlong) loop_count), buff);
5907       push_warning_printf(current_thd, Sql_condition::SL_WARNING,
5908                           ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE),
5909                           "count", buff, "benchmark");
5910     }
5911 
5912     null_value= 1;
5913     return 0;
5914   }
5915 
5916   null_value=0;
5917   for (ulonglong loop=0 ; loop < loop_count && !thd->killed; loop++)
5918   {
5919     switch (args[1]->result_type()) {
5920     case REAL_RESULT:
5921       (void) args[1]->val_real();
5922       break;
5923     case INT_RESULT:
5924       (void) args[1]->val_int();
5925       break;
5926     case STRING_RESULT:
5927       (void) args[1]->val_str(&tmp);
5928       break;
5929     case DECIMAL_RESULT:
5930       (void) args[1]->val_decimal(&tmp_decimal);
5931       break;
5932     case ROW_RESULT:
5933     default:
5934       // This case should never be chosen
5935       assert(0);
5936       return 0;
5937     }
5938   }
5939   return 0;
5940 }
5941 
5942 
print(String * str,enum_query_type query_type)5943 void Item_func_benchmark::print(String *str, enum_query_type query_type)
5944 {
5945   str->append(STRING_WITH_LEN("benchmark("));
5946   args[0]->print(str, query_type);
5947   str->append(',');
5948   args[1]->print(str, query_type);
5949   str->append(')');
5950 }
5951 
5952 
5953 /**
5954   Lock which is used to implement interruptible wait for SLEEP() function.
5955 */
5956 
5957 mysql_mutex_t LOCK_item_func_sleep;
5958 
5959 
5960 #ifdef HAVE_PSI_INTERFACE
5961 static PSI_mutex_key key_LOCK_item_func_sleep;
5962 
5963 
5964 static PSI_mutex_info item_func_sleep_mutexes[]=
5965 {
5966   { &key_LOCK_item_func_sleep, "LOCK_item_func_sleep", PSI_FLAG_GLOBAL}
5967 };
5968 
5969 
init_item_func_sleep_psi_keys()5970 static void init_item_func_sleep_psi_keys()
5971 {
5972   int count;
5973 
5974   count= array_elements(item_func_sleep_mutexes);
5975   mysql_mutex_register("sql", item_func_sleep_mutexes, count);
5976 }
5977 #endif
5978 
5979 
5980 static bool item_func_sleep_inited= false;
5981 
5982 
item_func_sleep_init()5983 void item_func_sleep_init()
5984 {
5985 #ifdef HAVE_PSI_INTERFACE
5986   init_item_func_sleep_psi_keys();
5987 #endif
5988 
5989   mysql_mutex_init(key_LOCK_item_func_sleep, &LOCK_item_func_sleep, MY_MUTEX_INIT_SLOW);
5990   item_func_sleep_inited= true;
5991 }
5992 
5993 
item_func_sleep_free()5994 void item_func_sleep_free()
5995 {
5996   if (item_func_sleep_inited)
5997   {
5998     item_func_sleep_inited= false;
5999     mysql_mutex_destroy(&LOCK_item_func_sleep);
6000   }
6001 }
6002 
6003 
itemize(Parse_context * pc,Item ** res)6004 bool Item_func_sleep::itemize(Parse_context *pc, Item **res)
6005 {
6006   if (skip_itemize(res))
6007     return false;
6008   if (super::itemize(pc, res))
6009     return true;
6010   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
6011   pc->thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
6012   return false;
6013 }
6014 
6015 
6016 /** This function is just used to create tests with time gaps. */
6017 
val_int()6018 longlong Item_func_sleep::val_int()
6019 {
6020   THD *thd= current_thd;
6021   Interruptible_wait timed_cond(thd);
6022   mysql_cond_t cond;
6023   double timeout;
6024   int error;
6025 
6026   assert(fixed == 1);
6027 
6028   timeout= args[0]->val_real();
6029 
6030   /*
6031     Report error or warning depending on the value of SQL_MODE.
6032     If SQL is STRICT then report error, else report warning and continue
6033     execution.
6034   */
6035 
6036   if (args[0]->null_value || timeout < 0)
6037   {
6038     if (!thd->lex->is_ignore() && thd->is_strict_mode())
6039     {
6040       my_error(ER_WRONG_ARGUMENTS, MYF(0), "sleep.");
6041       return 0;
6042     }
6043     else
6044       push_warning_printf(thd, Sql_condition::SL_WARNING, ER_WRONG_ARGUMENTS,
6045                           ER(ER_WRONG_ARGUMENTS), "sleep.");
6046   }
6047   /*
6048     On 64-bit OSX mysql_cond_timedwait() waits forever
6049     if passed abstime time has already been exceeded by
6050     the system time.
6051     When given a very short timeout (< 10 mcs) just return
6052     immediately.
6053     We assume that the lines between this test and the call
6054     to mysql_cond_timedwait() will be executed in less than 0.00001 sec.
6055   */
6056   if (timeout < 0.00001)
6057     return 0;
6058 
6059   timed_cond.set_timeout((ulonglong) (timeout * 1000000000.0));
6060 
6061   mysql_cond_init(key_item_func_sleep_cond, &cond);
6062   mysql_mutex_lock(&LOCK_item_func_sleep);
6063 
6064   thd->ENTER_COND(&cond, &LOCK_item_func_sleep, &stage_user_sleep, NULL);
6065 
6066   DEBUG_SYNC(current_thd, "func_sleep_before_sleep");
6067 
6068   error= 0;
6069   thd_wait_begin(thd, THD_WAIT_SLEEP);
6070   while (!thd->killed)
6071   {
6072     error= timed_cond.wait(&cond, &LOCK_item_func_sleep);
6073     if (error == ETIMEDOUT || error == ETIME)
6074       break;
6075     error= 0;
6076   }
6077   thd_wait_end(thd);
6078   mysql_mutex_unlock(&LOCK_item_func_sleep);
6079   thd->EXIT_COND(NULL);
6080 
6081   mysql_cond_destroy(&cond);
6082 
6083   return MY_TEST(!error); 		// Return 1 killed
6084 }
6085 
6086 /*
6087   @param cs  character set; IF we are creating the user_var_entry,
6088              we give it this character set.
6089 */
get_variable(THD * thd,const Name_string & name,const CHARSET_INFO * cs)6090 static user_var_entry *get_variable(THD *thd, const Name_string &name,
6091                                     const CHARSET_INFO *cs)
6092 {
6093   user_var_entry *entry;
6094   HASH *hash= & thd->user_vars;
6095 
6096   /* Protects thd->user_vars. */
6097   mysql_mutex_assert_owner(&thd->LOCK_thd_data);
6098 
6099   if (!(entry= (user_var_entry*) my_hash_search(hash, (uchar*) name.ptr(),
6100                                                  name.length())) &&
6101         cs != NULL)
6102   {
6103     if (!my_hash_inited(hash))
6104       return 0;
6105     if (!(entry= user_var_entry::create(thd, name, cs)))
6106       return 0;
6107     if (my_hash_insert(hash,(uchar*) entry))
6108     {
6109       my_free(entry);
6110       return 0;
6111     }
6112   }
6113   return entry;
6114 }
6115 
6116 
cleanup()6117 void Item_func_set_user_var::cleanup()
6118 {
6119   Item_func::cleanup();
6120   entry= NULL;
6121 }
6122 
6123 
set_entry(THD * thd,bool create_if_not_exists)6124 bool Item_func_set_user_var::set_entry(THD *thd, bool create_if_not_exists)
6125 {
6126   if (entry && thd->thread_id() == entry_thread_id)
6127   {} // update entry->update_query_id for PS
6128   else
6129   {
6130     const CHARSET_INFO *cs=  create_if_not_exists ?
6131           (args[0]->collation.derivation == DERIVATION_NUMERIC ?
6132           default_charset() : args[0]->collation.collation) : NULL;
6133 
6134     /* Protects thd->user_vars. */
6135     mysql_mutex_lock(&thd->LOCK_thd_data);
6136     entry= get_variable(thd, name, cs);
6137     mysql_mutex_unlock(&thd->LOCK_thd_data);
6138 
6139     if (entry == NULL)
6140     {
6141       entry_thread_id= 0;
6142       return TRUE;
6143     }
6144     entry_thread_id= thd->thread_id();
6145   }
6146   /*
6147     Remember the last query which updated it, this way a query can later know
6148     if this variable is a constant item in the query (it is if update_query_id
6149     is different from query_id).
6150 
6151     If this object has delayed setting of non-constness, we delay this
6152     until Item_func_set-user_var::save_item_result().
6153   */
6154   if (!delayed_non_constness)
6155     entry->update_query_id= thd->query_id;
6156   return FALSE;
6157 }
6158 
6159 
6160 /*
6161   When a user variable is updated (in a SET command or a query like
6162   SELECT @a:= ).
6163 */
6164 
fix_fields(THD * thd,Item ** ref)6165 bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref)
6166 {
6167   assert(fixed == 0);
6168   /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
6169   if (Item_func::fix_fields(thd, ref) || set_entry(thd, TRUE))
6170     return TRUE;
6171 
6172   null_item= (args[0]->type() == NULL_ITEM);
6173 
6174   cached_result_type= args[0]->result_type();
6175   return FALSE;
6176 }
6177 
6178 
6179 void
fix_length_and_dec()6180 Item_func_set_user_var::fix_length_and_dec()
6181 {
6182   maybe_null=args[0]->maybe_null;
6183   decimals=args[0]->decimals;
6184   collation.set(DERIVATION_IMPLICIT);
6185   /*
6186      this sets the character set of the item immediately; rules for the
6187      character set of the variable ("entry" object) are different: if "entry"
6188      did not exist previously, set_entry () has created it and has set its
6189      character set; but if it existed previously, it keeps its previous
6190      character set, which may change only when we are sure that the assignment
6191      is to be executed, i.e. in user_var_entry::store ().
6192   */
6193   if (args[0]->collation.derivation == DERIVATION_NUMERIC)
6194     fix_length_and_charset(args[0]->max_char_length(), default_charset());
6195   else
6196   {
6197     fix_length_and_charset(args[0]->max_char_length(),
6198                            args[0]->collation.collation);
6199   }
6200   unsigned_flag= args[0]->unsigned_flag;
6201 }
6202 
6203 
mem_realloc(size_t length)6204 bool user_var_entry::mem_realloc(size_t length)
6205 {
6206   if (length <= extra_size)
6207   {
6208     /* Enough space to store value in value struct */
6209     free_value();
6210     m_ptr= internal_buffer_ptr();
6211   }
6212   else
6213   {
6214     /* Allocate an external buffer */
6215     if (m_length != length)
6216     {
6217       if (m_ptr == internal_buffer_ptr())
6218         m_ptr= 0;
6219       if (!(m_ptr= (char*) my_realloc(key_memory_user_var_entry_value,
6220                                       m_ptr, length,
6221                                       MYF(MY_ALLOW_ZERO_PTR | MY_WME |
6222                                       ME_FATALERROR))))
6223         return true;
6224     }
6225   }
6226   return false;
6227 }
6228 
6229 
6230 /**
6231   Set value to user variable.
6232   @param ptr            pointer to buffer with new value
6233   @param length         length of new value
6234   @param type           type of new value
6235 
6236   @retval  false   on success
6237   @retval  true    on allocation error
6238 
6239 */
store(const void * from,size_t length,Item_result type)6240 bool user_var_entry::store(const void *from, size_t length, Item_result type)
6241 {
6242   assert_locked();
6243 
6244   // Store strings with end \0
6245   if (mem_realloc(length + MY_TEST(type == STRING_RESULT)))
6246     return true;
6247   if (type == STRING_RESULT)
6248     m_ptr[length]= 0;     // Store end \0
6249 
6250   // Avoid memcpy of a my_decimal object, use copy CTOR instead.
6251   if (type == DECIMAL_RESULT)
6252   {
6253     assert(length == sizeof(my_decimal));
6254     const my_decimal* dec= static_cast<const my_decimal*>(from);
6255     dec->sanity_check();
6256     new (m_ptr) my_decimal(*dec);
6257   }
6258   else
6259     memcpy(m_ptr, from, length);
6260 
6261   m_length= length;
6262   m_type= type;
6263   return false;
6264 }
6265 
6266 
6267 /**
6268   Set value to user variable.
6269 
6270   @param ptr            pointer to buffer with new value
6271   @param length         length of new value
6272   @param type           type of new value
6273   @param cs             charset info for new value
6274   @param dv             derivation for new value
6275   @param unsigned_arg   indiates if a value of type INT_RESULT is unsigned
6276 
6277   @note Sets error and fatal error if allocation fails.
6278 
6279   @retval
6280     false   success
6281   @retval
6282     true    failure
6283 */
6284 
store(const void * ptr,size_t length,Item_result type,const CHARSET_INFO * cs,Derivation dv,bool unsigned_arg)6285 bool user_var_entry::store(const void *ptr, size_t length, Item_result type,
6286                            const CHARSET_INFO *cs, Derivation dv,
6287                            bool unsigned_arg)
6288 {
6289   assert_locked();
6290 
6291   if (store(ptr, length, type))
6292     return true;
6293   collation.set(cs, dv);
6294   unsigned_flag= unsigned_arg;
6295   return false;
6296 }
6297 
lock()6298 void user_var_entry::lock()
6299 {
6300   assert(m_owner != NULL);
6301   mysql_mutex_lock(&m_owner->LOCK_thd_data);
6302 }
6303 
unlock()6304 void user_var_entry::unlock()
6305 {
6306   assert(m_owner != NULL);
6307   mysql_mutex_unlock(&m_owner->LOCK_thd_data);
6308 }
6309 
6310 bool
update_hash(const void * ptr,uint length,Item_result res_type,const CHARSET_INFO * cs,Derivation dv,bool unsigned_arg)6311 Item_func_set_user_var::update_hash(const void *ptr, uint length,
6312                                     Item_result res_type,
6313                                     const CHARSET_INFO *cs, Derivation dv,
6314                                     bool unsigned_arg)
6315 {
6316   entry->lock();
6317 
6318   /*
6319     If we set a variable explicitely to NULL then keep the old
6320     result type of the variable
6321   */
6322   // args[0]->null_value could be outdated
6323   if (args[0]->type() == Item::FIELD_ITEM)
6324     null_value= ((Item_field*)args[0])->field->is_null();
6325   else
6326     null_value= args[0]->null_value;
6327 
6328   if (ptr == NULL)
6329   {
6330     assert(length == 0);
6331     null_value= true;
6332   }
6333 
6334   if (null_value && null_item)
6335     res_type= entry->type();                    // Don't change type of item
6336 
6337   if (null_value)
6338     entry->set_null_value(res_type);
6339   else if (entry->store(ptr, length, res_type, cs, dv, unsigned_arg))
6340   {
6341     entry->unlock();
6342     null_value= 1;
6343     return 1;
6344   }
6345   entry->unlock();
6346   return 0;
6347 }
6348 
6349 
6350 /** Get the value of a variable as a double. */
6351 
val_real(my_bool * null_value) const6352 double user_var_entry::val_real(my_bool *null_value) const
6353 {
6354   if ((*null_value= (m_ptr == 0)))
6355     return 0.0;
6356 
6357   switch (m_type) {
6358   case REAL_RESULT:
6359     return *(double*) m_ptr;
6360   case INT_RESULT:
6361     return (double) *(longlong*) m_ptr;
6362   case DECIMAL_RESULT:
6363   {
6364     double result;
6365     my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, &result);
6366     return result;
6367   }
6368   case STRING_RESULT:
6369     return my_atof(m_ptr);                    // This is null terminated
6370   case ROW_RESULT:
6371     assert(1);				// Impossible
6372     break;
6373   }
6374   return 0.0;					// Impossible
6375 }
6376 
6377 
6378 /** Get the value of a variable as an integer. */
6379 
val_int(my_bool * null_value) const6380 longlong user_var_entry::val_int(my_bool *null_value) const
6381 {
6382   if ((*null_value= (m_ptr == 0)))
6383     return 0LL;
6384 
6385   switch (m_type) {
6386   case REAL_RESULT:
6387     return (longlong) *(double*) m_ptr;
6388   case INT_RESULT:
6389     return *(longlong*) m_ptr;
6390   case DECIMAL_RESULT:
6391   {
6392     longlong result;
6393     my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, 0, &result);
6394     return result;
6395   }
6396   case STRING_RESULT:
6397   {
6398     int error;
6399     return my_strtoll10(m_ptr, (char**) 0, &error);// String is null terminated
6400   }
6401   case ROW_RESULT:
6402     assert(1);				// Impossible
6403     break;
6404   }
6405   return 0LL;					// Impossible
6406 }
6407 
6408 
6409 /** Get the value of a variable as a string. */
6410 
val_str(my_bool * null_value,String * str,uint decimals) const6411 String *user_var_entry::val_str(my_bool *null_value, String *str,
6412 				uint decimals) const
6413 {
6414   if ((*null_value= (m_ptr == 0)))
6415     return (String*) 0;
6416 
6417   switch (m_type) {
6418   case REAL_RESULT:
6419     str->set_real(*(double*) m_ptr, decimals, collation.collation);
6420     break;
6421   case INT_RESULT:
6422     if (!unsigned_flag)
6423       str->set(*(longlong*) m_ptr, collation.collation);
6424     else
6425       str->set(*(ulonglong*) m_ptr, collation.collation);
6426     break;
6427   case DECIMAL_RESULT:
6428     str_set_decimal((my_decimal *) m_ptr, str, collation.collation);
6429     break;
6430   case STRING_RESULT:
6431     if (str->copy(m_ptr, m_length, collation.collation))
6432       str= 0;					// EOM error
6433     break;
6434   case ROW_RESULT:
6435     assert(1);				// Impossible
6436     break;
6437   }
6438   return(str);
6439 }
6440 
6441 /** Get the value of a variable as a decimal. */
6442 
val_decimal(my_bool * null_value,my_decimal * val) const6443 my_decimal *user_var_entry::val_decimal(my_bool *null_value, my_decimal *val) const
6444 {
6445   if ((*null_value= (m_ptr == 0)))
6446     return 0;
6447 
6448   switch (m_type) {
6449   case REAL_RESULT:
6450     double2my_decimal(E_DEC_FATAL_ERROR, *(double*) m_ptr, val);
6451     break;
6452   case INT_RESULT:
6453     int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) m_ptr, 0, val);
6454     break;
6455   case DECIMAL_RESULT:
6456     my_decimal2decimal((my_decimal *) m_ptr, val);
6457     break;
6458   case STRING_RESULT:
6459     str2my_decimal(E_DEC_FATAL_ERROR, m_ptr, m_length,
6460                    collation.collation, val);
6461     break;
6462   case ROW_RESULT:
6463     assert(1);				// Impossible
6464     break;
6465   }
6466   return(val);
6467 }
6468 
6469 /**
6470   This functions is invoked on SET \@variable or
6471   \@variable:= expression.
6472 
6473   Evaluate (and check expression), store results.
6474 
6475   @note
6476     For now it always return OK. All problem with value evaluating
6477     will be caught by thd->is_error() check in sql_set_variables().
6478 
6479   @retval
6480     FALSE OK.
6481 */
6482 
6483 bool
check(bool use_result_field)6484 Item_func_set_user_var::check(bool use_result_field)
6485 {
6486   DBUG_ENTER("Item_func_set_user_var::check");
6487   if (use_result_field && !result_field)
6488     use_result_field= FALSE;
6489 
6490   switch (cached_result_type) {
6491   case REAL_RESULT:
6492   {
6493     save_result.vreal= use_result_field ? result_field->val_real() :
6494                         args[0]->val_real();
6495     break;
6496   }
6497   case INT_RESULT:
6498   {
6499     save_result.vint= use_result_field ? result_field->val_int() :
6500                        args[0]->val_int();
6501     unsigned_flag= use_result_field ? ((Field_num*)result_field)->unsigned_flag:
6502                     args[0]->unsigned_flag;
6503     break;
6504   }
6505   case STRING_RESULT:
6506   {
6507     save_result.vstr= use_result_field ? result_field->val_str(&value) :
6508                        args[0]->val_str(&value);
6509     break;
6510   }
6511   case DECIMAL_RESULT:
6512   {
6513     save_result.vdec= use_result_field ?
6514                        result_field->val_decimal(&decimal_buff) :
6515                        args[0]->val_decimal(&decimal_buff);
6516     break;
6517   }
6518   case ROW_RESULT:
6519   default:
6520     // This case should never be chosen
6521     assert(0);
6522     break;
6523   }
6524   DBUG_RETURN(FALSE);
6525 }
6526 
6527 
6528 /**
6529   @brief Evaluate and store item's result.
6530   This function is invoked on "SELECT ... INTO @var ...".
6531 
6532   @param    item    An item to get value from.
6533 */
6534 
save_item_result(Item * item)6535 void Item_func_set_user_var::save_item_result(Item *item)
6536 {
6537   DBUG_ENTER("Item_func_set_user_var::save_item_result");
6538 
6539   switch (cached_result_type) {
6540   case REAL_RESULT:
6541     save_result.vreal= item->val_result();
6542     break;
6543   case INT_RESULT:
6544     save_result.vint= item->val_int_result();
6545     unsigned_flag= item->unsigned_flag;
6546     break;
6547   case STRING_RESULT:
6548     save_result.vstr= item->str_result(&value);
6549     break;
6550   case DECIMAL_RESULT:
6551     save_result.vdec= item->val_decimal_result(&decimal_buff);
6552     break;
6553   case ROW_RESULT:
6554   default:
6555     // Should never happen
6556     assert(0);
6557     break;
6558   }
6559   /*
6560     Set the ID of the query that last updated this variable. This is
6561     usually set by Item_func_set_user_var::set_entry(), but if this
6562     item has delayed setting of non-constness, we must do it now.
6563    */
6564   if (delayed_non_constness)
6565     entry->update_query_id= current_thd->query_id;
6566   DBUG_VOID_RETURN;
6567 }
6568 
6569 
6570 /**
6571   This functions is invoked on
6572   SET \@variable or \@variable:= expression.
6573 
6574   @note
6575     We have to store the expression as such in the variable, independent of
6576     the value method used by the user
6577 
6578   @retval
6579     0	OK
6580   @retval
6581     1	EOM Error
6582 
6583 */
6584 
6585 bool
update()6586 Item_func_set_user_var::update()
6587 {
6588   bool res= 0;
6589   DBUG_ENTER("Item_func_set_user_var::update");
6590 
6591   switch (cached_result_type) {
6592   case REAL_RESULT:
6593   {
6594     res= update_hash(&save_result.vreal,sizeof(save_result.vreal),
6595 		     REAL_RESULT, default_charset(), DERIVATION_IMPLICIT, 0);
6596     break;
6597   }
6598   case INT_RESULT:
6599   {
6600     res= update_hash(&save_result.vint, sizeof(save_result.vint),
6601                      INT_RESULT, default_charset(), DERIVATION_IMPLICIT,
6602                      unsigned_flag);
6603     break;
6604   }
6605   case STRING_RESULT:
6606   {
6607     if (!save_result.vstr)					// Null value
6608       res= update_hash(NULL, 0, STRING_RESULT, &my_charset_bin,
6609 		       DERIVATION_IMPLICIT, 0);
6610     else
6611       res= update_hash(save_result.vstr->ptr(),
6612 		       save_result.vstr->length(), STRING_RESULT,
6613 		       save_result.vstr->charset(),
6614 		       DERIVATION_IMPLICIT, 0);
6615     break;
6616   }
6617   case DECIMAL_RESULT:
6618   {
6619     if (!save_result.vdec)					// Null value
6620       res= update_hash(NULL, 0, DECIMAL_RESULT, &my_charset_bin,
6621                        DERIVATION_IMPLICIT, false);
6622     else
6623       res= update_hash(save_result.vdec,
6624                        sizeof(my_decimal), DECIMAL_RESULT,
6625                        default_charset(), DERIVATION_IMPLICIT, 0);
6626     break;
6627   }
6628   case ROW_RESULT:
6629   default:
6630     // This case should never be chosen
6631     assert(0);
6632     break;
6633   }
6634   DBUG_RETURN(res);
6635 }
6636 
6637 
val_real()6638 double Item_func_set_user_var::val_real()
6639 {
6640   assert(fixed == 1);
6641   check(0);
6642   update();					// Store expression
6643   return entry->val_real(&null_value);
6644 }
6645 
val_int()6646 longlong Item_func_set_user_var::val_int()
6647 {
6648   assert(fixed == 1);
6649   check(0);
6650   update();					// Store expression
6651   return entry->val_int(&null_value);
6652 }
6653 
val_str(String * str)6654 String *Item_func_set_user_var::val_str(String *str)
6655 {
6656   assert(fixed == 1);
6657   check(0);
6658   update();					// Store expression
6659   return entry->val_str(&null_value, str, decimals);
6660 }
6661 
6662 
val_decimal(my_decimal * val)6663 my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val)
6664 {
6665   assert(fixed == 1);
6666   check(0);
6667   update();					// Store expression
6668   return entry->val_decimal(&null_value, val);
6669 }
6670 
6671 
val_result()6672 double Item_func_set_user_var::val_result()
6673 {
6674   assert(fixed == 1);
6675   check(TRUE);
6676   update();					// Store expression
6677   return entry->val_real(&null_value);
6678 }
6679 
val_int_result()6680 longlong Item_func_set_user_var::val_int_result()
6681 {
6682   assert(fixed == 1);
6683   check(TRUE);
6684   update();					// Store expression
6685   return entry->val_int(&null_value);
6686 }
6687 
val_bool_result()6688 bool Item_func_set_user_var::val_bool_result()
6689 {
6690   assert(fixed == 1);
6691   check(TRUE);
6692   update();					// Store expression
6693   return entry->val_int(&null_value) != 0;
6694 }
6695 
str_result(String * str)6696 String *Item_func_set_user_var::str_result(String *str)
6697 {
6698   assert(fixed == 1);
6699   check(TRUE);
6700   update();					// Store expression
6701   return entry->val_str(&null_value, str, decimals);
6702 }
6703 
6704 
val_decimal_result(my_decimal * val)6705 my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val)
6706 {
6707   assert(fixed == 1);
6708   check(TRUE);
6709   update();					// Store expression
6710   return entry->val_decimal(&null_value, val);
6711 }
6712 
6713 
is_null_result()6714 bool Item_func_set_user_var::is_null_result()
6715 {
6716   assert(fixed == 1);
6717   check(TRUE);
6718   update();					// Store expression
6719   return is_null();
6720 }
6721 
6722 // just the assignment, for use in "SET @a:=5" type self-prints
print_assignment(String * str,enum_query_type query_type)6723 void Item_func_set_user_var::print_assignment(String *str,
6724                                               enum_query_type query_type)
6725 {
6726   str->append(STRING_WITH_LEN("@"));
6727   str->append(name);
6728   str->append(STRING_WITH_LEN(":="));
6729   args[0]->print(str, query_type);
6730 }
6731 
6732 // parenthesize assignment for use in "EXPLAIN EXTENDED SELECT (@e:=80)+5"
print(String * str,enum_query_type query_type)6733 void Item_func_set_user_var::print(String *str, enum_query_type query_type)
6734 {
6735   str->append(STRING_WITH_LEN("("));
6736   print_assignment(str, query_type);
6737   str->append(STRING_WITH_LEN(")"));
6738 }
6739 
send(Protocol * protocol,String * str_arg)6740 bool Item_func_set_user_var::send(Protocol *protocol, String *str_arg)
6741 {
6742   if (result_field)
6743   {
6744     check(1);
6745     update();
6746     /*
6747       Workaround for metadata check in Protocol_text. Legacy Protocol_text
6748       is so well designed that it sends fields in text format, and functions'
6749       results in binary format. When this func tries to send its data as a
6750       field it breaks metadata asserts in the P_text.
6751       TODO This func have to be changed to avoid sending data as a field.
6752     */
6753     return result_field->send_binary(protocol);
6754   }
6755   return Item::send(protocol, str_arg);
6756 }
6757 
make_field(Send_field * tmp_field)6758 void Item_func_set_user_var::make_field(Send_field *tmp_field)
6759 {
6760   if (result_field)
6761   {
6762     result_field->make_field(tmp_field);
6763     assert(tmp_field->table_name != 0);
6764     if (Item::item_name.is_set())
6765       tmp_field->col_name=Item::item_name.ptr();    // Use user supplied name
6766   }
6767   else
6768     Item::make_field(tmp_field);
6769 }
6770 
6771 
6772 /*
6773   Save the value of a user variable into a field
6774 
6775   SYNOPSIS
6776     save_in_field()
6777       field           target field to save the value to
6778       no_conversion   flag indicating whether conversions are allowed
6779 
6780   DESCRIPTION
6781     Save the function value into a field and update the user variable
6782     accordingly. If a result field is defined and the target field doesn't
6783     coincide with it then the value from the result field will be used as
6784     the new value of the user variable.
6785 
6786     The reason to have this method rather than simply using the result
6787     field in the val_xxx() methods is that the value from the result field
6788     not always can be used when the result field is defined.
6789     Let's consider the following cases:
6790     1) when filling a tmp table the result field is defined but the value of it
6791     is undefined because it has to be produced yet. Thus we can't use it.
6792     2) on execution of an INSERT ... SELECT statement the save_in_field()
6793     function will be called to fill the data in the new record. If the SELECT
6794     part uses a tmp table then the result field is defined and should be
6795     used in order to get the correct result.
6796 
6797     The difference between the SET_USER_VAR function and regular functions
6798     like CONCAT is that the Item_func objects for the regular functions are
6799     replaced by Item_field objects after the values of these functions have
6800     been stored in a tmp table. Yet an object of the Item_field class cannot
6801     be used to update a user variable.
6802     Due to this we have to handle the result field in a special way here and
6803     in the Item_func_set_user_var::send() function.
6804 
6805   RETURN VALUES
6806     FALSE       Ok
6807     TRUE        Error
6808 */
6809 
6810 type_conversion_status
save_in_field(Field * field,bool no_conversions,bool can_use_result_field)6811 Item_func_set_user_var::save_in_field(Field *field, bool no_conversions,
6812                                       bool can_use_result_field)
6813 {
6814   bool use_result_field= (!can_use_result_field ? 0 :
6815                           (result_field && result_field != field));
6816   type_conversion_status error;
6817 
6818   /* Update the value of the user variable */
6819   check(use_result_field);
6820   update();
6821 
6822   if (result_type() == STRING_RESULT ||
6823       (result_type() == REAL_RESULT &&
6824       field->result_type() == STRING_RESULT))
6825   {
6826     String *result;
6827     const CHARSET_INFO *cs= collation.collation;
6828     char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
6829     str_value.set_quick(buff, sizeof(buff), cs);
6830     result= entry->val_str(&null_value, &str_value, decimals);
6831 
6832     if (null_value)
6833     {
6834       str_value.set_quick(0, 0, cs);
6835       return set_field_to_null_with_conversions(field, no_conversions);
6836     }
6837 
6838     /* NOTE: If null_value == FALSE, "result" must be not NULL.  */
6839 
6840     field->set_notnull();
6841     error=field->store(result->ptr(),result->length(),cs);
6842     str_value.set_quick(0, 0, cs);
6843   }
6844   else if (result_type() == REAL_RESULT)
6845   {
6846     double nr= entry->val_real(&null_value);
6847     if (null_value)
6848       return set_field_to_null(field);
6849     field->set_notnull();
6850     error=field->store(nr);
6851   }
6852   else if (result_type() == DECIMAL_RESULT)
6853   {
6854     my_decimal decimal_value;
6855     my_decimal *val= entry->val_decimal(&null_value, &decimal_value);
6856     if (null_value)
6857       return set_field_to_null(field);
6858     field->set_notnull();
6859     error=field->store_decimal(val);
6860   }
6861   else
6862   {
6863     longlong nr= entry->val_int(&null_value);
6864     if (null_value)
6865       return set_field_to_null_with_conversions(field, no_conversions);
6866     field->set_notnull();
6867     error=field->store(nr, unsigned_flag);
6868   }
6869   return error;
6870 }
6871 
6872 
6873 String *
val_str(String * str)6874 Item_func_get_user_var::val_str(String *str)
6875 {
6876   assert(fixed == 1);
6877   DBUG_ENTER("Item_func_get_user_var::val_str");
6878   if (!var_entry)
6879     DBUG_RETURN((String*) 0);			// No such variable
6880   String *res= var_entry->val_str(&null_value, str, decimals);
6881   DBUG_RETURN(res);
6882 }
6883 
6884 
val_real()6885 double Item_func_get_user_var::val_real()
6886 {
6887   assert(fixed == 1);
6888   if (!var_entry)
6889     return 0.0;					// No such variable
6890   return (var_entry->val_real(&null_value));
6891 }
6892 
6893 
val_decimal(my_decimal * dec)6894 my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec)
6895 {
6896   assert(fixed == 1);
6897   if (!var_entry)
6898     return 0;
6899   return var_entry->val_decimal(&null_value, dec);
6900 }
6901 
6902 
val_int()6903 longlong Item_func_get_user_var::val_int()
6904 {
6905   assert(fixed == 1);
6906   if (!var_entry)
6907     return 0LL;				// No such variable
6908   return (var_entry->val_int(&null_value));
6909 }
6910 
6911 
6912 /**
6913   Get variable by name and, if necessary, put the record of variable
6914   use into the binary log.
6915 
6916   When a user variable is invoked from an update query (INSERT, UPDATE etc),
6917   stores this variable and its value in thd->user_var_events, so that it can be
6918   written to the binlog (will be written just before the query is written, see
6919   log.cc).
6920 
6921   @param      thd        Current thread
6922   @param      name       Variable name
6923   @param[out] out_entry  variable structure or NULL. The pointer is set
6924                          regardless of whether function succeeded or not.
6925 
6926   @retval
6927     0  OK
6928   @retval
6929     1  Failed to put appropriate record into binary log
6930 
6931 */
6932 
6933 static int
get_var_with_binlog(THD * thd,enum_sql_command sql_command,Name_string & name,user_var_entry ** out_entry)6934 get_var_with_binlog(THD *thd, enum_sql_command sql_command,
6935                     Name_string &name, user_var_entry **out_entry)
6936 {
6937   BINLOG_USER_VAR_EVENT *user_var_event;
6938   user_var_entry *var_entry;
6939 
6940   /* Protects thd->user_vars. */
6941   mysql_mutex_lock(&thd->LOCK_thd_data);
6942   var_entry= get_variable(thd, name, NULL);
6943   mysql_mutex_unlock(&thd->LOCK_thd_data);
6944 
6945   /*
6946     Any reference to user-defined variable which is done from stored
6947     function or trigger affects their execution and the execution of the
6948     calling statement. We must log all such variables even if they are
6949     not involved in table-updating statements.
6950   */
6951   if (!(opt_bin_log &&
6952        (is_update_query(sql_command) || thd->in_sub_stmt)))
6953   {
6954     *out_entry= var_entry;
6955     return 0;
6956   }
6957 
6958   if (!var_entry)
6959   {
6960     /*
6961       If the variable does not exist, it's NULL, but we want to create it so
6962       that it gets into the binlog (if it didn't, the slave could be
6963       influenced by a variable of the same name previously set by another
6964       thread).
6965       We create it like if it had been explicitly set with SET before.
6966       The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'.
6967       sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION'
6968       in dispatch_command()). Instead of building a one-element list to pass to
6969       sql_set_variables(), we could instead manually call check() and update();
6970       this would save memory and time; but calling sql_set_variables() makes
6971       one unique place to maintain (sql_set_variables()).
6972 
6973       Manipulation with lex is necessary since free_underlaid_joins
6974       is going to release memory belonging to the main query.
6975     */
6976 
6977     List<set_var_base> tmp_var_list;
6978     LEX *sav_lex= thd->lex, lex_tmp;
6979     thd->lex= &lex_tmp;
6980     lex_start(thd);
6981     tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
6982                                                                        new Item_null(),
6983                                                                        false)));
6984     /* Create the variable */
6985     if (sql_set_variables(thd, &tmp_var_list))
6986     {
6987       thd->lex= sav_lex;
6988       goto err;
6989     }
6990     thd->lex= sav_lex;
6991     mysql_mutex_lock(&thd->LOCK_thd_data);
6992     var_entry= get_variable(thd, name, NULL);
6993     mysql_mutex_unlock(&thd->LOCK_thd_data);
6994 
6995     if (var_entry == NULL)
6996       goto err;
6997   }
6998   else if (var_entry->used_query_id == thd->query_id ||
6999            mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id))
7000   {
7001     /*
7002        If this variable was already stored in user_var_events by this query
7003        (because it's used in more than one place in the query), don't store
7004        it.
7005     */
7006     *out_entry= var_entry;
7007     return 0;
7008   }
7009 
7010   size_t size;
7011   /*
7012     First we need to store value of var_entry, when the next situation
7013     appears:
7014     > set @a:=1;
7015     > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
7016     We have to write to binlog value @a= 1.
7017 
7018     We allocate the user_var_event on user_var_events_alloc pool, not on
7019     the this-statement-execution pool because in SPs user_var_event objects
7020     may need to be valid after current [SP] statement execution pool is
7021     destroyed.
7022   */
7023   size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length();
7024   if (!(user_var_event= (BINLOG_USER_VAR_EVENT *)
7025         alloc_root(thd->user_var_events_alloc, size)))
7026     goto err;
7027 
7028   user_var_event->value= (char*) user_var_event +
7029     ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT));
7030   user_var_event->user_var_event= var_entry;
7031   user_var_event->type= var_entry->type();
7032   user_var_event->charset_number= var_entry->collation.collation->number;
7033   user_var_event->unsigned_flag= var_entry->unsigned_flag;
7034   if (!var_entry->ptr())
7035   {
7036     /* NULL value*/
7037     user_var_event->length= 0;
7038     user_var_event->value= 0;
7039   }
7040   else
7041   {
7042     // Avoid memcpy of a my_decimal object, use copy CTOR instead.
7043     user_var_event->length= var_entry->length();
7044     if (user_var_event->type == DECIMAL_RESULT)
7045     {
7046       assert(var_entry->length() == sizeof(my_decimal));
7047       const my_decimal* dec=
7048         static_cast<const my_decimal*>
7049         (static_cast<const void*>(var_entry->ptr()));
7050       dec->sanity_check();
7051       new (user_var_event->value) my_decimal(*dec);
7052     }
7053     else
7054       memcpy(user_var_event->value, var_entry->ptr(),
7055              var_entry->length());
7056   }
7057   /* Mark that this variable has been used by this query */
7058   var_entry->used_query_id= thd->query_id;
7059   if (thd->user_var_events.push_back(user_var_event))
7060     goto err;
7061 
7062   *out_entry= var_entry;
7063   return 0;
7064 
7065 err:
7066   *out_entry= var_entry;
7067   return 1;
7068 }
7069 
fix_length_and_dec()7070 void Item_func_get_user_var::fix_length_and_dec()
7071 {
7072   THD *thd=current_thd;
7073   int error;
7074   maybe_null=1;
7075   decimals=NOT_FIXED_DEC;
7076   max_length=MAX_BLOB_WIDTH;
7077 
7078   error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry);
7079 
7080   /*
7081     If the variable didn't exist it has been created as a STRING-type.
7082     'var_entry' is NULL only if there occurred an error during the call to
7083     get_var_with_binlog.
7084   */
7085   if (!error && var_entry)
7086   {
7087     m_cached_result_type= var_entry->type();
7088     unsigned_flag= var_entry->unsigned_flag;
7089     max_length= var_entry->length();
7090 
7091     collation.set(var_entry->collation);
7092     switch(m_cached_result_type) {
7093     case REAL_RESULT:
7094       fix_char_length(DBL_DIG + 8);
7095       break;
7096     case INT_RESULT:
7097       fix_char_length(MAX_BIGINT_WIDTH);
7098       decimals=0;
7099       break;
7100     case STRING_RESULT:
7101       max_length= MAX_BLOB_WIDTH - 1;
7102       break;
7103     case DECIMAL_RESULT:
7104       fix_char_length(DECIMAL_MAX_STR_LENGTH);
7105       decimals= DECIMAL_MAX_SCALE;
7106       break;
7107     case ROW_RESULT:                            // Keep compiler happy
7108     default:
7109       assert(0);
7110       break;
7111     }
7112   }
7113   else
7114   {
7115     collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
7116     null_value= 1;
7117     m_cached_result_type= STRING_RESULT;
7118     max_length= MAX_BLOB_WIDTH;
7119   }
7120 }
7121 
7122 
const_item() const7123 bool Item_func_get_user_var::const_item() const
7124 {
7125   return (!var_entry || current_thd->query_id != var_entry->update_query_id);
7126 }
7127 
7128 
result_type() const7129 enum Item_result Item_func_get_user_var::result_type() const
7130 {
7131   return m_cached_result_type;
7132 }
7133 
7134 
print(String * str,enum_query_type query_type)7135 void Item_func_get_user_var::print(String *str, enum_query_type query_type)
7136 {
7137   str->append(STRING_WITH_LEN("(@"));
7138   append_identifier(current_thd, str, name);
7139   str->append(')');
7140 }
7141 
7142 
eq(const Item * item,bool binary_cmp) const7143 bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
7144 {
7145   /* Assume we don't have rtti */
7146   if (this == item)
7147     return 1;					// Same item is same.
7148   /* Check if other type is also a get_user_var() object */
7149   if (item->type() != FUNC_ITEM ||
7150       ((Item_func*) item)->functype() != functype())
7151     return 0;
7152   Item_func_get_user_var *other=(Item_func_get_user_var*) item;
7153   return name.eq_bin(other->name);
7154 }
7155 
7156 
set_value(THD * thd,sp_rcontext *,Item ** it)7157 bool Item_func_get_user_var::set_value(THD *thd,
7158                                        sp_rcontext * /*ctx*/, Item **it)
7159 {
7160   Item_func_set_user_var *suv= new Item_func_set_user_var(name, *it, false);
7161   /*
7162     Item_func_set_user_var is not fixed after construction, call
7163     fix_fields().
7164   */
7165   return (!suv || suv->fix_fields(thd, it) || suv->check(0) || suv->update());
7166 }
7167 
7168 
fix_fields(THD * thd,Item ** ref)7169 bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref)
7170 {
7171   assert(fixed == 0);
7172   assert(thd->lex->exchange);
7173   /*
7174     Let us set the same collation which is used for loading
7175     of fields in LOAD DATA INFILE.
7176     (Since Item_user_var_as_out_param is used only there).
7177   */
7178   const CHARSET_INFO *cs= thd->lex->exchange->cs ?
7179     thd->lex->exchange->cs : thd->variables.collation_database;
7180 
7181   if (Item::fix_fields(thd, ref))
7182     return true;
7183 
7184   /* Protects thd->user_vars. */
7185   mysql_mutex_lock(&thd->LOCK_thd_data);
7186   entry= get_variable(thd, name, cs);
7187   if (entry != NULL)
7188   {
7189     entry->set_type(STRING_RESULT);
7190     entry->update_query_id= thd->query_id;
7191   }
7192   mysql_mutex_unlock(&thd->LOCK_thd_data);
7193 
7194   if (entry == NULL)
7195     return true;
7196 
7197   return false;
7198 }
7199 
7200 
set_null_value(const CHARSET_INFO * cs)7201 void Item_user_var_as_out_param::set_null_value(const CHARSET_INFO* cs)
7202 {
7203   entry->lock();
7204   entry->set_null_value(STRING_RESULT);
7205   entry->unlock();
7206 }
7207 
7208 
set_value(const char * str,size_t length,const CHARSET_INFO * cs)7209 void Item_user_var_as_out_param::set_value(const char *str, size_t length,
7210                                            const CHARSET_INFO* cs)
7211 {
7212   entry->lock();
7213   entry->store((void*) str, length, STRING_RESULT, cs,
7214                DERIVATION_IMPLICIT, 0 /* unsigned_arg */);
7215   entry->unlock();
7216 }
7217 
7218 
val_real()7219 double Item_user_var_as_out_param::val_real()
7220 {
7221   assert(0);
7222   return 0.0;
7223 }
7224 
7225 
val_int()7226 longlong Item_user_var_as_out_param::val_int()
7227 {
7228   assert(0);
7229   return 0;
7230 }
7231 
7232 
val_str(String * str)7233 String* Item_user_var_as_out_param::val_str(String *str)
7234 {
7235   assert(0);
7236   return 0;
7237 }
7238 
7239 
val_decimal(my_decimal * decimal_buffer)7240 my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer)
7241 {
7242   assert(0);
7243   return 0;
7244 }
7245 
7246 
print(String * str,enum_query_type query_type)7247 void Item_user_var_as_out_param::print(String *str, enum_query_type query_type)
7248 {
7249   str->append('@');
7250   append_identifier(current_thd, str, name);
7251 }
7252 
7253 
7254 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)7255 Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg,
7256                        LEX_STRING *component_arg, const char *name_arg,
7257                        size_t name_len_arg)
7258   :var(NULL), var_type(var_type_arg), orig_var_type(var_type_arg),
7259   component(*component_arg), cache_present(0),
7260   var_tracker(var_arg)
7261 {
7262   /* copy() will allocate the name */
7263   item_name.copy(name_arg, (uint) name_len_arg);
7264 }
7265 
7266 
update_null_value()7267 void Item_func_get_system_var::update_null_value()
7268 {
7269   THD *thd= current_thd;
7270   int save_no_errors= thd->no_errors;
7271   thd->no_errors= TRUE;
7272   Item::update_null_value();
7273   thd->no_errors= save_no_errors;
7274 }
7275 
7276 
fix_length_and_dec()7277 void Item_func_get_system_var::fix_length_and_dec()
7278 {
7279   char *cptr;
7280   maybe_null= TRUE;
7281   max_length= 0;
7282 
7283   THD *const thd= current_thd;
7284 
7285   DEBUG_SYNC(current_thd, "after_error_checking");
7286 
7287   assert(var == NULL);
7288   var= var_tracker.bind_system_variable(thd);
7289   if (var == NULL)
7290     return;
7291 
7292   if (!var->check_scope(var_type))
7293   {
7294     if (var_type != OPT_DEFAULT)
7295     {
7296       my_error(ER_INCORRECT_GLOBAL_LOCAL_VAR, MYF(0),
7297                var->name.str, var_type == OPT_GLOBAL ? "SESSION" : "GLOBAL");
7298       return;
7299     }
7300     /* As there was no local variable, return the global value */
7301     var_type= OPT_GLOBAL;
7302   }
7303 
7304   switch (var->show_type())
7305   {
7306     case SHOW_LONG:
7307     case SHOW_INT:
7308     case SHOW_HA_ROWS:
7309     case SHOW_LONGLONG:
7310       unsigned_flag= TRUE;
7311       collation.set_numeric();
7312       fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS);
7313       decimals=0;
7314       break;
7315     case SHOW_SIGNED_INT:
7316     case SHOW_SIGNED_LONG:
7317     case SHOW_SIGNED_LONGLONG:
7318       unsigned_flag= FALSE;
7319       collation.set_numeric();
7320       fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS);
7321       decimals=0;
7322       break;
7323     case SHOW_CHAR:
7324     case SHOW_CHAR_PTR:
7325       mysql_mutex_lock(&LOCK_global_system_variables);
7326       cptr= var->show_type() == SHOW_CHAR ?
7327         (char*) var->value_ptr(thd, var_type, &component) :
7328         *(char**) var->value_ptr(thd, var_type, &component);
7329       if (cptr)
7330         max_length= system_charset_info->cset->numchars(system_charset_info,
7331                                                         cptr,
7332                                                         cptr + strlen(cptr));
7333       mysql_mutex_unlock(&LOCK_global_system_variables);
7334       collation.set(system_charset_info, DERIVATION_SYSCONST);
7335       max_length*= system_charset_info->mbmaxlen;
7336       decimals=NOT_FIXED_DEC;
7337       break;
7338     case SHOW_LEX_STRING:
7339       {
7340         mysql_mutex_lock(&LOCK_global_system_variables);
7341         LEX_STRING *ls= ((LEX_STRING*)var->value_ptr(thd, var_type, &component));
7342         max_length= system_charset_info->cset->numchars(system_charset_info,
7343                                                         ls->str,
7344                                                         ls->str + ls->length);
7345         mysql_mutex_unlock(&LOCK_global_system_variables);
7346         collation.set(system_charset_info, DERIVATION_SYSCONST);
7347         max_length*= system_charset_info->mbmaxlen;
7348         decimals=NOT_FIXED_DEC;
7349       }
7350       break;
7351     case SHOW_BOOL:
7352     case SHOW_MY_BOOL:
7353       unsigned_flag= FALSE;
7354       collation.set_numeric();
7355       fix_char_length(1);
7356       decimals=0;
7357       break;
7358     case SHOW_DOUBLE:
7359       unsigned_flag= FALSE;
7360       decimals= 6;
7361       collation.set_numeric();
7362       fix_char_length(DBL_DIG + 6);
7363       break;
7364     default:
7365       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7366       break;
7367   }
7368 }
7369 
7370 
print(String * str,enum_query_type query_type)7371 void Item_func_get_system_var::print(String *str, enum_query_type query_type)
7372 {
7373   str->append(item_name);
7374 }
7375 
7376 
result_type() const7377 enum Item_result Item_func_get_system_var::result_type() const
7378 {
7379   switch (var->show_type())
7380   {
7381     case SHOW_BOOL:
7382     case SHOW_MY_BOOL:
7383     case SHOW_INT:
7384     case SHOW_SIGNED_INT:
7385     case SHOW_LONG:
7386     case SHOW_SIGNED_LONG:
7387     case SHOW_LONGLONG:
7388     case SHOW_SIGNED_LONGLONG:
7389     case SHOW_HA_ROWS:
7390       return INT_RESULT;
7391     case SHOW_CHAR:
7392     case SHOW_CHAR_PTR:
7393     case SHOW_LEX_STRING:
7394       return STRING_RESULT;
7395     case SHOW_DOUBLE:
7396       return REAL_RESULT;
7397     default:
7398       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7399       return STRING_RESULT;                   // keep the compiler happy
7400   }
7401 }
7402 
7403 
field_type() const7404 enum_field_types Item_func_get_system_var::field_type() const
7405 {
7406   switch (var->show_type())
7407   {
7408     case SHOW_BOOL:
7409     case SHOW_MY_BOOL:
7410     case SHOW_INT:
7411     case SHOW_SIGNED_INT:
7412     case SHOW_LONG:
7413     case SHOW_SIGNED_LONG:
7414     case SHOW_LONGLONG:
7415     case SHOW_SIGNED_LONGLONG:
7416     case SHOW_HA_ROWS:
7417       return MYSQL_TYPE_LONGLONG;
7418     case SHOW_CHAR:
7419     case SHOW_CHAR_PTR:
7420     case SHOW_LEX_STRING:
7421       return MYSQL_TYPE_VARCHAR;
7422     case SHOW_DOUBLE:
7423       return MYSQL_TYPE_DOUBLE;
7424     default:
7425       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7426       return MYSQL_TYPE_VARCHAR;              // keep the compiler happy
7427   }
7428 }
7429 
7430 
7431 /*
7432   Uses var, var_type, component, cache_present, used_query_id, thd,
7433   cached_llval, null_value, cached_null_value
7434 */
7435 #define get_sys_var_safe(type) \
7436 do { \
7437   type value; \
7438   mysql_mutex_lock(&LOCK_global_system_variables); \
7439   value= *(type*) var->value_ptr(thd, var_type, &component); \
7440   mysql_mutex_unlock(&LOCK_global_system_variables); \
7441   cache_present |= GET_SYS_VAR_CACHE_LONG; \
7442   used_query_id= thd->query_id; \
7443   cached_llval= null_value ? 0 : (longlong) value; \
7444   cached_null_value= null_value; \
7445   return cached_llval; \
7446 } while (0)
7447 
7448 
val_int()7449 longlong Item_func_get_system_var::val_int()
7450 {
7451   THD *thd= current_thd;
7452 
7453   assert(var != NULL);
7454 
7455   if (cache_present && thd->query_id == used_query_id)
7456   {
7457     if (cache_present & GET_SYS_VAR_CACHE_LONG)
7458     {
7459       null_value= cached_null_value;
7460       return cached_llval;
7461     }
7462     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7463     {
7464       null_value= cached_null_value;
7465       cached_llval= (longlong) cached_dval;
7466       cache_present|= GET_SYS_VAR_CACHE_LONG;
7467       return cached_llval;
7468     }
7469     else if (cache_present & GET_SYS_VAR_CACHE_STRING)
7470     {
7471       null_value= cached_null_value;
7472       if (!null_value)
7473         cached_llval= longlong_from_string_with_check (cached_strval.charset(),
7474                                                        cached_strval.c_ptr(),
7475                                                        cached_strval.c_ptr() +
7476                                                        cached_strval.length());
7477       else
7478         cached_llval= 0;
7479       cache_present|= GET_SYS_VAR_CACHE_LONG;
7480       return cached_llval;
7481     }
7482   }
7483 
7484   switch (var->show_type())
7485   {
7486     case SHOW_INT:      get_sys_var_safe (uint);
7487     case SHOW_SIGNED_INT: get_sys_var_safe (int);
7488     case SHOW_LONG:     get_sys_var_safe (ulong);
7489     case SHOW_SIGNED_LONG: get_sys_var_safe (long);
7490     case SHOW_LONGLONG: get_sys_var_safe (ulonglong);
7491     case SHOW_SIGNED_LONGLONG: get_sys_var_safe (longlong);
7492     case SHOW_HA_ROWS:  get_sys_var_safe (ha_rows);
7493     case SHOW_BOOL:     get_sys_var_safe (bool);
7494     case SHOW_MY_BOOL:  get_sys_var_safe (my_bool);
7495     case SHOW_DOUBLE:
7496       {
7497         double dval= val_real();
7498 
7499         used_query_id= thd->query_id;
7500         cached_llval= (longlong) dval;
7501         cache_present|= GET_SYS_VAR_CACHE_LONG;
7502         return cached_llval;
7503       }
7504     case SHOW_CHAR:
7505     case SHOW_CHAR_PTR:
7506     case SHOW_LEX_STRING:
7507       {
7508         String *str_val= val_str(NULL);
7509         // Treat empty strings as NULL, like val_real() does.
7510         if (str_val && str_val->length())
7511           cached_llval= longlong_from_string_with_check (system_charset_info,
7512                                                           str_val->c_ptr(),
7513                                                           str_val->c_ptr() +
7514                                                           str_val->length());
7515         else
7516         {
7517           null_value= TRUE;
7518           cached_llval= 0;
7519         }
7520 
7521         cache_present|= GET_SYS_VAR_CACHE_LONG;
7522         return cached_llval;
7523       }
7524 
7525     default:
7526       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7527       return 0;                               // keep the compiler happy
7528   }
7529 }
7530 
7531 
val_str(String * str)7532 String* Item_func_get_system_var::val_str(String* str)
7533 {
7534   THD *thd= current_thd;
7535 
7536   assert(var != NULL);
7537 
7538   if (cache_present && thd->query_id == used_query_id)
7539   {
7540     if (cache_present & GET_SYS_VAR_CACHE_STRING)
7541     {
7542       null_value= cached_null_value;
7543       return null_value ? NULL : &cached_strval;
7544     }
7545     else if (cache_present & GET_SYS_VAR_CACHE_LONG)
7546     {
7547       null_value= cached_null_value;
7548       if (!null_value)
7549         cached_strval.set (cached_llval, collation.collation);
7550       cache_present|= GET_SYS_VAR_CACHE_STRING;
7551       return null_value ? NULL : &cached_strval;
7552     }
7553     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7554     {
7555       null_value= cached_null_value;
7556       if (!null_value)
7557         cached_strval.set_real (cached_dval, decimals, collation.collation);
7558       cache_present|= GET_SYS_VAR_CACHE_STRING;
7559       return null_value ? NULL : &cached_strval;
7560     }
7561   }
7562 
7563   str= &cached_strval;
7564   null_value= FALSE;
7565   switch (var->show_type())
7566   {
7567     case SHOW_CHAR:
7568     case SHOW_CHAR_PTR:
7569     case SHOW_LEX_STRING:
7570     {
7571       mysql_mutex_lock(&LOCK_global_system_variables);
7572       char *cptr= var->show_type() == SHOW_CHAR ?
7573         (char*) var->value_ptr(thd, var_type, &component) :
7574         *(char**) var->value_ptr(thd, var_type, &component);
7575       if (cptr)
7576       {
7577         size_t len= var->show_type() == SHOW_LEX_STRING ?
7578           ((LEX_STRING*)(var->value_ptr(thd, var_type, &component)))->length :
7579           strlen(cptr);
7580         if (str->copy(cptr, len, collation.collation))
7581         {
7582           null_value= TRUE;
7583           str= NULL;
7584         }
7585       }
7586       else
7587       {
7588         null_value= TRUE;
7589         str= NULL;
7590       }
7591       mysql_mutex_unlock(&LOCK_global_system_variables);
7592       break;
7593     }
7594 
7595     case SHOW_INT:
7596     case SHOW_SIGNED_INT:
7597     case SHOW_LONG:
7598     case SHOW_SIGNED_LONG:
7599     case SHOW_LONGLONG:
7600     case SHOW_SIGNED_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_SIGNED_INT:
7695     case SHOW_LONG:
7696     case SHOW_SIGNED_LONG:
7697     case SHOW_LONGLONG:
7698     case SHOW_SIGNED_LONGLONG:
7699     case SHOW_HA_ROWS:
7700     case SHOW_BOOL:
7701     case SHOW_MY_BOOL:
7702         cached_dval= (double) val_int();
7703         cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7704         used_query_id= thd->query_id;
7705         cached_null_value= null_value;
7706         return cached_dval;
7707     default:
7708       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7709       return 0;
7710   }
7711 }
7712 
7713 
eq(const Item * item,bool binary_cmp) const7714 bool Item_func_get_system_var::eq(const Item *item, bool binary_cmp) const
7715 {
7716   /* Assume we don't have rtti */
7717   if (this == item)
7718     return 1;					// Same item is same.
7719   /* Check if other type is also a get_user_var() object */
7720   if (item->type() != FUNC_ITEM ||
7721       ((Item_func*) item)->functype() != functype())
7722     return 0;
7723   Item_func_get_system_var *other=(Item_func_get_system_var*) item;
7724   return (var_tracker == other->var_tracker && var_type == other->var_type);
7725 }
7726 
7727 
cleanup()7728 void Item_func_get_system_var::cleanup()
7729 {
7730   Item_func::cleanup();
7731   cache_present= 0;
7732   var_type= orig_var_type;
7733   cached_strval.mem_free();
7734   var= NULL;
7735 }
7736 
7737 
itemize(Parse_context * pc,Item ** res)7738 bool Item_func_match::itemize(Parse_context *pc, Item **res)
7739 {
7740   if (skip_itemize(res))
7741     return false;
7742   if (super::itemize(pc, res) || against->itemize(pc, &against))
7743     return true;
7744   with_sum_func|= against->with_sum_func;
7745 
7746   pc->select->add_ftfunc_to_list(this);
7747   pc->thd->lex->set_using_match();
7748 
7749   switch (pc->select->parsing_place)
7750   {
7751     case CTX_WHERE:
7752     case CTX_ON:
7753       used_in_where_only= true;
7754       break;
7755     default:
7756       used_in_where_only= false;
7757   }
7758 
7759   return false;
7760 }
7761 
7762 
7763 /**
7764   Initialize searching within full-text index.
7765 
7766   @param thd    Thread handler
7767 
7768   @returns false if success, true if error
7769 */
7770 
init_search(THD * thd)7771 bool Item_func_match::init_search(THD *thd)
7772 {
7773   DBUG_ENTER("Item_func_match::init_search");
7774 
7775   /*
7776     We will skip execution if the item is not fixed
7777     with fix_field
7778   */
7779   if (!fixed)
7780     DBUG_RETURN(false);
7781 
7782   TABLE *const table= table_ref->table;
7783   /* Check if init_search() has been called before */
7784   if (ft_handler && !master)
7785   {
7786     /*
7787       We should reset ft_handler as it is cleaned up
7788       on destruction of FT_SELECT object
7789       (necessary in case of re-execution of subquery).
7790       TODO: FT_SELECT should not clean up ft_handler.
7791     */
7792     if (join_key)
7793       table->file->ft_handler= ft_handler;
7794     DBUG_RETURN(false);
7795   }
7796 
7797   if (key == NO_SUCH_KEY)
7798   {
7799     List<Item> fields;
7800     if (fields.push_back(new Item_string(" ",1, cmp_collation.collation)))
7801       DBUG_RETURN(true);
7802     for (uint i= 0; i < arg_count; i++)
7803       fields.push_back(args[i]);
7804     concat_ws=new Item_func_concat_ws(fields);
7805     if (concat_ws == NULL)
7806       DBUG_RETURN(true);
7807     /*
7808       Above function used only to get value and do not need fix_fields for it:
7809       Item_string - basic constant
7810       fields - fix_fields() was already called for this arguments
7811       Item_func_concat_ws - do not need fix_fields() to produce value
7812     */
7813     concat_ws->quick_fix_field();
7814   }
7815 
7816   if (master)
7817   {
7818     if (master->init_search(thd))
7819       DBUG_RETURN(true);
7820 
7821     ft_handler=master->ft_handler;
7822     DBUG_RETURN(false);
7823   }
7824 
7825   String *ft_tmp= 0;
7826 
7827   // MATCH ... AGAINST (NULL) is meaningless, but possible
7828   if (!(ft_tmp=key_item()->val_str(&value)))
7829   {
7830     ft_tmp= &value;
7831     value.set("",0,cmp_collation.collation);
7832   }
7833 
7834   if (ft_tmp->charset() != cmp_collation.collation)
7835   {
7836     uint dummy_errors;
7837     search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
7838                       cmp_collation.collation, &dummy_errors);
7839     ft_tmp= &search_value;
7840   }
7841 
7842   if (!table->is_created())
7843   {
7844      my_error(ER_NO_FT_MATERIALIZED_SUBQUERY, MYF(0));
7845      DBUG_RETURN(true);
7846   }
7847 
7848   assert(master == NULL);
7849   ft_handler= table->file->ft_init_ext_with_hints(key, ft_tmp, get_hints());
7850   if (thd->is_error())
7851     DBUG_RETURN(true);
7852 
7853   if (join_key)
7854     table->file->ft_handler=ft_handler;
7855 
7856   DBUG_RETURN(false);
7857 }
7858 
7859 
get_filtering_effect(table_map filter_for_table,table_map read_tables,const MY_BITMAP * fields_to_ignore,double rows_in_table)7860 float Item_func_match::get_filtering_effect(table_map filter_for_table,
7861                                             table_map read_tables,
7862                                             const MY_BITMAP *fields_to_ignore,
7863                                             double rows_in_table)
7864 {
7865   const Item_field* fld=
7866     contributes_to_filter(read_tables, filter_for_table, fields_to_ignore);
7867   if (!fld)
7868     return COND_FILTER_ALLPASS;
7869 
7870   /*
7871     MATCH () ... AGAINST" is similar to "LIKE '...'" which has the
7872     same selectivity as "col BETWEEN ...".
7873   */
7874   return fld->get_cond_filter_default_probability(rows_in_table,
7875                                                   COND_FILTER_BETWEEN);
7876 }
7877 
7878 
7879 /**
7880    Add field into table read set.
7881 
7882    @param field field to be added to the table read set.
7883 */
update_table_read_set(Field * field)7884 static void update_table_read_set(Field *field)
7885 {
7886   TABLE *table= field->table;
7887 
7888   if (!bitmap_fast_test_and_set(table->read_set, field->field_index))
7889     table->covering_keys.intersect(field->part_of_key);
7890 }
7891 
7892 
fix_fields(THD * thd,Item ** ref)7893 bool Item_func_match::fix_fields(THD *thd, Item **ref)
7894 {
7895   assert(fixed == 0);
7896   assert(arg_count > 0);
7897   Item *item= NULL;                        // Safe as arg_count is > 1
7898 
7899   maybe_null=1;
7900   join_key=0;
7901 
7902   /*
7903     const_item is assumed in quite a bit of places, so it would be difficult
7904     to remove;  If it would ever to be removed, this should include
7905     modifications to find_best and auto_close as complement to auto_init code
7906     above.
7907   */
7908   enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
7909   /*
7910     Since different engines require different columns for FTS index lookup
7911     we prevent updating of table read_set in argument's ::fix_fields().
7912   */
7913   thd->mark_used_columns= MARK_COLUMNS_NONE;
7914   if (Item_func::fix_fields(thd, ref) ||
7915       fix_func_arg(thd, &against) || !against->const_during_execution())
7916   {
7917     thd->mark_used_columns= save_mark_used_columns;
7918     my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
7919     return TRUE;
7920   }
7921   thd->mark_used_columns= save_mark_used_columns;
7922 
7923   bool allows_multi_table_search= true;
7924   const_item_cache=0;
7925   for (uint i= 0 ; i < arg_count ; i++)
7926   {
7927     item= args[i]= args[i]->real_item();
7928     if (item->type() != Item::FIELD_ITEM ||
7929         /* Cannot use FTS index with outer table field */
7930         (item->used_tables() & OUTER_REF_TABLE_BIT))
7931     {
7932       my_error(ER_WRONG_ARGUMENTS, MYF(0), "MATCH");
7933       return TRUE;
7934     }
7935     allows_multi_table_search &=
7936       allows_search_on_non_indexed_columns(((Item_field *)item)->field->table);
7937   }
7938 
7939   /*
7940     Check that all columns come from the same table.
7941     We've already checked that columns in MATCH are fields so
7942     PARAM_TABLE_BIT can only appear from AGAINST argument.
7943   */
7944   if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
7945     key=NO_SUCH_KEY;
7946 
7947   if (key == NO_SUCH_KEY && !allows_multi_table_search)
7948   {
7949     my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
7950     return TRUE;
7951   }
7952   table_ref= ((Item_field *)item)->table_ref;
7953 
7954   /*
7955     Here we make an assumption that if the engine supports
7956     fulltext extension(HA_CAN_FULLTEXT_EXT flag) then table
7957     can have FTS_DOC_ID column. Atm this is the only way
7958     to distinguish MyISAM and InnoDB engines.
7959     Generally table_ref should be available, but in case of
7960     a generated column's generation expression it's not. Thus
7961     we use field's table, at this moment it's already available.
7962   */
7963   TABLE *const table= table_ref ?
7964     table_ref->table :
7965     ((Item_field *)item)->field->table;
7966 
7967   if (!(table->file->ha_table_flags() & HA_CAN_FULLTEXT))
7968   {
7969     my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
7970     return 1;
7971   }
7972 
7973   if ((table->file->ha_table_flags() & HA_CAN_FULLTEXT_EXT))
7974   {
7975     Field *doc_id_field= table->fts_doc_id_field;
7976     /*
7977       Update read set with FTS_DOC_ID column so that indexes that have
7978       FTS_DOC_ID part can be considered as a covering index.
7979     */
7980     if (doc_id_field)
7981       update_table_read_set(doc_id_field);
7982     else
7983     {
7984       /* read_set needs to be updated for MATCH arguments */
7985       for (uint i= 0; i < arg_count; i++)
7986         update_table_read_set(((Item_field*)args[i])->field);
7987       /*
7988         Prevent index only accces by non-FTS index if table does not have
7989         FTS_DOC_ID column, find_relevance does not work properly without
7990         FTS_DOC_ID value. Decision for FTS index about index only access
7991         is made later by JOIN::fts_index_access() function.
7992       */
7993       table->covering_keys.clear_all();
7994     }
7995 
7996   }
7997   else
7998   {
7999     /*
8000       Since read_set is not updated for MATCH arguments
8001       it's necessary to update it here for MyISAM.
8002     */
8003     for (uint i= 0; i < arg_count; i++)
8004       update_table_read_set(((Item_field*)args[i])->field);
8005   }
8006 
8007   table->fulltext_searched=1;
8008 
8009   if (!master)
8010   {
8011     Prepared_stmt_arena_holder ps_arena_holder(thd);
8012     hints= new Ft_hints(flags);
8013     if (!hints)
8014     {
8015       my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
8016       return true;
8017     }
8018   }
8019   return agg_item_collations_for_comparison(cmp_collation, func_name(),
8020                                             args, arg_count, 0);
8021 }
8022 
fix_index()8023 bool Item_func_match::fix_index()
8024 {
8025   Item_field *item;
8026   TABLE *table;
8027   uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
8028   uint max_cnt=0, mkeys=0, i;
8029 
8030   if (!table_ref)
8031     goto err;
8032 
8033   /*
8034     We will skip execution if the item is not fixed
8035     with fix_field
8036   */
8037   if (!fixed)
8038   {
8039     if (allows_search_on_non_indexed_columns(table_ref->table))
8040       key= NO_SUCH_KEY;
8041 
8042     return false;
8043   }
8044   if (key == NO_SUCH_KEY)
8045     return 0;
8046 
8047   table= table_ref->table;
8048   for (keynr=0 ; keynr < table->s->keys ; keynr++)
8049   {
8050     if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
8051         (flags & FT_BOOL ? table->keys_in_use_for_query.is_set(keynr) :
8052                            table->s->keys_in_use.is_set(keynr)))
8053 
8054     {
8055       ft_to_key[fts]=keynr;
8056       ft_cnt[fts]=0;
8057       fts++;
8058     }
8059   }
8060 
8061   if (!fts)
8062     goto err;
8063 
8064   for (i= 0; i < arg_count; i++)
8065   {
8066     item=(Item_field*)args[i];
8067     for (keynr=0 ; keynr < fts ; keynr++)
8068     {
8069       KEY *ft_key=&table->key_info[ft_to_key[keynr]];
8070       uint key_parts=ft_key->user_defined_key_parts;
8071 
8072       for (uint part=0 ; part < key_parts ; part++)
8073       {
8074 	if (item->field->eq(ft_key->key_part[part].field))
8075 	  ft_cnt[keynr]++;
8076       }
8077     }
8078   }
8079 
8080   for (keynr=0 ; keynr < fts ; keynr++)
8081   {
8082     if (ft_cnt[keynr] > max_cnt)
8083     {
8084       mkeys=0;
8085       max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
8086       ft_to_key[mkeys]=ft_to_key[keynr];
8087       continue;
8088     }
8089     if (max_cnt && ft_cnt[keynr] == max_cnt)
8090     {
8091       mkeys++;
8092       ft_cnt[mkeys]=ft_cnt[keynr];
8093       ft_to_key[mkeys]=ft_to_key[keynr];
8094       continue;
8095     }
8096   }
8097 
8098   for (keynr=0 ; keynr <= mkeys ; keynr++)
8099   {
8100     // partial keys doesn't work
8101     if (max_cnt < arg_count ||
8102         max_cnt < table->key_info[ft_to_key[keynr]].user_defined_key_parts)
8103       continue;
8104 
8105     key=ft_to_key[keynr];
8106 
8107     return 0;
8108   }
8109 
8110 err:
8111   if (table_ref != 0 && allows_search_on_non_indexed_columns(table_ref->table))
8112   {
8113     key=NO_SUCH_KEY;
8114     return 0;
8115   }
8116   my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
8117              ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
8118   return 1;
8119 }
8120 
8121 
eq(const Item * item,bool binary_cmp) const8122 bool Item_func_match::eq(const Item *item, bool binary_cmp) const
8123 {
8124   /* We ignore FT_SORTED flag when checking for equality since result is
8125      equvialent regardless of sorting */
8126   if (item->type() != FUNC_ITEM ||
8127       ((Item_func*)item)->functype() != FT_FUNC ||
8128       (flags | FT_SORTED) != (((Item_func_match*)item)->flags | FT_SORTED))
8129     return 0;
8130 
8131   Item_func_match *ifm=(Item_func_match*) item;
8132 
8133   if (key == ifm->key && table_ref == ifm->table_ref &&
8134       key_item()->eq(ifm->key_item(), binary_cmp))
8135     return 1;
8136 
8137   return 0;
8138 }
8139 
8140 
val_real()8141 double Item_func_match::val_real()
8142 {
8143   assert(fixed == 1);
8144   DBUG_ENTER("Item_func_match::val");
8145   if (ft_handler == NULL)
8146     DBUG_RETURN(-1.0);
8147 
8148   TABLE *const table= table_ref->table;
8149   if (key != NO_SUCH_KEY && table->has_null_row()) // NULL row from outer join
8150     DBUG_RETURN(0.0);
8151 
8152   if (get_master()->join_key)
8153   {
8154     if (table->file->ft_handler)
8155       DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
8156     get_master()->join_key= 0;
8157   }
8158 
8159   if (key == NO_SUCH_KEY)
8160   {
8161     String *a= concat_ws->val_str(&value);
8162     if ((null_value= (a == 0)) || !a->length())
8163       DBUG_RETURN(0);
8164     DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
8165 				      (uchar *)a->ptr(), a->length()));
8166   }
8167   DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
8168                                                  table->record[0], 0));
8169 }
8170 
print(String * str,enum_query_type query_type)8171 void Item_func_match::print(String *str, enum_query_type query_type)
8172 {
8173   str->append(STRING_WITH_LEN("(match "));
8174   print_args(str, 0, query_type);
8175   str->append(STRING_WITH_LEN(" against ("));
8176   against->print(str, query_type);
8177   if (flags & FT_BOOL)
8178     str->append(STRING_WITH_LEN(" in boolean mode"));
8179   else if (flags & FT_EXPAND)
8180     str->append(STRING_WITH_LEN(" with query expansion"));
8181   str->append(STRING_WITH_LEN("))"));
8182 }
8183 
8184 
8185 /**
8186   Function sets FT hints(LIMIT, flags) depending on
8187   various join conditions.
8188 
8189   @param join     Pointer to JOIN object.
8190   @param ft_flag  FT flag value.
8191   @param ft_limit Limit value.
8192   @param no_cond  true if MATCH is not used in WHERE condition.
8193 */
8194 
set_hints(JOIN * join,uint ft_flag,ha_rows ft_limit,bool no_cond)8195 void Item_func_match::set_hints(JOIN *join, uint ft_flag,
8196                                 ha_rows ft_limit, bool no_cond)
8197 {
8198   assert(!master);
8199 
8200   if (!join)  // used for count() optimization
8201   {
8202     hints->set_hint_flag(ft_flag);
8203     return;
8204   }
8205 
8206   /* skip hints setting if there are aggregates(except of FT_NO_RANKING) */
8207   if (join->implicit_grouping || join->group_list || join->select_distinct)
8208   {
8209     /* 'No ranking' is possibe even if aggregates are present */
8210     if ((ft_flag & FT_NO_RANKING))
8211       hints->set_hint_flag(FT_NO_RANKING);
8212     return;
8213   }
8214 
8215   hints->set_hint_flag(ft_flag);
8216 
8217   /**
8218     Only one table is used, there is no aggregates,
8219     WHERE condition is a single MATCH expression
8220     (WHERE MATCH(..) or WHERE MATCH(..) [>=,>] value) or
8221     there is no WHERE condition.
8222   */
8223   if (join->primary_tables == 1 && (no_cond || is_simple_expression()))
8224     hints->set_hint_limit(ft_limit);
8225 }
8226 
8227 
val_int()8228 longlong Item_func_bit_xor::val_int()
8229 {
8230   assert(fixed == 1);
8231   ulonglong arg1= (ulonglong) args[0]->val_int();
8232   ulonglong arg2= (ulonglong) args[1]->val_int();
8233   if ((null_value= (args[0]->null_value || args[1]->null_value)))
8234     return 0;
8235   return (longlong) (arg1 ^ arg2);
8236 }
8237 
8238 
8239 /***************************************************************************
8240   System variables
8241 ****************************************************************************/
8242 
8243 /**
8244   @class Silence_deprecation_warnings
8245 
8246   @brief Disable deprecation warnings handler class
8247 */
8248 class Silence_deprecation_warnings : public Internal_error_handler
8249 {
8250 public:
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_severity_level * level,const char * msg)8251   virtual bool handle_condition(THD *thd,
8252                                 uint sql_errno,
8253                                 const char* sqlstate,
8254                                 Sql_condition::enum_severity_level *level,
8255                                 const char* msg)
8256   {
8257     return sql_errno == ER_WARN_DEPRECATED_SYNTAX;
8258   }
8259 };
8260 
8261 /**
8262   Return value of an system variable base[.name] as a constant item.
8263 
8264   @param pc                     Current parse context
8265   @param var_type               global / session
8266   @param name                   Name of base or system variable
8267   @param component              Component.
8268 
8269   @param unsafe                 If true and if the variable is written to a
8270                                 binlog then mark the statement as unsafe.
8271 
8272   @note
8273     If component.str = 0 then the variable name is in 'name'
8274 
8275   @return
8276     - 0  : error
8277     - #  : constant item
8278 */
8279 
8280 
get_system_var(Parse_context * pc,enum_var_type var_type,LEX_STRING name,LEX_STRING component,bool unsafe)8281 Item *get_system_var(Parse_context *pc,
8282                      enum_var_type var_type, LEX_STRING name,
8283                      LEX_STRING component, bool unsafe)
8284 {
8285   THD *thd= pc->thd;
8286   sys_var *var;
8287   LEX_STRING *base_name, *component_name;
8288 
8289   if (component.str)
8290   {
8291     base_name= &component;
8292     component_name= &name;
8293   }
8294   else
8295   {
8296     base_name= &name;
8297     component_name= &component;			// Empty string
8298   }
8299 
8300   if (!(var= find_sys_var(thd, base_name->str, base_name->length)))
8301     return 0;
8302   if (component.str)
8303   {
8304     if (!var->is_struct())
8305     {
8306       my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
8307       return 0;
8308     }
8309   }
8310   thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
8311 
8312   set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);
8313 
8314   var->do_deprecated_warning(thd);
8315 
8316   Item_func_get_system_var *item= new Item_func_get_system_var(var, var_type,
8317                                                                component_name,
8318                                                                NULL, 0);
8319   if (item == NULL)
8320     return NULL;  // OOM
8321 
8322   if (unsafe && !var->is_written_to_binlog(var_type))
8323     thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE);
8324 
8325 #ifndef EMBEDDED_LIBRARY
8326   if (var_type == OPT_GLOBAL && var->check_scope(OPT_GLOBAL))
8327   {
8328     String str;
8329     String *outStr;
8330     /* This object is just created for variable to string conversion.
8331        item object cannot be used after the conversion of the variable
8332        to string. It caches the data. */
8333     Item_func_get_system_var *si= new Item_func_get_system_var(var, var_type,
8334                                                                component_name,
8335                                                                NULL, 0);
8336 
8337     /* Disable deprecation warning during var to string conversion. */
8338     Silence_deprecation_warnings silencer;
8339     thd->push_internal_handler(&silencer);
8340 
8341     if (si)
8342       (void) si->fix_length_and_dec();
8343     outStr= si ? si->val_str(&str) : &str;
8344 
8345     thd->pop_internal_handler();
8346 
8347     if (mysql_audit_notify(thd, AUDIT_EVENT(MYSQL_AUDIT_GLOBAL_VARIABLE_GET),
8348                            var->name.str,
8349                            outStr ? outStr->ptr() : NULL,
8350                            outStr ? outStr->length() : 0))
8351       {
8352         return 0;
8353       }
8354   }
8355 #endif
8356 
8357   return item;
8358 }
8359 
8360 
itemize(Parse_context * pc,Item ** res)8361 bool Item_func_row_count::itemize(Parse_context *pc, Item **res)
8362 {
8363   if (skip_itemize(res))
8364     return false;
8365   if (super::itemize(pc, res))
8366     return true;
8367 
8368   LEX *lex= pc->thd->lex;
8369   lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8370   lex->safe_to_cache_query= 0;
8371   return false;
8372 }
8373 
val_int()8374 longlong Item_func_row_count::val_int()
8375 {
8376   assert(fixed == 1);
8377   THD *thd= current_thd;
8378 
8379   return thd->get_row_count_func();
8380 }
8381 
8382 
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)8383 Item_func_sp::Item_func_sp(const POS &pos,
8384                            const LEX_STRING &db_name,
8385                            const LEX_STRING &fn_name,
8386                            bool use_explicit_name,
8387                            PT_item_list *opt_list)
8388 : Item_func(pos, opt_list), m_sp(NULL), dummy_table(NULL), sp_result_field(NULL)
8389 {
8390   maybe_null= 1;
8391   with_stored_program= true;
8392   THD *thd= current_thd;
8393   m_name= new (thd->mem_root) sp_name(to_lex_cstring(db_name), fn_name,
8394                                       use_explicit_name);
8395 }
8396 
8397 
itemize(Parse_context * pc,Item ** res)8398 bool Item_func_sp::itemize(Parse_context *pc, Item **res)
8399 {
8400   if (skip_itemize(res))
8401     return false;
8402   if (super::itemize(pc, res))
8403     return true;
8404   if (m_name == NULL)
8405     return true; // OOM
8406 
8407   THD *thd= pc->thd;
8408   LEX *lex= thd->lex;
8409 
8410   context= lex->current_context();
8411   lex->safe_to_cache_query= false;
8412 
8413   if (m_name->m_db.str == NULL)
8414   {
8415     /* Cannot match the function since no database is selected */
8416     my_error(ER_NO_DB_ERROR, MYF(0));
8417     return true;
8418   }
8419 
8420   m_name->init_qname(thd);
8421   sp_add_used_routine(lex, thd, m_name, SP_TYPE_FUNCTION);
8422 
8423   dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE));
8424   if (dummy_table == NULL)
8425     return true;
8426   dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
8427 
8428   return false;
8429 }
8430 
8431 
8432 void
cleanup()8433 Item_func_sp::cleanup()
8434 {
8435   if (sp_result_field)
8436   {
8437     delete sp_result_field;
8438     sp_result_field= NULL;
8439   }
8440   m_sp= NULL;
8441   if (dummy_table != NULL)
8442     dummy_table->alias= NULL;
8443   Item_func::cleanup();
8444   tables_locked_cache= false;
8445   with_stored_program= true;
8446 }
8447 
8448 const char *
func_name() const8449 Item_func_sp::func_name() const
8450 {
8451   THD *thd= current_thd;
8452   /* Calculate length to avoid reallocation of string for sure */
8453   size_t len= (((m_name->m_explicit_name ? m_name->m_db.length : 0) +
8454                 m_name->m_name.length)*2 + //characters*quoting
8455                2 +                         // ` and `
8456                (m_name->m_explicit_name ?
8457                 3 : 0) +                   // '`', '`' and '.' for the db
8458                1 +                         // end of string
8459                ALIGN_SIZE(1));             // to avoid String reallocation
8460   String qname((char *)alloc_root(thd->mem_root, len), len,
8461                system_charset_info);
8462 
8463   qname.length(0);
8464   if (m_name->m_explicit_name)
8465   {
8466     append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length);
8467     qname.append('.');
8468   }
8469   append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length);
8470   return qname.ptr();
8471 }
8472 
8473 
get_initial_pseudo_tables() const8474 table_map Item_func_sp::get_initial_pseudo_tables() const
8475 {
8476   return m_sp->m_chistics->detistic ? 0 : RAND_TABLE_BIT;
8477 }
8478 
8479 
my_missing_function_error(const LEX_STRING & token,const char * func_name)8480 void my_missing_function_error(const LEX_STRING &token, const char *func_name)
8481 {
8482   if (token.length && is_lex_native_function (&token))
8483     my_error(ER_FUNC_INEXISTENT_NAME_COLLISION, MYF(0), func_name);
8484   else
8485     my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", func_name);
8486 }
8487 
8488 
8489 /**
8490   @brief Initialize the result field by creating a temporary dummy table
8491     and assign it to a newly created field object. Meta data used to
8492     create the field is fetched from the sp_head belonging to the stored
8493     proceedure found in the stored procedure functon cache.
8494 
8495   @note This function should be called from fix_fields to init the result
8496     field. It is some what related to Item_field.
8497 
8498   @see Item_field
8499 
8500   @param thd A pointer to the session and thread context.
8501 
8502   @return Function return error status.
8503   @retval TRUE is returned on an error
8504   @retval FALSE is returned on success.
8505 */
8506 
8507 bool
init_result_field(THD * thd)8508 Item_func_sp::init_result_field(THD *thd)
8509 {
8510   LEX_STRING empty_name= { C_STRING_WITH_LEN("") };
8511   TABLE_SHARE *share;
8512   DBUG_ENTER("Item_func_sp::init_result_field");
8513 
8514   assert(m_sp == NULL);
8515   assert(sp_result_field == NULL);
8516 
8517   Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8518     view_handler(thd, context->view_error_handler,
8519                  context->view_error_handler_arg);
8520   if (!(m_sp= sp_find_routine(thd, SP_TYPE_FUNCTION, m_name,
8521                                &thd->sp_func_cache, TRUE)))
8522   {
8523     my_missing_function_error (m_name->m_name, m_name->m_qname.str);
8524     DBUG_RETURN(TRUE);
8525   }
8526 
8527   /*
8528      A Field need to be attached to a Table.
8529      Below we "create" a dummy table by initializing
8530      the needed pointers.
8531    */
8532 
8533   share= dummy_table->s;
8534   dummy_table->alias = "";
8535   if (maybe_null)
8536     dummy_table->set_nullable();
8537   dummy_table->in_use= thd;
8538   dummy_table->copy_blobs= TRUE;
8539   share->table_cache_key = empty_name;
8540   share->table_name = empty_name;
8541 
8542   if (!(sp_result_field= m_sp->create_result_field(max_length, item_name.ptr(),
8543                                                    dummy_table)))
8544   {
8545    DBUG_RETURN(TRUE);
8546   }
8547 
8548   if (sp_result_field->pack_length() > sizeof(result_buf))
8549   {
8550     void *tmp;
8551     if (!(tmp= sql_alloc(sp_result_field->pack_length())))
8552       DBUG_RETURN(TRUE);
8553     sp_result_field->move_field((uchar*) tmp);
8554   }
8555   else
8556     sp_result_field->move_field(result_buf);
8557 
8558   sp_result_field->set_null_ptr((uchar *) &null_value, 1);
8559   DBUG_RETURN(FALSE);
8560 }
8561 
8562 
8563 /**
8564   @brief Initialize local members with values from the Field interface.
8565 
8566   @note called from Item::fix_fields.
8567 */
8568 
fix_length_and_dec()8569 void Item_func_sp::fix_length_and_dec()
8570 {
8571   DBUG_ENTER("Item_func_sp::fix_length_and_dec");
8572 
8573   assert(sp_result_field);
8574   decimals= sp_result_field->decimals();
8575   max_length= sp_result_field->field_length;
8576   collation.set(sp_result_field->charset());
8577   maybe_null= 1;
8578   unsigned_flag= MY_TEST(sp_result_field->flags & UNSIGNED_FLAG);
8579 
8580   DBUG_VOID_RETURN;
8581 }
8582 
8583 
val_json(Json_wrapper * result)8584 bool Item_func_sp::val_json(Json_wrapper *result)
8585 {
8586   if (sp_result_field->type() == MYSQL_TYPE_JSON)
8587   {
8588     if (execute())
8589     {
8590       return true;
8591     }
8592 
8593     Field_json *json_value= down_cast<Field_json *>(sp_result_field);
8594     return json_value->val_json(result);
8595   }
8596 
8597   /* purecov: begin deadcode */
8598   DBUG_ABORT();
8599   my_error(ER_INVALID_CAST_TO_JSON, MYF(0));
8600   return error_json();
8601   /* purecov: end */
8602 }
8603 
8604 
8605 type_conversion_status
save_in_field_inner(Field * field,bool no_conversions)8606 Item_func_sp::save_in_field_inner(Field *field, bool no_conversions)
8607 {
8608   return save_possibly_as_json(field, no_conversions);
8609 }
8610 
8611 
update_null_value()8612 void Item_func_sp::update_null_value()
8613 {
8614   /*
8615     This method is called when we try to check if the item value is NULL.
8616     We call Item_func_sp::execute() to get value of null_value attribute
8617     as a side effect of its execution.
8618     We ignore any error since update_null_value() doesn't return value.
8619     We used to delegate nullability check to Item::update_null_value as
8620     a result of a chain of function calls:
8621      Item_func_isnull::val_int --> Item_func::is_null -->
8622       Item::update_null_value -->Item_func_sp::val_int -->
8623         Field_varstring::val_int
8624     Such approach resulted in a call of push_warning_printf() in case
8625     if a stored program value couldn't be cast to integer (the case when
8626     for example there was a stored function that declared as returning
8627     varchar(1) and a function's implementation returned "Y" from its body).
8628   */
8629   execute();
8630 }
8631 
8632 
8633 /**
8634   @brief Execute function & store value in field.
8635 
8636   @return Function returns error status.
8637   @retval FALSE on success.
8638   @retval TRUE if an error occurred.
8639 */
8640 
8641 bool
execute()8642 Item_func_sp::execute()
8643 {
8644   THD *thd= current_thd;
8645 
8646   Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8647     view_handler(thd, context->view_error_handler,
8648                  context->view_error_handler_arg);
8649   /* Execute function and store the return value in the field. */
8650 
8651   if (execute_impl(thd))
8652   {
8653     null_value= 1;
8654     if (thd->killed)
8655       thd->send_kill_message();
8656     return TRUE;
8657   }
8658 
8659   /* Check that the field (the value) is not NULL. */
8660 
8661   null_value= sp_result_field->is_null();
8662 
8663   return null_value;
8664 }
8665 
8666 
8667 /**
8668    @brief Execute function and store the return value in the field.
8669 
8670    @note This function was intended to be the concrete implementation of
8671     the interface function execute. This was never realized.
8672 
8673    @return The error state.
8674    @retval FALSE on success
8675    @retval TRUE if an error occurred.
8676 */
8677 bool
execute_impl(THD * thd)8678 Item_func_sp::execute_impl(THD *thd)
8679 {
8680   bool err_status= TRUE;
8681   Sub_statement_state statement_state;
8682 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8683   Security_context *save_security_ctx= thd->security_context();
8684 #endif
8685   enum enum_sp_data_access access=
8686     (m_sp->m_chistics->daccess == SP_DEFAULT_ACCESS) ?
8687      SP_DEFAULT_ACCESS_MAPPING : m_sp->m_chistics->daccess;
8688 
8689   DBUG_ENTER("Item_func_sp::execute_impl");
8690 
8691 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8692   if (context->security_ctx)
8693   {
8694     /* Set view definer security context */
8695     thd->set_security_context(context->security_ctx);
8696   }
8697 #endif
8698   if (sp_check_access(thd))
8699     goto error;
8700 
8701   /*
8702     Throw an error if a non-deterministic function is called while
8703     statement-based replication (SBR) is active.
8704   */
8705 
8706   if (!m_sp->m_chistics->detistic && !trust_function_creators &&
8707       (access == SP_CONTAINS_SQL || access == SP_MODIFIES_SQL_DATA) &&
8708       (mysql_bin_log.is_open() &&
8709        thd->variables.binlog_format == BINLOG_FORMAT_STMT))
8710   {
8711     my_error(ER_BINLOG_UNSAFE_ROUTINE, MYF(0));
8712     goto error;
8713   }
8714   /*
8715     Disable the binlogging if this is not a SELECT statement. If this is a
8716     SELECT, leave binlogging on, so execute_function() code writes the
8717     function call into binlog.
8718   */
8719   thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION);
8720   err_status= m_sp->execute_function(thd, args, arg_count, sp_result_field);
8721   thd->restore_sub_statement_state(&statement_state);
8722 
8723 error:
8724 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8725   thd->set_security_context(save_security_ctx);
8726 #endif
8727 
8728   DBUG_RETURN(err_status);
8729 }
8730 
8731 
8732 void
make_field(Send_field * tmp_field)8733 Item_func_sp::make_field(Send_field *tmp_field)
8734 {
8735   DBUG_ENTER("Item_func_sp::make_field");
8736   assert(sp_result_field);
8737   sp_result_field->make_field(tmp_field);
8738   if (item_name.is_set())
8739     tmp_field->col_name= item_name.ptr();
8740   DBUG_VOID_RETURN;
8741 }
8742 
8743 
8744 enum enum_field_types
field_type() const8745 Item_func_sp::field_type() const
8746 {
8747   DBUG_ENTER("Item_func_sp::field_type");
8748   assert(sp_result_field);
8749   DBUG_RETURN(sp_result_field->type());
8750 }
8751 
8752 Item_result
result_type() const8753 Item_func_sp::result_type() const
8754 {
8755   DBUG_ENTER("Item_func_sp::result_type");
8756   DBUG_PRINT("info", ("m_sp = %p", (void *) m_sp));
8757   assert(sp_result_field);
8758   DBUG_RETURN(sp_result_field->result_type());
8759 }
8760 
8761 
itemize(Parse_context * pc,Item ** res)8762 bool Item_func_found_rows::itemize(Parse_context *pc, Item **res)
8763 {
8764   if (skip_itemize(res))
8765     return false;
8766   if (super::itemize(pc, res))
8767     return true;
8768   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8769   pc->thd->lex->safe_to_cache_query= false;
8770   return false;
8771 }
8772 
8773 
val_int()8774 longlong Item_func_found_rows::val_int()
8775 {
8776   assert(fixed == 1);
8777   return current_thd->found_rows();
8778 }
8779 
8780 
8781 Field *
tmp_table_field(TABLE * t_arg)8782 Item_func_sp::tmp_table_field(TABLE *t_arg)
8783 {
8784   DBUG_ENTER("Item_func_sp::tmp_table_field");
8785 
8786   assert(sp_result_field);
8787   DBUG_RETURN(sp_result_field);
8788 }
8789 
8790 
8791 /**
8792   @brief Checks if requested access to function can be granted to user.
8793     If function isn't found yet, it searches function first.
8794     If function can't be found or user don't have requested access
8795     error is raised.
8796 
8797   @param thd thread handler
8798 
8799   @return Indication if the access was granted or not.
8800   @retval FALSE Access is granted.
8801   @retval TRUE Requested access can't be granted or function doesn't exists.
8802 
8803 */
8804 
8805 bool
sp_check_access(THD * thd)8806 Item_func_sp::sp_check_access(THD *thd)
8807 {
8808   DBUG_ENTER("Item_func_sp::sp_check_access");
8809   assert(m_sp);
8810 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8811   if (check_routine_access(thd, EXECUTE_ACL,
8812 			   m_sp->m_db.str, m_sp->m_name.str, 0, FALSE))
8813     DBUG_RETURN(TRUE);
8814 #endif
8815 
8816   DBUG_RETURN(FALSE);
8817 }
8818 
8819 
8820 bool
fix_fields(THD * thd,Item ** ref)8821 Item_func_sp::fix_fields(THD *thd, Item **ref)
8822 {
8823   bool res;
8824 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8825   Security_context *save_security_ctx= thd->security_context();
8826 #endif
8827 
8828   DBUG_ENTER("Item_func_sp::fix_fields");
8829   assert(fixed == 0);
8830 
8831 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8832   /*
8833     Checking privileges to execute the function while creating view and
8834     executing the function of select.
8835    */
8836   if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) ||
8837       (thd->lex->sql_command == SQLCOM_CREATE_VIEW))
8838   {
8839     if (context->security_ctx)
8840     {
8841       /* Set view definer security context */
8842       thd->set_security_context(context->security_ctx);
8843     }
8844 
8845     /*
8846       Check whether user has execute privilege or not
8847      */
8848 
8849     Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8850       view_handler(thd, context->view_error_handler,
8851                    context->view_error_handler_arg);
8852 
8853     res= check_routine_access(thd, EXECUTE_ACL, m_name->m_db.str,
8854                               m_name->m_name.str, 0, FALSE);
8855     thd->set_security_context(save_security_ctx);
8856 
8857     if (res)
8858     {
8859       DBUG_RETURN(res);
8860     }
8861   }
8862 #endif
8863 
8864   /*
8865     We must call init_result_field before Item_func::fix_fields()
8866     to make m_sp and result_field members available to fix_length_and_dec(),
8867     which is called from Item_func::fix_fields().
8868   */
8869   res= init_result_field(thd);
8870 
8871   if (res)
8872     DBUG_RETURN(res);
8873 
8874   res= Item_func::fix_fields(thd, ref);
8875 
8876   /* These is reset/set by Item_func::fix_fields. */
8877   with_stored_program= true;
8878 
8879   if (res)
8880     DBUG_RETURN(res);
8881 
8882   if (thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)
8883   {
8884     /*
8885       Here we check privileges of the stored routine only during view
8886       creation, in order to validate the view.  A runtime check is
8887       perfomed in Item_func_sp::execute(), and this method is not
8888       called during context analysis.  Notice, that during view
8889       creation we do not infer into stored routine bodies and do not
8890       check privileges of its statements, which would probably be a
8891       good idea especially if the view has SQL SECURITY DEFINER and
8892       the used stored procedure has SQL SECURITY DEFINER.
8893     */
8894     res= sp_check_access(thd);
8895 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8896     /*
8897       Try to set and restore the security context to see whether it's valid
8898     */
8899     Security_context *save_secutiry_ctx;
8900     res= m_sp->set_security_ctx(thd, &save_secutiry_ctx);
8901     if (!res)
8902       m_sp->m_security_ctx.restore_security_context(thd, save_secutiry_ctx);
8903 
8904 #endif /* ! NO_EMBEDDED_ACCESS_CHECKS */
8905   }
8906 
8907   DBUG_RETURN(res);
8908 }
8909 
8910 
update_used_tables()8911 void Item_func_sp::update_used_tables()
8912 {
8913   Item_func::update_used_tables();
8914 
8915   /* This is reset by Item_func::update_used_tables(). */
8916   with_stored_program= true;
8917 }
8918 
8919 
8920 /*
8921   uuid_short handling.
8922 
8923   The short uuid is defined as a longlong that contains the following bytes:
8924 
8925   Bytes  Comment
8926   1      Server_id & 255
8927   4      Startup time of server in seconds
8928   3      Incrementor
8929 
8930   This means that an uuid is guaranteed to be unique
8931   even in a replication environment if the following holds:
8932 
8933   - The last byte of the server id is unique
8934   - If you between two shutdown of the server don't get more than
8935     an average of 2^24 = 16M calls to uuid_short() per second.
8936 */
8937 
8938 ulonglong uuid_value;
8939 
uuid_short_init()8940 void uuid_short_init()
8941 {
8942   uuid_value= ((((ulonglong) server_id) << 56) +
8943                (((ulonglong) server_start_time) << 24));
8944 }
8945 
8946 
itemize(Parse_context * pc,Item ** res)8947 bool Item_func_uuid_short::itemize(Parse_context *pc, Item **res)
8948 {
8949   if (skip_itemize(res))
8950     return false;
8951   if (super::itemize(pc, res))
8952     return true;
8953   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8954   pc->thd->lex->safe_to_cache_query= false;
8955   return false;
8956 }
8957 
8958 
val_int()8959 longlong Item_func_uuid_short::val_int()
8960 {
8961   ulonglong val;
8962   mysql_mutex_lock(&LOCK_uuid_generator);
8963   val= uuid_value++;
8964   mysql_mutex_unlock(&LOCK_uuid_generator);
8965   return (longlong) val;
8966 }
8967 
8968 
itemize(Parse_context * pc,Item ** res)8969 bool Item_func_version::itemize(Parse_context *pc, Item **res)
8970 {
8971   if (skip_itemize(res))
8972     return false;
8973   if (super::itemize(pc, res))
8974     return true;
8975   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8976   return false;
8977 }
8978 
8979