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   error= 0;
6067   thd_wait_begin(thd, THD_WAIT_SLEEP);
6068   while (!thd->killed)
6069   {
6070     error= timed_cond.wait(&cond, &LOCK_item_func_sleep);
6071     if (error == ETIMEDOUT || error == ETIME)
6072       break;
6073     error= 0;
6074   }
6075   thd_wait_end(thd);
6076   mysql_mutex_unlock(&LOCK_item_func_sleep);
6077   thd->EXIT_COND(NULL);
6078 
6079   mysql_cond_destroy(&cond);
6080 
6081   return MY_TEST(!error); 		// Return 1 killed
6082 }
6083 
6084 /*
6085   @param cs  character set; IF we are creating the user_var_entry,
6086              we give it this character set.
6087 */
get_variable(THD * thd,const Name_string & name,const CHARSET_INFO * cs)6088 static user_var_entry *get_variable(THD *thd, const Name_string &name,
6089                                     const CHARSET_INFO *cs)
6090 {
6091   user_var_entry *entry;
6092   HASH *hash= & thd->user_vars;
6093 
6094   /* Protects thd->user_vars. */
6095   mysql_mutex_assert_owner(&thd->LOCK_thd_data);
6096 
6097   if (!(entry= (user_var_entry*) my_hash_search(hash, (uchar*) name.ptr(),
6098                                                  name.length())) &&
6099         cs != NULL)
6100   {
6101     if (!my_hash_inited(hash))
6102       return 0;
6103     if (!(entry= user_var_entry::create(thd, name, cs)))
6104       return 0;
6105     if (my_hash_insert(hash,(uchar*) entry))
6106     {
6107       my_free(entry);
6108       return 0;
6109     }
6110   }
6111   return entry;
6112 }
6113 
6114 
cleanup()6115 void Item_func_set_user_var::cleanup()
6116 {
6117   Item_func::cleanup();
6118   entry= NULL;
6119 }
6120 
6121 
set_entry(THD * thd,bool create_if_not_exists)6122 bool Item_func_set_user_var::set_entry(THD *thd, bool create_if_not_exists)
6123 {
6124   if (entry && thd->thread_id() == entry_thread_id)
6125   {} // update entry->update_query_id for PS
6126   else
6127   {
6128     const CHARSET_INFO *cs=  create_if_not_exists ?
6129           (args[0]->collation.derivation == DERIVATION_NUMERIC ?
6130           default_charset() : args[0]->collation.collation) : NULL;
6131 
6132     /* Protects thd->user_vars. */
6133     mysql_mutex_lock(&thd->LOCK_thd_data);
6134     entry= get_variable(thd, name, cs);
6135     mysql_mutex_unlock(&thd->LOCK_thd_data);
6136 
6137     if (entry == NULL)
6138     {
6139       entry_thread_id= 0;
6140       return TRUE;
6141     }
6142     entry_thread_id= thd->thread_id();
6143   }
6144   /*
6145     Remember the last query which updated it, this way a query can later know
6146     if this variable is a constant item in the query (it is if update_query_id
6147     is different from query_id).
6148 
6149     If this object has delayed setting of non-constness, we delay this
6150     until Item_func_set-user_var::save_item_result().
6151   */
6152   if (!delayed_non_constness)
6153     entry->update_query_id= thd->query_id;
6154   return FALSE;
6155 }
6156 
6157 
6158 /*
6159   When a user variable is updated (in a SET command or a query like
6160   SELECT @a:= ).
6161 */
6162 
fix_fields(THD * thd,Item ** ref)6163 bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref)
6164 {
6165   assert(fixed == 0);
6166   /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
6167   if (Item_func::fix_fields(thd, ref) || set_entry(thd, TRUE))
6168     return TRUE;
6169 
6170   null_item= (args[0]->type() == NULL_ITEM);
6171 
6172   cached_result_type= args[0]->result_type();
6173   return FALSE;
6174 }
6175 
6176 
6177 void
fix_length_and_dec()6178 Item_func_set_user_var::fix_length_and_dec()
6179 {
6180   maybe_null=args[0]->maybe_null;
6181   decimals=args[0]->decimals;
6182   collation.set(DERIVATION_IMPLICIT);
6183   /*
6184      this sets the character set of the item immediately; rules for the
6185      character set of the variable ("entry" object) are different: if "entry"
6186      did not exist previously, set_entry () has created it and has set its
6187      character set; but if it existed previously, it keeps its previous
6188      character set, which may change only when we are sure that the assignment
6189      is to be executed, i.e. in user_var_entry::store ().
6190   */
6191   if (args[0]->collation.derivation == DERIVATION_NUMERIC)
6192     fix_length_and_charset(args[0]->max_char_length(), default_charset());
6193   else
6194   {
6195     fix_length_and_charset(args[0]->max_char_length(),
6196                            args[0]->collation.collation);
6197   }
6198   unsigned_flag= args[0]->unsigned_flag;
6199 }
6200 
6201 
mem_realloc(size_t length)6202 bool user_var_entry::mem_realloc(size_t length)
6203 {
6204   if (length <= extra_size)
6205   {
6206     /* Enough space to store value in value struct */
6207     free_value();
6208     m_ptr= internal_buffer_ptr();
6209   }
6210   else
6211   {
6212     /* Allocate an external buffer */
6213     if (m_length != length)
6214     {
6215       if (m_ptr == internal_buffer_ptr())
6216         m_ptr= 0;
6217       if (!(m_ptr= (char*) my_realloc(key_memory_user_var_entry_value,
6218                                       m_ptr, length,
6219                                       MYF(MY_ALLOW_ZERO_PTR | MY_WME |
6220                                       ME_FATALERROR))))
6221         return true;
6222     }
6223   }
6224   return false;
6225 }
6226 
6227 
6228 /**
6229   Set value to user variable.
6230   @param ptr            pointer to buffer with new value
6231   @param length         length of new value
6232   @param type           type of new value
6233 
6234   @retval  false   on success
6235   @retval  true    on allocation error
6236 
6237 */
store(const void * from,size_t length,Item_result type)6238 bool user_var_entry::store(const void *from, size_t length, Item_result type)
6239 {
6240   assert_locked();
6241 
6242   // Store strings with end \0
6243   if (mem_realloc(length + MY_TEST(type == STRING_RESULT)))
6244     return true;
6245   if (type == STRING_RESULT)
6246     m_ptr[length]= 0;     // Store end \0
6247 
6248   // Avoid memcpy of a my_decimal object, use copy CTOR instead.
6249   if (type == DECIMAL_RESULT)
6250   {
6251     assert(length == sizeof(my_decimal));
6252     const my_decimal* dec= static_cast<const my_decimal*>(from);
6253     dec->sanity_check();
6254     new (m_ptr) my_decimal(*dec);
6255   }
6256   else
6257     memcpy(m_ptr, from, length);
6258 
6259   m_length= length;
6260   m_type= type;
6261   return false;
6262 }
6263 
6264 
6265 /**
6266   Set value to user variable.
6267 
6268   @param ptr            pointer to buffer with new value
6269   @param length         length of new value
6270   @param type           type of new value
6271   @param cs             charset info for new value
6272   @param dv             derivation for new value
6273   @param unsigned_arg   indiates if a value of type INT_RESULT is unsigned
6274 
6275   @note Sets error and fatal error if allocation fails.
6276 
6277   @retval
6278     false   success
6279   @retval
6280     true    failure
6281 */
6282 
store(const void * ptr,size_t length,Item_result type,const CHARSET_INFO * cs,Derivation dv,bool unsigned_arg)6283 bool user_var_entry::store(const void *ptr, size_t length, Item_result type,
6284                            const CHARSET_INFO *cs, Derivation dv,
6285                            bool unsigned_arg)
6286 {
6287   assert_locked();
6288 
6289   if (store(ptr, length, type))
6290     return true;
6291   collation.set(cs, dv);
6292   unsigned_flag= unsigned_arg;
6293   return false;
6294 }
6295 
lock()6296 void user_var_entry::lock()
6297 {
6298   assert(m_owner != NULL);
6299   mysql_mutex_lock(&m_owner->LOCK_thd_data);
6300 }
6301 
unlock()6302 void user_var_entry::unlock()
6303 {
6304   assert(m_owner != NULL);
6305   mysql_mutex_unlock(&m_owner->LOCK_thd_data);
6306 }
6307 
6308 bool
update_hash(const void * ptr,uint length,Item_result res_type,const CHARSET_INFO * cs,Derivation dv,bool unsigned_arg)6309 Item_func_set_user_var::update_hash(const void *ptr, uint length,
6310                                     Item_result res_type,
6311                                     const CHARSET_INFO *cs, Derivation dv,
6312                                     bool unsigned_arg)
6313 {
6314   entry->lock();
6315 
6316   /*
6317     If we set a variable explicitely to NULL then keep the old
6318     result type of the variable
6319   */
6320   // args[0]->null_value could be outdated
6321   if (args[0]->type() == Item::FIELD_ITEM)
6322     null_value= ((Item_field*)args[0])->field->is_null();
6323   else
6324     null_value= args[0]->null_value;
6325 
6326   if (ptr == NULL)
6327   {
6328     assert(length == 0);
6329     null_value= true;
6330   }
6331 
6332   if (null_value && null_item)
6333     res_type= entry->type();                    // Don't change type of item
6334 
6335   if (null_value)
6336     entry->set_null_value(res_type);
6337   else if (entry->store(ptr, length, res_type, cs, dv, unsigned_arg))
6338   {
6339     entry->unlock();
6340     null_value= 1;
6341     return 1;
6342   }
6343   entry->unlock();
6344   return 0;
6345 }
6346 
6347 
6348 /** Get the value of a variable as a double. */
6349 
val_real(my_bool * null_value) const6350 double user_var_entry::val_real(my_bool *null_value) const
6351 {
6352   if ((*null_value= (m_ptr == 0)))
6353     return 0.0;
6354 
6355   switch (m_type) {
6356   case REAL_RESULT:
6357     return *(double*) m_ptr;
6358   case INT_RESULT:
6359     return (double) *(longlong*) m_ptr;
6360   case DECIMAL_RESULT:
6361   {
6362     double result;
6363     my_decimal2double(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, &result);
6364     return result;
6365   }
6366   case STRING_RESULT:
6367     return my_atof(m_ptr);                    // This is null terminated
6368   case ROW_RESULT:
6369     assert(1);				// Impossible
6370     break;
6371   }
6372   return 0.0;					// Impossible
6373 }
6374 
6375 
6376 /** Get the value of a variable as an integer. */
6377 
val_int(my_bool * null_value) const6378 longlong user_var_entry::val_int(my_bool *null_value) const
6379 {
6380   if ((*null_value= (m_ptr == 0)))
6381     return 0LL;
6382 
6383   switch (m_type) {
6384   case REAL_RESULT:
6385     return (longlong) *(double*) m_ptr;
6386   case INT_RESULT:
6387     return *(longlong*) m_ptr;
6388   case DECIMAL_RESULT:
6389   {
6390     longlong result;
6391     my_decimal2int(E_DEC_FATAL_ERROR, (my_decimal *) m_ptr, 0, &result);
6392     return result;
6393   }
6394   case STRING_RESULT:
6395   {
6396     int error;
6397     return my_strtoll10(m_ptr, (char**) 0, &error);// String is null terminated
6398   }
6399   case ROW_RESULT:
6400     assert(1);				// Impossible
6401     break;
6402   }
6403   return 0LL;					// Impossible
6404 }
6405 
6406 
6407 /** Get the value of a variable as a string. */
6408 
val_str(my_bool * null_value,String * str,uint decimals) const6409 String *user_var_entry::val_str(my_bool *null_value, String *str,
6410 				uint decimals) const
6411 {
6412   if ((*null_value= (m_ptr == 0)))
6413     return (String*) 0;
6414 
6415   switch (m_type) {
6416   case REAL_RESULT:
6417     str->set_real(*(double*) m_ptr, decimals, collation.collation);
6418     break;
6419   case INT_RESULT:
6420     if (!unsigned_flag)
6421       str->set(*(longlong*) m_ptr, collation.collation);
6422     else
6423       str->set(*(ulonglong*) m_ptr, collation.collation);
6424     break;
6425   case DECIMAL_RESULT:
6426     str_set_decimal((my_decimal *) m_ptr, str, collation.collation);
6427     break;
6428   case STRING_RESULT:
6429     if (str->copy(m_ptr, m_length, collation.collation))
6430       str= 0;					// EOM error
6431     break;
6432   case ROW_RESULT:
6433     assert(1);				// Impossible
6434     break;
6435   }
6436   return(str);
6437 }
6438 
6439 /** Get the value of a variable as a decimal. */
6440 
val_decimal(my_bool * null_value,my_decimal * val) const6441 my_decimal *user_var_entry::val_decimal(my_bool *null_value, my_decimal *val) const
6442 {
6443   if ((*null_value= (m_ptr == 0)))
6444     return 0;
6445 
6446   switch (m_type) {
6447   case REAL_RESULT:
6448     double2my_decimal(E_DEC_FATAL_ERROR, *(double*) m_ptr, val);
6449     break;
6450   case INT_RESULT:
6451     int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) m_ptr, 0, val);
6452     break;
6453   case DECIMAL_RESULT:
6454     my_decimal2decimal((my_decimal *) m_ptr, val);
6455     break;
6456   case STRING_RESULT:
6457     str2my_decimal(E_DEC_FATAL_ERROR, m_ptr, m_length,
6458                    collation.collation, val);
6459     break;
6460   case ROW_RESULT:
6461     assert(1);				// Impossible
6462     break;
6463   }
6464   return(val);
6465 }
6466 
6467 /**
6468   This functions is invoked on SET \@variable or
6469   \@variable:= expression.
6470 
6471   Evaluate (and check expression), store results.
6472 
6473   @note
6474     For now it always return OK. All problem with value evaluating
6475     will be caught by thd->is_error() check in sql_set_variables().
6476 
6477   @retval
6478     FALSE OK.
6479 */
6480 
6481 bool
check(bool use_result_field)6482 Item_func_set_user_var::check(bool use_result_field)
6483 {
6484   DBUG_ENTER("Item_func_set_user_var::check");
6485   if (use_result_field && !result_field)
6486     use_result_field= FALSE;
6487 
6488   switch (cached_result_type) {
6489   case REAL_RESULT:
6490   {
6491     save_result.vreal= use_result_field ? result_field->val_real() :
6492                         args[0]->val_real();
6493     break;
6494   }
6495   case INT_RESULT:
6496   {
6497     save_result.vint= use_result_field ? result_field->val_int() :
6498                        args[0]->val_int();
6499     unsigned_flag= use_result_field ? ((Field_num*)result_field)->unsigned_flag:
6500                     args[0]->unsigned_flag;
6501     break;
6502   }
6503   case STRING_RESULT:
6504   {
6505     save_result.vstr= use_result_field ? result_field->val_str(&value) :
6506                        args[0]->val_str(&value);
6507     break;
6508   }
6509   case DECIMAL_RESULT:
6510   {
6511     save_result.vdec= use_result_field ?
6512                        result_field->val_decimal(&decimal_buff) :
6513                        args[0]->val_decimal(&decimal_buff);
6514     break;
6515   }
6516   case ROW_RESULT:
6517   default:
6518     // This case should never be chosen
6519     assert(0);
6520     break;
6521   }
6522   DBUG_RETURN(FALSE);
6523 }
6524 
6525 
6526 /**
6527   @brief Evaluate and store item's result.
6528   This function is invoked on "SELECT ... INTO @var ...".
6529 
6530   @param    item    An item to get value from.
6531 */
6532 
save_item_result(Item * item)6533 void Item_func_set_user_var::save_item_result(Item *item)
6534 {
6535   DBUG_ENTER("Item_func_set_user_var::save_item_result");
6536 
6537   switch (cached_result_type) {
6538   case REAL_RESULT:
6539     save_result.vreal= item->val_result();
6540     break;
6541   case INT_RESULT:
6542     save_result.vint= item->val_int_result();
6543     unsigned_flag= item->unsigned_flag;
6544     break;
6545   case STRING_RESULT:
6546     save_result.vstr= item->str_result(&value);
6547     break;
6548   case DECIMAL_RESULT:
6549     save_result.vdec= item->val_decimal_result(&decimal_buff);
6550     break;
6551   case ROW_RESULT:
6552   default:
6553     // Should never happen
6554     assert(0);
6555     break;
6556   }
6557   /*
6558     Set the ID of the query that last updated this variable. This is
6559     usually set by Item_func_set_user_var::set_entry(), but if this
6560     item has delayed setting of non-constness, we must do it now.
6561    */
6562   if (delayed_non_constness)
6563     entry->update_query_id= current_thd->query_id;
6564   DBUG_VOID_RETURN;
6565 }
6566 
6567 
6568 /**
6569   This functions is invoked on
6570   SET \@variable or \@variable:= expression.
6571 
6572   @note
6573     We have to store the expression as such in the variable, independent of
6574     the value method used by the user
6575 
6576   @retval
6577     0	OK
6578   @retval
6579     1	EOM Error
6580 
6581 */
6582 
6583 bool
update()6584 Item_func_set_user_var::update()
6585 {
6586   bool res= 0;
6587   DBUG_ENTER("Item_func_set_user_var::update");
6588 
6589   switch (cached_result_type) {
6590   case REAL_RESULT:
6591   {
6592     res= update_hash(&save_result.vreal,sizeof(save_result.vreal),
6593 		     REAL_RESULT, default_charset(), DERIVATION_IMPLICIT, 0);
6594     break;
6595   }
6596   case INT_RESULT:
6597   {
6598     res= update_hash(&save_result.vint, sizeof(save_result.vint),
6599                      INT_RESULT, default_charset(), DERIVATION_IMPLICIT,
6600                      unsigned_flag);
6601     break;
6602   }
6603   case STRING_RESULT:
6604   {
6605     if (!save_result.vstr)					// Null value
6606       res= update_hash(NULL, 0, STRING_RESULT, &my_charset_bin,
6607 		       DERIVATION_IMPLICIT, 0);
6608     else
6609       res= update_hash(save_result.vstr->ptr(),
6610 		       save_result.vstr->length(), STRING_RESULT,
6611 		       save_result.vstr->charset(),
6612 		       DERIVATION_IMPLICIT, 0);
6613     break;
6614   }
6615   case DECIMAL_RESULT:
6616   {
6617     if (!save_result.vdec)					// Null value
6618       res= update_hash(NULL, 0, DECIMAL_RESULT, &my_charset_bin,
6619                        DERIVATION_IMPLICIT, false);
6620     else
6621       res= update_hash(save_result.vdec,
6622                        sizeof(my_decimal), DECIMAL_RESULT,
6623                        default_charset(), DERIVATION_IMPLICIT, 0);
6624     break;
6625   }
6626   case ROW_RESULT:
6627   default:
6628     // This case should never be chosen
6629     assert(0);
6630     break;
6631   }
6632   DBUG_RETURN(res);
6633 }
6634 
6635 
val_real()6636 double Item_func_set_user_var::val_real()
6637 {
6638   assert(fixed == 1);
6639   check(0);
6640   update();					// Store expression
6641   return entry->val_real(&null_value);
6642 }
6643 
val_int()6644 longlong Item_func_set_user_var::val_int()
6645 {
6646   assert(fixed == 1);
6647   check(0);
6648   update();					// Store expression
6649   return entry->val_int(&null_value);
6650 }
6651 
val_str(String * str)6652 String *Item_func_set_user_var::val_str(String *str)
6653 {
6654   assert(fixed == 1);
6655   check(0);
6656   update();					// Store expression
6657   return entry->val_str(&null_value, str, decimals);
6658 }
6659 
6660 
val_decimal(my_decimal * val)6661 my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val)
6662 {
6663   assert(fixed == 1);
6664   check(0);
6665   update();					// Store expression
6666   return entry->val_decimal(&null_value, val);
6667 }
6668 
6669 
val_result()6670 double Item_func_set_user_var::val_result()
6671 {
6672   assert(fixed == 1);
6673   check(TRUE);
6674   update();					// Store expression
6675   return entry->val_real(&null_value);
6676 }
6677 
val_int_result()6678 longlong Item_func_set_user_var::val_int_result()
6679 {
6680   assert(fixed == 1);
6681   check(TRUE);
6682   update();					// Store expression
6683   return entry->val_int(&null_value);
6684 }
6685 
val_bool_result()6686 bool Item_func_set_user_var::val_bool_result()
6687 {
6688   assert(fixed == 1);
6689   check(TRUE);
6690   update();					// Store expression
6691   return entry->val_int(&null_value) != 0;
6692 }
6693 
str_result(String * str)6694 String *Item_func_set_user_var::str_result(String *str)
6695 {
6696   assert(fixed == 1);
6697   check(TRUE);
6698   update();					// Store expression
6699   return entry->val_str(&null_value, str, decimals);
6700 }
6701 
6702 
val_decimal_result(my_decimal * val)6703 my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val)
6704 {
6705   assert(fixed == 1);
6706   check(TRUE);
6707   update();					// Store expression
6708   return entry->val_decimal(&null_value, val);
6709 }
6710 
6711 
is_null_result()6712 bool Item_func_set_user_var::is_null_result()
6713 {
6714   assert(fixed == 1);
6715   check(TRUE);
6716   update();					// Store expression
6717   return is_null();
6718 }
6719 
6720 // just the assignment, for use in "SET @a:=5" type self-prints
print_assignment(String * str,enum_query_type query_type)6721 void Item_func_set_user_var::print_assignment(String *str,
6722                                               enum_query_type query_type)
6723 {
6724   str->append(STRING_WITH_LEN("@"));
6725   str->append(name);
6726   str->append(STRING_WITH_LEN(":="));
6727   args[0]->print(str, query_type);
6728 }
6729 
6730 // parenthesize assignment for use in "EXPLAIN EXTENDED SELECT (@e:=80)+5"
print(String * str,enum_query_type query_type)6731 void Item_func_set_user_var::print(String *str, enum_query_type query_type)
6732 {
6733   str->append(STRING_WITH_LEN("("));
6734   print_assignment(str, query_type);
6735   str->append(STRING_WITH_LEN(")"));
6736 }
6737 
send(Protocol * protocol,String * str_arg)6738 bool Item_func_set_user_var::send(Protocol *protocol, String *str_arg)
6739 {
6740   if (result_field)
6741   {
6742     check(1);
6743     update();
6744     /*
6745       Workaround for metadata check in Protocol_text. Legacy Protocol_text
6746       is so well designed that it sends fields in text format, and functions'
6747       results in binary format. When this func tries to send its data as a
6748       field it breaks metadata asserts in the P_text.
6749       TODO This func have to be changed to avoid sending data as a field.
6750     */
6751     return result_field->send_binary(protocol);
6752   }
6753   return Item::send(protocol, str_arg);
6754 }
6755 
make_field(Send_field * tmp_field)6756 void Item_func_set_user_var::make_field(Send_field *tmp_field)
6757 {
6758   if (result_field)
6759   {
6760     result_field->make_field(tmp_field);
6761     assert(tmp_field->table_name != 0);
6762     if (Item::item_name.is_set())
6763       tmp_field->col_name=Item::item_name.ptr();    // Use user supplied name
6764   }
6765   else
6766     Item::make_field(tmp_field);
6767 }
6768 
6769 
6770 /*
6771   Save the value of a user variable into a field
6772 
6773   SYNOPSIS
6774     save_in_field()
6775       field           target field to save the value to
6776       no_conversion   flag indicating whether conversions are allowed
6777 
6778   DESCRIPTION
6779     Save the function value into a field and update the user variable
6780     accordingly. If a result field is defined and the target field doesn't
6781     coincide with it then the value from the result field will be used as
6782     the new value of the user variable.
6783 
6784     The reason to have this method rather than simply using the result
6785     field in the val_xxx() methods is that the value from the result field
6786     not always can be used when the result field is defined.
6787     Let's consider the following cases:
6788     1) when filling a tmp table the result field is defined but the value of it
6789     is undefined because it has to be produced yet. Thus we can't use it.
6790     2) on execution of an INSERT ... SELECT statement the save_in_field()
6791     function will be called to fill the data in the new record. If the SELECT
6792     part uses a tmp table then the result field is defined and should be
6793     used in order to get the correct result.
6794 
6795     The difference between the SET_USER_VAR function and regular functions
6796     like CONCAT is that the Item_func objects for the regular functions are
6797     replaced by Item_field objects after the values of these functions have
6798     been stored in a tmp table. Yet an object of the Item_field class cannot
6799     be used to update a user variable.
6800     Due to this we have to handle the result field in a special way here and
6801     in the Item_func_set_user_var::send() function.
6802 
6803   RETURN VALUES
6804     FALSE       Ok
6805     TRUE        Error
6806 */
6807 
6808 type_conversion_status
save_in_field(Field * field,bool no_conversions,bool can_use_result_field)6809 Item_func_set_user_var::save_in_field(Field *field, bool no_conversions,
6810                                       bool can_use_result_field)
6811 {
6812   bool use_result_field= (!can_use_result_field ? 0 :
6813                           (result_field && result_field != field));
6814   type_conversion_status error;
6815 
6816   /* Update the value of the user variable */
6817   check(use_result_field);
6818   update();
6819 
6820   if (result_type() == STRING_RESULT ||
6821       (result_type() == REAL_RESULT &&
6822       field->result_type() == STRING_RESULT))
6823   {
6824     String *result;
6825     const CHARSET_INFO *cs= collation.collation;
6826     char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
6827     str_value.set_quick(buff, sizeof(buff), cs);
6828     result= entry->val_str(&null_value, &str_value, decimals);
6829 
6830     if (null_value)
6831     {
6832       str_value.set_quick(0, 0, cs);
6833       return set_field_to_null_with_conversions(field, no_conversions);
6834     }
6835 
6836     /* NOTE: If null_value == FALSE, "result" must be not NULL.  */
6837 
6838     field->set_notnull();
6839     error=field->store(result->ptr(),result->length(),cs);
6840     str_value.set_quick(0, 0, cs);
6841   }
6842   else if (result_type() == REAL_RESULT)
6843   {
6844     double nr= entry->val_real(&null_value);
6845     if (null_value)
6846       return set_field_to_null(field);
6847     field->set_notnull();
6848     error=field->store(nr);
6849   }
6850   else if (result_type() == DECIMAL_RESULT)
6851   {
6852     my_decimal decimal_value;
6853     my_decimal *val= entry->val_decimal(&null_value, &decimal_value);
6854     if (null_value)
6855       return set_field_to_null(field);
6856     field->set_notnull();
6857     error=field->store_decimal(val);
6858   }
6859   else
6860   {
6861     longlong nr= entry->val_int(&null_value);
6862     if (null_value)
6863       return set_field_to_null_with_conversions(field, no_conversions);
6864     field->set_notnull();
6865     error=field->store(nr, unsigned_flag);
6866   }
6867   return error;
6868 }
6869 
6870 
6871 String *
val_str(String * str)6872 Item_func_get_user_var::val_str(String *str)
6873 {
6874   assert(fixed == 1);
6875   DBUG_ENTER("Item_func_get_user_var::val_str");
6876   if (!var_entry)
6877     DBUG_RETURN((String*) 0);			// No such variable
6878   String *res= var_entry->val_str(&null_value, str, decimals);
6879   DBUG_RETURN(res);
6880 }
6881 
6882 
val_real()6883 double Item_func_get_user_var::val_real()
6884 {
6885   assert(fixed == 1);
6886   if (!var_entry)
6887     return 0.0;					// No such variable
6888   return (var_entry->val_real(&null_value));
6889 }
6890 
6891 
val_decimal(my_decimal * dec)6892 my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec)
6893 {
6894   assert(fixed == 1);
6895   if (!var_entry)
6896     return 0;
6897   return var_entry->val_decimal(&null_value, dec);
6898 }
6899 
6900 
val_int()6901 longlong Item_func_get_user_var::val_int()
6902 {
6903   assert(fixed == 1);
6904   if (!var_entry)
6905     return 0LL;				// No such variable
6906   return (var_entry->val_int(&null_value));
6907 }
6908 
6909 
6910 /**
6911   Get variable by name and, if necessary, put the record of variable
6912   use into the binary log.
6913 
6914   When a user variable is invoked from an update query (INSERT, UPDATE etc),
6915   stores this variable and its value in thd->user_var_events, so that it can be
6916   written to the binlog (will be written just before the query is written, see
6917   log.cc).
6918 
6919   @param      thd        Current thread
6920   @param      name       Variable name
6921   @param[out] out_entry  variable structure or NULL. The pointer is set
6922                          regardless of whether function succeeded or not.
6923 
6924   @retval
6925     0  OK
6926   @retval
6927     1  Failed to put appropriate record into binary log
6928 
6929 */
6930 
6931 static int
get_var_with_binlog(THD * thd,enum_sql_command sql_command,Name_string & name,user_var_entry ** out_entry)6932 get_var_with_binlog(THD *thd, enum_sql_command sql_command,
6933                     Name_string &name, user_var_entry **out_entry)
6934 {
6935   BINLOG_USER_VAR_EVENT *user_var_event;
6936   user_var_entry *var_entry;
6937 
6938   /* Protects thd->user_vars. */
6939   mysql_mutex_lock(&thd->LOCK_thd_data);
6940   var_entry= get_variable(thd, name, NULL);
6941   mysql_mutex_unlock(&thd->LOCK_thd_data);
6942 
6943   /*
6944     Any reference to user-defined variable which is done from stored
6945     function or trigger affects their execution and the execution of the
6946     calling statement. We must log all such variables even if they are
6947     not involved in table-updating statements.
6948   */
6949   if (!(opt_bin_log &&
6950        (is_update_query(sql_command) || thd->in_sub_stmt)))
6951   {
6952     *out_entry= var_entry;
6953     return 0;
6954   }
6955 
6956   if (!var_entry)
6957   {
6958     /*
6959       If the variable does not exist, it's NULL, but we want to create it so
6960       that it gets into the binlog (if it didn't, the slave could be
6961       influenced by a variable of the same name previously set by another
6962       thread).
6963       We create it like if it had been explicitly set with SET before.
6964       The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'.
6965       sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION'
6966       in dispatch_command()). Instead of building a one-element list to pass to
6967       sql_set_variables(), we could instead manually call check() and update();
6968       this would save memory and time; but calling sql_set_variables() makes
6969       one unique place to maintain (sql_set_variables()).
6970 
6971       Manipulation with lex is necessary since free_underlaid_joins
6972       is going to release memory belonging to the main query.
6973     */
6974 
6975     List<set_var_base> tmp_var_list;
6976     LEX *sav_lex= thd->lex, lex_tmp;
6977     thd->lex= &lex_tmp;
6978     lex_start(thd);
6979     tmp_var_list.push_back(new set_var_user(new Item_func_set_user_var(name,
6980                                                                        new Item_null(),
6981                                                                        false)));
6982     /* Create the variable */
6983     if (sql_set_variables(thd, &tmp_var_list))
6984     {
6985       thd->lex= sav_lex;
6986       goto err;
6987     }
6988     thd->lex= sav_lex;
6989     mysql_mutex_lock(&thd->LOCK_thd_data);
6990     var_entry= get_variable(thd, name, NULL);
6991     mysql_mutex_unlock(&thd->LOCK_thd_data);
6992 
6993     if (var_entry == NULL)
6994       goto err;
6995   }
6996   else if (var_entry->used_query_id == thd->query_id ||
6997            mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id))
6998   {
6999     /*
7000        If this variable was already stored in user_var_events by this query
7001        (because it's used in more than one place in the query), don't store
7002        it.
7003     */
7004     *out_entry= var_entry;
7005     return 0;
7006   }
7007 
7008   size_t size;
7009   /*
7010     First we need to store value of var_entry, when the next situation
7011     appears:
7012     > set @a:=1;
7013     > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
7014     We have to write to binlog value @a= 1.
7015 
7016     We allocate the user_var_event on user_var_events_alloc pool, not on
7017     the this-statement-execution pool because in SPs user_var_event objects
7018     may need to be valid after current [SP] statement execution pool is
7019     destroyed.
7020   */
7021   size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length();
7022   if (!(user_var_event= (BINLOG_USER_VAR_EVENT *)
7023         alloc_root(thd->user_var_events_alloc, size)))
7024     goto err;
7025 
7026   user_var_event->value= (char*) user_var_event +
7027     ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT));
7028   user_var_event->user_var_event= var_entry;
7029   user_var_event->type= var_entry->type();
7030   user_var_event->charset_number= var_entry->collation.collation->number;
7031   user_var_event->unsigned_flag= var_entry->unsigned_flag;
7032   if (!var_entry->ptr())
7033   {
7034     /* NULL value*/
7035     user_var_event->length= 0;
7036     user_var_event->value= 0;
7037   }
7038   else
7039   {
7040     // Avoid memcpy of a my_decimal object, use copy CTOR instead.
7041     user_var_event->length= var_entry->length();
7042     if (user_var_event->type == DECIMAL_RESULT)
7043     {
7044       assert(var_entry->length() == sizeof(my_decimal));
7045       const my_decimal* dec=
7046         static_cast<const my_decimal*>
7047         (static_cast<const void*>(var_entry->ptr()));
7048       dec->sanity_check();
7049       new (user_var_event->value) my_decimal(*dec);
7050     }
7051     else
7052       memcpy(user_var_event->value, var_entry->ptr(),
7053              var_entry->length());
7054   }
7055   /* Mark that this variable has been used by this query */
7056   var_entry->used_query_id= thd->query_id;
7057   if (thd->user_var_events.push_back(user_var_event))
7058     goto err;
7059 
7060   *out_entry= var_entry;
7061   return 0;
7062 
7063 err:
7064   *out_entry= var_entry;
7065   return 1;
7066 }
7067 
fix_length_and_dec()7068 void Item_func_get_user_var::fix_length_and_dec()
7069 {
7070   THD *thd=current_thd;
7071   int error;
7072   maybe_null=1;
7073   decimals=NOT_FIXED_DEC;
7074   max_length=MAX_BLOB_WIDTH;
7075 
7076   error= get_var_with_binlog(thd, thd->lex->sql_command, name, &var_entry);
7077 
7078   /*
7079     If the variable didn't exist it has been created as a STRING-type.
7080     'var_entry' is NULL only if there occurred an error during the call to
7081     get_var_with_binlog.
7082   */
7083   if (!error && var_entry)
7084   {
7085     m_cached_result_type= var_entry->type();
7086     unsigned_flag= var_entry->unsigned_flag;
7087     max_length= var_entry->length();
7088 
7089     collation.set(var_entry->collation);
7090     switch(m_cached_result_type) {
7091     case REAL_RESULT:
7092       fix_char_length(DBL_DIG + 8);
7093       break;
7094     case INT_RESULT:
7095       fix_char_length(MAX_BIGINT_WIDTH);
7096       decimals=0;
7097       break;
7098     case STRING_RESULT:
7099       max_length= MAX_BLOB_WIDTH - 1;
7100       break;
7101     case DECIMAL_RESULT:
7102       fix_char_length(DECIMAL_MAX_STR_LENGTH);
7103       decimals= DECIMAL_MAX_SCALE;
7104       break;
7105     case ROW_RESULT:                            // Keep compiler happy
7106     default:
7107       assert(0);
7108       break;
7109     }
7110   }
7111   else
7112   {
7113     collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
7114     null_value= 1;
7115     m_cached_result_type= STRING_RESULT;
7116     max_length= MAX_BLOB_WIDTH;
7117   }
7118 }
7119 
7120 
const_item() const7121 bool Item_func_get_user_var::const_item() const
7122 {
7123   return (!var_entry || current_thd->query_id != var_entry->update_query_id);
7124 }
7125 
7126 
result_type() const7127 enum Item_result Item_func_get_user_var::result_type() const
7128 {
7129   return m_cached_result_type;
7130 }
7131 
7132 
print(String * str,enum_query_type query_type)7133 void Item_func_get_user_var::print(String *str, enum_query_type query_type)
7134 {
7135   str->append(STRING_WITH_LEN("(@"));
7136   append_identifier(current_thd, str, name);
7137   str->append(')');
7138 }
7139 
7140 
eq(const Item * item,bool binary_cmp) const7141 bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
7142 {
7143   /* Assume we don't have rtti */
7144   if (this == item)
7145     return 1;					// Same item is same.
7146   /* Check if other type is also a get_user_var() object */
7147   if (item->type() != FUNC_ITEM ||
7148       ((Item_func*) item)->functype() != functype())
7149     return 0;
7150   Item_func_get_user_var *other=(Item_func_get_user_var*) item;
7151   return name.eq_bin(other->name);
7152 }
7153 
7154 
set_value(THD * thd,sp_rcontext *,Item ** it)7155 bool Item_func_get_user_var::set_value(THD *thd,
7156                                        sp_rcontext * /*ctx*/, Item **it)
7157 {
7158   Item_func_set_user_var *suv= new Item_func_set_user_var(name, *it, false);
7159   /*
7160     Item_func_set_user_var is not fixed after construction, call
7161     fix_fields().
7162   */
7163   return (!suv || suv->fix_fields(thd, it) || suv->check(0) || suv->update());
7164 }
7165 
7166 
fix_fields(THD * thd,Item ** ref)7167 bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref)
7168 {
7169   assert(fixed == 0);
7170   assert(thd->lex->exchange);
7171   /*
7172     Let us set the same collation which is used for loading
7173     of fields in LOAD DATA INFILE.
7174     (Since Item_user_var_as_out_param is used only there).
7175   */
7176   const CHARSET_INFO *cs= thd->lex->exchange->cs ?
7177     thd->lex->exchange->cs : thd->variables.collation_database;
7178 
7179   if (Item::fix_fields(thd, ref))
7180     return true;
7181 
7182   /* Protects thd->user_vars. */
7183   mysql_mutex_lock(&thd->LOCK_thd_data);
7184   entry= get_variable(thd, name, cs);
7185   if (entry != NULL)
7186   {
7187     entry->set_type(STRING_RESULT);
7188     entry->update_query_id= thd->query_id;
7189   }
7190   mysql_mutex_unlock(&thd->LOCK_thd_data);
7191 
7192   if (entry == NULL)
7193     return true;
7194 
7195   return false;
7196 }
7197 
7198 
set_null_value(const CHARSET_INFO * cs)7199 void Item_user_var_as_out_param::set_null_value(const CHARSET_INFO* cs)
7200 {
7201   entry->lock();
7202   entry->set_null_value(STRING_RESULT);
7203   entry->unlock();
7204 }
7205 
7206 
set_value(const char * str,size_t length,const CHARSET_INFO * cs)7207 void Item_user_var_as_out_param::set_value(const char *str, size_t length,
7208                                            const CHARSET_INFO* cs)
7209 {
7210   entry->lock();
7211   entry->store((void*) str, length, STRING_RESULT, cs,
7212                DERIVATION_IMPLICIT, 0 /* unsigned_arg */);
7213   entry->unlock();
7214 }
7215 
7216 
val_real()7217 double Item_user_var_as_out_param::val_real()
7218 {
7219   assert(0);
7220   return 0.0;
7221 }
7222 
7223 
val_int()7224 longlong Item_user_var_as_out_param::val_int()
7225 {
7226   assert(0);
7227   return 0;
7228 }
7229 
7230 
val_str(String * str)7231 String* Item_user_var_as_out_param::val_str(String *str)
7232 {
7233   assert(0);
7234   return 0;
7235 }
7236 
7237 
val_decimal(my_decimal * decimal_buffer)7238 my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer)
7239 {
7240   assert(0);
7241   return 0;
7242 }
7243 
7244 
print(String * str,enum_query_type query_type)7245 void Item_user_var_as_out_param::print(String *str, enum_query_type query_type)
7246 {
7247   str->append('@');
7248   append_identifier(current_thd, str, name);
7249 }
7250 
7251 
7252 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)7253 Item_func_get_system_var(sys_var *var_arg, enum_var_type var_type_arg,
7254                        LEX_STRING *component_arg, const char *name_arg,
7255                        size_t name_len_arg)
7256   :var(NULL), var_type(var_type_arg), orig_var_type(var_type_arg),
7257   component(*component_arg), cache_present(0),
7258   var_tracker(var_arg)
7259 {
7260   /* copy() will allocate the name */
7261   item_name.copy(name_arg, (uint) name_len_arg);
7262 }
7263 
7264 
update_null_value()7265 void Item_func_get_system_var::update_null_value()
7266 {
7267   THD *thd= current_thd;
7268   int save_no_errors= thd->no_errors;
7269   thd->no_errors= TRUE;
7270   Item::update_null_value();
7271   thd->no_errors= save_no_errors;
7272 }
7273 
7274 
fix_length_and_dec()7275 void Item_func_get_system_var::fix_length_and_dec()
7276 {
7277   char *cptr;
7278   maybe_null= TRUE;
7279   max_length= 0;
7280 
7281   THD *const thd= current_thd;
7282 
7283   DEBUG_SYNC(current_thd, "after_error_checking");
7284 
7285   assert(var == NULL);
7286   var= var_tracker.bind_system_variable(thd);
7287   if (var == NULL)
7288     return;
7289 
7290   if (!var->check_scope(var_type))
7291   {
7292     if (var_type != OPT_DEFAULT)
7293     {
7294       my_error(ER_INCORRECT_GLOBAL_LOCAL_VAR, MYF(0),
7295                var->name.str, var_type == OPT_GLOBAL ? "SESSION" : "GLOBAL");
7296       return;
7297     }
7298     /* As there was no local variable, return the global value */
7299     var_type= OPT_GLOBAL;
7300   }
7301 
7302   switch (var->show_type())
7303   {
7304     case SHOW_LONG:
7305     case SHOW_INT:
7306     case SHOW_HA_ROWS:
7307     case SHOW_LONGLONG:
7308       unsigned_flag= TRUE;
7309       collation.set_numeric();
7310       fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS);
7311       decimals=0;
7312       break;
7313     case SHOW_SIGNED_LONG:
7314       unsigned_flag= FALSE;
7315       collation.set_numeric();
7316       fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS);
7317       decimals=0;
7318       break;
7319     case SHOW_CHAR:
7320     case SHOW_CHAR_PTR:
7321       mysql_mutex_lock(&LOCK_global_system_variables);
7322       cptr= var->show_type() == SHOW_CHAR ?
7323         (char*) var->value_ptr(thd, var_type, &component) :
7324         *(char**) var->value_ptr(thd, var_type, &component);
7325       if (cptr)
7326         max_length= system_charset_info->cset->numchars(system_charset_info,
7327                                                         cptr,
7328                                                         cptr + strlen(cptr));
7329       mysql_mutex_unlock(&LOCK_global_system_variables);
7330       collation.set(system_charset_info, DERIVATION_SYSCONST);
7331       max_length*= system_charset_info->mbmaxlen;
7332       decimals=NOT_FIXED_DEC;
7333       break;
7334     case SHOW_LEX_STRING:
7335       {
7336         mysql_mutex_lock(&LOCK_global_system_variables);
7337         LEX_STRING *ls= ((LEX_STRING*)var->value_ptr(thd, var_type, &component));
7338         max_length= system_charset_info->cset->numchars(system_charset_info,
7339                                                         ls->str,
7340                                                         ls->str + ls->length);
7341         mysql_mutex_unlock(&LOCK_global_system_variables);
7342         collation.set(system_charset_info, DERIVATION_SYSCONST);
7343         max_length*= system_charset_info->mbmaxlen;
7344         decimals=NOT_FIXED_DEC;
7345       }
7346       break;
7347     case SHOW_BOOL:
7348     case SHOW_MY_BOOL:
7349       unsigned_flag= FALSE;
7350       collation.set_numeric();
7351       fix_char_length(1);
7352       decimals=0;
7353       break;
7354     case SHOW_DOUBLE:
7355       unsigned_flag= FALSE;
7356       decimals= 6;
7357       collation.set_numeric();
7358       fix_char_length(DBL_DIG + 6);
7359       break;
7360     default:
7361       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7362       break;
7363   }
7364 }
7365 
7366 
print(String * str,enum_query_type query_type)7367 void Item_func_get_system_var::print(String *str, enum_query_type query_type)
7368 {
7369   str->append(item_name);
7370 }
7371 
7372 
result_type() const7373 enum Item_result Item_func_get_system_var::result_type() const
7374 {
7375   switch (var->show_type())
7376   {
7377     case SHOW_BOOL:
7378     case SHOW_MY_BOOL:
7379     case SHOW_INT:
7380     case SHOW_LONG:
7381     case SHOW_SIGNED_LONG:
7382     case SHOW_LONGLONG:
7383     case SHOW_HA_ROWS:
7384       return INT_RESULT;
7385     case SHOW_CHAR:
7386     case SHOW_CHAR_PTR:
7387     case SHOW_LEX_STRING:
7388       return STRING_RESULT;
7389     case SHOW_DOUBLE:
7390       return REAL_RESULT;
7391     default:
7392       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7393       return STRING_RESULT;                   // keep the compiler happy
7394   }
7395 }
7396 
7397 
field_type() const7398 enum_field_types Item_func_get_system_var::field_type() const
7399 {
7400   switch (var->show_type())
7401   {
7402     case SHOW_BOOL:
7403     case SHOW_MY_BOOL:
7404     case SHOW_INT:
7405     case SHOW_LONG:
7406     case SHOW_SIGNED_LONG:
7407     case SHOW_LONGLONG:
7408     case SHOW_HA_ROWS:
7409       return MYSQL_TYPE_LONGLONG;
7410     case SHOW_CHAR:
7411     case SHOW_CHAR_PTR:
7412     case SHOW_LEX_STRING:
7413       return MYSQL_TYPE_VARCHAR;
7414     case SHOW_DOUBLE:
7415       return MYSQL_TYPE_DOUBLE;
7416     default:
7417       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7418       return MYSQL_TYPE_VARCHAR;              // keep the compiler happy
7419   }
7420 }
7421 
7422 
7423 /*
7424   Uses var, var_type, component, cache_present, used_query_id, thd,
7425   cached_llval, null_value, cached_null_value
7426 */
7427 #define get_sys_var_safe(type) \
7428 do { \
7429   type value; \
7430   mysql_mutex_lock(&LOCK_global_system_variables); \
7431   value= *(type*) var->value_ptr(thd, var_type, &component); \
7432   mysql_mutex_unlock(&LOCK_global_system_variables); \
7433   cache_present |= GET_SYS_VAR_CACHE_LONG; \
7434   used_query_id= thd->query_id; \
7435   cached_llval= null_value ? 0 : (longlong) value; \
7436   cached_null_value= null_value; \
7437   return cached_llval; \
7438 } while (0)
7439 
7440 
val_int()7441 longlong Item_func_get_system_var::val_int()
7442 {
7443   THD *thd= current_thd;
7444 
7445   assert(var != NULL);
7446 
7447   if (cache_present && thd->query_id == used_query_id)
7448   {
7449     if (cache_present & GET_SYS_VAR_CACHE_LONG)
7450     {
7451       null_value= cached_null_value;
7452       return cached_llval;
7453     }
7454     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7455     {
7456       null_value= cached_null_value;
7457       cached_llval= (longlong) cached_dval;
7458       cache_present|= GET_SYS_VAR_CACHE_LONG;
7459       return cached_llval;
7460     }
7461     else if (cache_present & GET_SYS_VAR_CACHE_STRING)
7462     {
7463       null_value= cached_null_value;
7464       if (!null_value)
7465         cached_llval= longlong_from_string_with_check (cached_strval.charset(),
7466                                                        cached_strval.c_ptr(),
7467                                                        cached_strval.c_ptr() +
7468                                                        cached_strval.length());
7469       else
7470         cached_llval= 0;
7471       cache_present|= GET_SYS_VAR_CACHE_LONG;
7472       return cached_llval;
7473     }
7474   }
7475 
7476   switch (var->show_type())
7477   {
7478     case SHOW_INT:      get_sys_var_safe (uint);
7479     case SHOW_LONG:     get_sys_var_safe (ulong);
7480     case SHOW_SIGNED_LONG: get_sys_var_safe (long);
7481     case SHOW_LONGLONG: get_sys_var_safe (ulonglong);
7482     case SHOW_HA_ROWS:  get_sys_var_safe (ha_rows);
7483     case SHOW_BOOL:     get_sys_var_safe (bool);
7484     case SHOW_MY_BOOL:  get_sys_var_safe (my_bool);
7485     case SHOW_DOUBLE:
7486       {
7487         double dval= val_real();
7488 
7489         used_query_id= thd->query_id;
7490         cached_llval= (longlong) dval;
7491         cache_present|= GET_SYS_VAR_CACHE_LONG;
7492         return cached_llval;
7493       }
7494     case SHOW_CHAR:
7495     case SHOW_CHAR_PTR:
7496     case SHOW_LEX_STRING:
7497       {
7498         String *str_val= val_str(NULL);
7499         // Treat empty strings as NULL, like val_real() does.
7500         if (str_val && str_val->length())
7501           cached_llval= longlong_from_string_with_check (system_charset_info,
7502                                                           str_val->c_ptr(),
7503                                                           str_val->c_ptr() +
7504                                                           str_val->length());
7505         else
7506         {
7507           null_value= TRUE;
7508           cached_llval= 0;
7509         }
7510 
7511         cache_present|= GET_SYS_VAR_CACHE_LONG;
7512         return cached_llval;
7513       }
7514 
7515     default:
7516       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7517       return 0;                               // keep the compiler happy
7518   }
7519 }
7520 
7521 
val_str(String * str)7522 String* Item_func_get_system_var::val_str(String* str)
7523 {
7524   THD *thd= current_thd;
7525 
7526   assert(var != NULL);
7527 
7528   if (cache_present && thd->query_id == used_query_id)
7529   {
7530     if (cache_present & GET_SYS_VAR_CACHE_STRING)
7531     {
7532       null_value= cached_null_value;
7533       return null_value ? NULL : &cached_strval;
7534     }
7535     else if (cache_present & GET_SYS_VAR_CACHE_LONG)
7536     {
7537       null_value= cached_null_value;
7538       if (!null_value)
7539         cached_strval.set (cached_llval, collation.collation);
7540       cache_present|= GET_SYS_VAR_CACHE_STRING;
7541       return null_value ? NULL : &cached_strval;
7542     }
7543     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7544     {
7545       null_value= cached_null_value;
7546       if (!null_value)
7547         cached_strval.set_real (cached_dval, decimals, collation.collation);
7548       cache_present|= GET_SYS_VAR_CACHE_STRING;
7549       return null_value ? NULL : &cached_strval;
7550     }
7551   }
7552 
7553   str= &cached_strval;
7554   null_value= FALSE;
7555   switch (var->show_type())
7556   {
7557     case SHOW_CHAR:
7558     case SHOW_CHAR_PTR:
7559     case SHOW_LEX_STRING:
7560     {
7561       mysql_mutex_lock(&LOCK_global_system_variables);
7562       char *cptr= var->show_type() == SHOW_CHAR ?
7563         (char*) var->value_ptr(thd, var_type, &component) :
7564         *(char**) var->value_ptr(thd, var_type, &component);
7565       if (cptr)
7566       {
7567         size_t len= var->show_type() == SHOW_LEX_STRING ?
7568           ((LEX_STRING*)(var->value_ptr(thd, var_type, &component)))->length :
7569           strlen(cptr);
7570         if (str->copy(cptr, len, collation.collation))
7571         {
7572           null_value= TRUE;
7573           str= NULL;
7574         }
7575       }
7576       else
7577       {
7578         null_value= TRUE;
7579         str= NULL;
7580       }
7581       mysql_mutex_unlock(&LOCK_global_system_variables);
7582       break;
7583     }
7584 
7585     case SHOW_INT:
7586     case SHOW_LONG:
7587     case SHOW_SIGNED_LONG:
7588     case SHOW_LONGLONG:
7589     case SHOW_HA_ROWS:
7590     case SHOW_BOOL:
7591     case SHOW_MY_BOOL:
7592       str->set (val_int(), collation.collation);
7593       break;
7594     case SHOW_DOUBLE:
7595       str->set_real (val_real(), decimals, collation.collation);
7596       break;
7597 
7598     default:
7599       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7600       str= error_str();
7601       break;
7602   }
7603 
7604   cache_present|= GET_SYS_VAR_CACHE_STRING;
7605   used_query_id= thd->query_id;
7606   cached_null_value= null_value;
7607   return str;
7608 }
7609 
7610 
val_real()7611 double Item_func_get_system_var::val_real()
7612 {
7613   THD *thd= current_thd;
7614 
7615   assert(var != NULL);
7616 
7617   if (cache_present && thd->query_id == used_query_id)
7618   {
7619     if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
7620     {
7621       null_value= cached_null_value;
7622       return cached_dval;
7623     }
7624     else if (cache_present & GET_SYS_VAR_CACHE_LONG)
7625     {
7626       null_value= cached_null_value;
7627       cached_dval= (double)cached_llval;
7628       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7629       return cached_dval;
7630     }
7631     else if (cache_present & GET_SYS_VAR_CACHE_STRING)
7632     {
7633       null_value= cached_null_value;
7634       if (!null_value)
7635         cached_dval= double_from_string_with_check (cached_strval.charset(),
7636                                                     cached_strval.c_ptr(),
7637                                                     cached_strval.c_ptr() +
7638                                                     cached_strval.length());
7639       else
7640         cached_dval= 0;
7641       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7642       return cached_dval;
7643     }
7644   }
7645 
7646   switch (var->show_type())
7647   {
7648     case SHOW_DOUBLE:
7649       mysql_mutex_lock(&LOCK_global_system_variables);
7650       cached_dval= *(double*) var->value_ptr(thd, var_type, &component);
7651       mysql_mutex_unlock(&LOCK_global_system_variables);
7652       used_query_id= thd->query_id;
7653       cached_null_value= null_value;
7654       if (null_value)
7655         cached_dval= 0;
7656       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7657       return cached_dval;
7658     case SHOW_CHAR:
7659     case SHOW_LEX_STRING:
7660     case SHOW_CHAR_PTR:
7661       {
7662         mysql_mutex_lock(&LOCK_global_system_variables);
7663         char *cptr= var->show_type() == SHOW_CHAR ?
7664           (char*) var->value_ptr(thd, var_type, &component) :
7665           *(char**) var->value_ptr(thd, var_type, &component);
7666         // Treat empty strings as NULL, like val_int() does.
7667         if (cptr && *cptr)
7668           cached_dval= double_from_string_with_check (system_charset_info,
7669                                                 cptr, cptr + strlen (cptr));
7670         else
7671         {
7672           null_value= TRUE;
7673           cached_dval= 0;
7674         }
7675         mysql_mutex_unlock(&LOCK_global_system_variables);
7676         used_query_id= thd->query_id;
7677         cached_null_value= null_value;
7678         cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7679         return cached_dval;
7680       }
7681     case SHOW_INT:
7682     case SHOW_LONG:
7683     case SHOW_SIGNED_LONG:
7684     case SHOW_LONGLONG:
7685     case SHOW_HA_ROWS:
7686     case SHOW_BOOL:
7687     case SHOW_MY_BOOL:
7688         cached_dval= (double) val_int();
7689         cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
7690         used_query_id= thd->query_id;
7691         cached_null_value= null_value;
7692         return cached_dval;
7693     default:
7694       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
7695       return 0;
7696   }
7697 }
7698 
7699 
eq(const Item * item,bool binary_cmp) const7700 bool Item_func_get_system_var::eq(const Item *item, bool binary_cmp) const
7701 {
7702   /* Assume we don't have rtti */
7703   if (this == item)
7704     return 1;					// Same item is same.
7705   /* Check if other type is also a get_user_var() object */
7706   if (item->type() != FUNC_ITEM ||
7707       ((Item_func*) item)->functype() != functype())
7708     return 0;
7709   Item_func_get_system_var *other=(Item_func_get_system_var*) item;
7710   return (var_tracker == other->var_tracker && var_type == other->var_type);
7711 }
7712 
7713 
cleanup()7714 void Item_func_get_system_var::cleanup()
7715 {
7716   Item_func::cleanup();
7717   cache_present= 0;
7718   var_type= orig_var_type;
7719   cached_strval.mem_free();
7720   var= NULL;
7721 }
7722 
7723 
itemize(Parse_context * pc,Item ** res)7724 bool Item_func_match::itemize(Parse_context *pc, Item **res)
7725 {
7726   if (skip_itemize(res))
7727     return false;
7728   if (super::itemize(pc, res) || against->itemize(pc, &against))
7729     return true;
7730   with_sum_func|= against->with_sum_func;
7731 
7732   pc->select->add_ftfunc_to_list(this);
7733   pc->thd->lex->set_using_match();
7734 
7735   switch (pc->select->parsing_place)
7736   {
7737     case CTX_WHERE:
7738     case CTX_ON:
7739       used_in_where_only= true;
7740       break;
7741     default:
7742       used_in_where_only= false;
7743   }
7744 
7745   return false;
7746 }
7747 
7748 
7749 /**
7750   Initialize searching within full-text index.
7751 
7752   @param thd    Thread handler
7753 
7754   @returns false if success, true if error
7755 */
7756 
init_search(THD * thd)7757 bool Item_func_match::init_search(THD *thd)
7758 {
7759   DBUG_ENTER("Item_func_match::init_search");
7760 
7761   /*
7762     We will skip execution if the item is not fixed
7763     with fix_field
7764   */
7765   if (!fixed)
7766     DBUG_RETURN(false);
7767 
7768   TABLE *const table= table_ref->table;
7769   /* Check if init_search() has been called before */
7770   if (ft_handler && !master)
7771   {
7772     /*
7773       We should reset ft_handler as it is cleaned up
7774       on destruction of FT_SELECT object
7775       (necessary in case of re-execution of subquery).
7776       TODO: FT_SELECT should not clean up ft_handler.
7777     */
7778     if (join_key)
7779       table->file->ft_handler= ft_handler;
7780     DBUG_RETURN(false);
7781   }
7782 
7783   if (key == NO_SUCH_KEY)
7784   {
7785     List<Item> fields;
7786     if (fields.push_back(new Item_string(" ",1, cmp_collation.collation)))
7787       DBUG_RETURN(true);
7788     for (uint i= 0; i < arg_count; i++)
7789       fields.push_back(args[i]);
7790     concat_ws=new Item_func_concat_ws(fields);
7791     if (concat_ws == NULL)
7792       DBUG_RETURN(true);
7793     /*
7794       Above function used only to get value and do not need fix_fields for it:
7795       Item_string - basic constant
7796       fields - fix_fields() was already called for this arguments
7797       Item_func_concat_ws - do not need fix_fields() to produce value
7798     */
7799     concat_ws->quick_fix_field();
7800   }
7801 
7802   if (master)
7803   {
7804     if (master->init_search(thd))
7805       DBUG_RETURN(true);
7806 
7807     ft_handler=master->ft_handler;
7808     DBUG_RETURN(false);
7809   }
7810 
7811   String *ft_tmp= 0;
7812 
7813   // MATCH ... AGAINST (NULL) is meaningless, but possible
7814   if (!(ft_tmp=key_item()->val_str(&value)))
7815   {
7816     ft_tmp= &value;
7817     value.set("",0,cmp_collation.collation);
7818   }
7819 
7820   if (ft_tmp->charset() != cmp_collation.collation)
7821   {
7822     uint dummy_errors;
7823     search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
7824                       cmp_collation.collation, &dummy_errors);
7825     ft_tmp= &search_value;
7826   }
7827 
7828   if (!table->is_created())
7829   {
7830      my_error(ER_NO_FT_MATERIALIZED_SUBQUERY, MYF(0));
7831      DBUG_RETURN(true);
7832   }
7833 
7834   assert(master == NULL);
7835   ft_handler= table->file->ft_init_ext_with_hints(key, ft_tmp, get_hints());
7836   if (thd->is_error())
7837     DBUG_RETURN(true);
7838 
7839   if (join_key)
7840     table->file->ft_handler=ft_handler;
7841 
7842   DBUG_RETURN(false);
7843 }
7844 
7845 
get_filtering_effect(table_map filter_for_table,table_map read_tables,const MY_BITMAP * fields_to_ignore,double rows_in_table)7846 float Item_func_match::get_filtering_effect(table_map filter_for_table,
7847                                             table_map read_tables,
7848                                             const MY_BITMAP *fields_to_ignore,
7849                                             double rows_in_table)
7850 {
7851   const Item_field* fld=
7852     contributes_to_filter(read_tables, filter_for_table, fields_to_ignore);
7853   if (!fld)
7854     return COND_FILTER_ALLPASS;
7855 
7856   /*
7857     MATCH () ... AGAINST" is similar to "LIKE '...'" which has the
7858     same selectivity as "col BETWEEN ...".
7859   */
7860   return fld->get_cond_filter_default_probability(rows_in_table,
7861                                                   COND_FILTER_BETWEEN);
7862 }
7863 
7864 
7865 /**
7866    Add field into table read set.
7867 
7868    @param field field to be added to the table read set.
7869 */
update_table_read_set(Field * field)7870 static void update_table_read_set(Field *field)
7871 {
7872   TABLE *table= field->table;
7873 
7874   if (!bitmap_fast_test_and_set(table->read_set, field->field_index))
7875     table->covering_keys.intersect(field->part_of_key);
7876 }
7877 
7878 
fix_fields(THD * thd,Item ** ref)7879 bool Item_func_match::fix_fields(THD *thd, Item **ref)
7880 {
7881   assert(fixed == 0);
7882   assert(arg_count > 0);
7883   Item *item= NULL;                        // Safe as arg_count is > 1
7884 
7885   maybe_null=1;
7886   join_key=0;
7887 
7888   /*
7889     const_item is assumed in quite a bit of places, so it would be difficult
7890     to remove;  If it would ever to be removed, this should include
7891     modifications to find_best and auto_close as complement to auto_init code
7892     above.
7893   */
7894   enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
7895   /*
7896     Since different engines require different columns for FTS index lookup
7897     we prevent updating of table read_set in argument's ::fix_fields().
7898   */
7899   thd->mark_used_columns= MARK_COLUMNS_NONE;
7900   if (Item_func::fix_fields(thd, ref) ||
7901       fix_func_arg(thd, &against) || !against->const_during_execution())
7902   {
7903     thd->mark_used_columns= save_mark_used_columns;
7904     my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
7905     return TRUE;
7906   }
7907   thd->mark_used_columns= save_mark_used_columns;
7908 
7909   bool allows_multi_table_search= true;
7910   const_item_cache=0;
7911   for (uint i= 0 ; i < arg_count ; i++)
7912   {
7913     item= args[i]= args[i]->real_item();
7914     if (item->type() != Item::FIELD_ITEM ||
7915         /* Cannot use FTS index with outer table field */
7916         (item->used_tables() & OUTER_REF_TABLE_BIT))
7917     {
7918       my_error(ER_WRONG_ARGUMENTS, MYF(0), "MATCH");
7919       return TRUE;
7920     }
7921     allows_multi_table_search &=
7922       allows_search_on_non_indexed_columns(((Item_field *)item)->field->table);
7923   }
7924 
7925   /*
7926     Check that all columns come from the same table.
7927     We've already checked that columns in MATCH are fields so
7928     PARAM_TABLE_BIT can only appear from AGAINST argument.
7929   */
7930   if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
7931     key=NO_SUCH_KEY;
7932 
7933   if (key == NO_SUCH_KEY && !allows_multi_table_search)
7934   {
7935     my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
7936     return TRUE;
7937   }
7938   table_ref= ((Item_field *)item)->table_ref;
7939 
7940   /*
7941     Here we make an assumption that if the engine supports
7942     fulltext extension(HA_CAN_FULLTEXT_EXT flag) then table
7943     can have FTS_DOC_ID column. Atm this is the only way
7944     to distinguish MyISAM and InnoDB engines.
7945     Generally table_ref should be available, but in case of
7946     a generated column's generation expression it's not. Thus
7947     we use field's table, at this moment it's already available.
7948   */
7949   TABLE *const table= table_ref ?
7950     table_ref->table :
7951     ((Item_field *)item)->field->table;
7952 
7953   if (!(table->file->ha_table_flags() & HA_CAN_FULLTEXT))
7954   {
7955     my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
7956     return 1;
7957   }
7958 
7959   if ((table->file->ha_table_flags() & HA_CAN_FULLTEXT_EXT))
7960   {
7961     Field *doc_id_field= table->fts_doc_id_field;
7962     /*
7963       Update read set with FTS_DOC_ID column so that indexes that have
7964       FTS_DOC_ID part can be considered as a covering index.
7965     */
7966     if (doc_id_field)
7967       update_table_read_set(doc_id_field);
7968     else
7969     {
7970       /* read_set needs to be updated for MATCH arguments */
7971       for (uint i= 0; i < arg_count; i++)
7972         update_table_read_set(((Item_field*)args[i])->field);
7973       /*
7974         Prevent index only accces by non-FTS index if table does not have
7975         FTS_DOC_ID column, find_relevance does not work properly without
7976         FTS_DOC_ID value. Decision for FTS index about index only access
7977         is made later by JOIN::fts_index_access() function.
7978       */
7979       table->covering_keys.clear_all();
7980     }
7981 
7982   }
7983   else
7984   {
7985     /*
7986       Since read_set is not updated for MATCH arguments
7987       it's necessary to update it here for MyISAM.
7988     */
7989     for (uint i= 0; i < arg_count; i++)
7990       update_table_read_set(((Item_field*)args[i])->field);
7991   }
7992 
7993   table->fulltext_searched=1;
7994 
7995   if (!master)
7996   {
7997     Prepared_stmt_arena_holder ps_arena_holder(thd);
7998     hints= new Ft_hints(flags);
7999     if (!hints)
8000     {
8001       my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0));
8002       return true;
8003     }
8004   }
8005   return agg_item_collations_for_comparison(cmp_collation, func_name(),
8006                                             args, arg_count, 0);
8007 }
8008 
fix_index()8009 bool Item_func_match::fix_index()
8010 {
8011   Item_field *item;
8012   TABLE *table;
8013   uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
8014   uint max_cnt=0, mkeys=0, i;
8015 
8016   if (!table_ref)
8017     goto err;
8018 
8019   /*
8020     We will skip execution if the item is not fixed
8021     with fix_field
8022   */
8023   if (!fixed)
8024   {
8025     if (allows_search_on_non_indexed_columns(table_ref->table))
8026       key= NO_SUCH_KEY;
8027 
8028     return false;
8029   }
8030   if (key == NO_SUCH_KEY)
8031     return 0;
8032 
8033   table= table_ref->table;
8034   for (keynr=0 ; keynr < table->s->keys ; keynr++)
8035   {
8036     if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
8037         (flags & FT_BOOL ? table->keys_in_use_for_query.is_set(keynr) :
8038                            table->s->keys_in_use.is_set(keynr)))
8039 
8040     {
8041       ft_to_key[fts]=keynr;
8042       ft_cnt[fts]=0;
8043       fts++;
8044     }
8045   }
8046 
8047   if (!fts)
8048     goto err;
8049 
8050   for (i= 0; i < arg_count; i++)
8051   {
8052     item=(Item_field*)args[i];
8053     for (keynr=0 ; keynr < fts ; keynr++)
8054     {
8055       KEY *ft_key=&table->key_info[ft_to_key[keynr]];
8056       uint key_parts=ft_key->user_defined_key_parts;
8057 
8058       for (uint part=0 ; part < key_parts ; part++)
8059       {
8060 	if (item->field->eq(ft_key->key_part[part].field))
8061 	  ft_cnt[keynr]++;
8062       }
8063     }
8064   }
8065 
8066   for (keynr=0 ; keynr < fts ; keynr++)
8067   {
8068     if (ft_cnt[keynr] > max_cnt)
8069     {
8070       mkeys=0;
8071       max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
8072       ft_to_key[mkeys]=ft_to_key[keynr];
8073       continue;
8074     }
8075     if (max_cnt && ft_cnt[keynr] == max_cnt)
8076     {
8077       mkeys++;
8078       ft_cnt[mkeys]=ft_cnt[keynr];
8079       ft_to_key[mkeys]=ft_to_key[keynr];
8080       continue;
8081     }
8082   }
8083 
8084   for (keynr=0 ; keynr <= mkeys ; keynr++)
8085   {
8086     // partial keys doesn't work
8087     if (max_cnt < arg_count ||
8088         max_cnt < table->key_info[ft_to_key[keynr]].user_defined_key_parts)
8089       continue;
8090 
8091     key=ft_to_key[keynr];
8092 
8093     return 0;
8094   }
8095 
8096 err:
8097   if (table_ref != 0 && allows_search_on_non_indexed_columns(table_ref->table))
8098   {
8099     key=NO_SUCH_KEY;
8100     return 0;
8101   }
8102   my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
8103              ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
8104   return 1;
8105 }
8106 
8107 
eq(const Item * item,bool binary_cmp) const8108 bool Item_func_match::eq(const Item *item, bool binary_cmp) const
8109 {
8110   /* We ignore FT_SORTED flag when checking for equality since result is
8111      equvialent regardless of sorting */
8112   if (item->type() != FUNC_ITEM ||
8113       ((Item_func*)item)->functype() != FT_FUNC ||
8114       (flags | FT_SORTED) != (((Item_func_match*)item)->flags | FT_SORTED))
8115     return 0;
8116 
8117   Item_func_match *ifm=(Item_func_match*) item;
8118 
8119   if (key == ifm->key && table_ref == ifm->table_ref &&
8120       key_item()->eq(ifm->key_item(), binary_cmp))
8121     return 1;
8122 
8123   return 0;
8124 }
8125 
8126 
val_real()8127 double Item_func_match::val_real()
8128 {
8129   assert(fixed == 1);
8130   DBUG_ENTER("Item_func_match::val");
8131   if (ft_handler == NULL)
8132     DBUG_RETURN(-1.0);
8133 
8134   TABLE *const table= table_ref->table;
8135   if (key != NO_SUCH_KEY && table->has_null_row()) // NULL row from outer join
8136     DBUG_RETURN(0.0);
8137 
8138   if (get_master()->join_key)
8139   {
8140     if (table->file->ft_handler)
8141       DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
8142     get_master()->join_key= 0;
8143   }
8144 
8145   if (key == NO_SUCH_KEY)
8146   {
8147     String *a= concat_ws->val_str(&value);
8148     if ((null_value= (a == 0)) || !a->length())
8149       DBUG_RETURN(0);
8150     DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
8151 				      (uchar *)a->ptr(), a->length()));
8152   }
8153   DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
8154                                                  table->record[0], 0));
8155 }
8156 
print(String * str,enum_query_type query_type)8157 void Item_func_match::print(String *str, enum_query_type query_type)
8158 {
8159   str->append(STRING_WITH_LEN("(match "));
8160   print_args(str, 0, query_type);
8161   str->append(STRING_WITH_LEN(" against ("));
8162   against->print(str, query_type);
8163   if (flags & FT_BOOL)
8164     str->append(STRING_WITH_LEN(" in boolean mode"));
8165   else if (flags & FT_EXPAND)
8166     str->append(STRING_WITH_LEN(" with query expansion"));
8167   str->append(STRING_WITH_LEN("))"));
8168 }
8169 
8170 
8171 /**
8172   Function sets FT hints(LIMIT, flags) depending on
8173   various join conditions.
8174 
8175   @param join     Pointer to JOIN object.
8176   @param ft_flag  FT flag value.
8177   @param ft_limit Limit value.
8178   @param no_cond  true if MATCH is not used in WHERE condition.
8179 */
8180 
set_hints(JOIN * join,uint ft_flag,ha_rows ft_limit,bool no_cond)8181 void Item_func_match::set_hints(JOIN *join, uint ft_flag,
8182                                 ha_rows ft_limit, bool no_cond)
8183 {
8184   assert(!master);
8185 
8186   if (!join)  // used for count() optimization
8187   {
8188     hints->set_hint_flag(ft_flag);
8189     return;
8190   }
8191 
8192   /* skip hints setting if there are aggregates(except of FT_NO_RANKING) */
8193   if (join->implicit_grouping || join->group_list || join->select_distinct)
8194   {
8195     /* 'No ranking' is possibe even if aggregates are present */
8196     if ((ft_flag & FT_NO_RANKING))
8197       hints->set_hint_flag(FT_NO_RANKING);
8198     return;
8199   }
8200 
8201   hints->set_hint_flag(ft_flag);
8202 
8203   /**
8204     Only one table is used, there is no aggregates,
8205     WHERE condition is a single MATCH expression
8206     (WHERE MATCH(..) or WHERE MATCH(..) [>=,>] value) or
8207     there is no WHERE condition.
8208   */
8209   if (join->primary_tables == 1 && (no_cond || is_simple_expression()))
8210     hints->set_hint_limit(ft_limit);
8211 }
8212 
8213 
val_int()8214 longlong Item_func_bit_xor::val_int()
8215 {
8216   assert(fixed == 1);
8217   ulonglong arg1= (ulonglong) args[0]->val_int();
8218   ulonglong arg2= (ulonglong) args[1]->val_int();
8219   if ((null_value= (args[0]->null_value || args[1]->null_value)))
8220     return 0;
8221   return (longlong) (arg1 ^ arg2);
8222 }
8223 
8224 
8225 /***************************************************************************
8226   System variables
8227 ****************************************************************************/
8228 
8229 /**
8230   @class Silence_deprecation_warnings
8231 
8232   @brief Disable deprecation warnings handler class
8233 */
8234 class Silence_deprecation_warnings : public Internal_error_handler
8235 {
8236 public:
handle_condition(THD * thd,uint sql_errno,const char * sqlstate,Sql_condition::enum_severity_level * level,const char * msg)8237   virtual bool handle_condition(THD *thd,
8238                                 uint sql_errno,
8239                                 const char* sqlstate,
8240                                 Sql_condition::enum_severity_level *level,
8241                                 const char* msg)
8242   {
8243     return sql_errno == ER_WARN_DEPRECATED_SYNTAX;
8244   }
8245 };
8246 
8247 /**
8248   Return value of an system variable base[.name] as a constant item.
8249 
8250   @param pc                     Current parse context
8251   @param var_type               global / session
8252   @param name                   Name of base or system variable
8253   @param component              Component.
8254 
8255   @param unsafe                 If true and if the variable is written to a
8256                                 binlog then mark the statement as unsafe.
8257 
8258   @note
8259     If component.str = 0 then the variable name is in 'name'
8260 
8261   @return
8262     - 0  : error
8263     - #  : constant item
8264 */
8265 
8266 
get_system_var(Parse_context * pc,enum_var_type var_type,LEX_STRING name,LEX_STRING component,bool unsafe)8267 Item *get_system_var(Parse_context *pc,
8268                      enum_var_type var_type, LEX_STRING name,
8269                      LEX_STRING component, bool unsafe)
8270 {
8271   THD *thd= pc->thd;
8272   sys_var *var;
8273   LEX_STRING *base_name, *component_name;
8274 
8275   if (component.str)
8276   {
8277     base_name= &component;
8278     component_name= &name;
8279   }
8280   else
8281   {
8282     base_name= &name;
8283     component_name= &component;			// Empty string
8284   }
8285 
8286   if (!(var= find_sys_var(thd, base_name->str, base_name->length)))
8287     return 0;
8288   if (component.str)
8289   {
8290     if (!var->is_struct())
8291     {
8292       my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name->str);
8293       return 0;
8294     }
8295   }
8296   thd->lex->set_uncacheable(pc->select, UNCACHEABLE_SIDEEFFECT);
8297 
8298   set_if_smaller(component_name->length, MAX_SYS_VAR_LENGTH);
8299 
8300   var->do_deprecated_warning(thd);
8301 
8302   Item_func_get_system_var *item= new Item_func_get_system_var(var, var_type,
8303                                                                component_name,
8304                                                                NULL, 0);
8305   if (item == NULL)
8306     return NULL;  // OOM
8307 
8308   if (unsafe && !var->is_written_to_binlog(var_type))
8309     thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_VARIABLE);
8310 
8311 #ifndef EMBEDDED_LIBRARY
8312   if (var_type == OPT_GLOBAL && var->check_scope(OPT_GLOBAL))
8313   {
8314     String str;
8315     String *outStr;
8316     /* This object is just created for variable to string conversion.
8317        item object cannot be used after the conversion of the variable
8318        to string. It caches the data. */
8319     Item_func_get_system_var *si= new Item_func_get_system_var(var, var_type,
8320                                                                component_name,
8321                                                                NULL, 0);
8322 
8323     /* Disable deprecation warning during var to string conversion. */
8324     Silence_deprecation_warnings silencer;
8325     thd->push_internal_handler(&silencer);
8326 
8327     if (si)
8328       (void) si->fix_length_and_dec();
8329     outStr= si ? si->val_str(&str) : &str;
8330 
8331     thd->pop_internal_handler();
8332 
8333     if (mysql_audit_notify(thd, AUDIT_EVENT(MYSQL_AUDIT_GLOBAL_VARIABLE_GET),
8334                            var->name.str,
8335                            outStr ? outStr->ptr() : NULL,
8336                            outStr ? outStr->length() : 0))
8337       {
8338         return 0;
8339       }
8340   }
8341 #endif
8342 
8343   return item;
8344 }
8345 
8346 
itemize(Parse_context * pc,Item ** res)8347 bool Item_func_row_count::itemize(Parse_context *pc, Item **res)
8348 {
8349   if (skip_itemize(res))
8350     return false;
8351   if (super::itemize(pc, res))
8352     return true;
8353 
8354   LEX *lex= pc->thd->lex;
8355   lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8356   lex->safe_to_cache_query= 0;
8357   return false;
8358 }
8359 
val_int()8360 longlong Item_func_row_count::val_int()
8361 {
8362   assert(fixed == 1);
8363   THD *thd= current_thd;
8364 
8365   return thd->get_row_count_func();
8366 }
8367 
8368 
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)8369 Item_func_sp::Item_func_sp(const POS &pos,
8370                            const LEX_STRING &db_name,
8371                            const LEX_STRING &fn_name,
8372                            bool use_explicit_name,
8373                            PT_item_list *opt_list)
8374 : Item_func(pos, opt_list), m_sp(NULL), dummy_table(NULL), sp_result_field(NULL)
8375 {
8376   maybe_null= 1;
8377   with_stored_program= true;
8378   THD *thd= current_thd;
8379   m_name= new (thd->mem_root) sp_name(to_lex_cstring(db_name), fn_name,
8380                                       use_explicit_name);
8381 }
8382 
8383 
itemize(Parse_context * pc,Item ** res)8384 bool Item_func_sp::itemize(Parse_context *pc, Item **res)
8385 {
8386   if (skip_itemize(res))
8387     return false;
8388   if (super::itemize(pc, res))
8389     return true;
8390   if (m_name == NULL)
8391     return true; // OOM
8392 
8393   THD *thd= pc->thd;
8394   LEX *lex= thd->lex;
8395 
8396   context= lex->current_context();
8397   lex->safe_to_cache_query= false;
8398 
8399   if (m_name->m_db.str == NULL)
8400   {
8401     /* Cannot match the function since no database is selected */
8402     my_error(ER_NO_DB_ERROR, MYF(0));
8403     return true;
8404   }
8405 
8406   m_name->init_qname(thd);
8407   sp_add_used_routine(lex, thd, m_name, SP_TYPE_FUNCTION);
8408 
8409   dummy_table= (TABLE*) sql_calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE));
8410   if (dummy_table == NULL)
8411     return true;
8412   dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
8413 
8414   return false;
8415 }
8416 
8417 
8418 void
cleanup()8419 Item_func_sp::cleanup()
8420 {
8421   if (sp_result_field)
8422   {
8423     delete sp_result_field;
8424     sp_result_field= NULL;
8425   }
8426   m_sp= NULL;
8427   if (dummy_table != NULL)
8428     dummy_table->alias= NULL;
8429   Item_func::cleanup();
8430   tables_locked_cache= false;
8431   with_stored_program= true;
8432 }
8433 
8434 const char *
func_name() const8435 Item_func_sp::func_name() const
8436 {
8437   THD *thd= current_thd;
8438   /* Calculate length to avoid reallocation of string for sure */
8439   size_t len= (((m_name->m_explicit_name ? m_name->m_db.length : 0) +
8440                 m_name->m_name.length)*2 + //characters*quoting
8441                2 +                         // ` and `
8442                (m_name->m_explicit_name ?
8443                 3 : 0) +                   // '`', '`' and '.' for the db
8444                1 +                         // end of string
8445                ALIGN_SIZE(1));             // to avoid String reallocation
8446   String qname((char *)alloc_root(thd->mem_root, len), len,
8447                system_charset_info);
8448 
8449   qname.length(0);
8450   if (m_name->m_explicit_name)
8451   {
8452     append_identifier(thd, &qname, m_name->m_db.str, m_name->m_db.length);
8453     qname.append('.');
8454   }
8455   append_identifier(thd, &qname, m_name->m_name.str, m_name->m_name.length);
8456   return qname.ptr();
8457 }
8458 
8459 
get_initial_pseudo_tables() const8460 table_map Item_func_sp::get_initial_pseudo_tables() const
8461 {
8462   return m_sp->m_chistics->detistic ? 0 : RAND_TABLE_BIT;
8463 }
8464 
8465 
my_missing_function_error(const LEX_STRING & token,const char * func_name)8466 void my_missing_function_error(const LEX_STRING &token, const char *func_name)
8467 {
8468   if (token.length && is_lex_native_function (&token))
8469     my_error(ER_FUNC_INEXISTENT_NAME_COLLISION, MYF(0), func_name);
8470   else
8471     my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", func_name);
8472 }
8473 
8474 
8475 /**
8476   @brief Initialize the result field by creating a temporary dummy table
8477     and assign it to a newly created field object. Meta data used to
8478     create the field is fetched from the sp_head belonging to the stored
8479     proceedure found in the stored procedure functon cache.
8480 
8481   @note This function should be called from fix_fields to init the result
8482     field. It is some what related to Item_field.
8483 
8484   @see Item_field
8485 
8486   @param thd A pointer to the session and thread context.
8487 
8488   @return Function return error status.
8489   @retval TRUE is returned on an error
8490   @retval FALSE is returned on success.
8491 */
8492 
8493 bool
init_result_field(THD * thd)8494 Item_func_sp::init_result_field(THD *thd)
8495 {
8496   LEX_STRING empty_name= { C_STRING_WITH_LEN("") };
8497   TABLE_SHARE *share;
8498   DBUG_ENTER("Item_func_sp::init_result_field");
8499 
8500   assert(m_sp == NULL);
8501   assert(sp_result_field == NULL);
8502 
8503   Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8504     view_handler(thd, context->view_error_handler,
8505                  context->view_error_handler_arg);
8506   if (!(m_sp= sp_find_routine(thd, SP_TYPE_FUNCTION, m_name,
8507                                &thd->sp_func_cache, TRUE)))
8508   {
8509     my_missing_function_error (m_name->m_name, m_name->m_qname.str);
8510     DBUG_RETURN(TRUE);
8511   }
8512 
8513   /*
8514      A Field need to be attached to a Table.
8515      Below we "create" a dummy table by initializing
8516      the needed pointers.
8517    */
8518 
8519   share= dummy_table->s;
8520   dummy_table->alias = "";
8521   if (maybe_null)
8522     dummy_table->set_nullable();
8523   dummy_table->in_use= thd;
8524   dummy_table->copy_blobs= TRUE;
8525   share->table_cache_key = empty_name;
8526   share->table_name = empty_name;
8527 
8528   if (!(sp_result_field= m_sp->create_result_field(max_length, item_name.ptr(),
8529                                                    dummy_table)))
8530   {
8531    DBUG_RETURN(TRUE);
8532   }
8533 
8534   if (sp_result_field->pack_length() > sizeof(result_buf))
8535   {
8536     void *tmp;
8537     if (!(tmp= sql_alloc(sp_result_field->pack_length())))
8538       DBUG_RETURN(TRUE);
8539     sp_result_field->move_field((uchar*) tmp);
8540   }
8541   else
8542     sp_result_field->move_field(result_buf);
8543 
8544   sp_result_field->set_null_ptr((uchar *) &null_value, 1);
8545   DBUG_RETURN(FALSE);
8546 }
8547 
8548 
8549 /**
8550   @brief Initialize local members with values from the Field interface.
8551 
8552   @note called from Item::fix_fields.
8553 */
8554 
fix_length_and_dec()8555 void Item_func_sp::fix_length_and_dec()
8556 {
8557   DBUG_ENTER("Item_func_sp::fix_length_and_dec");
8558 
8559   assert(sp_result_field);
8560   decimals= sp_result_field->decimals();
8561   max_length= sp_result_field->field_length;
8562   collation.set(sp_result_field->charset());
8563   maybe_null= 1;
8564   unsigned_flag= MY_TEST(sp_result_field->flags & UNSIGNED_FLAG);
8565 
8566   DBUG_VOID_RETURN;
8567 }
8568 
8569 
val_json(Json_wrapper * result)8570 bool Item_func_sp::val_json(Json_wrapper *result)
8571 {
8572   if (sp_result_field->type() == MYSQL_TYPE_JSON)
8573   {
8574     if (execute())
8575     {
8576       return true;
8577     }
8578 
8579     Field_json *json_value= down_cast<Field_json *>(sp_result_field);
8580     return json_value->val_json(result);
8581   }
8582 
8583   /* purecov: begin deadcode */
8584   DBUG_ABORT();
8585   my_error(ER_INVALID_CAST_TO_JSON, MYF(0));
8586   return error_json();
8587   /* purecov: end */
8588 }
8589 
8590 
8591 type_conversion_status
save_in_field_inner(Field * field,bool no_conversions)8592 Item_func_sp::save_in_field_inner(Field *field, bool no_conversions)
8593 {
8594   return save_possibly_as_json(field, no_conversions);
8595 }
8596 
8597 
update_null_value()8598 void Item_func_sp::update_null_value()
8599 {
8600   /*
8601     This method is called when we try to check if the item value is NULL.
8602     We call Item_func_sp::execute() to get value of null_value attribute
8603     as a side effect of its execution.
8604     We ignore any error since update_null_value() doesn't return value.
8605     We used to delegate nullability check to Item::update_null_value as
8606     a result of a chain of function calls:
8607      Item_func_isnull::val_int --> Item_func::is_null -->
8608       Item::update_null_value -->Item_func_sp::val_int -->
8609         Field_varstring::val_int
8610     Such approach resulted in a call of push_warning_printf() in case
8611     if a stored program value couldn't be cast to integer (the case when
8612     for example there was a stored function that declared as returning
8613     varchar(1) and a function's implementation returned "Y" from its body).
8614   */
8615   execute();
8616 }
8617 
8618 
8619 /**
8620   @brief Execute function & store value in field.
8621 
8622   @return Function returns error status.
8623   @retval FALSE on success.
8624   @retval TRUE if an error occurred.
8625 */
8626 
8627 bool
execute()8628 Item_func_sp::execute()
8629 {
8630   THD *thd= current_thd;
8631 
8632   Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8633     view_handler(thd, context->view_error_handler,
8634                  context->view_error_handler_arg);
8635   /* Execute function and store the return value in the field. */
8636 
8637   if (execute_impl(thd))
8638   {
8639     null_value= 1;
8640     if (thd->killed)
8641       thd->send_kill_message();
8642     return TRUE;
8643   }
8644 
8645   /* Check that the field (the value) is not NULL. */
8646 
8647   null_value= sp_result_field->is_null();
8648 
8649   return null_value;
8650 }
8651 
8652 
8653 /**
8654    @brief Execute function and store the return value in the field.
8655 
8656    @note This function was intended to be the concrete implementation of
8657     the interface function execute. This was never realized.
8658 
8659    @return The error state.
8660    @retval FALSE on success
8661    @retval TRUE if an error occurred.
8662 */
8663 bool
execute_impl(THD * thd)8664 Item_func_sp::execute_impl(THD *thd)
8665 {
8666   bool err_status= TRUE;
8667   Sub_statement_state statement_state;
8668 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8669   Security_context *save_security_ctx= thd->security_context();
8670 #endif
8671   enum enum_sp_data_access access=
8672     (m_sp->m_chistics->daccess == SP_DEFAULT_ACCESS) ?
8673      SP_DEFAULT_ACCESS_MAPPING : m_sp->m_chistics->daccess;
8674 
8675   DBUG_ENTER("Item_func_sp::execute_impl");
8676 
8677 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8678   if (context->security_ctx)
8679   {
8680     /* Set view definer security context */
8681     thd->set_security_context(context->security_ctx);
8682   }
8683 #endif
8684   if (sp_check_access(thd))
8685     goto error;
8686 
8687   /*
8688     Throw an error if a non-deterministic function is called while
8689     statement-based replication (SBR) is active.
8690   */
8691 
8692   if (!m_sp->m_chistics->detistic && !trust_function_creators &&
8693       (access == SP_CONTAINS_SQL || access == SP_MODIFIES_SQL_DATA) &&
8694       (mysql_bin_log.is_open() &&
8695        thd->variables.binlog_format == BINLOG_FORMAT_STMT))
8696   {
8697     my_error(ER_BINLOG_UNSAFE_ROUTINE, MYF(0));
8698     goto error;
8699   }
8700   /*
8701     Disable the binlogging if this is not a SELECT statement. If this is a
8702     SELECT, leave binlogging on, so execute_function() code writes the
8703     function call into binlog.
8704   */
8705   thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION);
8706   err_status= m_sp->execute_function(thd, args, arg_count, sp_result_field);
8707   thd->restore_sub_statement_state(&statement_state);
8708 
8709 error:
8710 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8711   thd->set_security_context(save_security_ctx);
8712 #endif
8713 
8714   DBUG_RETURN(err_status);
8715 }
8716 
8717 
8718 void
make_field(Send_field * tmp_field)8719 Item_func_sp::make_field(Send_field *tmp_field)
8720 {
8721   DBUG_ENTER("Item_func_sp::make_field");
8722   assert(sp_result_field);
8723   sp_result_field->make_field(tmp_field);
8724   if (item_name.is_set())
8725     tmp_field->col_name= item_name.ptr();
8726   DBUG_VOID_RETURN;
8727 }
8728 
8729 
8730 enum enum_field_types
field_type() const8731 Item_func_sp::field_type() const
8732 {
8733   DBUG_ENTER("Item_func_sp::field_type");
8734   assert(sp_result_field);
8735   DBUG_RETURN(sp_result_field->type());
8736 }
8737 
8738 Item_result
result_type() const8739 Item_func_sp::result_type() const
8740 {
8741   DBUG_ENTER("Item_func_sp::result_type");
8742   DBUG_PRINT("info", ("m_sp = %p", (void *) m_sp));
8743   assert(sp_result_field);
8744   DBUG_RETURN(sp_result_field->result_type());
8745 }
8746 
8747 
itemize(Parse_context * pc,Item ** res)8748 bool Item_func_found_rows::itemize(Parse_context *pc, Item **res)
8749 {
8750   if (skip_itemize(res))
8751     return false;
8752   if (super::itemize(pc, res))
8753     return true;
8754   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8755   pc->thd->lex->safe_to_cache_query= false;
8756   return false;
8757 }
8758 
8759 
val_int()8760 longlong Item_func_found_rows::val_int()
8761 {
8762   assert(fixed == 1);
8763   return current_thd->found_rows();
8764 }
8765 
8766 
8767 Field *
tmp_table_field(TABLE * t_arg)8768 Item_func_sp::tmp_table_field(TABLE *t_arg)
8769 {
8770   DBUG_ENTER("Item_func_sp::tmp_table_field");
8771 
8772   assert(sp_result_field);
8773   DBUG_RETURN(sp_result_field);
8774 }
8775 
8776 
8777 /**
8778   @brief Checks if requested access to function can be granted to user.
8779     If function isn't found yet, it searches function first.
8780     If function can't be found or user don't have requested access
8781     error is raised.
8782 
8783   @param thd thread handler
8784 
8785   @return Indication if the access was granted or not.
8786   @retval FALSE Access is granted.
8787   @retval TRUE Requested access can't be granted or function doesn't exists.
8788 
8789 */
8790 
8791 bool
sp_check_access(THD * thd)8792 Item_func_sp::sp_check_access(THD *thd)
8793 {
8794   DBUG_ENTER("Item_func_sp::sp_check_access");
8795   assert(m_sp);
8796 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8797   if (check_routine_access(thd, EXECUTE_ACL,
8798 			   m_sp->m_db.str, m_sp->m_name.str, 0, FALSE))
8799     DBUG_RETURN(TRUE);
8800 #endif
8801 
8802   DBUG_RETURN(FALSE);
8803 }
8804 
8805 
8806 bool
fix_fields(THD * thd,Item ** ref)8807 Item_func_sp::fix_fields(THD *thd, Item **ref)
8808 {
8809   bool res;
8810 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8811   Security_context *save_security_ctx= thd->security_context();
8812 #endif
8813 
8814   DBUG_ENTER("Item_func_sp::fix_fields");
8815   assert(fixed == 0);
8816 
8817 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8818   /*
8819     Checking privileges to execute the function while creating view and
8820     executing the function of select.
8821    */
8822   if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) ||
8823       (thd->lex->sql_command == SQLCOM_CREATE_VIEW))
8824   {
8825     if (context->security_ctx)
8826     {
8827       /* Set view definer security context */
8828       thd->set_security_context(context->security_ctx);
8829     }
8830 
8831     /*
8832       Check whether user has execute privilege or not
8833      */
8834 
8835     Internal_error_handler_holder<View_error_handler, TABLE_LIST>
8836       view_handler(thd, context->view_error_handler,
8837                    context->view_error_handler_arg);
8838 
8839     res= check_routine_access(thd, EXECUTE_ACL, m_name->m_db.str,
8840                               m_name->m_name.str, 0, FALSE);
8841     thd->set_security_context(save_security_ctx);
8842 
8843     if (res)
8844     {
8845       DBUG_RETURN(res);
8846     }
8847   }
8848 #endif
8849 
8850   /*
8851     We must call init_result_field before Item_func::fix_fields()
8852     to make m_sp and result_field members available to fix_length_and_dec(),
8853     which is called from Item_func::fix_fields().
8854   */
8855   res= init_result_field(thd);
8856 
8857   if (res)
8858     DBUG_RETURN(res);
8859 
8860   res= Item_func::fix_fields(thd, ref);
8861 
8862   /* These is reset/set by Item_func::fix_fields. */
8863   with_stored_program= true;
8864 
8865   if (res)
8866     DBUG_RETURN(res);
8867 
8868   if (thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)
8869   {
8870     /*
8871       Here we check privileges of the stored routine only during view
8872       creation, in order to validate the view.  A runtime check is
8873       perfomed in Item_func_sp::execute(), and this method is not
8874       called during context analysis.  Notice, that during view
8875       creation we do not infer into stored routine bodies and do not
8876       check privileges of its statements, which would probably be a
8877       good idea especially if the view has SQL SECURITY DEFINER and
8878       the used stored procedure has SQL SECURITY DEFINER.
8879     */
8880     res= sp_check_access(thd);
8881 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8882     /*
8883       Try to set and restore the security context to see whether it's valid
8884     */
8885     Security_context *save_secutiry_ctx;
8886     res= m_sp->set_security_ctx(thd, &save_secutiry_ctx);
8887     if (!res)
8888       m_sp->m_security_ctx.restore_security_context(thd, save_secutiry_ctx);
8889 
8890 #endif /* ! NO_EMBEDDED_ACCESS_CHECKS */
8891   }
8892 
8893   DBUG_RETURN(res);
8894 }
8895 
8896 
update_used_tables()8897 void Item_func_sp::update_used_tables()
8898 {
8899   Item_func::update_used_tables();
8900 
8901   /* This is reset by Item_func::update_used_tables(). */
8902   with_stored_program= true;
8903 }
8904 
8905 
8906 /*
8907   uuid_short handling.
8908 
8909   The short uuid is defined as a longlong that contains the following bytes:
8910 
8911   Bytes  Comment
8912   1      Server_id & 255
8913   4      Startup time of server in seconds
8914   3      Incrementor
8915 
8916   This means that an uuid is guaranteed to be unique
8917   even in a replication environment if the following holds:
8918 
8919   - The last byte of the server id is unique
8920   - If you between two shutdown of the server don't get more than
8921     an average of 2^24 = 16M calls to uuid_short() per second.
8922 */
8923 
8924 ulonglong uuid_value;
8925 
uuid_short_init()8926 void uuid_short_init()
8927 {
8928   uuid_value= ((((ulonglong) server_id) << 56) +
8929                (((ulonglong) server_start_time) << 24));
8930 }
8931 
8932 
itemize(Parse_context * pc,Item ** res)8933 bool Item_func_uuid_short::itemize(Parse_context *pc, Item **res)
8934 {
8935   if (skip_itemize(res))
8936     return false;
8937   if (super::itemize(pc, res))
8938     return true;
8939   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8940   pc->thd->lex->safe_to_cache_query= false;
8941   return false;
8942 }
8943 
8944 
val_int()8945 longlong Item_func_uuid_short::val_int()
8946 {
8947   ulonglong val;
8948   mysql_mutex_lock(&LOCK_uuid_generator);
8949   val= uuid_value++;
8950   mysql_mutex_unlock(&LOCK_uuid_generator);
8951   return (longlong) val;
8952 }
8953 
8954 
itemize(Parse_context * pc,Item ** res)8955 bool Item_func_version::itemize(Parse_context *pc, Item **res)
8956 {
8957   if (skip_itemize(res))
8958     return false;
8959   if (super::itemize(pc, res))
8960     return true;
8961   pc->thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_SYSTEM_FUNCTION);
8962   return false;
8963 }
8964 
8965