1 /* Copyright (c) 2000, 2015, Oracle and/or its affiliates.
2    Copyright (c) 2009, 2021, MariaDB
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; version 2 of the License.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program; if not, write to the Free Software
15    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
16 
17 /**
18   @file
19 
20   @brief
21   This file defines all numerical functions
22 */
23 
24 #ifdef USE_PRAGMA_IMPLEMENTATION
25 #pragma implementation				// gcc: Class implementation
26 #endif
27 
28 #include "sql_plugin.h"
29 #include "sql_priv.h"
30 /*
31   It is necessary to include set_var.h instead of item.h because there
32   are dependencies on include order for set_var.h and item.h. This
33   will be resolved later.
34 */
35 #include "sql_class.h"                          // set_var.h: THD
36 #include "set_var.h"
37 #include "slave.h"				// for wait_for_master_pos
38 #include "sql_show.h"                           // append_identifier
39 #include "strfunc.h"                            // find_type
40 #include "sql_parse.h"                          // is_update_query
41 #include "sql_acl.h"                            // EXECUTE_ACL
42 #include "mysqld.h"                             // LOCK_short_uuid_generator
43 #include "rpl_mi.h"
44 #include "sql_time.h"
45 #include <m_ctype.h>
46 #include <hash.h>
47 #include <time.h>
48 #include <ft_global.h>
49 #include <my_bit.h>
50 
51 #include "sp_head.h"
52 #include "sp_rcontext.h"
53 #include "sp.h"
54 #include "set_var.h"
55 #include "debug_sync.h"
56 #include "sql_base.h"
57 #include "sql_cte.h"
58 
59 #ifdef NO_EMBEDDED_ACCESS_CHECKS
60 #define sp_restore_security_context(A,B) while (0) {}
61 #endif
62 
check_reserved_words(const LEX_CSTRING * name)63 bool check_reserved_words(const LEX_CSTRING *name)
64 {
65   if (lex_string_eq(name, STRING_WITH_LEN("GLOBAL")) ||
66       lex_string_eq(name, STRING_WITH_LEN("LOCAL")) ||
67       lex_string_eq(name, STRING_WITH_LEN("SESSION")))
68     return TRUE;
69   return FALSE;
70 }
71 
72 
73 /**
74    Test if the sum of arguments overflows the ulonglong range.
75 */
test_if_sum_overflows_ull(ulonglong arg1,ulonglong arg2)76 static inline bool test_if_sum_overflows_ull(ulonglong arg1, ulonglong arg2)
77 {
78   return ULONGLONG_MAX - arg1 < arg2;
79 }
80 
81 
82 /**
83   Allocate memory for arguments using tmp_args or thd->alloc().
84   @retval false  - success
85   @retval true   - error (arg_count is set to 0 for conveniece)
86 */
alloc_arguments(THD * thd,uint count)87 bool Item_args::alloc_arguments(THD *thd, uint count)
88 {
89   if (count <= 2)
90   {
91     args= tmp_arg;
92     return false;
93   }
94   if ((args= (Item**) thd->alloc(sizeof(Item*) * count)) == NULL)
95   {
96     arg_count= 0;
97     return true;
98   }
99   return false;
100 }
101 
102 
set_arguments(THD * thd,List<Item> & list)103 void Item_args::set_arguments(THD *thd, List<Item> &list)
104 {
105   if (alloc_arguments(thd, list.elements))
106     return;
107   List_iterator_fast<Item> li(list);
108   Item *item;
109   for (arg_count= 0; (item= li++); )
110     args[arg_count++]= item;
111 }
112 
113 
Item_args(THD * thd,const Item_args * other)114 Item_args::Item_args(THD *thd, const Item_args *other)
115   :arg_count(other->arg_count)
116 {
117   if (arg_count <= 2)
118   {
119     args= tmp_arg;
120   }
121   else if (!(args= (Item**) thd->alloc(sizeof(Item*) * arg_count)))
122   {
123     arg_count= 0;
124     return;
125   }
126   if (arg_count)
127     memcpy(args, other->args, sizeof(Item*) * arg_count);
128 }
129 
130 
sync_with_sum_func_and_with_field(List<Item> & list)131 void Item_func::sync_with_sum_func_and_with_field(List<Item> &list)
132 {
133   List_iterator_fast<Item> li(list);
134   Item *item;
135   while ((item= li++))
136   {
137     join_with_sum_func(item);
138     with_window_func|= item->with_window_func;
139     with_field|= item->with_field;
140     with_param|= item->with_param;
141   }
142 }
143 
144 
check_argument_types_like_args0() const145 bool Item_func::check_argument_types_like_args0() const
146 {
147   if (arg_count < 2)
148     return false;
149   uint cols= args[0]->cols();
150   bool is_scalar= args[0]->type_handler()->is_scalar_type();
151   for (uint i= 1; i < arg_count; i++)
152   {
153     if (is_scalar != args[i]->type_handler()->is_scalar_type())
154     {
155       my_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION, MYF(0),
156                args[0]->type_handler()->name().ptr(),
157                args[i]->type_handler()->name().ptr(), func_name());
158       return true;
159     }
160     if (args[i]->check_cols(cols))
161       return true;
162   }
163   return false;
164 }
165 
166 
check_argument_types_or_binary(const Type_handler * handler,uint start,uint end) const167 bool Item_func::check_argument_types_or_binary(const Type_handler *handler,
168                                                uint start, uint end) const
169 {
170   for (uint i= start; i < end ; i++)
171   {
172     DBUG_ASSERT(i < arg_count);
173     if (args[i]->check_type_or_binary(func_name(), handler))
174       return true;
175   }
176   return false;
177 }
178 
179 
check_argument_types_traditional_scalar(uint start,uint end) const180 bool Item_func::check_argument_types_traditional_scalar(uint start,
181                                                         uint end) const
182 {
183   for (uint i= start; i < end ; i++)
184   {
185     DBUG_ASSERT(i < arg_count);
186     if (args[i]->check_type_traditional_scalar(func_name()))
187       return true;
188   }
189   return false;
190 }
191 
192 
check_argument_types_can_return_int(uint start,uint end) const193 bool Item_func::check_argument_types_can_return_int(uint start,
194                                                     uint end) const
195 {
196   for (uint i= start; i < end ; i++)
197   {
198     DBUG_ASSERT(i < arg_count);
199     if (args[i]->check_type_can_return_int(func_name()))
200       return true;
201   }
202   return false;
203 }
204 
205 
check_argument_types_can_return_real(uint start,uint end) const206 bool Item_func::check_argument_types_can_return_real(uint start,
207                                                      uint end) const
208 {
209   for (uint i= start; i < end ; i++)
210   {
211     DBUG_ASSERT(i < arg_count);
212     if (args[i]->check_type_can_return_real(func_name()))
213       return true;
214   }
215   return false;
216 }
217 
218 
check_argument_types_can_return_text(uint start,uint end) const219 bool Item_func::check_argument_types_can_return_text(uint start,
220                                                      uint end) const
221 {
222   for (uint i= start; i < end ; i++)
223   {
224     DBUG_ASSERT(i < arg_count);
225     if (args[i]->check_type_can_return_text(func_name()))
226       return true;
227   }
228   return false;
229 }
230 
231 
check_argument_types_can_return_str(uint start,uint end) const232 bool Item_func::check_argument_types_can_return_str(uint start,
233                                                     uint end) const
234 {
235   for (uint i= start; i < end ; i++)
236   {
237     DBUG_ASSERT(i < arg_count);
238     if (args[i]->check_type_can_return_str(func_name()))
239       return true;
240   }
241   return false;
242 }
243 
244 
check_argument_types_can_return_date(uint start,uint end) const245 bool Item_func::check_argument_types_can_return_date(uint start,
246                                                      uint end) const
247 {
248   for (uint i= start; i < end ; i++)
249   {
250     DBUG_ASSERT(i < arg_count);
251     if (args[i]->check_type_can_return_date(func_name()))
252       return true;
253   }
254   return false;
255 }
256 
257 
check_argument_types_can_return_time(uint start,uint end) const258 bool Item_func::check_argument_types_can_return_time(uint start,
259                                                      uint end) const
260 {
261   for (uint i= start; i < end ; i++)
262   {
263     DBUG_ASSERT(i < arg_count);
264     if (args[i]->check_type_can_return_time(func_name()))
265       return true;
266   }
267   return false;
268 }
269 
270 
check_argument_types_scalar(uint start,uint end) const271 bool Item_func::check_argument_types_scalar(uint start, uint end) const
272 {
273   for (uint i= start; i < end; i++)
274   {
275     DBUG_ASSERT(i < arg_count);
276     if (args[i]->check_type_scalar(func_name()))
277       return true;
278   }
279   return false;
280 }
281 
282 
283 /*
284   Resolve references to table column for a function and its argument
285 
286   SYNOPSIS:
287   fix_fields()
288   thd		Thread object
289   ref		Pointer to where this object is used.  This reference
290 		is used if we want to replace this object with another
291 		one (for example in the summary functions).
292 
293   DESCRIPTION
294     Call fix_fields() for all arguments to the function.  The main intention
295     is to allow all Item_field() objects to setup pointers to the table fields.
296 
297     Sets as a side effect the following class variables:
298       maybe_null        Set if any argument may return NULL
299       with_sum_func     Set if any of the arguments contains a sum function
300       with_window_func  Set if any of the arguments contain a window function
301       with_field        Set if any of the arguments contains or is a field
302       used_tables_cache Set to union of the tables used by arguments
303 
304       str_value.charset If this is a string function, set this to the
305 			character set for the first argument.
306 			If any argument is binary, this is set to binary
307 
308    If for any item any of the defaults are wrong, then this can
309    be fixed in the fix_length_and_dec() function that is called
310    after this one or by writing a specialized fix_fields() for the
311    item.
312 
313   RETURN VALUES
314   FALSE	ok
315   TRUE	Got error.  Stored with my_error().
316 */
317 
318 bool
fix_fields(THD * thd,Item ** ref)319 Item_func::fix_fields(THD *thd, Item **ref)
320 {
321   DBUG_ASSERT(fixed == 0);
322   Item **arg,**arg_end;
323   uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
324 
325   /*
326     The Used_tables_and_const_cache of "this" was initialized by
327     the constructor, or by Item_func::cleanup().
328   */
329   DBUG_ASSERT(used_tables_cache == 0);
330   DBUG_ASSERT(const_item_cache == true);
331 
332   not_null_tables_cache= 0;
333 
334   /*
335     Use stack limit of STACK_MIN_SIZE * 2 since
336     on some platforms a recursive call to fix_fields
337     requires more than STACK_MIN_SIZE bytes (e.g. for
338     MIPS, it takes about 22kB to make one recursive
339     call to Item_func::fix_fields())
340   */
341   if (check_stack_overrun(thd, STACK_MIN_SIZE * 2, buff))
342     return TRUE;				// Fatal error if flag is set!
343   if (arg_count)
344   {						// Print purify happy
345     for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
346     {
347       Item *item;
348       /*
349 	We can't yet set item to *arg as fix_fields may change *arg
350 	We shouldn't call fix_fields() twice, so check 'fixed' field first
351       */
352       if ((*arg)->fix_fields_if_needed(thd, arg))
353 	return TRUE;				/* purecov: inspected */
354       item= *arg;
355 
356       if (item->maybe_null)
357 	maybe_null=1;
358 
359       join_with_sum_func(item);
360       with_param= with_param || item->with_param;
361       with_window_func= with_window_func || item->with_window_func;
362       with_field= with_field || item->with_field;
363       used_tables_and_const_cache_join(item);
364       not_null_tables_cache|= item->not_null_tables();
365       m_with_subquery|= item->with_subquery();
366     }
367   }
368   if (check_arguments())
369     return true;
370   if (fix_length_and_dec())
371     return TRUE;
372   fixed= 1;
373   return FALSE;
374 }
375 
376 void
quick_fix_field()377 Item_func::quick_fix_field()
378 {
379   Item **arg,**arg_end;
380   if (arg_count)
381   {
382     for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
383     {
384       if (!(*arg)->is_fixed())
385         (*arg)->quick_fix_field();
386     }
387   }
388   fixed= 1;
389 }
390 
391 
392 bool
eval_not_null_tables(void * opt_arg)393 Item_func::eval_not_null_tables(void *opt_arg)
394 {
395   Item **arg,**arg_end;
396   not_null_tables_cache= 0;
397   if (arg_count)
398   {
399     for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
400     {
401       not_null_tables_cache|= (*arg)->not_null_tables();
402     }
403   }
404   return FALSE;
405 }
406 
407 
408 bool
find_not_null_fields(table_map allowed)409 Item_func::find_not_null_fields(table_map allowed)
410 {
411   if (~allowed & used_tables())
412     return false;
413 
414   Item **arg,**arg_end;
415   if (arg_count)
416   {
417     for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
418     {
419       if (!(*arg)->find_not_null_fields(allowed))
420         continue;
421     }
422   }
423   return false;
424 }
425 
426 
fix_after_pullout(st_select_lex * new_parent,Item ** ref,bool merge)427 void Item_func::fix_after_pullout(st_select_lex *new_parent, Item **ref,
428                                   bool merge)
429 {
430   Item **arg,**arg_end;
431 
432   used_tables_and_const_cache_init();
433   not_null_tables_cache= 0;
434 
435   if (arg_count)
436   {
437     for (arg=args, arg_end=args+arg_count; arg != arg_end ; arg++)
438     {
439       (*arg)->fix_after_pullout(new_parent, arg, merge);
440       Item *item= *arg;
441 
442       used_tables_and_const_cache_join(item);
443       not_null_tables_cache|= item->not_null_tables();
444     }
445   }
446 }
447 
448 
traverse_cond(Cond_traverser traverser,void * argument,traverse_order order)449 void Item_func::traverse_cond(Cond_traverser traverser,
450                               void *argument, traverse_order order)
451 {
452   if (arg_count)
453   {
454     Item **arg,**arg_end;
455 
456     switch (order) {
457     case(PREFIX):
458       (*traverser)(this, argument);
459       for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
460       {
461 	(*arg)->traverse_cond(traverser, argument, order);
462       }
463       break;
464     case (POSTFIX):
465       for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
466       {
467 	(*arg)->traverse_cond(traverser, argument, order);
468       }
469       (*traverser)(this, argument);
470     }
471   }
472   else
473     (*traverser)(this, argument);
474 }
475 
476 
transform_args(THD * thd,Item_transformer transformer,uchar * arg)477 bool Item_args::transform_args(THD *thd, Item_transformer transformer, uchar *arg)
478 {
479   for (uint i= 0; i < arg_count; i++)
480   {
481     Item *new_item= args[i]->transform(thd, transformer, arg);
482     if (!new_item)
483       return true;
484     /*
485       THD::change_item_tree() should be called only if the tree was
486       really transformed, i.e. when a new item has been created.
487       Otherwise we'll be allocating a lot of unnecessary memory for
488       change records at each execution.
489     */
490     if (args[i] != new_item)
491       thd->change_item_tree(&args[i], new_item);
492   }
493   return false;
494 }
495 
496 
497 /**
498   Transform an Item_func object with a transformer callback function.
499 
500     The function recursively applies the transform method to each
501     argument of the Item_func node.
502     If the call of the method for an argument item returns a new item
503     the old item is substituted for a new one.
504     After this the transformer is applied to the root node
505     of the Item_func object.
506   @param transformer   the transformer callback function to be applied to
507                        the nodes of the tree of the object
508   @param argument      parameter to be passed to the transformer
509 
510   @return
511     Item returned as the result of transformation of the root node
512 */
513 
transform(THD * thd,Item_transformer transformer,uchar * argument)514 Item *Item_func::transform(THD *thd, Item_transformer transformer, uchar *argument)
515 {
516   DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
517   if (transform_args(thd, transformer, argument))
518     return 0;
519   return (this->*transformer)(thd, argument);
520 }
521 
522 
523 /**
524   Compile Item_func object with a processor and a transformer
525   callback functions.
526 
527     First the function applies the analyzer to the root node of
528     the Item_func object. Then if the analyzer succeeds (returns TRUE)
529     the function recursively applies the compile method to each argument
530     of the Item_func node.
531     If the call of the method for an argument item returns a new item
532     the old item is substituted for a new one.
533     After this the transformer is applied to the root node
534     of the Item_func object.
535     The compile function is not called if the analyzer returns NULL
536     in the parameter arg_p.
537 
538   @param analyzer      the analyzer callback function to be applied to the
539                        nodes of the tree of the object
540   @param[in,out] arg_p parameter to be passed to the processor
541   @param transformer   the transformer callback function to be applied to the
542                        nodes of the tree of the object
543   @param arg_t         parameter to be passed to the transformer
544 
545   @return
546     Item returned as the result of transformation of the root node
547 */
548 
compile(THD * thd,Item_analyzer analyzer,uchar ** arg_p,Item_transformer transformer,uchar * arg_t)549 Item *Item_func::compile(THD *thd, Item_analyzer analyzer, uchar **arg_p,
550                          Item_transformer transformer, uchar *arg_t)
551 {
552   if (!(this->*analyzer)(arg_p))
553     return 0;
554   if (*arg_p && arg_count)
555   {
556     Item **arg,**arg_end;
557     for (arg= args, arg_end= args+arg_count; arg != arg_end; arg++)
558     {
559       /*
560         The same parameter value of arg_p must be passed
561         to analyze any argument of the condition formula.
562       */
563       uchar *arg_v= *arg_p;
564       Item *new_item= (*arg)->compile(thd, analyzer, &arg_v, transformer,
565                                       arg_t);
566       if (new_item && *arg != new_item)
567         thd->change_item_tree(arg, new_item);
568     }
569   }
570   return (this->*transformer)(thd, arg_t);
571 }
572 
573 
propagate_equal_fields(THD * thd,const Item::Context & ctx,COND_EQUAL * cond)574 void Item_args::propagate_equal_fields(THD *thd,
575                                        const Item::Context &ctx,
576                                        COND_EQUAL *cond)
577 {
578   uint i;
579   for (i= 0; i < arg_count; i++)
580     args[i]->propagate_equal_fields_and_change_item_tree(thd, ctx, cond,
581                                                          &args[i]);
582 }
583 
584 
value_depends_on_sql_mode_bit_or() const585 Sql_mode_dependency Item_args::value_depends_on_sql_mode_bit_or() const
586 {
587   Sql_mode_dependency res;
588   for (uint i= 0; i < arg_count; i++)
589     res|= args[i]->value_depends_on_sql_mode();
590   return res;
591 }
592 
593 
594 /**
595   See comments in Item_cond::split_sum_func()
596 */
597 
split_sum_func(THD * thd,Ref_ptr_array ref_pointer_array,List<Item> & fields,uint flags)598 void Item_func::split_sum_func(THD *thd,  Ref_ptr_array ref_pointer_array,
599                                List<Item> &fields, uint flags)
600 {
601   Item **arg, **arg_end;
602   for (arg= args, arg_end= args+arg_count; arg != arg_end ; arg++)
603     (*arg)->split_sum_func2(thd, ref_pointer_array, fields, arg,
604                             flags | SPLIT_SUM_SKIP_REGISTERED);
605 }
606 
607 
not_null_tables() const608 table_map Item_func::not_null_tables() const
609 {
610   return not_null_tables_cache;
611 }
612 
613 
print(String * str,enum_query_type query_type)614 void Item_func::print(String *str, enum_query_type query_type)
615 {
616   str->append(func_name());
617   str->append('(');
618   print_args(str, 0, query_type);
619   str->append(')');
620 }
621 
622 
print_args(String * str,uint from,enum_query_type query_type)623 void Item_func::print_args(String *str, uint from, enum_query_type query_type)
624 {
625   for (uint i=from ; i < arg_count ; i++)
626   {
627     if (i != from)
628       str->append(',');
629     args[i]->print(str, query_type);
630   }
631 }
632 
633 
print_op(String * str,enum_query_type query_type)634 void Item_func::print_op(String *str, enum_query_type query_type)
635 {
636   for (uint i=0 ; i < arg_count-1 ; i++)
637   {
638     args[i]->print_parenthesised(str, query_type, precedence());
639     str->append(' ');
640     str->append(func_name());
641     str->append(' ');
642   }
643   args[arg_count-1]->print_parenthesised(str, query_type, higher_precedence());
644 }
645 
646 
eq(const Item * item,bool binary_cmp) const647 bool Item_func::eq(const Item *item, bool binary_cmp) const
648 {
649   /* Assume we don't have rtti */
650   if (this == item)
651     return 1;
652   /*
653     Ensure that we are comparing two functions and that the function
654     is deterministic.
655   */
656   if (item->type() != FUNC_ITEM || (used_tables() & RAND_TABLE_BIT))
657     return 0;
658   Item_func *item_func=(Item_func*) item;
659   Item_func::Functype func_type;
660   if ((func_type= functype()) != item_func->functype() ||
661       arg_count != item_func->arg_count ||
662       (func_type != Item_func::FUNC_SP &&
663        func_name() != item_func->func_name()) ||
664       (func_type == Item_func::FUNC_SP &&
665        my_strcasecmp(system_charset_info, func_name(), item_func->func_name())))
666     return 0;
667   return Item_args::eq(item_func, binary_cmp);
668 }
669 
670 
671 /*
672 bool Item_func::is_expensive_processor(uchar *arg)
673 {
674   return is_expensive();
675 }
676 */
677 
678 
fix_attributes(Item ** items,uint nitems)679 bool Item_hybrid_func::fix_attributes(Item **items, uint nitems)
680 {
681   bool rc= Item_hybrid_func::type_handler()->
682              Item_hybrid_func_fix_attributes(current_thd,
683                                              func_name(), this, this,
684                                              items, nitems);
685   DBUG_ASSERT(!rc || current_thd->is_error());
686   return rc;
687 }
688 
689 
val_str(String * str)690 String *Item_real_func::val_str(String *str)
691 {
692   DBUG_ASSERT(fixed == 1);
693   double nr= val_real();
694   if (null_value)
695     return 0; /* purecov: inspected */
696   str->set_real(nr, decimals, collation.collation);
697   return str;
698 }
699 
700 
val_decimal(my_decimal * decimal_value)701 my_decimal *Item_real_func::val_decimal(my_decimal *decimal_value)
702 {
703   DBUG_ASSERT(fixed);
704   double nr= val_real();
705   if (null_value)
706     return 0; /* purecov: inspected */
707   double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
708   return decimal_value;
709 }
710 
711 
712 #ifdef HAVE_DLOPEN
fix_num_length_and_dec()713 void Item_udf_func::fix_num_length_and_dec()
714 {
715   uint fl_length= 0;
716   decimals=0;
717   for (uint i=0 ; i < arg_count ; i++)
718   {
719     set_if_bigger(decimals,args[i]->decimals);
720     set_if_bigger(fl_length, args[i]->max_length);
721   }
722   max_length=float_length(decimals);
723   if (fl_length > max_length)
724   {
725     decimals= NOT_FIXED_DEC;
726     max_length= float_length(NOT_FIXED_DEC);
727   }
728 }
729 #endif
730 
731 
signal_divide_by_null()732 void Item_func::signal_divide_by_null()
733 {
734   THD *thd= current_thd;
735   if (thd->variables.sql_mode & MODE_ERROR_FOR_DIVISION_BY_ZERO)
736     push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_DIVISION_BY_ZERO,
737                  ER_THD(thd, ER_DIVISION_BY_ZERO));
738   null_value= 1;
739 }
740 
741 
get_tmp_table_item(THD * thd)742 Item *Item_func::get_tmp_table_item(THD *thd)
743 {
744   if (!Item_func::with_sum_func() && !const_item())
745     return new (thd->mem_root) Item_temptable_field(thd, result_field);
746   return copy_or_same(thd);
747 }
748 
val_real()749 double Item_int_func::val_real()
750 {
751   DBUG_ASSERT(fixed == 1);
752 
753   return unsigned_flag ? (double) ((ulonglong) val_int()) : (double) val_int();
754 }
755 
756 
val_str(String * str)757 String *Item_int_func::val_str(String *str)
758 {
759   DBUG_ASSERT(fixed == 1);
760   longlong nr=val_int();
761   if (null_value)
762     return 0;
763   str->set_int(nr, unsigned_flag, collation.collation);
764   return str;
765 }
766 
767 
fix_length_and_dec()768 bool Item_func_connection_id::fix_length_and_dec()
769 {
770   if (Item_long_func::fix_length_and_dec())
771     return TRUE;
772   max_length= 10;
773   return FALSE;
774 }
775 
776 
fix_fields(THD * thd,Item ** ref)777 bool Item_func_connection_id::fix_fields(THD *thd, Item **ref)
778 {
779   if (Item_int_func::fix_fields(thd, ref))
780     return TRUE;
781   thd->thread_specific_used= TRUE;
782   value= thd->variables.pseudo_thread_id;
783   return FALSE;
784 }
785 
786 
fix_type_handler(const Type_aggregator * aggregator)787 bool Item_num_op::fix_type_handler(const Type_aggregator *aggregator)
788 {
789   DBUG_ASSERT(arg_count == 2);
790   const Type_handler *h0= args[0]->cast_to_int_type_handler();
791   const Type_handler *h1= args[1]->cast_to_int_type_handler();
792   if (!aggregate_for_num_op(aggregator, h0, h1))
793     return false;
794   my_error(ER_ILLEGAL_PARAMETER_DATA_TYPES2_FOR_OPERATION, MYF(0),
795            h0->name().ptr(), h1->name().ptr(), func_name());
796   return true;
797 }
798 
799 
fix_length_and_dec(void)800 bool Item_func_plus::fix_length_and_dec(void)
801 {
802   DBUG_ENTER("Item_func_plus::fix_length_and_dec");
803   DBUG_PRINT("info", ("name %s", func_name()));
804   const Type_aggregator *aggregator= &type_handler_data->m_type_aggregator_for_plus;
805   DBUG_EXECUTE_IF("num_op", aggregator= &type_handler_data->m_type_aggregator_for_result;);
806   DBUG_ASSERT(aggregator->is_commutative());
807   if (fix_type_handler(aggregator))
808     DBUG_RETURN(TRUE);
809   if (Item_func_plus::type_handler()->Item_func_plus_fix_length_and_dec(this))
810     DBUG_RETURN(TRUE);
811   DBUG_PRINT("info", ("Type: %s", type_handler()->name().ptr()));
812   DBUG_RETURN(FALSE);
813 }
814 
815 
val_str_from_int_op(String * str)816 String *Item_func_hybrid_field_type::val_str_from_int_op(String *str)
817 {
818   longlong nr= int_op();
819   if (null_value)
820     return 0; /* purecov: inspected */
821   str->set_int(nr, unsigned_flag, collation.collation);
822   return str;
823 }
824 
val_real_from_int_op()825 double Item_func_hybrid_field_type::val_real_from_int_op()
826 {
827   longlong result= int_op();
828   return unsigned_flag ? (double) ((ulonglong) result) : (double) result;
829 }
830 
831 my_decimal *
val_decimal_from_int_op(my_decimal * dec)832 Item_func_hybrid_field_type::val_decimal_from_int_op(my_decimal *dec)
833 {
834   longlong result= int_op();
835   if (null_value)
836     return NULL;
837   int2my_decimal(E_DEC_FATAL_ERROR, result, unsigned_flag, dec);
838   return dec;
839 }
840 
841 
val_str_from_real_op(String * str)842 String *Item_func_hybrid_field_type::val_str_from_real_op(String *str)
843 {
844   double nr= real_op();
845   if (null_value)
846     return 0; /* purecov: inspected */
847   str->set_real(nr, decimals, collation.collation);
848   return str;
849 }
850 
val_int_from_real_op()851 longlong Item_func_hybrid_field_type::val_int_from_real_op()
852 {
853   return Converter_double_to_longlong(real_op(), unsigned_flag).result();
854 }
855 
856 my_decimal *
val_decimal_from_real_op(my_decimal * dec)857 Item_func_hybrid_field_type::val_decimal_from_real_op(my_decimal *dec)
858 {
859   double result= (double) real_op();
860   if (null_value)
861     return NULL;
862   double2my_decimal(E_DEC_FATAL_ERROR, result, dec);
863   return dec;
864 }
865 
866 
val_str_from_date_op(String * str)867 String *Item_func_hybrid_field_type::val_str_from_date_op(String *str)
868 {
869   MYSQL_TIME ltime;
870   if (date_op_with_null_check(current_thd, &ltime) ||
871       (null_value= str->alloc(MAX_DATE_STRING_REP_LENGTH)))
872     return (String *) 0;
873   str->length(my_TIME_to_str(&ltime, const_cast<char*>(str->ptr()), decimals));
874   str->set_charset(&my_charset_bin);
875   DBUG_ASSERT(!null_value);
876   return str;
877 }
878 
val_real_from_date_op()879 double Item_func_hybrid_field_type::val_real_from_date_op()
880 {
881   MYSQL_TIME ltime;
882   if (date_op_with_null_check(current_thd, &ltime))
883     return 0;
884   return TIME_to_double(&ltime);
885 }
886 
val_int_from_date_op()887 longlong Item_func_hybrid_field_type::val_int_from_date_op()
888 {
889   MYSQL_TIME ltime;
890   if (date_op_with_null_check(current_thd, &ltime))
891     return 0;
892   return TIME_to_ulonglong(&ltime);
893 }
894 
895 my_decimal *
val_decimal_from_date_op(my_decimal * dec)896 Item_func_hybrid_field_type::val_decimal_from_date_op(my_decimal *dec)
897 {
898   MYSQL_TIME ltime;
899   if (date_op_with_null_check(current_thd, &ltime))
900   {
901     my_decimal_set_zero(dec);
902     return 0;
903   }
904   return date2my_decimal(&ltime, dec);
905 }
906 
907 
val_str_from_time_op(String * str)908 String *Item_func_hybrid_field_type::val_str_from_time_op(String *str)
909 {
910   MYSQL_TIME ltime;
911   if (time_op_with_null_check(current_thd, &ltime) ||
912       (null_value= my_TIME_to_str(&ltime, str, decimals)))
913     return NULL;
914   return str;
915 }
916 
val_real_from_time_op()917 double Item_func_hybrid_field_type::val_real_from_time_op()
918 {
919   MYSQL_TIME ltime;
920   return time_op_with_null_check(current_thd, &ltime) ? 0 :
921          TIME_to_double(&ltime);
922 }
923 
val_int_from_time_op()924 longlong Item_func_hybrid_field_type::val_int_from_time_op()
925 {
926   MYSQL_TIME ltime;
927   return time_op_with_null_check(current_thd, &ltime) ? 0 :
928          TIME_to_ulonglong(&ltime);
929 }
930 
931 my_decimal *
val_decimal_from_time_op(my_decimal * dec)932 Item_func_hybrid_field_type::val_decimal_from_time_op(my_decimal *dec)
933 {
934   MYSQL_TIME ltime;
935   if (time_op_with_null_check(current_thd, &ltime))
936   {
937     my_decimal_set_zero(dec);
938     return 0;
939   }
940   return date2my_decimal(&ltime, dec);
941 }
942 
943 
val_real_from_str_op()944 double Item_func_hybrid_field_type::val_real_from_str_op()
945 {
946   String *res= str_op_with_null_check(&str_value);
947   return res ? double_from_string_with_check(res) : 0.0;
948 }
949 
val_int_from_str_op()950 longlong Item_func_hybrid_field_type::val_int_from_str_op()
951 {
952   String *res= str_op_with_null_check(&str_value);
953   return res ? longlong_from_string_with_check(res) : 0;
954 }
955 
956 my_decimal *
val_decimal_from_str_op(my_decimal * decimal_value)957 Item_func_hybrid_field_type::val_decimal_from_str_op(my_decimal *decimal_value)
958 {
959   String *res= str_op_with_null_check(&str_value);
960   return res ? decimal_from_string_with_check(decimal_value, res) : 0;
961 }
962 
963 
print(String * str,enum_query_type query_type)964 void Item_func_signed::print(String *str, enum_query_type query_type)
965 {
966   str->append(STRING_WITH_LEN("cast("));
967   args[0]->print(str, query_type);
968   str->append(STRING_WITH_LEN(" as signed)"));
969 
970 }
971 
972 
print(String * str,enum_query_type query_type)973 void Item_func_unsigned::print(String *str, enum_query_type query_type)
974 {
975   str->append(STRING_WITH_LEN("cast("));
976   args[0]->print(str, query_type);
977   str->append(STRING_WITH_LEN(" as unsigned)"));
978 
979 }
980 
981 
val_decimal(my_decimal * dec)982 my_decimal *Item_decimal_typecast::val_decimal(my_decimal *dec)
983 {
984   VDec tmp(args[0]);
985   bool sign;
986   uint precision;
987 
988   if ((null_value= tmp.is_null()))
989     return NULL;
990   tmp.round_to(dec, decimals, HALF_UP);
991   sign= dec->sign();
992   if (unsigned_flag)
993   {
994     if (sign)
995     {
996       my_decimal_set_zero(dec);
997       goto err;
998     }
999   }
1000   precision= my_decimal_length_to_precision(max_length,
1001                                             decimals, unsigned_flag);
1002   if (precision - decimals < (uint) my_decimal_intg(dec))
1003   {
1004     max_my_decimal(dec, precision, decimals);
1005     dec->sign(sign);
1006     goto err;
1007   }
1008   return dec;
1009 
1010 err:
1011   THD *thd= current_thd;
1012   push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1013                       ER_WARN_DATA_OUT_OF_RANGE,
1014                       ER_THD(thd, ER_WARN_DATA_OUT_OF_RANGE),
1015                       name.str, 1L);
1016   return dec;
1017 }
1018 
1019 
print(String * str,enum_query_type query_type)1020 void Item_decimal_typecast::print(String *str, enum_query_type query_type)
1021 {
1022   char len_buf[20*3 + 1];
1023   char *end;
1024 
1025   uint precision= my_decimal_length_to_precision(max_length, decimals,
1026                                                  unsigned_flag);
1027   str->append(STRING_WITH_LEN("cast("));
1028   args[0]->print(str, query_type);
1029   str->append(STRING_WITH_LEN(" as decimal("));
1030 
1031   end=int10_to_str(precision, len_buf,10);
1032   str->append(len_buf, (uint32) (end - len_buf));
1033 
1034   str->append(',');
1035 
1036   end=int10_to_str(decimals, len_buf,10);
1037   str->append(len_buf, (uint32) (end - len_buf));
1038 
1039   str->append(')');
1040   str->append(')');
1041 }
1042 
1043 
val_real_with_truncate(double max_value)1044 double Item_real_typecast::val_real_with_truncate(double max_value)
1045 {
1046   int error;
1047   double tmp= args[0]->val_real();
1048   if ((null_value= args[0]->null_value))
1049     return 0.0;
1050 
1051   if (unlikely((error= truncate_double(&tmp, max_length, decimals,
1052                                        false/*unsigned_flag*/, max_value))))
1053   {
1054     /*
1055       We don't want automatic escalation from a warning to an error
1056       in this scenario:
1057         INSERT INTO t1 (float_field) VALUES (CAST(1e100 AS FLOAT));
1058       The above statement should work even in the strict mode.
1059       So let's use a note rather than a warning.
1060     */
1061     THD *thd= current_thd;
1062     push_warning_printf(thd,
1063                         Sql_condition::WARN_LEVEL_NOTE,
1064                         ER_WARN_DATA_OUT_OF_RANGE,
1065                         ER_THD(thd, ER_WARN_DATA_OUT_OF_RANGE),
1066                         name.str, (ulong) 1);
1067     if (error < 0)
1068     {
1069       null_value= 1;                            // Illegal value
1070       tmp= 0.0;
1071     }
1072   }
1073   return tmp;
1074 }
1075 
1076 
print(String * str,enum_query_type query_type)1077 void Item_real_typecast::print(String *str, enum_query_type query_type)
1078 {
1079   char len_buf[20*3 + 1];
1080   char *end;
1081 
1082   str->append(STRING_WITH_LEN("cast("));
1083   args[0]->print(str, query_type);
1084   str->append(STRING_WITH_LEN(" as "));
1085   str->append(type_handler()->name().ptr());
1086   if (decimals != NOT_FIXED_DEC)
1087   {
1088     str->append('(');
1089     end= int10_to_str(max_length, len_buf,10);
1090     str->append(len_buf, (uint32) (end - len_buf));
1091     str->append(',');
1092     end= int10_to_str(decimals, len_buf,10);
1093     str->append(len_buf, (uint32) (end - len_buf));
1094     str->append(')');
1095   }
1096   str->append(')');
1097 }
1098 
real_op()1099 double Item_func_plus::real_op()
1100 {
1101   double value= args[0]->val_real() + args[1]->val_real();
1102   if ((null_value=args[0]->null_value || args[1]->null_value))
1103     return 0.0;
1104   return check_float_overflow(value);
1105 }
1106 
1107 #if defined(__powerpc64__) && GCC_VERSION >= 6003 && GCC_VERSION <= 10002
1108 #pragma GCC push_options
1109 #pragma GCC optimize ("no-expensive-optimizations")
1110 #endif
1111 
int_op()1112 longlong Item_func_plus::int_op()
1113 {
1114   longlong val0= args[0]->val_int();
1115   longlong val1= args[1]->val_int();
1116   bool     res_unsigned= FALSE;
1117   longlong res;
1118 
1119   if ((null_value= args[0]->null_value || args[1]->null_value))
1120     return 0;
1121   /*
1122     First check whether the result can be represented as a
1123     (bool unsigned_flag, longlong value) pair, then check if it is compatible
1124     with this Item's unsigned_flag by calling check_integer_overflow().
1125   */
1126   if (args[0]->unsigned_flag)
1127   {
1128     if (args[1]->unsigned_flag || val1 >= 0)
1129     {
1130       if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) val1))
1131         goto err;
1132       res_unsigned= TRUE;
1133     }
1134     else
1135     {
1136       /* val1 is negative */
1137       if ((ulonglong) val0 > (ulonglong) LONGLONG_MAX)
1138         res_unsigned= TRUE;
1139     }
1140   }
1141   else
1142   {
1143     if (args[1]->unsigned_flag)
1144     {
1145       if (val0 >= 0)
1146       {
1147         if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) val1))
1148           goto err;
1149         res_unsigned= TRUE;
1150       }
1151       else
1152       {
1153         if ((ulonglong) val1 > (ulonglong) LONGLONG_MAX)
1154           res_unsigned= TRUE;
1155       }
1156     }
1157     else
1158     {
1159       if (val0 >=0 && val1 >= 0)
1160         res_unsigned= TRUE;
1161       else if (val0 < 0 && val1 < 0 && val0 < (LONGLONG_MIN - val1))
1162         goto err;
1163     }
1164   }
1165 
1166 #ifndef WITH_UBSAN
1167   res= val0 + val1;
1168 #else
1169   if (res_unsigned)
1170     res= (longlong) ((ulonglong) val0 + (ulonglong) val1);
1171   else
1172     res= val0+val1;
1173 #endif /* WITH_UBSAN */
1174 
1175   return check_integer_overflow(res, res_unsigned);
1176 
1177 err:
1178   return raise_integer_overflow();
1179 }
1180 
1181 #if defined(__powerpc64__) && GCC_VERSION >= 6003 && GCC_VERSION <= 10002
1182 #pragma GCC pop_options
1183 #endif
1184 
1185 /**
1186   Calculate plus of two decimals.
1187 
1188   @param decimal_value	Buffer that can be used to store result
1189 
1190   @retval
1191     0  Value was NULL;  In this case null_value is set
1192   @retval
1193     \# Value of operation as a decimal
1194 */
1195 
decimal_op(my_decimal * decimal_value)1196 my_decimal *Item_func_plus::decimal_op(my_decimal *decimal_value)
1197 {
1198   VDec2_lazy val(args[0], args[1]);
1199   if (!(null_value= (val.has_null() ||
1200                      check_decimal_overflow(my_decimal_add(E_DEC_FATAL_ERROR &
1201                                                            ~E_DEC_OVERFLOW,
1202                                                            decimal_value,
1203                                                            val.m_a.ptr(),
1204                                                            val.m_b.ptr())) > 3)))
1205     return decimal_value;
1206   return 0;
1207 }
1208 
1209 /**
1210   Set precision of results for additive operations (+ and -)
1211 */
result_precision()1212 void Item_func_additive_op::result_precision()
1213 {
1214   decimals= MY_MAX(args[0]->decimal_scale(), args[1]->decimal_scale());
1215   int arg1_int= args[0]->decimal_precision() - args[0]->decimal_scale();
1216   int arg2_int= args[1]->decimal_precision() - args[1]->decimal_scale();
1217   int precision= MY_MAX(arg1_int, arg2_int) + 1 + decimals;
1218 
1219   DBUG_ASSERT(arg1_int >= 0);
1220   DBUG_ASSERT(arg2_int >= 0);
1221 
1222   max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
1223                                                            unsigned_flag);
1224 }
1225 
1226 
1227 /**
1228   The following function is here to allow the user to force
1229   subtraction of UNSIGNED BIGINT to return negative values.
1230 */
fix_unsigned_flag()1231 void Item_func_minus::fix_unsigned_flag()
1232 {
1233   if (unsigned_flag &&
1234       (current_thd->variables.sql_mode & MODE_NO_UNSIGNED_SUBTRACTION))
1235   {
1236     unsigned_flag=0;
1237     set_handler(Item_func_minus::type_handler()->type_handler_signed());
1238   }
1239 }
1240 
1241 
fix_length_and_dec()1242 bool Item_func_minus::fix_length_and_dec()
1243 {
1244   DBUG_ENTER("Item_func_minus::fix_length_and_dec");
1245   DBUG_PRINT("info", ("name %s", func_name()));
1246   const Type_aggregator *aggregator= &type_handler_data->m_type_aggregator_for_minus;
1247   DBUG_EXECUTE_IF("num_op", aggregator= &type_handler_data->m_type_aggregator_non_commutative_test;);
1248   DBUG_ASSERT(!aggregator->is_commutative());
1249   if (fix_type_handler(aggregator))
1250     DBUG_RETURN(TRUE);
1251   if (Item_func_minus::type_handler()->Item_func_minus_fix_length_and_dec(this))
1252     DBUG_RETURN(TRUE);
1253   DBUG_PRINT("info", ("Type: %s", type_handler()->name().ptr()));
1254   m_depends_on_sql_mode_no_unsigned_subtraction= unsigned_flag;
1255   fix_unsigned_flag();
1256   DBUG_RETURN(FALSE);
1257 }
1258 
1259 
value_depends_on_sql_mode() const1260 Sql_mode_dependency Item_func_minus::value_depends_on_sql_mode() const
1261 {
1262   Sql_mode_dependency dep= Item_func_additive_op::value_depends_on_sql_mode();
1263   if (m_depends_on_sql_mode_no_unsigned_subtraction)
1264     dep|= Sql_mode_dependency(0, MODE_NO_UNSIGNED_SUBTRACTION);
1265   return dep;
1266 }
1267 
1268 
real_op()1269 double Item_func_minus::real_op()
1270 {
1271   double value= args[0]->val_real() - args[1]->val_real();
1272   if ((null_value=args[0]->null_value || args[1]->null_value))
1273     return 0.0;
1274   return check_float_overflow(value);
1275 }
1276 
1277 
1278 #if defined(__powerpc64__) && GCC_VERSION >= 6003 && GCC_VERSION <= 10002
1279 #pragma GCC push_options
1280 #pragma GCC optimize ("no-expensive-optimizations")
1281 #endif
1282 
int_op()1283 longlong Item_func_minus::int_op()
1284 {
1285   longlong val0= args[0]->val_int();
1286   longlong val1= args[1]->val_int();
1287   bool     res_unsigned= FALSE;
1288   longlong res;
1289 
1290   if ((null_value= args[0]->null_value || args[1]->null_value))
1291     return 0;
1292 
1293   /*
1294     First check whether the result can be represented as a
1295     (bool unsigned_flag, longlong value) pair, then check if it is compatible
1296     with this Item's unsigned_flag by calling check_integer_overflow().
1297   */
1298   if (args[0]->unsigned_flag)
1299   {
1300     if (args[1]->unsigned_flag)
1301     {
1302       if ((ulonglong) val0 < (ulonglong) val1)
1303         goto err;
1304       res_unsigned= TRUE;
1305     }
1306     else
1307     {
1308       if (val1 >= 0)
1309       {
1310         if ((ulonglong) val0 > (ulonglong) val1)
1311           res_unsigned= TRUE;
1312       }
1313       else
1314       {
1315         if (test_if_sum_overflows_ull((ulonglong) val0, (ulonglong) -val1))
1316           goto err;
1317         res_unsigned= TRUE;
1318       }
1319     }
1320   }
1321   else
1322   {
1323     if (args[1]->unsigned_flag)
1324     {
1325       if (((ulonglong) val0 - (ulonglong) LONGLONG_MIN) < (ulonglong) val1)
1326         goto err;
1327     }
1328     else
1329     {
1330       if (val0 > 0 && val1 < 0)
1331         res_unsigned= TRUE;
1332       else if (val0 < 0 && val1 > 0 && val0 < (LONGLONG_MIN + val1))
1333         goto err;
1334     }
1335   }
1336 #ifndef WITH_UBSAN
1337   res= val0 - val1;
1338 #else
1339   if (res_unsigned)
1340     res= (longlong) ((ulonglong) val0 - (ulonglong) val1);
1341   else
1342     res= val0 - val1;
1343 #endif /* WITH_UBSAN */
1344 
1345   return check_integer_overflow(res, res_unsigned);
1346 
1347 err:
1348   return raise_integer_overflow();
1349 }
1350 
1351 #if defined(__powerpc64__) && GCC_VERSION >= 6003 && GCC_VERSION <= 10002
1352 #pragma GCC pop_options
1353 #endif
1354 
1355 /**
1356   See Item_func_plus::decimal_op for comments.
1357 */
1358 
decimal_op(my_decimal * decimal_value)1359 my_decimal *Item_func_minus::decimal_op(my_decimal *decimal_value)
1360 {
1361   VDec2_lazy val(args[0], args[1]);
1362   if (!(null_value= (val.has_null() ||
1363                      check_decimal_overflow(my_decimal_sub(E_DEC_FATAL_ERROR &
1364                                                            ~E_DEC_OVERFLOW,
1365                                                            decimal_value,
1366                                                            val.m_a.ptr(),
1367                                                            val.m_b.ptr())) > 3)))
1368     return decimal_value;
1369   return 0;
1370 }
1371 
1372 
real_op()1373 double Item_func_mul::real_op()
1374 {
1375   DBUG_ASSERT(fixed == 1);
1376   double value= args[0]->val_real() * args[1]->val_real();
1377   if ((null_value=args[0]->null_value || args[1]->null_value))
1378     return 0.0;
1379   return check_float_overflow(value);
1380 }
1381 
1382 
int_op()1383 longlong Item_func_mul::int_op()
1384 {
1385   DBUG_ASSERT(fixed == 1);
1386   longlong a= args[0]->val_int();
1387   longlong b= args[1]->val_int();
1388   longlong res;
1389   ulonglong res0, res1;
1390   ulong a0, a1, b0, b1;
1391   bool     res_unsigned= FALSE;
1392   bool     a_negative= FALSE, b_negative= FALSE;
1393 
1394   if ((null_value= args[0]->null_value || args[1]->null_value))
1395     return 0;
1396 
1397   /*
1398     First check whether the result can be represented as a
1399     (bool unsigned_flag, longlong value) pair, then check if it is compatible
1400     with this Item's unsigned_flag by calling check_integer_overflow().
1401 
1402     Let a = a1 * 2^32 + a0 and b = b1 * 2^32 + b0. Then
1403     a * b = (a1 * 2^32 + a0) * (b1 * 2^32 + b0) = a1 * b1 * 2^64 +
1404             + (a1 * b0 + a0 * b1) * 2^32 + a0 * b0;
1405     We can determine if the above sum overflows the ulonglong range by
1406     sequentially checking the following conditions:
1407     1. If both a1 and b1 are non-zero.
1408     2. Otherwise, if (a1 * b0 + a0 * b1) is greater than ULONG_MAX.
1409     3. Otherwise, if (a1 * b0 + a0 * b1) * 2^32 + a0 * b0 is greater than
1410     ULONGLONG_MAX.
1411 
1412     Since we also have to take the unsigned_flag for a and b into account,
1413     it is easier to first work with absolute values and set the
1414     correct sign later.
1415   */
1416   if (!args[0]->unsigned_flag && a < 0)
1417   {
1418     a_negative= TRUE;
1419     a= -a;
1420   }
1421   if (!args[1]->unsigned_flag && b < 0)
1422   {
1423     b_negative= TRUE;
1424     b= -b;
1425   }
1426 
1427   a0= 0xFFFFFFFFUL & a;
1428   a1= ((ulonglong) a) >> 32;
1429   b0= 0xFFFFFFFFUL & b;
1430   b1= ((ulonglong) b) >> 32;
1431 
1432   if (a1 && b1)
1433     goto err;
1434 
1435   res1= (ulonglong) a1 * b0 + (ulonglong) a0 * b1;
1436   if (res1 > 0xFFFFFFFFUL)
1437     goto err;
1438 
1439   res1= res1 << 32;
1440   res0= (ulonglong) a0 * b0;
1441 
1442   if (test_if_sum_overflows_ull(res1, res0))
1443     goto err;
1444   res= res1 + res0;
1445 
1446   if (a_negative != b_negative)
1447   {
1448     if ((ulonglong) res > (ulonglong) LONGLONG_MIN + 1)
1449       goto err;
1450     res= -res;
1451   }
1452   else
1453     res_unsigned= TRUE;
1454 
1455   return check_integer_overflow(res, res_unsigned);
1456 
1457 err:
1458   return raise_integer_overflow();
1459 }
1460 
1461 
1462 /** See Item_func_plus::decimal_op for comments. */
1463 
decimal_op(my_decimal * decimal_value)1464 my_decimal *Item_func_mul::decimal_op(my_decimal *decimal_value)
1465 {
1466   VDec2_lazy val(args[0], args[1]);
1467   if (!(null_value= (val.has_null() ||
1468                      check_decimal_overflow(my_decimal_mul(E_DEC_FATAL_ERROR &
1469                                                            ~E_DEC_OVERFLOW,
1470                                                            decimal_value,
1471                                                            val.m_a.ptr(),
1472                                                            val.m_b.ptr())) > 3)))
1473     return decimal_value;
1474   return 0;
1475 }
1476 
1477 
result_precision()1478 void Item_func_mul::result_precision()
1479 {
1480   decimals= MY_MIN(args[0]->decimal_scale() + args[1]->decimal_scale(),
1481                    DECIMAL_MAX_SCALE);
1482   uint est_prec = args[0]->decimal_precision() + args[1]->decimal_precision();
1483   uint precision= MY_MIN(est_prec, DECIMAL_MAX_PRECISION);
1484   max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
1485                                                            unsigned_flag);
1486 }
1487 
1488 
fix_length_and_dec(void)1489 bool Item_func_mul::fix_length_and_dec(void)
1490 {
1491   DBUG_ENTER("Item_func_mul::fix_length_and_dec");
1492   DBUG_PRINT("info", ("name %s", func_name()));
1493   const Type_aggregator *aggregator= &type_handler_data->m_type_aggregator_for_mul;
1494   DBUG_EXECUTE_IF("num_op", aggregator= &type_handler_data->m_type_aggregator_for_result;);
1495   DBUG_ASSERT(aggregator->is_commutative());
1496   if (fix_type_handler(aggregator))
1497     DBUG_RETURN(TRUE);
1498   if (Item_func_mul::type_handler()->Item_func_mul_fix_length_and_dec(this))
1499     DBUG_RETURN(TRUE);
1500   DBUG_PRINT("info", ("Type: %s", type_handler()->name().ptr()));
1501   DBUG_RETURN(FALSE);
1502 }
1503 
1504 
real_op()1505 double Item_func_div::real_op()
1506 {
1507   DBUG_ASSERT(fixed == 1);
1508   double value= args[0]->val_real();
1509   double val2= args[1]->val_real();
1510   if ((null_value= args[0]->null_value || args[1]->null_value))
1511     return 0.0;
1512   if (val2 == 0.0)
1513   {
1514     signal_divide_by_null();
1515     return 0.0;
1516   }
1517   return check_float_overflow(value/val2);
1518 }
1519 
1520 
decimal_op(my_decimal * decimal_value)1521 my_decimal *Item_func_div::decimal_op(my_decimal *decimal_value)
1522 {
1523   int err;
1524   VDec2_lazy val(args[0], args[1]);
1525   if ((null_value= val.has_null()))
1526     return 0;
1527   if ((err= check_decimal_overflow(my_decimal_div(E_DEC_FATAL_ERROR &
1528                                                   ~E_DEC_OVERFLOW &
1529                                                   ~E_DEC_DIV_ZERO,
1530                                                   decimal_value,
1531                                                   val.m_a.ptr(), val.m_b.ptr(),
1532                                                   prec_increment))) > 3)
1533   {
1534     if (err == E_DEC_DIV_ZERO)
1535       signal_divide_by_null();
1536     null_value= 1;
1537     return 0;
1538   }
1539   return decimal_value;
1540 }
1541 
1542 
result_precision()1543 void Item_func_div::result_precision()
1544 {
1545   /*
1546     We need to add args[1]->divisor_precision_increment(),
1547     to properly handle the cases like this:
1548       SELECT 5.05 / 0.014; -> 360.714286
1549     i.e. when the divisor has a zero integer part
1550     and non-zero digits appear only after the decimal point.
1551     Precision in this example is calculated as
1552       args[0]->decimal_precision()           +  // 3
1553       args[1]->divisor_precision_increment() +  // 3
1554       prec_increment                            // 4
1555     which gives 10 decimals digits.
1556   */
1557   uint precision=MY_MIN(args[0]->decimal_precision() +
1558                      args[1]->divisor_precision_increment() + prec_increment,
1559                      DECIMAL_MAX_PRECISION);
1560   decimals= MY_MIN(args[0]->decimal_scale() + prec_increment, DECIMAL_MAX_SCALE);
1561   max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
1562                                                            unsigned_flag);
1563 }
1564 
1565 
fix_length_and_dec_double(void)1566 void Item_func_div::fix_length_and_dec_double(void)
1567 {
1568   Item_num_op::fix_length_and_dec_double();
1569   decimals= MY_MAX(args[0]->decimals, args[1]->decimals) + prec_increment;
1570   set_if_smaller(decimals, NOT_FIXED_DEC);
1571   uint tmp= float_length(decimals);
1572   if (decimals == NOT_FIXED_DEC)
1573     max_length= tmp;
1574   else
1575   {
1576     max_length=args[0]->max_length - args[0]->decimals + decimals;
1577     set_if_smaller(max_length, tmp);
1578   }
1579 }
1580 
1581 
fix_length_and_dec_int(void)1582 void Item_func_div::fix_length_and_dec_int(void)
1583 {
1584   set_handler(&type_handler_newdecimal);
1585   DBUG_PRINT("info", ("Type changed: %s", type_handler()->name().ptr()));
1586   Item_num_op::fix_length_and_dec_decimal();
1587 }
1588 
1589 
fix_length_and_dec()1590 bool Item_func_div::fix_length_and_dec()
1591 {
1592   DBUG_ENTER("Item_func_div::fix_length_and_dec");
1593   DBUG_PRINT("info", ("name %s", func_name()));
1594   prec_increment= current_thd->variables.div_precincrement;
1595   maybe_null= 1; // division by zero
1596 
1597   const Type_aggregator *aggregator= &type_handler_data->m_type_aggregator_for_div;
1598   DBUG_EXECUTE_IF("num_op", aggregator= &type_handler_data->m_type_aggregator_non_commutative_test;);
1599   DBUG_ASSERT(!aggregator->is_commutative());
1600   if (fix_type_handler(aggregator))
1601     DBUG_RETURN(TRUE);
1602   if (Item_func_div::type_handler()->Item_func_div_fix_length_and_dec(this))
1603     DBUG_RETURN(TRUE);
1604   DBUG_PRINT("info", ("Type: %s", type_handler()->name().ptr()));
1605   DBUG_RETURN(FALSE);
1606 }
1607 
1608 
1609 /* Integer division */
val_int()1610 longlong Item_func_int_div::val_int()
1611 {
1612   DBUG_ASSERT(fixed == 1);
1613 
1614   /*
1615     Perform division using DECIMAL math if either of the operands has a
1616     non-integer type
1617   */
1618   if (args[0]->result_type() != INT_RESULT ||
1619       args[1]->result_type() != INT_RESULT)
1620   {
1621     VDec2_lazy val(args[0], args[1]);
1622     if ((null_value= val.has_null()))
1623       return 0;
1624 
1625     int err;
1626     my_decimal tmp;
1627     if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, &tmp,
1628                              val.m_a.ptr(), val.m_b.ptr(), 0)) > 3)
1629     {
1630       if (err == E_DEC_DIV_ZERO)
1631         signal_divide_by_null();
1632       return 0;
1633     }
1634 
1635     my_decimal truncated;
1636     if (tmp.round_to(&truncated, 0, TRUNCATE))
1637       DBUG_ASSERT(false);
1638 
1639     longlong res;
1640     if (my_decimal2int(E_DEC_FATAL_ERROR, &truncated, unsigned_flag, &res) &
1641         E_DEC_OVERFLOW)
1642       raise_integer_overflow();
1643     return res;
1644   }
1645 
1646   Longlong_hybrid val0= args[0]->to_longlong_hybrid();
1647   Longlong_hybrid val1= args[1]->to_longlong_hybrid();
1648   if ((null_value= (args[0]->null_value || args[1]->null_value)))
1649     return 0;
1650   if (val1 == 0)
1651   {
1652     signal_divide_by_null();
1653     return 0;
1654   }
1655 
1656   bool res_negative= val0.neg() != val1.neg();
1657   ulonglong res= val0.abs() / val1.abs();
1658   if (res_negative)
1659   {
1660     if (res > (ulonglong) LONGLONG_MAX)
1661       return raise_integer_overflow();
1662     res= (ulonglong) (-(longlong) res);
1663   }
1664   return check_integer_overflow(res, !res_negative);
1665 }
1666 
1667 
fix_length_and_dec()1668 bool Item_func_int_div::fix_length_and_dec()
1669 {
1670   uint32 prec= args[0]->decimal_int_part();
1671   set_if_smaller(prec, MY_INT64_NUM_DECIMAL_DIGITS);
1672   fix_char_length(prec);
1673   maybe_null=1;
1674   unsigned_flag=args[0]->unsigned_flag | args[1]->unsigned_flag;
1675   return false;
1676 }
1677 
1678 
int_op()1679 longlong Item_func_mod::int_op()
1680 {
1681   DBUG_ASSERT(fixed == 1);
1682   Longlong_hybrid val0= args[0]->to_longlong_hybrid();
1683   Longlong_hybrid val1= args[1]->to_longlong_hybrid();
1684 
1685   if ((null_value= args[0]->null_value || args[1]->null_value))
1686     return 0; /* purecov: inspected */
1687   if (val1 == 0)
1688   {
1689     signal_divide_by_null();
1690     return 0;
1691   }
1692 
1693   /*
1694     '%' is calculated by integer division internally. Since dividing
1695     LONGLONG_MIN by -1 generates SIGFPE, we calculate using unsigned values and
1696     then adjust the sign appropriately.
1697   */
1698   ulonglong res= val0.abs() % val1.abs();
1699   return check_integer_overflow(val0.neg() ? -(longlong) res : res,
1700                                 !val0.neg());
1701 }
1702 
real_op()1703 double Item_func_mod::real_op()
1704 {
1705   DBUG_ASSERT(fixed == 1);
1706   double value= args[0]->val_real();
1707   double val2=  args[1]->val_real();
1708   if ((null_value= args[0]->null_value || args[1]->null_value))
1709     return 0.0; /* purecov: inspected */
1710   if (val2 == 0.0)
1711   {
1712     signal_divide_by_null();
1713     return 0.0;
1714   }
1715   return fmod(value,val2);
1716 }
1717 
1718 
decimal_op(my_decimal * decimal_value)1719 my_decimal *Item_func_mod::decimal_op(my_decimal *decimal_value)
1720 {
1721   VDec2_lazy val(args[0], args[1]);
1722   if ((null_value= val.has_null()))
1723     return 0;
1724   switch (my_decimal_mod(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, decimal_value,
1725                          val.m_a.ptr(), val.m_b.ptr())) {
1726   case E_DEC_TRUNCATED:
1727   case E_DEC_OK:
1728     return decimal_value;
1729   case E_DEC_DIV_ZERO:
1730     signal_divide_by_null();
1731     /* fall through */
1732   default:
1733     null_value= 1;
1734     return 0;
1735   }
1736 }
1737 
1738 
result_precision()1739 void Item_func_mod::result_precision()
1740 {
1741   unsigned_flag= args[0]->unsigned_flag;
1742   decimals= MY_MAX(args[0]->decimal_scale(), args[1]->decimal_scale());
1743   uint prec= MY_MAX(args[0]->decimal_precision(), args[1]->decimal_precision());
1744   fix_char_length(my_decimal_precision_to_length_no_truncation(prec, decimals,
1745                                                                unsigned_flag));
1746 }
1747 
1748 
fix_length_and_dec()1749 bool Item_func_mod::fix_length_and_dec()
1750 {
1751   DBUG_ENTER("Item_func_mod::fix_length_and_dec");
1752   DBUG_PRINT("info", ("name %s", func_name()));
1753   maybe_null= true; // division by zero
1754   const Type_aggregator *aggregator= &type_handler_data->m_type_aggregator_for_mod;
1755   DBUG_EXECUTE_IF("num_op", aggregator= &type_handler_data->m_type_aggregator_non_commutative_test;);
1756   DBUG_ASSERT(!aggregator->is_commutative());
1757   if (fix_type_handler(aggregator))
1758     DBUG_RETURN(TRUE);
1759   if (Item_func_mod::type_handler()->Item_func_mod_fix_length_and_dec(this))
1760     DBUG_RETURN(TRUE);
1761   DBUG_PRINT("info", ("Type: %s", type_handler()->name().ptr()));
1762   DBUG_RETURN(FALSE);
1763 }
1764 
calc_hash_for_unique(ulong & nr1,ulong & nr2,String * str)1765 static void calc_hash_for_unique(ulong &nr1, ulong &nr2, String *str)
1766 {
1767   CHARSET_INFO *cs;
1768   uchar l[4];
1769   int4store(l, str->length());
1770   cs= str->charset();
1771   cs->hash_sort(l, sizeof(l), &nr1, &nr2);
1772   cs= str->charset();
1773   cs->hash_sort((uchar *)str->ptr(), str->length(), &nr1, &nr2);
1774 }
1775 
val_int()1776 longlong  Item_func_hash::val_int()
1777 {
1778   DBUG_EXECUTE_IF("same_long_unique_hash", return 9;);
1779   unsigned_flag= true;
1780   ulong nr1= 1,nr2= 4;
1781   String * str;
1782   for(uint i= 0;i<arg_count;i++)
1783   {
1784     str = args[i]->val_str();
1785     if(args[i]->null_value)
1786     {
1787       null_value= 1;
1788       return 0;
1789     }
1790    calc_hash_for_unique(nr1, nr2, str);
1791   }
1792   null_value= 0;
1793   return   (longlong)nr1;
1794 }
1795 
1796 
fix_length_and_dec()1797 bool Item_func_hash::fix_length_and_dec()
1798 {
1799   decimals= 0;
1800   max_length= 8;
1801   return false;
1802 }
1803 
1804 
1805 
real_op()1806 double Item_func_neg::real_op()
1807 {
1808   double value= args[0]->val_real();
1809   null_value= args[0]->null_value;
1810   return -value;
1811 }
1812 
1813 
int_op()1814 longlong Item_func_neg::int_op()
1815 {
1816   longlong value= args[0]->val_int();
1817   if ((null_value= args[0]->null_value))
1818     return 0;
1819   if (args[0]->unsigned_flag &&
1820       (ulonglong) value > (ulonglong) LONGLONG_MAX + 1)
1821     return raise_integer_overflow();
1822 
1823   if (value == LONGLONG_MIN)
1824   {
1825     if (args[0]->unsigned_flag != unsigned_flag)
1826       /* negation of LONGLONG_MIN is LONGLONG_MIN. */
1827       return LONGLONG_MIN;
1828     else
1829       return raise_integer_overflow();
1830   }
1831 
1832   return check_integer_overflow(-value, !args[0]->unsigned_flag && value < 0);
1833 }
1834 
1835 
decimal_op(my_decimal * decimal_value)1836 my_decimal *Item_func_neg::decimal_op(my_decimal *decimal_value)
1837 {
1838   VDec value(args[0]);
1839   if (!(null_value= value.is_null()))
1840   {
1841     my_decimal2decimal(value.ptr(), decimal_value);
1842     my_decimal_neg(decimal_value);
1843     return decimal_value;
1844   }
1845   return 0;
1846 }
1847 
1848 
fix_length_and_dec_int()1849 void Item_func_neg::fix_length_and_dec_int()
1850 {
1851   max_length= args[0]->max_length + 1;
1852   set_handler(type_handler_long_or_longlong());
1853 
1854   /*
1855     If this is in integer context keep the context as integer if possible
1856     (This is how multiplication and other integer functions works)
1857     Use val() to get value as arg_type doesn't mean that item is
1858     Item_int or Item_float due to existence of Item_param.
1859   */
1860   if (args[0]->const_item())
1861   {
1862     longlong val= args[0]->val_int();
1863     if ((ulonglong) val >= (ulonglong) LONGLONG_MIN &&
1864         ((ulonglong) val != (ulonglong) LONGLONG_MIN ||
1865          !args[0]->is_of_type(CONST_ITEM, INT_RESULT)))
1866     {
1867       /*
1868         Ensure that result is converted to DECIMAL, as longlong can't hold
1869         the negated number
1870       */
1871       set_handler(&type_handler_newdecimal);
1872       DBUG_PRINT("info", ("Type changed: DECIMAL_RESULT"));
1873     }
1874   }
1875   unsigned_flag= false;
1876 }
1877 
1878 
fix_length_and_dec_double()1879 void Item_func_neg::fix_length_and_dec_double()
1880 {
1881   set_handler(&type_handler_double);
1882   decimals= args[0]->decimals; // Preserve NOT_FIXED_DEC
1883   max_length= args[0]->max_length + 1;
1884   // Limit length with something reasonable
1885   uint32 mlen= type_handler()->max_display_length(this);
1886   set_if_smaller(max_length, mlen);
1887   unsigned_flag= false;
1888 }
1889 
1890 
fix_length_and_dec_decimal()1891 void Item_func_neg::fix_length_and_dec_decimal()
1892 {
1893   set_handler(&type_handler_newdecimal);
1894   decimals= args[0]->decimal_scale(); // Do not preserve NOT_FIXED_DEC
1895   max_length= args[0]->max_length + 1;
1896   unsigned_flag= false;
1897 }
1898 
1899 
fix_length_and_dec()1900 bool Item_func_neg::fix_length_and_dec()
1901 {
1902   DBUG_ENTER("Item_func_neg::fix_length_and_dec");
1903   DBUG_PRINT("info", ("name %s", func_name()));
1904   if (args[0]->cast_to_int_type_handler()->
1905       Item_func_neg_fix_length_and_dec(this))
1906     DBUG_RETURN(TRUE);
1907   DBUG_PRINT("info", ("Type: %s", type_handler()->name().ptr()));
1908   DBUG_RETURN(FALSE);
1909 }
1910 
1911 
real_op()1912 double Item_func_abs::real_op()
1913 {
1914   double value= args[0]->val_real();
1915   null_value= args[0]->null_value;
1916   return fabs(value);
1917 }
1918 
1919 
int_op()1920 longlong Item_func_abs::int_op()
1921 {
1922   longlong value= args[0]->val_int();
1923   if ((null_value= args[0]->null_value))
1924     return 0;
1925   if (unsigned_flag)
1926     return value;
1927   /* -LONGLONG_MIN = LONGLONG_MAX + 1 => outside of signed longlong range */
1928   if (value == LONGLONG_MIN)
1929     return raise_integer_overflow();
1930   return (value >= 0) ? value : -value;
1931 }
1932 
1933 
decimal_op(my_decimal * decimal_value)1934 my_decimal *Item_func_abs::decimal_op(my_decimal *decimal_value)
1935 {
1936   VDec value(args[0]);
1937   if (!(null_value= value.is_null()))
1938   {
1939     my_decimal2decimal(value.ptr(), decimal_value);
1940     if (decimal_value->sign())
1941       my_decimal_neg(decimal_value);
1942     return decimal_value;
1943   }
1944   return 0;
1945 }
1946 
fix_length_and_dec_int()1947 void Item_func_abs::fix_length_and_dec_int()
1948 {
1949   max_length= args[0]->max_length;
1950   unsigned_flag= args[0]->unsigned_flag;
1951   set_handler(type_handler_long_or_longlong());
1952 }
1953 
1954 
fix_length_and_dec_double()1955 void Item_func_abs::fix_length_and_dec_double()
1956 {
1957   set_handler(&type_handler_double);
1958   decimals= args[0]->decimals; // Preserve NOT_FIXED_DEC
1959   max_length= float_length(decimals);
1960   unsigned_flag= args[0]->unsigned_flag;
1961 }
1962 
1963 
fix_length_and_dec_decimal()1964 void Item_func_abs::fix_length_and_dec_decimal()
1965 {
1966   set_handler(&type_handler_newdecimal);
1967   decimals= args[0]->decimal_scale(); // Do not preserve NOT_FIXED_DEC
1968   max_length= args[0]->max_length;
1969   unsigned_flag= args[0]->unsigned_flag;
1970 }
1971 
1972 
fix_length_and_dec()1973 bool Item_func_abs::fix_length_and_dec()
1974 {
1975   DBUG_ENTER("Item_func_abs::fix_length_and_dec");
1976   DBUG_PRINT("info", ("name %s", func_name()));
1977   if (args[0]->cast_to_int_type_handler()->
1978       Item_func_abs_fix_length_and_dec(this))
1979     DBUG_RETURN(TRUE);
1980   DBUG_PRINT("info", ("Type: %s", type_handler()->name().ptr()));
1981   DBUG_RETURN(FALSE);
1982 }
1983 
1984 
1985 /** Gateway to natural LOG function. */
val_real()1986 double Item_func_ln::val_real()
1987 {
1988   DBUG_ASSERT(fixed == 1);
1989   double value= args[0]->val_real();
1990   if ((null_value= args[0]->null_value))
1991     return 0.0;
1992   if (value <= 0.0)
1993   {
1994     signal_divide_by_null();
1995     return 0.0;
1996   }
1997   return log(value);
1998 }
1999 
2000 /**
2001   Extended but so slower LOG function.
2002 
2003   We have to check if all values are > zero and first one is not one
2004   as these are the cases then result is not a number.
2005 */
val_real()2006 double Item_func_log::val_real()
2007 {
2008   DBUG_ASSERT(fixed == 1);
2009   double value= args[0]->val_real();
2010   if ((null_value= args[0]->null_value))
2011     return 0.0;
2012   if (value <= 0.0)
2013   {
2014     signal_divide_by_null();
2015     return 0.0;
2016   }
2017   if (arg_count == 2)
2018   {
2019     double value2= args[1]->val_real();
2020     if ((null_value= args[1]->null_value))
2021       return 0.0;
2022     if (value2 <= 0.0 || value == 1.0)
2023     {
2024       signal_divide_by_null();
2025       return 0.0;
2026     }
2027     return log(value2) / log(value);
2028   }
2029   return log(value);
2030 }
2031 
val_real()2032 double Item_func_log2::val_real()
2033 {
2034   DBUG_ASSERT(fixed == 1);
2035   double value= args[0]->val_real();
2036 
2037   if ((null_value=args[0]->null_value))
2038     return 0.0;
2039   if (value <= 0.0)
2040   {
2041     signal_divide_by_null();
2042     return 0.0;
2043   }
2044   return log(value) / M_LN2;
2045 }
2046 
val_real()2047 double Item_func_log10::val_real()
2048 {
2049   DBUG_ASSERT(fixed == 1);
2050   double value= args[0]->val_real();
2051   if ((null_value= args[0]->null_value))
2052     return 0.0;
2053   if (value <= 0.0)
2054   {
2055     signal_divide_by_null();
2056     return 0.0;
2057   }
2058   return log10(value);
2059 }
2060 
val_real()2061 double Item_func_exp::val_real()
2062 {
2063   DBUG_ASSERT(fixed == 1);
2064   double value= args[0]->val_real();
2065   if ((null_value=args[0]->null_value))
2066     return 0.0; /* purecov: inspected */
2067   return check_float_overflow(exp(value));
2068 }
2069 
val_real()2070 double Item_func_sqrt::val_real()
2071 {
2072   DBUG_ASSERT(fixed == 1);
2073   double value= args[0]->val_real();
2074   if ((null_value=(args[0]->null_value || value < 0)))
2075     return 0.0; /* purecov: inspected */
2076   return sqrt(value);
2077 }
2078 
val_real()2079 double Item_func_pow::val_real()
2080 {
2081   DBUG_ASSERT(fixed == 1);
2082   double value= args[0]->val_real();
2083   double val2= args[1]->val_real();
2084   if ((null_value=(args[0]->null_value || args[1]->null_value)))
2085     return 0.0; /* purecov: inspected */
2086   return check_float_overflow(pow(value,val2));
2087 }
2088 
2089 // Trigonometric functions
2090 
val_real()2091 double Item_func_acos::val_real()
2092 {
2093   DBUG_ASSERT(fixed == 1);
2094   /* One can use this to defer SELECT processing. */
2095   DEBUG_SYNC(current_thd, "before_acos_function");
2096   // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
2097   volatile double value= args[0]->val_real();
2098   if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
2099     return 0.0;
2100   return acos(value);
2101 }
2102 
val_real()2103 double Item_func_asin::val_real()
2104 {
2105   DBUG_ASSERT(fixed == 1);
2106   // the volatile's for BUG #2338 to calm optimizer down (because of gcc's bug)
2107   volatile double value= args[0]->val_real();
2108   if ((null_value=(args[0]->null_value || (value < -1.0 || value > 1.0))))
2109     return 0.0;
2110   return asin(value);
2111 }
2112 
val_real()2113 double Item_func_atan::val_real()
2114 {
2115   DBUG_ASSERT(fixed == 1);
2116   double value= args[0]->val_real();
2117   if ((null_value=args[0]->null_value))
2118     return 0.0;
2119   if (arg_count == 2)
2120   {
2121     double val2= args[1]->val_real();
2122     if ((null_value=args[1]->null_value))
2123       return 0.0;
2124     return check_float_overflow(atan2(value,val2));
2125   }
2126   return atan(value);
2127 }
2128 
val_real()2129 double Item_func_cos::val_real()
2130 {
2131   DBUG_ASSERT(fixed == 1);
2132   double value= args[0]->val_real();
2133   if ((null_value=args[0]->null_value))
2134     return 0.0;
2135   return cos(value);
2136 }
2137 
val_real()2138 double Item_func_sin::val_real()
2139 {
2140   DBUG_ASSERT(fixed == 1);
2141   double value= args[0]->val_real();
2142   if ((null_value=args[0]->null_value))
2143     return 0.0;
2144   return sin(value);
2145 }
2146 
val_real()2147 double Item_func_tan::val_real()
2148 {
2149   DBUG_ASSERT(fixed == 1);
2150   double value= args[0]->val_real();
2151   if ((null_value=args[0]->null_value))
2152     return 0.0;
2153   return check_float_overflow(tan(value));
2154 }
2155 
2156 
val_real()2157 double Item_func_cot::val_real()
2158 {
2159   DBUG_ASSERT(fixed == 1);
2160   double value= args[0]->val_real();
2161   if ((null_value=args[0]->null_value))
2162     return 0.0;
2163   return check_float_overflow(1.0 / tan(value));
2164 }
2165 
2166 
2167 // Shift-functions, same as << and >> in C/C++
2168 
2169 
2170 class Func_handler_shift_left_int_to_ulonglong:
2171         public Item_handled_func::Handler_ulonglong
2172 {
2173 public:
to_longlong_null(Item_handled_func * item) const2174   Longlong_null to_longlong_null(Item_handled_func *item) const
2175   {
2176     DBUG_ASSERT(item->is_fixed());
2177     return item->arguments()[0]->to_longlong_null() <<
2178            item->arguments()[1]->to_longlong_null();
2179   }
2180 };
2181 
2182 
2183 class Func_handler_shift_left_decimal_to_ulonglong:
2184         public Item_handled_func::Handler_ulonglong
2185 {
2186 public:
to_longlong_null(Item_handled_func * item) const2187   Longlong_null to_longlong_null(Item_handled_func *item) const
2188   {
2189     DBUG_ASSERT(item->is_fixed());
2190     return VDec(item->arguments()[0]).to_xlonglong_null() <<
2191            item->arguments()[1]->to_longlong_null();
2192   }
2193 };
2194 
2195 
fix_length_and_dec()2196 bool Item_func_shift_left::fix_length_and_dec()
2197 {
2198   static Func_handler_shift_left_int_to_ulonglong ha_int_to_ull;
2199   static Func_handler_shift_left_decimal_to_ulonglong ha_dec_to_ull;
2200   return fix_length_and_dec_op1_std(&ha_int_to_ull, &ha_dec_to_ull);
2201 }
2202 
2203 
2204 class Func_handler_shift_right_int_to_ulonglong:
2205         public Item_handled_func::Handler_ulonglong
2206 {
2207 public:
to_longlong_null(Item_handled_func * item) const2208   Longlong_null to_longlong_null(Item_handled_func *item) const
2209   {
2210     DBUG_ASSERT(item->fixed == 1);
2211     return item->arguments()[0]->to_longlong_null() >>
2212            item->arguments()[1]->to_longlong_null();
2213   }
2214 };
2215 
2216 
2217 class Func_handler_shift_right_decimal_to_ulonglong:
2218         public Item_handled_func::Handler_ulonglong
2219 {
2220 public:
to_longlong_null(Item_handled_func * item) const2221   Longlong_null to_longlong_null(Item_handled_func *item) const
2222   {
2223     DBUG_ASSERT(item->is_fixed());
2224     return VDec(item->arguments()[0]).to_xlonglong_null() >>
2225            item->arguments()[1]->to_longlong_null();
2226   }
2227 };
2228 
2229 
fix_length_and_dec()2230 bool Item_func_shift_right::fix_length_and_dec()
2231 {
2232   static Func_handler_shift_right_int_to_ulonglong ha_int_to_ull;
2233   static Func_handler_shift_right_decimal_to_ulonglong ha_dec_to_ull;
2234   return fix_length_and_dec_op1_std(&ha_int_to_ull, &ha_dec_to_ull);
2235 }
2236 
2237 
2238 class Func_handler_bit_neg_int_to_ulonglong:
2239         public Item_handled_func::Handler_ulonglong
2240 {
2241 public:
to_longlong_null(Item_handled_func * item) const2242   Longlong_null to_longlong_null(Item_handled_func *item) const
2243   {
2244     DBUG_ASSERT(item->is_fixed());
2245     return ~ item->arguments()[0]->to_longlong_null();
2246   }
2247 };
2248 
2249 
2250 class Func_handler_bit_neg_decimal_to_ulonglong:
2251         public Item_handled_func::Handler_ulonglong
2252 {
2253 public:
to_longlong_null(Item_handled_func * item) const2254   Longlong_null to_longlong_null(Item_handled_func *item) const
2255   {
2256     DBUG_ASSERT(item->is_fixed());
2257     return ~ VDec(item->arguments()[0]).to_xlonglong_null();
2258   }
2259 };
2260 
2261 
fix_length_and_dec()2262 bool Item_func_bit_neg::fix_length_and_dec()
2263 {
2264   static Func_handler_bit_neg_int_to_ulonglong ha_int_to_ull;
2265   static Func_handler_bit_neg_decimal_to_ulonglong ha_dec_to_ull;
2266   return fix_length_and_dec_op1_std(&ha_int_to_ull, &ha_dec_to_ull);
2267 }
2268 
2269 
2270 // Conversion functions
2271 
fix_length_and_dec_int_or_decimal()2272 void Item_func_int_val::fix_length_and_dec_int_or_decimal()
2273 {
2274   DBUG_ASSERT(args[0]->cmp_type() == DECIMAL_RESULT);
2275   DBUG_ASSERT(args[0]->max_length <= DECIMAL_MAX_STR_LENGTH);
2276   /*
2277     FLOOR() for negative numbers can increase length:   floor(-9.9) -> -10
2278     CEILING() for positive numbers can increase length:  ceil(9.9)  -> 10
2279   */
2280   decimal_round_mode mode= round_mode();
2281   uint length_increase= args[0]->decimals > 0 &&
2282                         (mode == CEILING ||
2283                          (mode == FLOOR && !args[0]->unsigned_flag)) ? 1 : 0;
2284   uint precision= args[0]->decimal_int_part() + length_increase;
2285   set_if_bigger(precision, 1);
2286 
2287   /*
2288     The BIGINT data type can store:
2289     UNSIGNED BIGINT: 0..18446744073709551615                     - up to 19 digits
2290       SIGNED BIGINT:   -9223372036854775808..9223372036854775807 - up to 18 digits
2291 
2292     The INT data type can store:
2293         UNSIGNED INT:  0..4294967295          - up to 9 digits
2294           SIGNED INT: -2147483648..2147483647 - up to 9 digits
2295   */
2296   if (precision > 18)
2297   {
2298     unsigned_flag= args[0]->unsigned_flag;
2299     fix_char_length(
2300       my_decimal_precision_to_length_no_truncation(precision, 0,
2301                                                    unsigned_flag));
2302     set_handler(&type_handler_newdecimal);
2303   }
2304   else
2305   {
2306     uint sign_length= (unsigned_flag= args[0]->unsigned_flag) ? 0 : 1;
2307     fix_char_length(precision + sign_length);
2308     if (precision > 9)
2309     {
2310       if (unsigned_flag)
2311         set_handler(&type_handler_ulonglong);
2312       else
2313         set_handler(&type_handler_slonglong);
2314     }
2315     else
2316     {
2317       if (unsigned_flag)
2318         set_handler(&type_handler_ulong);
2319       else
2320         set_handler(&type_handler_slong);
2321     }
2322   }
2323 }
2324 
2325 
fix_length_and_dec_double()2326 void Item_func_int_val::fix_length_and_dec_double()
2327 {
2328   set_handler(&type_handler_double);
2329   max_length= float_length(0);
2330   decimals= 0;
2331 }
2332 
2333 
fix_length_and_dec()2334 bool Item_func_int_val::fix_length_and_dec()
2335 {
2336   DBUG_ENTER("Item_func_int_val::fix_length_and_dec");
2337   DBUG_PRINT("info", ("name %s", func_name()));
2338   /*
2339     We don't want to translate ENUM/SET to CHAR here.
2340     So let's call real_type_handler(), not type_handler().
2341   */
2342   if (args[0]->real_type_handler()->Item_func_int_val_fix_length_and_dec(this))
2343     DBUG_RETURN(TRUE);
2344   DBUG_PRINT("info", ("Type: %s", real_type_handler()->name().ptr()));
2345   DBUG_RETURN(FALSE);
2346 }
2347 
2348 
int_op()2349 longlong Item_func_ceiling::int_op()
2350 {
2351   switch (args[0]->result_type()) {
2352   case STRING_RESULT: // hex hybrid
2353   case INT_RESULT:
2354     return val_int_from_item(args[0]);
2355   case DECIMAL_RESULT:
2356     return VDec_op(this).to_longlong(unsigned_flag);
2357   default:
2358     break;
2359   }
2360   return (longlong) Item_func_ceiling::real_op();
2361 }
2362 
2363 
real_op()2364 double Item_func_ceiling::real_op()
2365 {
2366   /*
2367     the volatile's for BUG #3051 to calm optimizer down (because of gcc's
2368     bug)
2369   */
2370   volatile double value= args[0]->val_real();
2371   null_value= args[0]->null_value;
2372   return ceil(value);
2373 }
2374 
2375 
decimal_op(my_decimal * decimal_value)2376 my_decimal *Item_func_ceiling::decimal_op(my_decimal *decimal_value)
2377 {
2378   VDec value(args[0]);
2379   if (!(null_value= (value.is_null() ||
2380                      value.round_to(decimal_value, 0, CEILING) > 1)))
2381     return decimal_value;
2382   return 0;
2383 }
2384 
2385 
date_op(THD * thd,MYSQL_TIME * to,date_mode_t fuzzydate)2386 bool Item_func_ceiling::date_op(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate)
2387 {
2388   Datetime::Options opt(thd, TIME_FRAC_TRUNCATE);
2389   Datetime *tm= new (to) Datetime(thd, args[0], opt);
2390   tm->ceiling(thd);
2391   null_value= !tm->is_valid_datetime();
2392   DBUG_ASSERT(maybe_null || !null_value);
2393   return null_value;
2394 }
2395 
2396 
time_op(THD * thd,MYSQL_TIME * to)2397 bool Item_func_ceiling::time_op(THD *thd, MYSQL_TIME *to)
2398 {
2399   static const Time::Options_for_round opt;
2400   Time *tm= new (to) Time(thd, args[0], opt);
2401   tm->ceiling();
2402   null_value= !tm->is_valid_time();
2403   DBUG_ASSERT(maybe_null || !null_value);
2404   return null_value;
2405 }
2406 
2407 
int_op()2408 longlong Item_func_floor::int_op()
2409 {
2410   switch (args[0]->result_type()) {
2411   case STRING_RESULT: // hex hybrid
2412   case INT_RESULT:
2413     return val_int_from_item(args[0]);
2414   case DECIMAL_RESULT:
2415   {
2416     my_decimal dec_buf, *dec;
2417     return (!(dec= Item_func_floor::decimal_op(&dec_buf))) ? 0 :
2418            dec->to_longlong(unsigned_flag);
2419   }
2420   default:
2421     break;
2422   }
2423   return (longlong) Item_func_floor::real_op();
2424 }
2425 
2426 
real_op()2427 double Item_func_floor::real_op()
2428 {
2429   /*
2430     the volatile's for BUG #3051 to calm optimizer down (because of gcc's
2431     bug)
2432   */
2433   volatile double value= args[0]->val_real();
2434   null_value= args[0]->null_value;
2435   return floor(value);
2436 }
2437 
2438 
decimal_op(my_decimal * decimal_value)2439 my_decimal *Item_func_floor::decimal_op(my_decimal *decimal_value)
2440 {
2441   VDec value(args[0]);
2442   if (!(null_value= (value.is_null() ||
2443                      value.round_to(decimal_value, 0, FLOOR) > 1)))
2444     return decimal_value;
2445   return 0;
2446 }
2447 
2448 
date_op(THD * thd,MYSQL_TIME * to,date_mode_t fuzzydate)2449 bool Item_func_floor::date_op(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate)
2450 {
2451   // DATETIME is not negative, so FLOOR means just truncation
2452   Datetime::Options opt(thd, TIME_FRAC_TRUNCATE);
2453   Datetime *tm= new (to) Datetime(thd, args[0], opt, 0);
2454   null_value= !tm->is_valid_datetime();
2455   DBUG_ASSERT(maybe_null || !null_value);
2456   return null_value;
2457 }
2458 
2459 
time_op(THD * thd,MYSQL_TIME * to)2460 bool Item_func_floor::time_op(THD *thd, MYSQL_TIME *to)
2461 {
2462   static const Time::Options_for_round opt;
2463   Time *tm= new (to) Time(thd, args[0], opt);
2464   tm->floor();
2465   null_value= !tm->is_valid_time();
2466   DBUG_ASSERT(maybe_null || !null_value);
2467   return null_value;
2468 }
2469 
2470 
fix_length_and_dec_decimal(uint decimals_to_set)2471 void Item_func_round::fix_length_and_dec_decimal(uint decimals_to_set)
2472 {
2473   int decimals_delta= args[0]->decimals - decimals_to_set;
2474   int length_increase= (decimals_delta <= 0 || truncate) ? 0 : 1;
2475   int precision= args[0]->decimal_precision() + length_increase -
2476                                                 decimals_delta;
2477   DBUG_ASSERT(decimals_to_set <= DECIMAL_MAX_SCALE);
2478   set_handler(&type_handler_newdecimal);
2479   unsigned_flag= args[0]->unsigned_flag;
2480   decimals= decimals_to_set;
2481   if (!precision)
2482     precision= 1; // DECIMAL(0,0) -> DECIMAL(1,0)
2483   max_length= my_decimal_precision_to_length_no_truncation(precision,
2484                                                            decimals,
2485                                                            unsigned_flag);
2486 }
2487 
fix_length_and_dec_double(uint decimals_to_set)2488 void Item_func_round::fix_length_and_dec_double(uint decimals_to_set)
2489 {
2490   set_handler(&type_handler_double);
2491   unsigned_flag= args[0]->unsigned_flag;
2492   decimals= decimals_to_set;
2493   max_length= float_length(decimals_to_set);
2494 }
2495 
2496 
fix_arg_decimal()2497 void Item_func_round::fix_arg_decimal()
2498 {
2499   if (args[1]->const_item())
2500   {
2501     Longlong_hybrid dec= args[1]->to_longlong_hybrid();
2502     if (args[1]->null_value)
2503       fix_length_and_dec_double(NOT_FIXED_DEC);
2504     else
2505       fix_length_and_dec_decimal(dec.to_uint(DECIMAL_MAX_SCALE));
2506   }
2507   else
2508   {
2509     set_handler(&type_handler_newdecimal);
2510     unsigned_flag= args[0]->unsigned_flag;
2511     decimals= args[0]->decimals;
2512     max_length= float_length(args[0]->decimals) + 1;
2513   }
2514 }
2515 
2516 
fix_arg_double()2517 void Item_func_round::fix_arg_double()
2518 {
2519   if (args[1]->const_item())
2520   {
2521     Longlong_hybrid dec= args[1]->to_longlong_hybrid();
2522     fix_length_and_dec_double(args[1]->null_value ? NOT_FIXED_DEC :
2523                               dec.to_uint(NOT_FIXED_DEC));
2524   }
2525   else
2526     fix_length_and_dec_double(args[0]->decimals);
2527 }
2528 
2529 
fix_arg_temporal(const Type_handler * h,uint int_part_length)2530 void Item_func_round::fix_arg_temporal(const Type_handler *h,
2531                                        uint int_part_length)
2532 {
2533   set_handler(h);
2534   if (args[1]->const_item() && !args[1]->is_expensive())
2535   {
2536     Longlong_hybrid_null dec= args[1]->to_longlong_hybrid_null();
2537     fix_attributes_temporal(int_part_length,
2538                             dec.is_null() ? args[0]->decimals :
2539                             dec.to_uint(TIME_SECOND_PART_DIGITS));
2540   }
2541   else
2542     fix_attributes_temporal(int_part_length, args[0]->decimals);
2543 }
2544 
2545 
fix_arg_time()2546 void Item_func_round::fix_arg_time()
2547 {
2548   fix_arg_temporal(&type_handler_time2, MIN_TIME_WIDTH);
2549 }
2550 
2551 
fix_arg_datetime()2552 void Item_func_round::fix_arg_datetime()
2553 {
2554   /*
2555     Day increment operations are not supported for '0000-00-00',
2556     see get_date_from_daynr() for details. Therefore, expressions like
2557       ROUND('0000-00-00 23:59:59.999999')
2558     return NULL.
2559   */
2560   if (!truncate)
2561     maybe_null= true;
2562   fix_arg_temporal(&type_handler_datetime2, MAX_DATETIME_WIDTH);
2563 }
2564 
2565 
test_if_length_can_increase()2566 bool Item_func_round::test_if_length_can_increase()
2567 {
2568   if (truncate)
2569     return false;
2570   if (args[1]->const_item() && !args[1]->is_expensive())
2571   {
2572     // Length can increase in some cases: e.g. ROUND(9,-1) -> 10.
2573     Longlong_hybrid val1= args[1]->to_longlong_hybrid();
2574     return !args[1]->null_value && val1.neg();
2575   }
2576   return true; // ROUND(x,n), where n is not a constant.
2577 }
2578 
2579 
2580 /**
2581   Calculate data type and attributes for INT-alike input.
2582 
2583   @param [IN] preferred - The preferred data type handler for simple cases
2584                           such as ROUND(x) and TRUNCATE(x,0), when the input
2585                           is short enough to fit into an integer type
2586                           (without extending to DECIMAL).
2587                           - If `preferred` is not NULL, then the code tries
2588                             to preserve the given data type handler and
2589                             the data type attributes `preferred_attrs`.
2590                           - If `preferred` is NULL, then the code fully
2591                             calculates attributes using
2592                             args[0]->decimal_precision() and chooses between
2593                             INT and BIGINT, depending on attributes.
2594   @param [IN] preferred_attrs - The preferred data type attributes for
2595                                 simple cases.
2596 */
fix_arg_int(const Type_handler * preferred,const Type_std_attributes * preferred_attrs,bool use_decimal_on_length_increase)2597 void Item_func_round::fix_arg_int(const Type_handler *preferred,
2598                                   const Type_std_attributes *preferred_attrs,
2599                                   bool use_decimal_on_length_increase)
2600 {
2601   DBUG_ASSERT(args[0]->decimals == 0);
2602 
2603   Type_std_attributes::set(preferred_attrs);
2604   if (!test_if_length_can_increase())
2605   {
2606     // Preserve the exact data type and attributes
2607     set_handler(preferred);
2608   }
2609   else
2610   {
2611     max_length++;
2612     if (use_decimal_on_length_increase)
2613       set_handler(&type_handler_newdecimal);
2614     else
2615       set_handler(type_handler_long_or_longlong());
2616   }
2617 }
2618 
2619 
fix_arg_hex_hybrid()2620 void Item_func_round::fix_arg_hex_hybrid()
2621 {
2622   DBUG_ASSERT(args[0]->decimals == 0);
2623   DBUG_ASSERT(args[0]->decimal_precision() < DECIMAL_LONGLONG_DIGITS);
2624   DBUG_ASSERT(args[0]->unsigned_flag); // no needs to add sign length
2625   bool length_can_increase= test_if_length_can_increase();
2626   max_length= args[0]->decimal_precision() + MY_TEST(length_can_increase);
2627   unsigned_flag= true;
2628   decimals= 0;
2629   if (length_can_increase && args[0]->max_length >= 8)
2630     set_handler(&type_handler_newdecimal);
2631   else
2632     set_handler(type_handler_long_or_longlong());
2633 }
2634 
2635 
my_double_round(double value,longlong dec,bool dec_unsigned,bool truncate)2636 double my_double_round(double value, longlong dec, bool dec_unsigned,
2637                        bool truncate)
2638 {
2639   double tmp;
2640   bool dec_negative= (dec < 0) && !dec_unsigned;
2641   ulonglong abs_dec= dec_negative ? -dec : dec;
2642   /*
2643     tmp2 is here to avoid return the value with 80 bit precision
2644     This will fix that the test round(0.1,1) = round(0.1,1) is true
2645     Tagging with volatile is no guarantee, it may still be optimized away...
2646   */
2647   volatile double tmp2;
2648 
2649   tmp=(abs_dec < array_elements(log_10) ?
2650        log_10[abs_dec] : pow(10.0,(double) abs_dec));
2651 
2652   // Pre-compute these, to avoid optimizing away e.g. 'floor(v/tmp) * tmp'.
2653   volatile double value_div_tmp= value / tmp;
2654   volatile double value_mul_tmp= value * tmp;
2655 
2656   if (!dec_negative && std::isinf(tmp)) // "dec" is too large positive number
2657     return value;
2658 
2659   if (dec_negative && std::isinf(tmp))
2660     tmp2= 0.0;
2661   else if (!dec_negative && std::isinf(value_mul_tmp))
2662     tmp2= value;
2663   else if (truncate)
2664   {
2665     if (value >= 0.0)
2666       tmp2= dec < 0 ? floor(value_div_tmp) * tmp : floor(value_mul_tmp) / tmp;
2667     else
2668       tmp2= dec < 0 ? ceil(value_div_tmp) * tmp : ceil(value_mul_tmp) / tmp;
2669   }
2670   else
2671     tmp2=dec < 0 ? rint(value_div_tmp) * tmp : rint(value_mul_tmp) / tmp;
2672 
2673   return tmp2;
2674 }
2675 
2676 
real_op()2677 double Item_func_round::real_op()
2678 {
2679   double value= args[0]->val_real();
2680 
2681   if (!(null_value= args[0]->null_value))
2682   {
2683     longlong dec= args[1]->val_int();
2684     if (!(null_value= args[1]->null_value))
2685       return my_double_round(value, dec, args[1]->unsigned_flag, truncate);
2686   }
2687   return 0.0;
2688 }
2689 
2690 /*
2691   Rounds a given value to a power of 10 specified as the 'to' argument,
2692   avoiding overflows when the value is close to the ulonglong range boundary.
2693 */
2694 
my_unsigned_round(ulonglong value,ulonglong to)2695 static inline ulonglong my_unsigned_round(ulonglong value, ulonglong to)
2696 {
2697   ulonglong tmp= value / to * to;
2698   return (value - tmp < (to >> 1)) ? tmp : tmp + to;
2699 }
2700 
2701 
int_op()2702 longlong Item_func_round::int_op()
2703 {
2704   longlong value= args[0]->val_int();
2705   longlong dec= args[1]->val_int();
2706   decimals= 0;
2707   ulonglong abs_dec;
2708   if ((null_value= args[0]->null_value || args[1]->null_value))
2709     return 0;
2710   if ((dec >= 0) || args[1]->unsigned_flag)
2711     return value; // integer have not digits after point
2712 
2713   abs_dec= -dec;
2714   longlong tmp;
2715 
2716   if(abs_dec >= array_elements(log_10_int))
2717     return 0;
2718 
2719   tmp= log_10_int[abs_dec];
2720 
2721   if (truncate)
2722     value= (unsigned_flag) ?
2723       ((ulonglong) value / tmp) * tmp : (value / tmp) * tmp;
2724   else
2725     value= (unsigned_flag || value >= 0) ?
2726       my_unsigned_round((ulonglong) value, tmp) :
2727       -(longlong) my_unsigned_round((ulonglong) -value, tmp);
2728   return value;
2729 }
2730 
2731 
decimal_op(my_decimal * decimal_value)2732 my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value)
2733 {
2734   VDec value(args[0]);
2735   longlong dec= args[1]->val_int();
2736   if (dec >= 0 || args[1]->unsigned_flag)
2737     dec= MY_MIN((ulonglong) dec, decimals);
2738   else if (dec < INT_MIN)
2739     dec= INT_MIN;
2740 
2741   if (!(null_value= (value.is_null() || args[1]->null_value ||
2742                      value.round_to(decimal_value, (uint) dec,
2743                                     truncate ? TRUNCATE : HALF_UP) > 1)))
2744     return decimal_value;
2745   return 0;
2746 }
2747 
2748 
time_op(THD * thd,MYSQL_TIME * to)2749 bool Item_func_round::time_op(THD *thd, MYSQL_TIME *to)
2750 {
2751   DBUG_ASSERT(args[0]->type_handler()->mysql_timestamp_type() ==
2752               MYSQL_TIMESTAMP_TIME);
2753   Time::Options_for_round opt(truncate ? TIME_FRAC_TRUNCATE : TIME_FRAC_ROUND);
2754   Longlong_hybrid_null dec= args[1]->to_longlong_hybrid_null();
2755   Time *tm= new (to) Time(thd, args[0], opt,
2756                           dec.to_uint(TIME_SECOND_PART_DIGITS));
2757   null_value= !tm->is_valid_time() || dec.is_null();
2758   DBUG_ASSERT(maybe_null || !null_value);
2759   return null_value;
2760 }
2761 
2762 
date_op(THD * thd,MYSQL_TIME * to,date_mode_t fuzzydate)2763 bool Item_func_round::date_op(THD *thd, MYSQL_TIME *to, date_mode_t fuzzydate)
2764 {
2765   DBUG_ASSERT(args[0]->type_handler()->mysql_timestamp_type() ==
2766               MYSQL_TIMESTAMP_DATETIME);
2767   Datetime::Options opt(thd, truncate ? TIME_FRAC_TRUNCATE : TIME_FRAC_ROUND);
2768   Longlong_hybrid_null dec= args[1]->to_longlong_hybrid_null();
2769   Datetime *tm= new (to) Datetime(thd, args[0], opt,
2770                                   dec.to_uint(TIME_SECOND_PART_DIGITS));
2771   null_value= !tm->is_valid_datetime() || dec.is_null();
2772   DBUG_ASSERT(maybe_null || !null_value);
2773   return null_value;
2774 }
2775 
2776 
seed_random(Item * arg)2777 void Item_func_rand::seed_random(Item *arg)
2778 {
2779   /*
2780     TODO: do not do reinit 'rand' for every execute of PS/SP if
2781     args[0] is a constant.
2782   */
2783   uint32 tmp= (uint32) arg->val_int();
2784 #ifdef WITH_WSREP
2785   if (WSREP_ON)
2786   {
2787     THD *thd= current_thd;
2788     if (WSREP(thd))
2789     {
2790       if (wsrep_thd_is_applying(thd))
2791         tmp= thd->wsrep_rand;
2792       else
2793         thd->wsrep_rand= tmp;
2794     }
2795   }
2796 #endif /* WITH_WSREP */
2797 
2798   my_rnd_init(rand, (uint32) (tmp*0x10001L+55555555L),
2799              (uint32) (tmp*0x10000001L));
2800 }
2801 
2802 
fix_fields(THD * thd,Item ** ref)2803 bool Item_func_rand::fix_fields(THD *thd,Item **ref)
2804 {
2805   if (Item_real_func::fix_fields(thd, ref))
2806     return TRUE;
2807   used_tables_cache|= RAND_TABLE_BIT;
2808   if (arg_count)
2809   {					// Only use argument once in query
2810     /*
2811       Allocate rand structure once: we must use thd->stmt_arena
2812       to create rand in proper mem_root if it's a prepared statement or
2813       stored procedure.
2814 
2815       No need to send a Rand log event if seed was given eg: RAND(seed),
2816       as it will be replicated in the query as such.
2817     */
2818     if (!rand && !(rand= (struct my_rnd_struct*)
2819                    thd->stmt_arena->alloc(sizeof(*rand))))
2820       return TRUE;
2821   }
2822   else
2823   {
2824     /*
2825       Save the seed only the first time RAND() is used in the query
2826       Once events are forwarded rather than recreated,
2827       the following can be skipped if inside the slave thread
2828     */
2829     if (!thd->rand_used)
2830     {
2831       thd->rand_used= 1;
2832       thd->rand_saved_seed1= thd->rand.seed1;
2833       thd->rand_saved_seed2= thd->rand.seed2;
2834     }
2835     rand= &thd->rand;
2836   }
2837   return FALSE;
2838 }
2839 
update_used_tables()2840 void Item_func_rand::update_used_tables()
2841 {
2842   Item_real_func::update_used_tables();
2843   used_tables_cache|= RAND_TABLE_BIT;
2844 }
2845 
2846 
val_real()2847 double Item_func_rand::val_real()
2848 {
2849   DBUG_ASSERT(fixed == 1);
2850   if (arg_count)
2851   {
2852     if (!args[0]->const_item())
2853       seed_random(args[0]);
2854     else if (first_eval)
2855     {
2856       /*
2857         Constantness of args[0] may be set during JOIN::optimize(), if arg[0]
2858         is a field item of "constant" table. Thus, we have to evaluate
2859         seed_random() for constant arg there but not at the fix_fields method.
2860       */
2861       first_eval= FALSE;
2862       seed_random(args[0]);
2863     }
2864   }
2865   return my_rnd(rand);
2866 }
2867 
val_int()2868 longlong Item_func_sign::val_int()
2869 {
2870   DBUG_ASSERT(fixed == 1);
2871   double value= args[0]->val_real();
2872   null_value=args[0]->null_value;
2873   return value < 0.0 ? -1 : (value > 0 ? 1 : 0);
2874 }
2875 
2876 
val_real()2877 double Item_func_units::val_real()
2878 {
2879   DBUG_ASSERT(fixed == 1);
2880   double value= args[0]->val_real();
2881   if ((null_value=args[0]->null_value))
2882     return 0;
2883   return check_float_overflow(value * mul + add);
2884 }
2885 
2886 
fix_attributes(Item ** items,uint nitems)2887 bool Item_func_min_max::fix_attributes(Item **items, uint nitems)
2888 {
2889   bool rc= Item_func_min_max::type_handler()->
2890              Item_func_min_max_fix_attributes(current_thd, this, items, nitems);
2891   DBUG_ASSERT(!rc || current_thd->is_error());
2892   return rc;
2893 }
2894 
2895 
2896 /*
2897   Compare item arguments using DATETIME/DATE/TIME representation.
2898 
2899   DESCRIPTION
2900     Compare item arguments as DATETIME values and return the index of the
2901     least/greatest argument in the arguments array.
2902     The correct DATE/DATETIME value of the found argument is
2903     stored to the value pointer, if latter is provided.
2904 
2905   RETURN
2906    1	If one of arguments is NULL or there was a execution error
2907    0    Otherwise
2908 */
2909 
get_date_native(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)2910 bool Item_func_min_max::get_date_native(THD *thd, MYSQL_TIME *ltime,
2911                                         date_mode_t fuzzydate)
2912 {
2913   longlong UNINIT_VAR(min_max);
2914   DBUG_ASSERT(fixed == 1);
2915 
2916   for (uint i=0; i < arg_count ; i++)
2917   {
2918     longlong res= args[i]->val_datetime_packed(thd);
2919 
2920     /* Check if we need to stop (because of error or KILL) and stop the loop */
2921     if (unlikely(args[i]->null_value))
2922       return (null_value= 1);
2923 
2924     if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0)
2925       min_max= res;
2926   }
2927   unpack_time(min_max, ltime, mysql_timestamp_type());
2928 
2929   if (!(fuzzydate & TIME_TIME_ONLY) &&
2930       unlikely((null_value= check_date_with_warn(thd, ltime, fuzzydate,
2931                                          MYSQL_TIMESTAMP_ERROR))))
2932     return true;
2933 
2934   return (null_value= 0);
2935 }
2936 
2937 
get_time_native(THD * thd,MYSQL_TIME * ltime)2938 bool Item_func_min_max::get_time_native(THD *thd, MYSQL_TIME *ltime)
2939 {
2940   DBUG_ASSERT(fixed == 1);
2941 
2942   Time value(thd, args[0], Time::Options(thd), decimals);
2943   if (!value.is_valid_time())
2944     return (null_value= true);
2945 
2946   for (uint i= 1; i < arg_count ; i++)
2947   {
2948     Time tmp(thd, args[i], Time::Options(thd), decimals);
2949     if (!tmp.is_valid_time())
2950       return (null_value= true);
2951 
2952     int cmp= value.cmp(&tmp);
2953     if ((cmp_sign < 0 ? cmp : -cmp) < 0)
2954       value= tmp;
2955   }
2956   value.copy_to_mysql_time(ltime);
2957   return (null_value= 0);
2958 }
2959 
2960 
val_str_native(String * str)2961 String *Item_func_min_max::val_str_native(String *str)
2962 {
2963   String *UNINIT_VAR(res);
2964   for (uint i=0; i < arg_count ; i++)
2965   {
2966     if (i == 0)
2967       res=args[i]->val_str(str);
2968     else
2969     {
2970       String *res2;
2971       res2= args[i]->val_str(res == str ? &tmp_value : str);
2972       if (res2)
2973       {
2974         int cmp= sortcmp(res,res2,collation.collation);
2975         if ((cmp_sign < 0 ? cmp : -cmp) < 0)
2976           res=res2;
2977       }
2978     }
2979     if ((null_value= args[i]->null_value))
2980       return 0;
2981   }
2982   res->set_charset(collation.collation);
2983   return res;
2984 }
2985 
2986 
val_real_native()2987 double Item_func_min_max::val_real_native()
2988 {
2989   double value=0.0;
2990   for (uint i=0; i < arg_count ; i++)
2991   {
2992     if (i == 0)
2993       value= args[i]->val_real();
2994     else
2995     {
2996       double tmp= args[i]->val_real();
2997       if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
2998 	value=tmp;
2999     }
3000     if ((null_value= args[i]->null_value))
3001       break;
3002   }
3003   return value;
3004 }
3005 
3006 
val_int_native()3007 longlong Item_func_min_max::val_int_native()
3008 {
3009   DBUG_ASSERT(fixed == 1);
3010   longlong value=0;
3011   for (uint i=0; i < arg_count ; i++)
3012   {
3013     if (i == 0)
3014       value=args[i]->val_int();
3015     else
3016     {
3017       longlong tmp=args[i]->val_int();
3018       if (!args[i]->null_value && (tmp < value ? cmp_sign : -cmp_sign) > 0)
3019 	value=tmp;
3020     }
3021     if ((null_value= args[i]->null_value))
3022       break;
3023   }
3024   return value;
3025 }
3026 
3027 
val_decimal_native(my_decimal * dec)3028 my_decimal *Item_func_min_max::val_decimal_native(my_decimal *dec)
3029 {
3030   DBUG_ASSERT(fixed == 1);
3031   my_decimal tmp_buf, *tmp, *UNINIT_VAR(res);
3032 
3033   for (uint i=0; i < arg_count ; i++)
3034   {
3035     if (i == 0)
3036       res= args[i]->val_decimal(dec);
3037     else
3038     {
3039       tmp= args[i]->val_decimal(&tmp_buf);      // Zero if NULL
3040       if (tmp && (my_decimal_cmp(tmp, res) * cmp_sign) < 0)
3041       {
3042         if (tmp == &tmp_buf)
3043         {
3044           /* Move value out of tmp_buf as this will be reused on next loop */
3045           my_decimal2decimal(tmp, dec);
3046           res= dec;
3047         }
3048         else
3049           res= tmp;
3050       }
3051     }
3052     if ((null_value= args[i]->null_value))
3053     {
3054       res= 0;
3055       break;
3056     }
3057   }
3058   return res;
3059 }
3060 
3061 
val_native(THD * thd,Native * native)3062 bool Item_func_min_max::val_native(THD *thd, Native *native)
3063 {
3064   DBUG_ASSERT(fixed == 1);
3065   const Type_handler *handler= Item_hybrid_func::type_handler();
3066   NativeBuffer<STRING_BUFFER_USUAL_SIZE> cur;
3067   for (uint i= 0; i < arg_count; i++)
3068   {
3069     if (val_native_with_conversion_from_item(thd, args[i],
3070                                              i == 0 ? native : &cur,
3071                                              handler))
3072       return true;
3073     if (i > 0)
3074     {
3075       int cmp= handler->cmp_native(*native, cur);
3076       if ((cmp_sign < 0 ? cmp : -cmp) < 0 && native->copy(cur))
3077         return null_value= true;
3078     }
3079   }
3080   return null_value= false;
3081 }
3082 
3083 
val_int()3084 longlong Item_func_bit_length::val_int()
3085 {
3086   DBUG_ASSERT(fixed == 1);
3087   String *res= args[0]->val_str(&value);
3088   return (null_value= !res) ? 0 : (longlong) res->length() * 8;
3089 }
3090 
3091 
val_int()3092 longlong Item_func_octet_length::val_int()
3093 {
3094   DBUG_ASSERT(fixed == 1);
3095   String *res=args[0]->val_str(&value);
3096   if (!res)
3097   {
3098     null_value=1;
3099     return 0; /* purecov: inspected */
3100   }
3101   null_value=0;
3102   return (longlong) res->length();
3103 }
3104 
3105 
val_int()3106 longlong Item_func_char_length::val_int()
3107 {
3108   DBUG_ASSERT(fixed == 1);
3109   String *res=args[0]->val_str(&value);
3110   if (!res)
3111   {
3112     null_value=1;
3113     return 0; /* purecov: inspected */
3114   }
3115   null_value=0;
3116   return (longlong) res->numchars();
3117 }
3118 
3119 
val_int()3120 longlong Item_func_coercibility::val_int()
3121 {
3122   DBUG_ASSERT(fixed == 1);
3123   null_value= 0;
3124   return (longlong) args[0]->collation.derivation;
3125 }
3126 
3127 
val_int()3128 longlong Item_func_locate::val_int()
3129 {
3130   DBUG_ASSERT(fixed == 1);
3131   String *a=args[0]->val_str(&value1);
3132   String *b=args[1]->val_str(&value2);
3133   if (!a || !b)
3134   {
3135     null_value=1;
3136     return 0; /* purecov: inspected */
3137   }
3138   null_value=0;
3139   /* must be longlong to avoid truncation */
3140   longlong start=  0;
3141   longlong start0= 0;
3142   my_match_t match;
3143 
3144   if (arg_count == 3)
3145   {
3146     start0= start= args[2]->val_int();
3147 
3148     if ((start <= 0) || (start > a->length()))
3149       return 0;
3150     start0--; start--;
3151 
3152     /* start is now sufficiently valid to pass to charpos function */
3153     start= a->charpos((int) start);
3154 
3155     if (start + b->length() > a->length())
3156       return 0;
3157   }
3158 
3159   if (!b->length())				// Found empty string at start
3160     return start + 1;
3161 
3162   if (!cmp_collation.collation->instr(a->ptr() + start,
3163                                       (uint) (a->length() - start),
3164                                       b->ptr(), b->length(),
3165                                       &match, 1))
3166     return 0;
3167   return (longlong) match.mb_len + start0 + 1;
3168 }
3169 
3170 
print(String * str,enum_query_type query_type)3171 void Item_func_locate::print(String *str, enum_query_type query_type)
3172 {
3173   str->append(STRING_WITH_LEN("locate("));
3174   args[1]->print(str, query_type);
3175   str->append(',');
3176   args[0]->print(str, query_type);
3177   if (arg_count == 3)
3178   {
3179     str->append(',');
3180     args[2]->print(str, query_type);
3181   }
3182   str->append(')');
3183 }
3184 
3185 
val_int()3186 longlong Item_func_field::val_int()
3187 {
3188   DBUG_ASSERT(fixed == 1);
3189 
3190   if (cmp_type == STRING_RESULT)
3191   {
3192     String *field;
3193     if (!(field= args[0]->val_str(&value)))
3194       return 0;
3195     for (uint i=1 ; i < arg_count ; i++)
3196     {
3197       String *tmp_value=args[i]->val_str(&tmp);
3198       if (tmp_value && !sortcmp(field,tmp_value,cmp_collation.collation))
3199         return (longlong) (i);
3200     }
3201   }
3202   else if (cmp_type == INT_RESULT)
3203   {
3204     longlong val= args[0]->val_int();
3205     if (args[0]->null_value)
3206       return 0;
3207     for (uint i=1; i < arg_count ; i++)
3208     {
3209       if (val == args[i]->val_int() && !args[i]->null_value)
3210         return (longlong) (i);
3211     }
3212   }
3213   else if (cmp_type == DECIMAL_RESULT)
3214   {
3215     VDec dec(args[0]);
3216     if (dec.is_null())
3217       return 0;
3218     my_decimal dec_arg_buf;
3219     for (uint i=1; i < arg_count; i++)
3220     {
3221       my_decimal *dec_arg= args[i]->val_decimal(&dec_arg_buf);
3222       if (!args[i]->null_value && !dec.cmp(dec_arg))
3223         return (longlong) (i);
3224     }
3225   }
3226   else
3227   {
3228     double val= args[0]->val_real();
3229     if (args[0]->null_value)
3230       return 0;
3231     for (uint i=1; i < arg_count ; i++)
3232     {
3233       if (val == args[i]->val_real() && !args[i]->null_value)
3234         return (longlong) (i);
3235     }
3236   }
3237   return 0;
3238 }
3239 
3240 
fix_length_and_dec()3241 bool Item_func_field::fix_length_and_dec()
3242 {
3243   maybe_null=0; max_length=3;
3244   cmp_type= args[0]->result_type();
3245   for (uint i=1; i < arg_count ; i++)
3246     cmp_type= item_cmp_type(cmp_type, args[i]->result_type());
3247   if (cmp_type == STRING_RESULT)
3248     return agg_arg_charsets_for_comparison(cmp_collation, args, arg_count);
3249   return FALSE;
3250 }
3251 
3252 
val_int()3253 longlong Item_func_ascii::val_int()
3254 {
3255   DBUG_ASSERT(fixed == 1);
3256   String *res=args[0]->val_str(&value);
3257   if (!res)
3258   {
3259     null_value=1;
3260     return 0;
3261   }
3262   null_value=0;
3263   return (longlong) (res->length() ? (uchar) (*res)[0] : (uchar) 0);
3264 }
3265 
val_int()3266 longlong Item_func_ord::val_int()
3267 {
3268   DBUG_ASSERT(fixed == 1);
3269   String *res=args[0]->val_str(&value);
3270   if (!res)
3271   {
3272     null_value=1;
3273     return 0;
3274   }
3275   null_value=0;
3276   if (!res->length()) return 0;
3277 #ifdef USE_MB
3278   if (res->use_mb())
3279   {
3280     const char *str=res->ptr();
3281     uint32 n=0, l=my_ismbchar(res->charset(),str,str+res->length());
3282     if (!l)
3283       return (longlong)((uchar) *str);
3284     while (l--)
3285       n=(n<<8)|(uint32)((uchar) *str++);
3286     return (longlong) n;
3287   }
3288 #endif
3289   return (longlong) ((uchar) (*res)[0]);
3290 }
3291 
3292 	/* Search after a string in a string of strings separated by ',' */
3293 	/* Returns number of found type >= 1 or 0 if not found */
3294 	/* This optimizes searching in enums to bit testing! */
3295 
fix_length_and_dec()3296 bool Item_func_find_in_set::fix_length_and_dec()
3297 {
3298   decimals=0;
3299   max_length=3;					// 1-999
3300   if (args[0]->const_item() && args[1]->type() == FIELD_ITEM)
3301   {
3302     Field *field= ((Item_field*) args[1])->field;
3303     if (field->real_type() == MYSQL_TYPE_SET)
3304     {
3305       String *find=args[0]->val_str(&value);
3306       if (find)
3307       {
3308         // find is not NULL pointer so args[0] is not a null-value
3309         DBUG_ASSERT(!args[0]->null_value);
3310 	enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
3311 			      find->length(), 0);
3312 	enum_bit=0;
3313 	if (enum_value)
3314 	  enum_bit= 1ULL << (enum_value-1);
3315       }
3316     }
3317   }
3318   return agg_arg_charsets_for_comparison(cmp_collation, args, 2);
3319 }
3320 
3321 static const char separator=',';
3322 
val_int()3323 longlong Item_func_find_in_set::val_int()
3324 {
3325   DBUG_ASSERT(fixed == 1);
3326   if (enum_value)
3327   {
3328     // enum_value is set iff args[0]->const_item() in fix_length_and_dec().
3329     DBUG_ASSERT(args[0]->const_item());
3330 
3331     ulonglong tmp= (ulonglong) args[1]->val_int();
3332     null_value= args[1]->null_value;
3333     /*
3334       No need to check args[0]->null_value since enum_value is set iff
3335       args[0] is a non-null const item. Note: no DBUG_ASSERT on
3336       args[0]->null_value here because args[0] may have been replaced
3337       by an Item_cache on which val_int() has not been called. See
3338       BUG#11766317
3339     */
3340     if (!null_value)
3341     {
3342       if (tmp & enum_bit)
3343         return enum_value;
3344     }
3345     return 0L;
3346   }
3347 
3348   String *find=args[0]->val_str(&value);
3349   String *buffer=args[1]->val_str(&value2);
3350   if (!find || !buffer)
3351   {
3352     null_value=1;
3353     return 0; /* purecov: inspected */
3354   }
3355   null_value=0;
3356 
3357   if ((int) (buffer->length() - find->length()) >= 0)
3358   {
3359     my_wc_t wc= 0;
3360     CHARSET_INFO *cs= cmp_collation.collation;
3361     const char *str_begin= buffer->ptr();
3362     const char *str_end= buffer->ptr();
3363     const char *real_end= str_end+buffer->length();
3364     const char *find_str= find->ptr();
3365     uint find_str_len= find->length();
3366     int position= 0;
3367     while (1)
3368     {
3369       int symbol_len;
3370       if ((symbol_len= cs->mb_wc(&wc, (uchar*) str_end,
3371                                  (uchar*) real_end)) > 0)
3372       {
3373         const char *substr_end= str_end + symbol_len;
3374         bool is_last_item= (substr_end == real_end);
3375         bool is_separator= (wc == (my_wc_t) separator);
3376         if (is_separator || is_last_item)
3377         {
3378           position++;
3379           if (is_last_item && !is_separator)
3380             str_end= substr_end;
3381           if (!cs->strnncoll(str_begin, (uint) (str_end - str_begin),
3382                              find_str, find_str_len))
3383             return (longlong) position;
3384           else
3385             str_begin= substr_end;
3386         }
3387         str_end= substr_end;
3388       }
3389       else if (str_end - str_begin == 0 &&
3390                find_str_len == 0 &&
3391                wc == (my_wc_t) separator)
3392         return (longlong) ++position;
3393       else
3394         return 0;
3395     }
3396   }
3397   return 0;
3398 }
3399 
3400 
3401 class Func_handler_bit_count_int_to_slong:
3402         public Item_handled_func::Handler_slong2
3403 {
3404 public:
to_longlong_null(Item_handled_func * item) const3405   Longlong_null to_longlong_null(Item_handled_func *item) const
3406   {
3407     DBUG_ASSERT(item->is_fixed());
3408     return item->arguments()[0]->to_longlong_null().bit_count();
3409   }
3410 };
3411 
3412 
3413 class Func_handler_bit_count_decimal_to_slong:
3414         public Item_handled_func::Handler_slong2
3415 {
3416 public:
to_longlong_null(Item_handled_func * item) const3417   Longlong_null to_longlong_null(Item_handled_func *item) const
3418   {
3419     DBUG_ASSERT(item->is_fixed());
3420     return VDec(item->arguments()[0]).to_xlonglong_null().bit_count();
3421   }
3422 };
3423 
3424 
fix_length_and_dec()3425 bool Item_func_bit_count::fix_length_and_dec()
3426 {
3427   static Func_handler_bit_count_int_to_slong ha_int_to_slong;
3428   static Func_handler_bit_count_decimal_to_slong ha_dec_to_slong;
3429   set_func_handler(args[0]->cmp_type() == INT_RESULT ?
3430                    (const Handler *) &ha_int_to_slong :
3431                    (const Handler *) &ha_dec_to_slong);
3432   return m_func_handler->fix_length_and_dec(this);
3433 }
3434 
3435 
3436 /****************************************************************************
3437 ** Functions to handle dynamic loadable functions
3438 ** Original source by: Alexis Mikhailov <root@medinf.chuvashia.su>
3439 ** Rewritten by monty.
3440 ****************************************************************************/
3441 
3442 #ifdef HAVE_DLOPEN
3443 
cleanup()3444 void udf_handler::cleanup()
3445 {
3446   if (!not_original)
3447   {
3448     if (initialized)
3449     {
3450       if (u_d->func_deinit != NULL)
3451       {
3452         Udf_func_deinit deinit= u_d->func_deinit;
3453         (*deinit)(&initid);
3454       }
3455       free_udf(u_d);
3456       initialized= FALSE;
3457     }
3458     if (buffers)				// Because of bug in ecc
3459       delete [] buffers;
3460     buffers= 0;
3461   }
3462 }
3463 
3464 
3465 bool
fix_fields(THD * thd,Item_func_or_sum * func,uint arg_count,Item ** arguments)3466 udf_handler::fix_fields(THD *thd, Item_func_or_sum *func,
3467 			uint arg_count, Item **arguments)
3468 {
3469   uchar buff[STACK_BUFF_ALLOC];			// Max argument in function
3470   DBUG_ENTER("Item_udf_func::fix_fields");
3471 
3472   if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
3473     DBUG_RETURN(TRUE);				// Fatal error flag is set!
3474 
3475   udf_func *tmp_udf=find_udf(u_d->name.str,u_d->name.length,1);
3476 
3477   if (!tmp_udf)
3478   {
3479     my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str);
3480     DBUG_RETURN(TRUE);
3481   }
3482   u_d=tmp_udf;
3483   args=arguments;
3484 
3485   /* Fix all arguments */
3486   func->maybe_null=0;
3487   func->used_tables_and_const_cache_init();
3488 
3489   if ((f_args.arg_count=arg_count))
3490   {
3491     if (!(f_args.arg_type= (Item_result*)
3492 	  thd->alloc(f_args.arg_count*sizeof(Item_result))))
3493 
3494     {
3495       free_udf(u_d);
3496       DBUG_RETURN(TRUE);
3497     }
3498     uint i;
3499     Item **arg,**arg_end;
3500     With_sum_func_cache *with_sum_func_cache= func->get_with_sum_func_cache();
3501     for (i=0, arg=arguments, arg_end=arguments+arg_count;
3502 	 arg != arg_end ;
3503 	 arg++,i++)
3504     {
3505       if ((*arg)->fix_fields_if_needed_for_scalar(thd, arg))
3506 	DBUG_RETURN(true);
3507       // we can't assign 'item' before, because fix_fields() can change arg
3508       Item *item= *arg;
3509       /*
3510 	TODO: We should think about this. It is not always
3511 	right way just to set an UDF result to return my_charset_bin
3512 	if one argument has binary sorting order.
3513 	The result collation should be calculated according to arguments
3514 	derivations in some cases and should not in other cases.
3515 	Moreover, some arguments can represent a numeric input
3516 	which doesn't effect the result character set and collation.
3517 	There is no a general rule for UDF. Everything depends on
3518         the particular user defined function.
3519       */
3520       if (item->collation.collation->state & MY_CS_BINSORT)
3521 	func->collation.set(&my_charset_bin);
3522       if (item->maybe_null)
3523 	func->maybe_null=1;
3524       if (with_sum_func_cache)
3525         with_sum_func_cache->join_with_sum_func(item);
3526       func->with_window_func= func->with_window_func ||
3527                               item->with_window_func;
3528       func->with_field= func->with_field || item->with_field;
3529       func->with_param= func->with_param || item->with_param;
3530       func->With_subquery_cache::join(item);
3531       func->used_tables_and_const_cache_join(item);
3532       f_args.arg_type[i]=item->result_type();
3533     }
3534     if (!(buffers=new (thd->mem_root) String[arg_count]) ||
3535         !multi_alloc_root(thd->mem_root,
3536                           &f_args.args,              arg_count * sizeof(char *),
3537                           &f_args.lengths,           arg_count * sizeof(long),
3538                           &f_args.maybe_null,        arg_count * sizeof(char),
3539                           &num_buffer,               arg_count * sizeof(double),
3540                           &f_args.attributes,        arg_count * sizeof(char *),
3541                           &f_args.attribute_lengths, arg_count * sizeof(long),
3542                           NullS))
3543     {
3544       free_udf(u_d);
3545       DBUG_RETURN(TRUE);
3546     }
3547   }
3548   if (func->fix_length_and_dec())
3549     DBUG_RETURN(TRUE);
3550   initid.max_length=func->max_length;
3551   initid.maybe_null=func->maybe_null;
3552   initid.const_item=func->const_item_cache;
3553   initid.decimals=func->decimals;
3554   initid.ptr=0;
3555   for (uint i1= 0 ; i1 < arg_count ; i1++)
3556     buffers[i1].set_thread_specific();
3557 
3558   if (u_d->func_init)
3559   {
3560     char init_msg_buff[MYSQL_ERRMSG_SIZE];
3561     char *to=num_buffer;
3562     for (uint i=0; i < arg_count; i++)
3563     {
3564       /*
3565        For a constant argument i, args->args[i] points to the argument value.
3566        For non-constant, args->args[i] is NULL.
3567       */
3568       f_args.args[i]= NULL;         /* Non-const unless updated below. */
3569 
3570       f_args.lengths[i]= arguments[i]->max_length;
3571       f_args.maybe_null[i]= (char) arguments[i]->maybe_null;
3572       f_args.attributes[i]= arguments[i]->name.str;
3573       f_args.attribute_lengths[i]= (ulong)arguments[i]->name.length;
3574 
3575       if (arguments[i]->const_item())
3576       {
3577         switch (arguments[i]->result_type()) {
3578         case STRING_RESULT:
3579         case DECIMAL_RESULT:
3580         {
3581           String *res= arguments[i]->val_str(&buffers[i]);
3582           if (arguments[i]->null_value)
3583             continue;
3584           f_args.args[i]= (char*) res->c_ptr_safe();
3585           f_args.lengths[i]= res->length();
3586           break;
3587         }
3588         case INT_RESULT:
3589           *((longlong*) to)= arguments[i]->val_int();
3590           if (arguments[i]->null_value)
3591             continue;
3592           f_args.args[i]= to;
3593           to+= ALIGN_SIZE(sizeof(longlong));
3594           break;
3595         case REAL_RESULT:
3596           *((double*) to)= arguments[i]->val_real();
3597           if (arguments[i]->null_value)
3598             continue;
3599           f_args.args[i]= to;
3600           to+= ALIGN_SIZE(sizeof(double));
3601           break;
3602         case ROW_RESULT:
3603         case TIME_RESULT:
3604           DBUG_ASSERT(0);          // This case should never be chosen
3605           break;
3606         }
3607       }
3608     }
3609     Udf_func_init init= u_d->func_init;
3610     if (unlikely((error=(uchar) init(&initid, &f_args, init_msg_buff))))
3611     {
3612       my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
3613                u_d->name.str, init_msg_buff);
3614       free_udf(u_d);
3615       DBUG_RETURN(TRUE);
3616     }
3617     func->max_length=MY_MIN(initid.max_length,MAX_BLOB_WIDTH);
3618     func->maybe_null=initid.maybe_null;
3619     /*
3620       The above call for init() can reset initid.const_item to "false",
3621       e.g. when the UDF function wants to be non-deterministic.
3622       See sequence_init() in udf_example.cc.
3623     */
3624     func->const_item_cache= initid.const_item;
3625     func->decimals=MY_MIN(initid.decimals,NOT_FIXED_DEC);
3626   }
3627   initialized=1;
3628   if (unlikely(error))
3629   {
3630     my_error(ER_CANT_INITIALIZE_UDF, MYF(0),
3631              u_d->name.str, ER_THD(thd, ER_UNKNOWN_ERROR));
3632     DBUG_RETURN(TRUE);
3633   }
3634   DBUG_RETURN(FALSE);
3635 }
3636 
3637 
get_arguments()3638 bool udf_handler::get_arguments()
3639 {
3640   if (unlikely(error))
3641     return 1;					// Got an error earlier
3642   char *to= num_buffer;
3643   uint str_count=0;
3644   for (uint i=0; i < f_args.arg_count; i++)
3645   {
3646     f_args.args[i]=0;
3647     switch (f_args.arg_type[i]) {
3648     case STRING_RESULT:
3649     case DECIMAL_RESULT:
3650       {
3651 	String *res=args[i]->val_str(&buffers[str_count++]);
3652 	if (!(args[i]->null_value))
3653 	{
3654 	  f_args.args[i]=    (char*) res->ptr();
3655 	  f_args.lengths[i]= res->length();
3656 	}
3657 	else
3658 	{
3659 	  f_args.lengths[i]= 0;
3660 	}
3661 	break;
3662       }
3663     case INT_RESULT:
3664       *((longlong*) to) = args[i]->val_int();
3665       if (!args[i]->null_value)
3666       {
3667 	f_args.args[i]=to;
3668 	to+= ALIGN_SIZE(sizeof(longlong));
3669       }
3670       break;
3671     case REAL_RESULT:
3672       *((double*) to)= args[i]->val_real();
3673       if (!args[i]->null_value)
3674       {
3675 	f_args.args[i]=to;
3676 	to+= ALIGN_SIZE(sizeof(double));
3677       }
3678       break;
3679     case ROW_RESULT:
3680     case TIME_RESULT:
3681       DBUG_ASSERT(0);              // This case should never be chosen
3682       break;
3683     }
3684   }
3685   return 0;
3686 }
3687 
3688 /**
3689   @return
3690     (String*)NULL in case of NULL values
3691 */
val_str(String * str,String * save_str)3692 String *udf_handler::val_str(String *str,String *save_str)
3693 {
3694   uchar is_null_tmp=0;
3695   ulong res_length;
3696   DBUG_ENTER("udf_handler::val_str");
3697 
3698   if (get_arguments())
3699     DBUG_RETURN(0);
3700   char * (*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
3701     (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
3702     u_d->func;
3703 
3704   if ((res_length=str->alloced_length()) < MAX_FIELD_WIDTH)
3705   {						// This happens VERY seldom
3706     if (str->alloc(MAX_FIELD_WIDTH))
3707     {
3708       error=1;
3709       DBUG_RETURN(0);
3710     }
3711   }
3712   char *res=func(&initid, &f_args, (char*) str->ptr(), &res_length,
3713 		 &is_null_tmp, &error);
3714   DBUG_PRINT("info", ("udf func returned, res_length: %lu", res_length));
3715   if (is_null_tmp || !res || unlikely(error))	// The !res is for safety
3716   {
3717     DBUG_PRINT("info", ("Null or error"));
3718     DBUG_RETURN(0);
3719   }
3720   if (res == str->ptr())
3721   {
3722     str->length(res_length);
3723     DBUG_PRINT("exit", ("str: %*.s", (int) str->length(), str->ptr()));
3724     DBUG_RETURN(str);
3725   }
3726   save_str->set(res, res_length, str->charset());
3727   DBUG_PRINT("exit", ("save_str: %s", save_str->ptr()));
3728   DBUG_RETURN(save_str);
3729 }
3730 
3731 
3732 /*
3733   For the moment, UDF functions are returning DECIMAL values as strings
3734 */
3735 
val_decimal(my_bool * null_value,my_decimal * dec_buf)3736 my_decimal *udf_handler::val_decimal(my_bool *null_value, my_decimal *dec_buf)
3737 {
3738   char buf[DECIMAL_MAX_STR_LENGTH+1], *end;
3739   ulong res_length= DECIMAL_MAX_STR_LENGTH;
3740 
3741   if (get_arguments())
3742   {
3743     *null_value=1;
3744     return 0;
3745   }
3746   char *(*func)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *)=
3747     (char* (*)(UDF_INIT *, UDF_ARGS *, char *, ulong *, uchar *, uchar *))
3748     u_d->func;
3749 
3750   char *res= func(&initid, &f_args, buf, &res_length, &is_null, &error);
3751   if (is_null || unlikely(error))
3752   {
3753     *null_value= 1;
3754     return 0;
3755   }
3756   end= res+ res_length;
3757   str2my_decimal(E_DEC_FATAL_ERROR, res, dec_buf, &end);
3758   return dec_buf;
3759 }
3760 
3761 
cleanup()3762 void Item_udf_func::cleanup()
3763 {
3764   udf.cleanup();
3765   Item_func::cleanup();
3766 }
3767 
3768 
print(String * str,enum_query_type query_type)3769 void Item_udf_func::print(String *str, enum_query_type query_type)
3770 {
3771   str->append(func_name());
3772   str->append('(');
3773   for (uint i=0 ; i < arg_count ; i++)
3774   {
3775     if (i != 0)
3776       str->append(',');
3777     args[i]->print_item_w_name(str, query_type);
3778   }
3779   str->append(')');
3780 }
3781 
3782 
val_real()3783 double Item_func_udf_float::val_real()
3784 {
3785   double res;
3786   my_bool tmp_null_value;
3787   DBUG_ASSERT(fixed == 1);
3788   DBUG_ENTER("Item_func_udf_float::val");
3789   DBUG_PRINT("info",("result_type: %d  arg_count: %d",
3790 		     args[0]->result_type(), arg_count));
3791   res= udf.val(&tmp_null_value);
3792   null_value= tmp_null_value;
3793   DBUG_RETURN(res);
3794 }
3795 
3796 
val_str(String * str)3797 String *Item_func_udf_float::val_str(String *str)
3798 {
3799   DBUG_ASSERT(fixed == 1);
3800   double nr= val_real();
3801   if (null_value)
3802     return 0;					/* purecov: inspected */
3803   str->set_real(nr,decimals,&my_charset_bin);
3804   return str;
3805 }
3806 
3807 
val_int()3808 longlong Item_func_udf_int::val_int()
3809 {
3810   longlong res;
3811   my_bool tmp_null_value;
3812   DBUG_ASSERT(fixed == 1);
3813   DBUG_ENTER("Item_func_udf_int::val_int");
3814   res= udf.val_int(&tmp_null_value);
3815   null_value= tmp_null_value;
3816   DBUG_RETURN(res);
3817 }
3818 
3819 
val_str(String * str)3820 String *Item_func_udf_int::val_str(String *str)
3821 {
3822   DBUG_ASSERT(fixed == 1);
3823   longlong nr=val_int();
3824   if (null_value)
3825     return 0;
3826   str->set_int(nr, unsigned_flag, &my_charset_bin);
3827   return str;
3828 }
3829 
3830 
val_decimal(my_decimal * dec_buf)3831 my_decimal *Item_func_udf_decimal::val_decimal(my_decimal *dec_buf)
3832 {
3833   my_decimal *res;
3834   my_bool tmp_null_value;
3835   DBUG_ASSERT(fixed == 1);
3836   DBUG_ENTER("Item_func_udf_decimal::val_decimal");
3837   DBUG_PRINT("info",("result_type: %d  arg_count: %d",
3838                      args[0]->result_type(), arg_count));
3839 
3840   res= udf.val_decimal(&tmp_null_value, dec_buf);
3841   null_value= tmp_null_value;
3842   DBUG_RETURN(res);
3843 }
3844 
3845 
3846 /* Default max_length is max argument length */
3847 
fix_length_and_dec()3848 bool Item_func_udf_str::fix_length_and_dec()
3849 {
3850   DBUG_ENTER("Item_func_udf_str::fix_length_and_dec");
3851   max_length=0;
3852   for (uint i = 0; i < arg_count; i++)
3853     set_if_bigger(max_length,args[i]->max_length);
3854   DBUG_RETURN(FALSE);
3855 }
3856 
val_str(String * str)3857 String *Item_func_udf_str::val_str(String *str)
3858 {
3859   DBUG_ASSERT(fixed == 1);
3860   String *res=udf.val_str(str,&str_value);
3861   null_value = !res;
3862   return res;
3863 }
3864 
3865 
3866 /**
3867   @note
3868   This has to come last in the udf_handler methods, or C for AIX
3869   version 6.0.0.0 fails to compile with debugging enabled. (Yes, really.)
3870 */
3871 
~udf_handler()3872 udf_handler::~udf_handler()
3873 {
3874   /* Everything should be properly cleaned up by this moment. */
3875   DBUG_ASSERT(not_original || !(initialized || buffers));
3876 }
3877 
3878 #else
get_arguments()3879 bool udf_handler::get_arguments() { return 0; }
3880 #endif /* HAVE_DLOPEN */
3881 
3882 
val_int()3883 longlong Item_master_pos_wait::val_int()
3884 {
3885   DBUG_ASSERT(fixed == 1);
3886   THD* thd = current_thd;
3887   String *log_name = args[0]->val_str(&value);
3888   int event_count= 0;
3889   DBUG_ENTER("Item_master_pos_wait::val_int");
3890 
3891   null_value=0;
3892   if (thd->slave_thread || !log_name || !log_name->length())
3893   {
3894     null_value = 1;
3895     DBUG_RETURN(0);
3896   }
3897 #ifdef HAVE_REPLICATION
3898   longlong pos = (ulong)args[1]->val_int();
3899   longlong timeout = (arg_count>=3) ? args[2]->val_int() : 0 ;
3900   String connection_name_buff;
3901   LEX_CSTRING connection_name;
3902   Master_info *mi= NULL;
3903   if (arg_count >= 4)
3904   {
3905     String *con;
3906     if (!(con= args[3]->val_str(&connection_name_buff)))
3907       goto err;
3908 
3909     connection_name.str= con->ptr();
3910     connection_name.length= con->length();
3911     if (check_master_connection_name(&connection_name))
3912     {
3913       my_error(ER_WRONG_ARGUMENTS, MYF(ME_WARNING),
3914                "MASTER_CONNECTION_NAME");
3915       goto err;
3916     }
3917   }
3918   else
3919     connection_name= thd->variables.default_master_connection;
3920 
3921   if (!(mi= get_master_info(&connection_name, Sql_condition::WARN_LEVEL_WARN)))
3922     goto err;
3923 
3924   if ((event_count = mi->rli.wait_for_pos(thd, log_name, pos, timeout)) == -2)
3925   {
3926     null_value = 1;
3927     event_count=0;
3928   }
3929   mi->release();
3930 #endif
3931   DBUG_PRINT("exit", ("event_count: %d  null_value: %d", event_count,
3932                       (int) null_value));
3933   DBUG_RETURN(event_count);
3934 
3935 #ifdef HAVE_REPLICATION
3936 err:
3937   {
3938     null_value = 1;
3939     DBUG_RETURN(0);
3940   }
3941 #endif
3942 }
3943 
3944 
val_int()3945 longlong Item_master_gtid_wait::val_int()
3946 {
3947   DBUG_ASSERT(fixed == 1);
3948   longlong result= 0;
3949   String *gtid_pos __attribute__((unused)) = args[0]->val_str(&value);
3950   DBUG_ENTER("Item_master_gtid_wait::val_int");
3951 
3952   if (args[0]->null_value)
3953   {
3954     null_value= 1;
3955     DBUG_RETURN(0);
3956   }
3957 
3958   null_value=0;
3959 #ifdef HAVE_REPLICATION
3960   THD* thd= current_thd;
3961   longlong timeout_us;
3962 
3963   if (arg_count==2 && !args[1]->null_value)
3964     timeout_us= (longlong)(1e6*args[1]->val_real());
3965   else
3966     timeout_us= (longlong)-1;
3967 
3968   result= rpl_global_gtid_waiting.wait_for_pos(thd, gtid_pos, timeout_us);
3969 #else
3970   null_value= 0;
3971 #endif /* REPLICATION */
3972   DBUG_RETURN(result);
3973 }
3974 
3975 
3976 /**
3977   Enables a session to wait on a condition until a timeout or a network
3978   disconnect occurs.
3979 
3980   @remark The connection is polled every m_interrupt_interval nanoseconds.
3981 */
3982 
3983 class Interruptible_wait
3984 {
3985   THD *m_thd;
3986   struct timespec m_abs_timeout;
3987   static const ulonglong m_interrupt_interval;
3988 
3989   public:
Interruptible_wait(THD * thd)3990     Interruptible_wait(THD *thd)
3991     : m_thd(thd) {}
3992 
~Interruptible_wait()3993     ~Interruptible_wait() {}
3994 
3995   public:
3996     /**
3997       Set the absolute timeout.
3998 
3999       @param timeout The amount of time in nanoseconds to wait
4000     */
set_timeout(ulonglong timeout)4001     void set_timeout(ulonglong timeout)
4002     {
4003       /*
4004         Calculate the absolute system time at the start so it can
4005         be controlled in slices. It relies on the fact that once
4006         the absolute time passes, the timed wait call will fail
4007         automatically with a timeout error.
4008       */
4009       set_timespec_nsec(m_abs_timeout, timeout);
4010     }
4011 
4012     /** The timed wait. */
4013     int wait(mysql_cond_t *, mysql_mutex_t *);
4014 };
4015 
4016 
4017 /** Time to wait before polling the connection status. */
4018 const ulonglong Interruptible_wait::m_interrupt_interval= 5 * 1000000000ULL;
4019 
4020 
4021 /**
4022   Wait for a given condition to be signaled.
4023 
4024   @param cond   The condition variable to wait on.
4025   @param mutex  The associated mutex.
4026 
4027   @remark The absolute timeout is preserved across calls.
4028 
4029   @retval return value from mysql_cond_timedwait
4030 */
4031 
wait(mysql_cond_t * cond,mysql_mutex_t * mutex)4032 int Interruptible_wait::wait(mysql_cond_t *cond, mysql_mutex_t *mutex)
4033 {
4034   int error;
4035   struct timespec timeout;
4036 
4037   while (1)
4038   {
4039     /* Wait for a fixed interval. */
4040     set_timespec_nsec(timeout, m_interrupt_interval);
4041 
4042     /* But only if not past the absolute timeout. */
4043     if (cmp_timespec(timeout, m_abs_timeout) > 0)
4044       timeout= m_abs_timeout;
4045 
4046     error= mysql_cond_timedwait(cond, mutex, &timeout);
4047     if (m_thd->check_killed())
4048       break;
4049     if (error == ETIMEDOUT || error == ETIME)
4050     {
4051       /* Return error if timed out or connection is broken. */
4052       if (!cmp_timespec(timeout, m_abs_timeout) || !m_thd->is_connected())
4053         break;
4054     }
4055     /* Otherwise, propagate status to the caller. */
4056     else
4057       break;
4058   }
4059 
4060   return error;
4061 }
4062 
4063 
4064 /**
4065   For locks with EXPLICIT duration, MDL returns a new ticket
4066   every time a lock is granted. This allows to implement recursive
4067   locks without extra allocation or additional data structures, such
4068   as below. However, if there are too many tickets in the same
4069   MDL_context, MDL_context::find_ticket() is getting too slow,
4070   since it's using a linear search.
4071   This is why a separate structure is allocated for a user
4072   level lock, and before requesting a new lock from MDL,
4073   GET_LOCK() checks thd->ull_hash if such lock is already granted,
4074   and if so, simply increments a reference counter.
4075 */
4076 
4077 class User_level_lock
4078 {
4079 public:
4080   MDL_ticket *lock;
4081   int refs;
4082 };
4083 
4084 
4085 /** Extract a hash key from User_level_lock. */
4086 
ull_get_key(const uchar * ptr,size_t * length,my_bool not_used)4087 uchar *ull_get_key(const uchar *ptr, size_t *length,
4088                    my_bool not_used __attribute__((unused)))
4089 {
4090   User_level_lock *ull = (User_level_lock*) ptr;
4091   MDL_key *key = ull->lock->get_key();
4092   *length= key->length();
4093   return (uchar*) key->ptr();
4094 }
4095 
4096 
4097 /**
4098   Release all user level locks for this THD.
4099 */
4100 
mysql_ull_cleanup(THD * thd)4101 void mysql_ull_cleanup(THD *thd)
4102 {
4103   User_level_lock *ull;
4104   DBUG_ENTER("mysql_ull_cleanup");
4105 
4106   for (uint i= 0; i < thd->ull_hash.records; i++)
4107   {
4108     ull = (User_level_lock*) my_hash_element(&thd->ull_hash, i);
4109     thd->mdl_context.release_lock(ull->lock);
4110     my_free(ull);
4111   }
4112 
4113   my_hash_free(&thd->ull_hash);
4114 
4115   DBUG_VOID_RETURN;
4116 }
4117 
4118 
4119 /**
4120   Set explicit duration for metadata locks corresponding to
4121   user level locks to protect them from being released at the end
4122   of transaction.
4123 */
4124 
mysql_ull_set_explicit_lock_duration(THD * thd)4125 void mysql_ull_set_explicit_lock_duration(THD *thd)
4126 {
4127   User_level_lock *ull;
4128   DBUG_ENTER("mysql_ull_set_explicit_lock_duration");
4129 
4130   for (uint i= 0; i < thd->ull_hash.records; i++)
4131   {
4132     ull= (User_level_lock*) my_hash_element(&thd->ull_hash, i);
4133     thd->mdl_context.set_lock_duration(ull->lock, MDL_EXPLICIT);
4134   }
4135   DBUG_VOID_RETURN;
4136 }
4137 
4138 
4139 /**
4140   When MDL detects a lock wait timeout, it pushes
4141   an error into the statement diagnostics area.
4142   For GET_LOCK(), lock wait timeout is not an error,
4143   but a special return value (0).
4144   Similarly, killing get_lock wait is not an error either,
4145   but a return value NULL.
4146   Capture and suppress lock wait timeouts and kills.
4147 */
4148 
4149 class Lock_wait_timeout_handler: public Internal_error_handler
4150 {
4151 public:
Lock_wait_timeout_handler()4152   Lock_wait_timeout_handler() :m_lock_wait_timeout(false) {}
4153 
4154   bool m_lock_wait_timeout;
4155 
4156   bool handle_condition(THD * /* thd */, uint sql_errno,
4157                         const char * /* sqlstate */,
4158                         Sql_condition::enum_warning_level* /* level */,
4159                         const char *message,
4160                         Sql_condition ** /* cond_hdl */);
4161 };
4162 
4163 bool
4164 Lock_wait_timeout_handler::
handle_condition(THD * thd,uint sql_errno,const char *,Sql_condition::enum_warning_level *,const char * message,Sql_condition **)4165 handle_condition(THD *thd, uint sql_errno,
4166                  const char * /* sqlstate */,
4167                  Sql_condition::enum_warning_level* /* level */,
4168                  const char *message,
4169                  Sql_condition ** /* cond_hdl */)
4170 {
4171   if (sql_errno == ER_LOCK_WAIT_TIMEOUT)
4172   {
4173     m_lock_wait_timeout= true;
4174     return true;                                /* condition handled */
4175   }
4176   if (thd->is_killed())
4177     return true;
4178 
4179   return false;
4180 }
4181 
4182 
ull_name_ok(String * name)4183 static int ull_name_ok(String *name)
4184 {
4185   if (!name || !name->length())
4186     return 0;
4187 
4188   if (name->length() > NAME_LEN)
4189   {
4190     my_error(ER_TOO_LONG_IDENT, MYF(0), name->c_ptr_safe());
4191     return 0;
4192   }
4193   return 1;
4194 }
4195 
4196 
4197 /**
4198   Get a user level lock.
4199 
4200   @retval
4201     1    : Got lock
4202   @retval
4203     0    : Timeout
4204   @retval
4205     NULL : Error
4206 */
4207 
val_int()4208 longlong Item_func_get_lock::val_int()
4209 {
4210   DBUG_ASSERT(fixed == 1);
4211   String *res= args[0]->val_str(&value);
4212   double timeout= args[1]->val_real();
4213   THD *thd= current_thd;
4214   User_level_lock *ull;
4215   DBUG_ENTER("Item_func_get_lock::val_int");
4216 
4217   null_value= 1;
4218   /*
4219     In slave thread no need to get locks, everything is serialized. Anyway
4220     there is no way to make GET_LOCK() work on slave like it did on master
4221     (i.e. make it return exactly the same value) because we don't have the
4222     same other concurrent threads environment. No matter what we return here,
4223     it's not guaranteed to be same as on master.
4224   */
4225   if (thd->slave_thread)
4226   {
4227     null_value= 0;
4228     DBUG_RETURN(1);
4229   }
4230 
4231   if (args[1]->null_value ||
4232       (!args[1]->unsigned_flag && ((longlong) timeout < 0)))
4233   {
4234     char buf[22];
4235     if (args[1]->null_value)
4236       strmov(buf, "NULL");
4237     else
4238       llstr(((longlong) timeout), buf);
4239     push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4240                         ER_WRONG_VALUE_FOR_TYPE, ER(ER_WRONG_VALUE_FOR_TYPE),
4241                         "timeout", buf, "get_lock");
4242     null_value= 1;
4243     DBUG_RETURN(0);
4244   }
4245 
4246   if (!ull_name_ok(res))
4247     DBUG_RETURN(0);
4248   DBUG_PRINT("enter", ("lock: %.*s", res->length(), res->ptr()));
4249   /* HASH entries are of type User_level_lock. */
4250   if (! my_hash_inited(&thd->ull_hash) &&
4251         my_hash_init(key_memory_User_level_lock, &thd->ull_hash,
4252                      &my_charset_bin, 16 /* small hash */, 0, 0, ull_get_key,
4253                      NULL, 0))
4254   {
4255     DBUG_RETURN(0);
4256   }
4257 
4258   MDL_request ull_request;
4259   MDL_REQUEST_INIT(&ull_request, MDL_key::USER_LOCK, res->c_ptr_safe(), "",
4260                    MDL_SHARED_NO_WRITE, MDL_EXPLICIT);
4261   MDL_key *ull_key= &ull_request.key;
4262 
4263 
4264   if ((ull= (User_level_lock*)
4265        my_hash_search(&thd->ull_hash, ull_key->ptr(), ull_key->length())))
4266   {
4267     /* Recursive lock */
4268     ull->refs++;
4269     null_value= 0;
4270     DBUG_PRINT("info", ("recursive lock, ref-count: %d", (int) ull->refs));
4271     DBUG_RETURN(1);
4272   }
4273 
4274   Lock_wait_timeout_handler lock_wait_timeout_handler;
4275   thd->push_internal_handler(&lock_wait_timeout_handler);
4276   bool error= thd->mdl_context.acquire_lock(&ull_request, timeout);
4277   (void) thd->pop_internal_handler();
4278   if (unlikely(error))
4279   {
4280     if (lock_wait_timeout_handler.m_lock_wait_timeout)
4281       null_value= 0;
4282     DBUG_RETURN(0);
4283   }
4284 
4285   ull= (User_level_lock*) my_malloc(key_memory_User_level_lock,
4286                                     sizeof(User_level_lock),
4287                                     MYF(MY_WME|MY_THREAD_SPECIFIC));
4288   if (ull == NULL)
4289   {
4290     thd->mdl_context.release_lock(ull_request.ticket);
4291     DBUG_RETURN(0);
4292   }
4293 
4294   ull->lock= ull_request.ticket;
4295   ull->refs= 1;
4296 
4297   if (my_hash_insert(&thd->ull_hash, (uchar*) ull))
4298   {
4299     thd->mdl_context.release_lock(ull->lock);
4300     my_free(ull);
4301     DBUG_RETURN(0);
4302   }
4303   null_value= 0;
4304 
4305   DBUG_RETURN(1);
4306 }
4307 
4308 
4309 /**
4310   Release all user level locks.
4311   @return
4312     - N if N-lock released
4313     - 0 if lock wasn't held
4314 */
val_int()4315 longlong Item_func_release_all_locks::val_int()
4316 {
4317   DBUG_ASSERT(fixed == 1);
4318   THD *thd= current_thd;
4319   ulong num_unlocked= 0;
4320   DBUG_ENTER("Item_func_release_all_locks::val_int");
4321   for (size_t i= 0; i < thd->ull_hash.records; i++)
4322   {
4323     auto ull= (User_level_lock *) my_hash_element(&thd->ull_hash, i);
4324     thd->mdl_context.release_lock(ull->lock);
4325     num_unlocked+= ull->refs;
4326     my_free(ull);
4327   }
4328   my_hash_free(&thd->ull_hash);
4329   DBUG_RETURN(num_unlocked);
4330 }
4331 
4332 
4333 /**
4334   Release a user level lock.
4335   @return
4336     - 1 if lock released
4337     - 0 if lock wasn't held
4338     - (SQL) NULL if no such lock
4339 */
4340 
val_int()4341 longlong Item_func_release_lock::val_int()
4342 {
4343   DBUG_ASSERT(fixed == 1);
4344   String *res= args[0]->val_str(&value);
4345   THD *thd= current_thd;
4346   DBUG_ENTER("Item_func_release_lock::val_int");
4347   null_value= 1;
4348 
4349   if (!ull_name_ok(res))
4350     DBUG_RETURN(0);
4351 
4352   DBUG_PRINT("enter", ("lock: %.*s", res->length(), res->ptr()));
4353 
4354   MDL_key ull_key;
4355   ull_key.mdl_key_init(MDL_key::USER_LOCK, res->c_ptr_safe(), "");
4356 
4357   User_level_lock *ull;
4358 
4359   if (!my_hash_inited(&thd->ull_hash) ||
4360       !(ull=
4361         (User_level_lock*) my_hash_search(&thd->ull_hash,
4362                                           ull_key.ptr(), ull_key.length())))
4363   {
4364     null_value= thd->mdl_context.get_lock_owner(&ull_key) == 0;
4365     DBUG_RETURN(0);
4366   }
4367   DBUG_PRINT("info", ("ref count: %d", (int) ull->refs));
4368   null_value= 0;
4369   if (--ull->refs == 0)
4370   {
4371     my_hash_delete(&thd->ull_hash, (uchar*) ull);
4372     thd->mdl_context.release_lock(ull->lock);
4373     my_free(ull);
4374   }
4375   DBUG_RETURN(1);
4376 }
4377 
4378 
4379 /**
4380   Check a user level lock.
4381 
4382   Sets null_value=TRUE on error.
4383 
4384   @retval
4385     1		Available
4386   @retval
4387     0		Already taken, or error
4388 */
4389 
val_int()4390 longlong Item_func_is_free_lock::val_int()
4391 {
4392   DBUG_ASSERT(fixed == 1);
4393   String *res= args[0]->val_str(&value);
4394   THD *thd= current_thd;
4395   null_value= 1;
4396 
4397   if (!ull_name_ok(res))
4398     return 0;
4399 
4400   MDL_key ull_key;
4401   ull_key.mdl_key_init(MDL_key::USER_LOCK, res->c_ptr_safe(), "");
4402 
4403   null_value= 0;
4404   return thd->mdl_context.get_lock_owner(&ull_key) == 0;
4405 }
4406 
4407 
val_int()4408 longlong Item_func_is_used_lock::val_int()
4409 {
4410   DBUG_ASSERT(fixed == 1);
4411   String *res= args[0]->val_str(&value);
4412   THD *thd= current_thd;
4413   null_value= 1;
4414 
4415   if (!ull_name_ok(res))
4416     return 0;
4417 
4418   MDL_key ull_key;
4419   ull_key.mdl_key_init(MDL_key::USER_LOCK, res->c_ptr_safe(), "");
4420   ulong thread_id = thd->mdl_context.get_lock_owner(&ull_key);
4421   if (thread_id == 0)
4422     return 0;
4423 
4424   null_value= 0;
4425   return thread_id;
4426 }
4427 
4428 
val_int()4429 longlong Item_func_last_insert_id::val_int()
4430 {
4431   THD *thd= current_thd;
4432   DBUG_ASSERT(fixed == 1);
4433   if (arg_count)
4434   {
4435     longlong value= args[0]->val_int();
4436     null_value= args[0]->null_value;
4437     /*
4438       LAST_INSERT_ID(X) must affect the client's mysql_insert_id() as
4439       documented in the manual. We don't want to touch
4440       first_successful_insert_id_in_cur_stmt because it would make
4441       LAST_INSERT_ID(X) take precedence over an generated auto_increment
4442       value for this row.
4443     */
4444     thd->arg_of_last_insert_id_function= TRUE;
4445     thd->first_successful_insert_id_in_prev_stmt= value;
4446     return value;
4447   }
4448   return
4449     static_cast<longlong>(thd->read_first_successful_insert_id_in_prev_stmt());
4450 }
4451 
4452 
fix_fields(THD * thd,Item ** ref)4453 bool Item_func_last_insert_id::fix_fields(THD *thd, Item **ref)
4454 {
4455   thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
4456   return Item_int_func::fix_fields(thd, ref);
4457 }
4458 
4459 
4460 /* This function is just used to test speed of different functions */
4461 
val_int()4462 longlong Item_func_benchmark::val_int()
4463 {
4464   DBUG_ASSERT(fixed == 1);
4465   char buff[MAX_FIELD_WIDTH];
4466   String tmp(buff,sizeof(buff), &my_charset_bin);
4467   my_decimal tmp_decimal;
4468   THD *thd= current_thd;
4469   ulonglong loop_count;
4470 
4471   loop_count= (ulonglong) args[0]->val_int();
4472 
4473   if (args[0]->null_value ||
4474       (!args[0]->unsigned_flag && (((longlong) loop_count) < 0)))
4475   {
4476     if (!args[0]->null_value)
4477     {
4478       char buff[22];
4479       llstr(((longlong) loop_count), buff);
4480       push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
4481                           ER_WRONG_VALUE_FOR_TYPE,
4482                           ER_THD(thd, ER_WRONG_VALUE_FOR_TYPE),
4483                           "count", buff, "benchmark");
4484     }
4485 
4486     null_value= 1;
4487     return 0;
4488   }
4489 
4490   null_value=0;
4491   for (ulonglong loop=0 ; loop < loop_count && !thd->killed; loop++)
4492   {
4493     switch (args[1]->result_type()) {
4494     case REAL_RESULT:
4495       (void) args[1]->val_real();
4496       break;
4497     case INT_RESULT:
4498       (void) args[1]->val_int();
4499       break;
4500     case STRING_RESULT:
4501       (void) args[1]->val_str(&tmp);
4502       break;
4503     case DECIMAL_RESULT:
4504       (void) args[1]->val_decimal(&tmp_decimal);
4505       break;
4506     case ROW_RESULT:
4507     case TIME_RESULT:
4508       DBUG_ASSERT(0);              // This case should never be chosen
4509       return 0;
4510     }
4511   }
4512   return 0;
4513 }
4514 
4515 
print(String * str,enum_query_type query_type)4516 void Item_func_benchmark::print(String *str, enum_query_type query_type)
4517 {
4518   str->append(STRING_WITH_LEN("benchmark("));
4519   args[0]->print(str, query_type);
4520   str->append(',');
4521   args[1]->print(str, query_type);
4522   str->append(')');
4523 }
4524 
4525 
4526 mysql_mutex_t LOCK_item_func_sleep;
4527 
4528 #ifdef HAVE_PSI_INTERFACE
4529 static PSI_mutex_key key_LOCK_item_func_sleep;
4530 
4531 static PSI_mutex_info item_func_sleep_mutexes[]=
4532 {
4533   { &key_LOCK_item_func_sleep, "LOCK_item_func_sleep", PSI_FLAG_GLOBAL}
4534 };
4535 
4536 
init_item_func_sleep_psi_keys(void)4537 static void init_item_func_sleep_psi_keys(void)
4538 {
4539   const char* category= "sql";
4540   int count;
4541 
4542   if (PSI_server == NULL)
4543     return;
4544 
4545   count= array_elements(item_func_sleep_mutexes);
4546   PSI_server->register_mutex(category, item_func_sleep_mutexes, count);
4547 }
4548 #endif
4549 
4550 static bool item_func_sleep_inited= 0;
4551 
4552 
item_func_sleep_init(void)4553 void item_func_sleep_init(void)
4554 {
4555 #ifdef HAVE_PSI_INTERFACE
4556   init_item_func_sleep_psi_keys();
4557 #endif
4558 
4559   mysql_mutex_init(key_LOCK_item_func_sleep, &LOCK_item_func_sleep, MY_MUTEX_INIT_SLOW);
4560   item_func_sleep_inited= 1;
4561 }
4562 
4563 
item_func_sleep_free(void)4564 void item_func_sleep_free(void)
4565 {
4566   if (item_func_sleep_inited)
4567   {
4568     item_func_sleep_inited= 0;
4569     mysql_mutex_destroy(&LOCK_item_func_sleep);
4570   }
4571 }
4572 
4573 
4574 /** This function is just used to create tests with time gaps. */
4575 
val_int()4576 longlong Item_func_sleep::val_int()
4577 {
4578   THD *thd= current_thd;
4579   Interruptible_wait timed_cond(thd);
4580   mysql_cond_t cond;
4581   double timeout;
4582   int error;
4583 
4584   DBUG_ASSERT(fixed == 1);
4585 
4586   timeout= args[0]->val_real();
4587   /*
4588     On 64-bit OSX mysql_cond_timedwait() waits forever
4589     if passed abstime time has already been exceeded by
4590     the system time.
4591     When given a very short timeout (< 10 mcs) just return
4592     immediately.
4593     We assume that the lines between this test and the call
4594     to mysql_cond_timedwait() will be executed in less than 0.00001 sec.
4595   */
4596   if (timeout < 0.00001)
4597     return 0;
4598 
4599   timed_cond.set_timeout((ulonglong) (timeout * 1000000000.0));
4600 
4601   mysql_cond_init(key_item_func_sleep_cond, &cond, NULL);
4602   mysql_mutex_lock(&LOCK_item_func_sleep);
4603 
4604   THD_STAGE_INFO(thd, stage_user_sleep);
4605   thd->mysys_var->current_mutex= &LOCK_item_func_sleep;
4606   thd->mysys_var->current_cond=  &cond;
4607 
4608   error= 0;
4609   thd_wait_begin(thd, THD_WAIT_SLEEP);
4610   while (!thd->killed)
4611   {
4612     error= timed_cond.wait(&cond, &LOCK_item_func_sleep);
4613     if (error == ETIMEDOUT || error == ETIME)
4614       break;
4615     error= 0;
4616   }
4617   thd_wait_end(thd);
4618   mysql_mutex_unlock(&LOCK_item_func_sleep);
4619   mysql_mutex_lock(&thd->mysys_var->mutex);
4620   thd->mysys_var->current_mutex= 0;
4621   thd->mysys_var->current_cond=  0;
4622   mysql_mutex_unlock(&thd->mysys_var->mutex);
4623 
4624   mysql_cond_destroy(&cond);
4625 
4626   DBUG_EXECUTE_IF("sleep_inject_query_done_debug_sync", {
4627       debug_sync_set_action
4628         (thd, STRING_WITH_LEN("dispatch_command_end SIGNAL query_done"));
4629     };);
4630 
4631   return MY_TEST(!error);                  // Return 1 killed
4632 }
4633 
4634 
check_vcol_func_processor(void * arg)4635 bool Item_func_user_var::check_vcol_func_processor(void *arg)
4636 {
4637   return mark_unsupported_function("@", name.str, arg, VCOL_NON_DETERMINISTIC);
4638 }
4639 
4640 #define extra_size sizeof(double)
4641 
get_variable(HASH * hash,LEX_CSTRING * name,bool create_if_not_exists)4642 user_var_entry *get_variable(HASH *hash, LEX_CSTRING *name,
4643                              bool create_if_not_exists)
4644 {
4645   user_var_entry *entry;
4646 
4647   if (!(entry = (user_var_entry*) my_hash_search(hash, (uchar*) name->str,
4648                                                  name->length)) &&
4649       create_if_not_exists)
4650   {
4651     size_t size=ALIGN_SIZE(sizeof(user_var_entry))+name->length+1+extra_size;
4652     if (!my_hash_inited(hash))
4653       return 0;
4654     if (!(entry = (user_var_entry*) my_malloc(key_memory_user_var_entry, size,
4655                                               MYF(MY_WME | ME_FATAL |
4656                                                   MY_THREAD_SPECIFIC))))
4657       return 0;
4658     entry->name.str=(char*) entry+ ALIGN_SIZE(sizeof(user_var_entry))+
4659       extra_size;
4660     entry->name.length=name->length;
4661     entry->value=0;
4662     entry->length=0;
4663     entry->update_query_id=0;
4664     entry->set_charset(NULL);
4665     entry->unsigned_flag= 0;
4666     /*
4667       If we are here, we were called from a SET or a query which sets a
4668       variable. Imagine it is this:
4669       INSERT INTO t SELECT @a:=10, @a:=@a+1.
4670       Then when we have a Item_func_get_user_var (because of the @a+1) so we
4671       think we have to write the value of @a to the binlog. But before that,
4672       we have a Item_func_set_user_var to create @a (@a:=10), in this we mark
4673       the variable as "already logged" (line below) so that it won't be logged
4674       by Item_func_get_user_var (because that's not necessary).
4675     */
4676     entry->used_query_id=current_thd->query_id;
4677     entry->type=STRING_RESULT;
4678     memcpy((char*) entry->name.str, name->str, name->length+1);
4679     if (my_hash_insert(hash,(uchar*) entry))
4680     {
4681       my_free(entry);
4682       return 0;
4683     }
4684   }
4685   return entry;
4686 }
4687 
4688 
cleanup()4689 void Item_func_set_user_var::cleanup()
4690 {
4691   Item_func::cleanup();
4692   m_var_entry= NULL;
4693 }
4694 
4695 
set_entry(THD * thd,bool create_if_not_exists)4696 bool Item_func_set_user_var::set_entry(THD *thd, bool create_if_not_exists)
4697 {
4698   if (m_var_entry && thd->thread_id == entry_thread_id)
4699     goto end; // update entry->update_query_id for PS
4700   if (!(m_var_entry= get_variable(&thd->user_vars, &name, create_if_not_exists)))
4701   {
4702     entry_thread_id= 0;
4703     return TRUE;
4704   }
4705   entry_thread_id= thd->thread_id;
4706   /*
4707      Remember the last query which updated it, this way a query can later know
4708      if this variable is a constant item in the query (it is if update_query_id
4709      is different from query_id).
4710   */
4711 end:
4712   m_var_entry->update_query_id= thd->query_id;
4713   return FALSE;
4714 }
4715 
4716 
4717 /*
4718   When a user variable is updated (in a SET command or a query like
4719   SELECT @a:= ).
4720 */
4721 
fix_fields(THD * thd,Item ** ref)4722 bool Item_func_set_user_var::fix_fields(THD *thd, Item **ref)
4723 {
4724   DBUG_ASSERT(fixed == 0);
4725   /* fix_fields will call Item_func_set_user_var::fix_length_and_dec */
4726   if (Item_func::fix_fields(thd, ref) || set_entry(thd, TRUE))
4727     return TRUE;
4728   /*
4729     As it is wrong and confusing to associate any
4730     character set with NULL, @a should be latin2
4731     after this query sequence:
4732 
4733       SET @a=_latin2'string';
4734       SET @a=NULL;
4735 
4736     I.e. the second query should not change the charset
4737     to the current default value, but should keep the
4738     original value assigned during the first query.
4739     In order to do it, we don't copy charset
4740     from the argument if the argument is NULL
4741     and the variable has previously been initialized.
4742   */
4743   null_item= (args[0]->type() == NULL_ITEM);
4744   if (!m_var_entry->charset() || !null_item)
4745     m_var_entry->set_charset(args[0]->collation.derivation == DERIVATION_NUMERIC ?
4746                              &my_charset_numeric : args[0]->collation.collation);
4747   collation.set(m_var_entry->charset(),
4748                 args[0]->collation.derivation == DERIVATION_NUMERIC ?
4749                 DERIVATION_NUMERIC : DERIVATION_IMPLICIT);
4750   switch (args[0]->result_type()) {
4751   case STRING_RESULT:
4752   case TIME_RESULT:
4753     set_handler(type_handler_long_blob.
4754                 type_handler_adjusted_to_max_octet_length(max_length,
4755                                                           collation.collation));
4756     break;
4757   case REAL_RESULT:
4758     set_handler(&type_handler_double);
4759     break;
4760   case INT_RESULT:
4761     set_handler(Type_handler::type_handler_long_or_longlong(max_char_length(),
4762                                                             unsigned_flag));
4763     break;
4764   case DECIMAL_RESULT:
4765     set_handler(&type_handler_newdecimal);
4766     break;
4767   case ROW_RESULT:
4768     DBUG_ASSERT(0);
4769     set_handler(&type_handler_row);
4770     break;
4771   }
4772   if (thd->lex->current_select)
4773   {
4774     /*
4775       When this function is used in a derived table/view force the derived
4776       table to be materialized to preserve possible side-effect of setting a
4777       user variable.
4778     */
4779     SELECT_LEX_UNIT *unit= thd->lex->current_select->master_unit();
4780     TABLE_LIST *derived;
4781     for (derived= unit->derived;
4782          derived;
4783          derived= unit->derived)
4784     {
4785       derived->set_materialized_derived();
4786       derived->prohibit_cond_pushdown= true;
4787       if (unit->with_element && unit->with_element->is_recursive)
4788         break;
4789       unit= derived->select_lex->master_unit();
4790     }
4791   }
4792 
4793   return FALSE;
4794 }
4795 
4796 
4797 bool
fix_length_and_dec()4798 Item_func_set_user_var::fix_length_and_dec()
4799 {
4800   maybe_null=args[0]->maybe_null;
4801   decimals=args[0]->decimals;
4802   if (args[0]->collation.derivation == DERIVATION_NUMERIC)
4803   {
4804     collation.set(DERIVATION_NUMERIC);
4805     fix_length_and_charset(args[0]->max_char_length(), &my_charset_numeric);
4806   }
4807   else
4808   {
4809     collation.set(DERIVATION_IMPLICIT);
4810     fix_length_and_charset(args[0]->max_char_length(),
4811                            args[0]->collation.collation);
4812   }
4813   unsigned_flag= args[0]->unsigned_flag;
4814   return FALSE;
4815 }
4816 
4817 
4818 /*
4819   Mark field in read_map
4820 
4821   NOTES
4822     This is used by filesort to register used fields in a a temporary
4823     column read set or to register used fields in a view
4824 */
4825 
register_field_in_read_map(void * arg)4826 bool Item_func_set_user_var::register_field_in_read_map(void *arg)
4827 {
4828   if (result_field)
4829   {
4830     TABLE *table= (TABLE *) arg;
4831     if (result_field->table == table || !table)
4832       bitmap_set_bit(result_field->table->read_set, result_field->field_index);
4833     if (result_field->vcol_info)
4834       return result_field->vcol_info->
4835                expr->walk(&Item::register_field_in_read_map, 1, arg);
4836   }
4837   return 0;
4838 }
4839 
4840 /*
4841   Mark field in bitmap supplied as *arg
4842 
4843 */
4844 
register_field_in_bitmap(void * arg)4845 bool Item_func_set_user_var::register_field_in_bitmap(void *arg)
4846 {
4847   MY_BITMAP *bitmap = (MY_BITMAP *) arg;
4848   DBUG_ASSERT(bitmap);
4849   if (result_field)
4850   {
4851     if (!bitmap)
4852       return 1;
4853     bitmap_set_bit(bitmap, result_field->field_index);
4854   }
4855   return 0;
4856 }
4857 
4858 /**
4859   Set value to user variable.
4860 
4861   @param entry          pointer to structure representing variable
4862   @param set_null       should we set NULL value ?
4863   @param ptr            pointer to buffer with new value
4864   @param length         length of new value
4865   @param type           type of new value
4866   @param cs             charset info for new value
4867   @param dv             derivation for new value
4868   @param unsigned_arg   indicates if a value of type INT_RESULT is unsigned
4869 
4870   @note Sets error and fatal error if allocation fails.
4871 
4872   @retval
4873     false   success
4874   @retval
4875     true    failure
4876 */
4877 
4878 bool
update_hash(user_var_entry * entry,bool set_null,void * ptr,size_t length,Item_result type,CHARSET_INFO * cs,bool unsigned_arg)4879 update_hash(user_var_entry *entry, bool set_null, void *ptr, size_t length,
4880             Item_result type, CHARSET_INFO *cs,
4881             bool unsigned_arg)
4882 {
4883   if (set_null)
4884   {
4885     char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
4886     if (entry->value && entry->value != pos)
4887       my_free(entry->value);
4888     entry->value= 0;
4889     entry->length= 0;
4890   }
4891   else
4892   {
4893     if (type == STRING_RESULT)
4894       length++;					// Store strings with end \0
4895     if (length <= extra_size)
4896     {
4897       /* Save value in value struct */
4898       char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
4899       if (entry->value != pos)
4900       {
4901 	if (entry->value)
4902 	  my_free(entry->value);
4903 	entry->value=pos;
4904       }
4905     }
4906     else
4907     {
4908       /* Allocate variable */
4909       if (entry->length != length)
4910       {
4911 	char *pos= (char*) entry+ ALIGN_SIZE(sizeof(user_var_entry));
4912 	if (entry->value == pos)
4913 	  entry->value=0;
4914         entry->value= (char*) my_realloc(key_memory_user_var_entry_value,
4915                                          entry->value, length,
4916                                          MYF(MY_ALLOW_ZERO_PTR | MY_WME |
4917                                              ME_FATAL | MY_THREAD_SPECIFIC));
4918         if (!entry->value)
4919 	  return 1;
4920       }
4921     }
4922     if (type == STRING_RESULT)
4923     {
4924       length--;					// Fix length change above
4925       entry->value[length]= 0;			// Store end \0
4926     }
4927     if (length)
4928       memmove(entry->value, ptr, length);
4929     if (type == DECIMAL_RESULT)
4930       ((my_decimal*)entry->value)->fix_buffer_pointer();
4931     entry->length= length;
4932     entry->set_charset(cs);
4933     entry->unsigned_flag= unsigned_arg;
4934   }
4935   entry->type=type;
4936 #ifdef USER_VAR_TRACKING
4937 #ifndef EMBEDDED_LIBRARY
4938   THD *thd= current_thd;
4939   thd->session_tracker.user_variables.mark_as_changed(thd, entry);
4940 #endif
4941 #endif // USER_VAR_TRACKING
4942   return 0;
4943 }
4944 
4945 
4946 bool
update_hash(void * ptr,size_t length,Item_result res_type,CHARSET_INFO * cs,bool unsigned_arg)4947 Item_func_set_user_var::update_hash(void *ptr, size_t length,
4948                                     Item_result res_type,
4949                                     CHARSET_INFO *cs,
4950                                     bool unsigned_arg)
4951 {
4952   /*
4953     If we set a variable explicitly to NULL then keep the old
4954     result type of the variable
4955   */
4956   if (args[0]->type() == Item::FIELD_ITEM)
4957   {
4958     /* args[0]->null_value may be outdated */
4959     null_value= ((Item_field*)args[0])->field->is_null();
4960   }
4961   else
4962     null_value= args[0]->null_value;
4963   if (null_value && null_item)
4964     res_type= m_var_entry->type;                 // Don't change type of item
4965   if (::update_hash(m_var_entry, null_value,
4966                     ptr, length, res_type, cs, unsigned_arg))
4967   {
4968     null_value= 1;
4969     return 1;
4970   }
4971   return 0;
4972 }
4973 
4974 
4975 /** Get the value of a variable as a double. */
4976 
val_real(bool * null_value)4977 double user_var_entry::val_real(bool *null_value)
4978 {
4979   if ((*null_value= (value == 0)))
4980     return 0.0;
4981 
4982   switch (type) {
4983   case REAL_RESULT:
4984     return *(double*) value;
4985   case INT_RESULT:
4986     return (double) *(longlong*) value;
4987   case DECIMAL_RESULT:
4988     return ((my_decimal *)value)->to_double();
4989   case STRING_RESULT:
4990     return my_atof(value);                      // This is null terminated
4991   case ROW_RESULT:
4992   case TIME_RESULT:
4993     DBUG_ASSERT(0);				// Impossible
4994     break;
4995   }
4996   return 0.0;					// Impossible
4997 }
4998 
4999 
5000 /** Get the value of a variable as an integer. */
5001 
val_int(bool * null_value) const5002 longlong user_var_entry::val_int(bool *null_value) const
5003 {
5004   if ((*null_value= (value == 0)))
5005     return 0;
5006 
5007   switch (type) {
5008   case REAL_RESULT:
5009     return (longlong) *(double*) value;
5010   case INT_RESULT:
5011     return *(longlong*) value;
5012   case DECIMAL_RESULT:
5013     return ((my_decimal *)value)->to_longlong(false);
5014   case STRING_RESULT:
5015   {
5016     int error;
5017     return my_strtoll10(value, (char**) 0, &error);// String is null terminated
5018   }
5019   case ROW_RESULT:
5020   case TIME_RESULT:
5021     DBUG_ASSERT(0);				// Impossible
5022     break;
5023   }
5024   return 0;					// Impossible
5025 }
5026 
5027 
5028 /** Get the value of a variable as a string. */
5029 
val_str(bool * null_value,String * str,uint decimals) const5030 String *user_var_entry::val_str(bool *null_value, String *str,
5031                                 uint decimals) const
5032 {
5033   if ((*null_value= (value == 0)))
5034     return (String*) 0;
5035 
5036   switch (type) {
5037   case REAL_RESULT:
5038     str->set_real(*(double*) value, decimals, charset());
5039     break;
5040   case INT_RESULT:
5041     if (!unsigned_flag)
5042       str->set(*(longlong*) value, charset());
5043     else
5044       str->set(*(ulonglong*) value, charset());
5045     break;
5046   case DECIMAL_RESULT:
5047     str_set_decimal((my_decimal *) value, str, charset());
5048     break;
5049   case STRING_RESULT:
5050     if (str->copy(value, length, charset()))
5051       str= 0;					// EOM error
5052     break;
5053   case ROW_RESULT:
5054   case TIME_RESULT:
5055     DBUG_ASSERT(0);				// Impossible
5056     break;
5057   }
5058   return(str);
5059 }
5060 
5061 /** Get the value of a variable as a decimal. */
5062 
val_decimal(bool * null_value,my_decimal * val)5063 my_decimal *user_var_entry::val_decimal(bool *null_value, my_decimal *val)
5064 {
5065   if ((*null_value= (value == 0)))
5066     return 0;
5067 
5068   switch (type) {
5069   case REAL_RESULT:
5070     double2my_decimal(E_DEC_FATAL_ERROR, *(double*) value, val);
5071     break;
5072   case INT_RESULT:
5073     int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) value, 0, val);
5074     break;
5075   case DECIMAL_RESULT:
5076     my_decimal2decimal((my_decimal *) value, val);
5077     break;
5078   case STRING_RESULT:
5079     str2my_decimal(E_DEC_FATAL_ERROR, value, length, charset(), val);
5080     break;
5081   case ROW_RESULT:
5082   case TIME_RESULT:
5083     DBUG_ASSERT(0);				// Impossible
5084     break;
5085   }
5086   return(val);
5087 }
5088 
5089 /**
5090   This functions is invoked on SET \@variable or
5091   \@variable:= expression.
5092 
5093   Evaluate (and check expression), store results.
5094 
5095   @note
5096     For now it always return OK. All problem with value evaluating
5097     will be caught by thd->is_error() check in sql_set_variables().
5098 
5099   @retval
5100     FALSE OK.
5101 */
5102 
5103 bool
check(bool use_result_field)5104 Item_func_set_user_var::check(bool use_result_field)
5105 {
5106   DBUG_ENTER("Item_func_set_user_var::check");
5107   if (use_result_field && !result_field)
5108     use_result_field= FALSE;
5109 
5110   switch (result_type()) {
5111   case REAL_RESULT:
5112   {
5113     save_result.vreal= use_result_field ? result_field->val_real() :
5114                         args[0]->val_real();
5115     break;
5116   }
5117   case INT_RESULT:
5118   {
5119     save_result.vint= use_result_field ? result_field->val_int() :
5120                        args[0]->val_int();
5121     unsigned_flag= (use_result_field ?
5122                     ((Field_num*)result_field)->unsigned_flag:
5123                     args[0]->unsigned_flag);
5124     break;
5125   }
5126   case STRING_RESULT:
5127   {
5128     save_result.vstr= use_result_field ? result_field->val_str(&value) :
5129                        args[0]->val_str(&value);
5130     break;
5131   }
5132   case DECIMAL_RESULT:
5133   {
5134     save_result.vdec= use_result_field ?
5135                        result_field->val_decimal(&decimal_buff) :
5136                        args[0]->val_decimal(&decimal_buff);
5137     break;
5138   }
5139   case ROW_RESULT:
5140   case TIME_RESULT:
5141     DBUG_ASSERT(0);                // This case should never be chosen
5142     break;
5143   }
5144   DBUG_RETURN(FALSE);
5145 }
5146 
5147 
5148 /**
5149   @brief Evaluate and store item's result.
5150   This function is invoked on "SELECT ... INTO @var ...".
5151 
5152   @param    item    An item to get value from.
5153 */
5154 
save_item_result(Item * item)5155 void Item_func_set_user_var::save_item_result(Item *item)
5156 {
5157   DBUG_ENTER("Item_func_set_user_var::save_item_result");
5158 
5159   switch (args[0]->result_type()) {
5160   case REAL_RESULT:
5161     save_result.vreal= item->val_result();
5162     break;
5163   case INT_RESULT:
5164     save_result.vint= item->val_int_result();
5165     unsigned_flag= item->unsigned_flag;
5166     break;
5167   case STRING_RESULT:
5168     save_result.vstr= item->str_result(&value);
5169     break;
5170   case DECIMAL_RESULT:
5171     save_result.vdec= item->val_decimal_result(&decimal_buff);
5172     break;
5173   case ROW_RESULT:
5174   case TIME_RESULT:
5175     DBUG_ASSERT(0);                // This case should never be chosen
5176     break;
5177   }
5178   DBUG_VOID_RETURN;
5179 }
5180 
5181 
5182 /**
5183   This functions is invoked on
5184   SET \@variable or \@variable:= expression.
5185 
5186   @note
5187     We have to store the expression as such in the variable, independent of
5188     the value method used by the user
5189 
5190   @retval
5191     0	OK
5192   @retval
5193     1	EOM Error
5194 
5195 */
5196 
5197 bool
update()5198 Item_func_set_user_var::update()
5199 {
5200   bool res= 0;
5201   DBUG_ENTER("Item_func_set_user_var::update");
5202 
5203   switch (result_type()) {
5204   case REAL_RESULT:
5205   {
5206     res= update_hash((void*) &save_result.vreal,sizeof(save_result.vreal),
5207 		     REAL_RESULT, &my_charset_numeric, 0);
5208     break;
5209   }
5210   case INT_RESULT:
5211   {
5212     res= update_hash((void*) &save_result.vint, sizeof(save_result.vint),
5213                      INT_RESULT, &my_charset_numeric, unsigned_flag);
5214     break;
5215   }
5216   case STRING_RESULT:
5217   {
5218     if (!save_result.vstr)					// Null value
5219       res= update_hash((void*) 0, 0, STRING_RESULT, &my_charset_bin, 0);
5220     else
5221       res= update_hash((void*) save_result.vstr->ptr(),
5222 		       save_result.vstr->length(), STRING_RESULT,
5223 		       save_result.vstr->charset(), 0);
5224     break;
5225   }
5226   case DECIMAL_RESULT:
5227   {
5228     if (!save_result.vdec)					// Null value
5229       res= update_hash((void*) 0, 0, DECIMAL_RESULT, &my_charset_bin, 0);
5230     else
5231       res= update_hash((void*) save_result.vdec,
5232                        sizeof(my_decimal), DECIMAL_RESULT,
5233                        &my_charset_numeric, 0);
5234     break;
5235   }
5236   case ROW_RESULT:
5237   case TIME_RESULT:
5238     DBUG_ASSERT(0);                // This case should never be chosen
5239     break;
5240   }
5241   DBUG_RETURN(res);
5242 }
5243 
5244 
val_real()5245 double Item_func_set_user_var::val_real()
5246 {
5247   DBUG_ASSERT(fixed == 1);
5248   check(0);
5249   update();					// Store expression
5250   return m_var_entry->val_real(&null_value);
5251 }
5252 
val_int()5253 longlong Item_func_set_user_var::val_int()
5254 {
5255   DBUG_ASSERT(fixed == 1);
5256   check(0);
5257   update();					// Store expression
5258   return m_var_entry->val_int(&null_value);
5259 }
5260 
val_str(String * str)5261 String *Item_func_set_user_var::val_str(String *str)
5262 {
5263   DBUG_ASSERT(fixed == 1);
5264   check(0);
5265   update();					// Store expression
5266   return m_var_entry->val_str(&null_value, str, decimals);
5267 }
5268 
5269 
val_decimal(my_decimal * val)5270 my_decimal *Item_func_set_user_var::val_decimal(my_decimal *val)
5271 {
5272   DBUG_ASSERT(fixed == 1);
5273   check(0);
5274   update();					// Store expression
5275   return m_var_entry->val_decimal(&null_value, val);
5276 }
5277 
5278 
val_result()5279 double Item_func_set_user_var::val_result()
5280 {
5281   DBUG_ASSERT(fixed == 1);
5282   check(TRUE);
5283   update();					// Store expression
5284   return m_var_entry->val_real(&null_value);
5285 }
5286 
val_int_result()5287 longlong Item_func_set_user_var::val_int_result()
5288 {
5289   DBUG_ASSERT(fixed == 1);
5290   check(TRUE);
5291   update();					// Store expression
5292   return m_var_entry->val_int(&null_value);
5293 }
5294 
val_bool_result()5295 bool Item_func_set_user_var::val_bool_result()
5296 {
5297   DBUG_ASSERT(fixed == 1);
5298   check(TRUE);
5299   update();					// Store expression
5300   return m_var_entry->val_int(&null_value) != 0;
5301 }
5302 
str_result(String * str)5303 String *Item_func_set_user_var::str_result(String *str)
5304 {
5305   DBUG_ASSERT(fixed == 1);
5306   check(TRUE);
5307   update();					// Store expression
5308   return m_var_entry->val_str(&null_value, str, decimals);
5309 }
5310 
5311 
val_decimal_result(my_decimal * val)5312 my_decimal *Item_func_set_user_var::val_decimal_result(my_decimal *val)
5313 {
5314   DBUG_ASSERT(fixed == 1);
5315   check(TRUE);
5316   update();					// Store expression
5317   return m_var_entry->val_decimal(&null_value, val);
5318 }
5319 
5320 
is_null_result()5321 bool Item_func_set_user_var::is_null_result()
5322 {
5323   DBUG_ASSERT(fixed == 1);
5324   check(TRUE);
5325   update();					// Store expression
5326   return is_null();
5327 }
5328 
5329 
print(String * str,enum_query_type query_type)5330 void Item_func_set_user_var::print(String *str, enum_query_type query_type)
5331 {
5332   str->append(STRING_WITH_LEN("@"));
5333   str->append(&name);
5334   str->append(STRING_WITH_LEN(":="));
5335   args[0]->print_parenthesised(str, query_type, precedence());
5336 }
5337 
5338 
print_as_stmt(String * str,enum_query_type query_type)5339 void Item_func_set_user_var::print_as_stmt(String *str,
5340                                            enum_query_type query_type)
5341 {
5342   str->append(STRING_WITH_LEN("set @"));
5343   str->append(&name);
5344   str->append(STRING_WITH_LEN(":="));
5345   args[0]->print_parenthesised(str, query_type, precedence());
5346 }
5347 
send(Protocol * protocol,st_value * buffer)5348 bool Item_func_set_user_var::send(Protocol *protocol, st_value *buffer)
5349 {
5350   if (result_field)
5351   {
5352     check(1);
5353     update();
5354     return protocol->store(result_field);
5355   }
5356   return Item::send(protocol, buffer);
5357 }
5358 
make_send_field(THD * thd,Send_field * tmp_field)5359 void Item_func_set_user_var::make_send_field(THD *thd, Send_field *tmp_field)
5360 {
5361   if (result_field)
5362   {
5363     result_field->make_send_field(tmp_field);
5364     DBUG_ASSERT(tmp_field->table_name.str != 0);
5365     if (Item::name.str)
5366       tmp_field->col_name= Item::name;          // Use user supplied name
5367   }
5368   else
5369     Item::make_send_field(thd, tmp_field);
5370 }
5371 
5372 
5373 /*
5374   Save the value of a user variable into a field
5375 
5376   SYNOPSIS
5377     save_in_field()
5378       field           target field to save the value to
5379       no_conversion   flag indicating whether conversions are allowed
5380 
5381   DESCRIPTION
5382     Save the function value into a field and update the user variable
5383     accordingly. If a result field is defined and the target field doesn't
5384     coincide with it then the value from the result field will be used as
5385     the new value of the user variable.
5386 
5387     The reason to have this method rather than simply using the result
5388     field in the val_xxx() methods is that the value from the result field
5389     not always can be used when the result field is defined.
5390     Let's consider the following cases:
5391     1) when filling a tmp table the result field is defined but the value of it
5392     is undefined because it has to be produced yet. Thus we can't use it.
5393     2) on execution of an INSERT ... SELECT statement the save_in_field()
5394     function will be called to fill the data in the new record. If the SELECT
5395     part uses a tmp table then the result field is defined and should be
5396     used in order to get the correct result.
5397 
5398     The difference between the SET_USER_VAR function and regular functions
5399     like CONCAT is that the Item_func objects for the regular functions are
5400     replaced by Item_field objects after the values of these functions have
5401     been stored in a tmp table. Yet an object of the Item_field class cannot
5402     be used to update a user variable.
5403     Due to this we have to handle the result field in a special way here and
5404     in the Item_func_set_user_var::send() function.
5405 
5406   RETURN VALUES
5407     FALSE       Ok
5408     TRUE        Error
5409 */
5410 
save_in_field(Field * field,bool no_conversions,bool can_use_result_field)5411 int Item_func_set_user_var::save_in_field(Field *field, bool no_conversions,
5412                                           bool can_use_result_field)
5413 {
5414   bool use_result_field= (!can_use_result_field ? 0 :
5415                           (result_field && result_field != field));
5416   int error;
5417 
5418   /* Update the value of the user variable */
5419   check(use_result_field);
5420   update();
5421 
5422   if (result_type() == STRING_RESULT ||
5423       (result_type() == REAL_RESULT &&
5424        field->result_type() == STRING_RESULT))
5425   {
5426     String *result;
5427     CHARSET_INFO *cs= collation.collation;
5428     char buff[MAX_FIELD_WIDTH];		// Alloc buffer for small columns
5429     str_value.set_quick(buff, sizeof(buff), cs);
5430     result= m_var_entry->val_str(&null_value, &str_value, decimals);
5431 
5432     if (null_value)
5433     {
5434       str_value.set_quick(0, 0, cs);
5435       return set_field_to_null_with_conversions(field, no_conversions);
5436     }
5437 
5438     /* NOTE: If null_value == FALSE, "result" must be not NULL.  */
5439 
5440     field->set_notnull();
5441     error=field->store(result->ptr(),result->length(),cs);
5442     str_value.set_quick(0, 0, cs);
5443   }
5444   else if (result_type() == REAL_RESULT)
5445   {
5446     double nr= m_var_entry->val_real(&null_value);
5447     if (null_value)
5448       return set_field_to_null(field);
5449     field->set_notnull();
5450     error=field->store(nr);
5451   }
5452   else if (result_type() == DECIMAL_RESULT)
5453   {
5454     my_decimal decimal_value;
5455     my_decimal *val= m_var_entry->val_decimal(&null_value, &decimal_value);
5456     if (null_value)
5457       return set_field_to_null(field);
5458     field->set_notnull();
5459     error=field->store_decimal(val);
5460   }
5461   else
5462   {
5463     longlong nr= m_var_entry->val_int(&null_value);
5464     if (null_value)
5465       return set_field_to_null_with_conversions(field, no_conversions);
5466     field->set_notnull();
5467     error=field->store(nr, unsigned_flag);
5468   }
5469   return error;
5470 }
5471 
5472 
5473 String *
val_str(String * str)5474 Item_func_get_user_var::val_str(String *str)
5475 {
5476   DBUG_ASSERT(fixed == 1);
5477   DBUG_ENTER("Item_func_get_user_var::val_str");
5478   if (!m_var_entry)
5479     DBUG_RETURN((String*) 0);			// No such variable
5480   DBUG_RETURN(m_var_entry->val_str(&null_value, str, decimals));
5481 }
5482 
5483 
val_real()5484 double Item_func_get_user_var::val_real()
5485 {
5486   DBUG_ASSERT(fixed == 1);
5487   if (!m_var_entry)
5488     return 0.0;					// No such variable
5489   return (m_var_entry->val_real(&null_value));
5490 }
5491 
5492 
val_decimal(my_decimal * dec)5493 my_decimal *Item_func_get_user_var::val_decimal(my_decimal *dec)
5494 {
5495   DBUG_ASSERT(fixed == 1);
5496   if (!m_var_entry)
5497     return 0;
5498   return m_var_entry->val_decimal(&null_value, dec);
5499 }
5500 
5501 
val_int()5502 longlong Item_func_get_user_var::val_int()
5503 {
5504   DBUG_ASSERT(fixed == 1);
5505   if (!m_var_entry)
5506     return 0;				// No such variable
5507   return (m_var_entry->val_int(&null_value));
5508 }
5509 
5510 
5511 /**
5512   Get variable by name and, if necessary, put the record of variable
5513   use into the binary log.
5514 
5515   When a user variable is invoked from an update query (INSERT, UPDATE etc),
5516   stores this variable and its value in thd->user_var_events, so that it can be
5517   written to the binlog (will be written just before the query is written, see
5518   log.cc).
5519 
5520   @param      thd        Current thread
5521   @param      name       Variable name
5522   @param[out] out_entry  variable structure or NULL. The pointer is set
5523                          regardless of whether function succeeded or not.
5524 
5525   @retval
5526     0  OK
5527   @retval
5528     1  Failed to put appropriate record into binary log
5529 
5530 */
5531 
5532 static int
get_var_with_binlog(THD * thd,enum_sql_command sql_command,LEX_CSTRING * name,user_var_entry ** out_entry)5533 get_var_with_binlog(THD *thd, enum_sql_command sql_command,
5534                     LEX_CSTRING *name, user_var_entry **out_entry)
5535 {
5536   BINLOG_USER_VAR_EVENT *user_var_event;
5537   user_var_entry *var_entry;
5538   var_entry= get_variable(&thd->user_vars, name, 0);
5539 
5540   /*
5541     Any reference to user-defined variable which is done from stored
5542     function or trigger affects their execution and the execution of the
5543     calling statement. We must log all such variables even if they are
5544     not involved in table-updating statements.
5545   */
5546   if (!(opt_bin_log &&
5547        (is_update_query(sql_command) || thd->in_sub_stmt)))
5548   {
5549     *out_entry= var_entry;
5550     return 0;
5551   }
5552 
5553   if (!var_entry)
5554   {
5555     /*
5556       If the variable does not exist, it's NULL, but we want to create it so
5557       that it gets into the binlog (if it didn't, the slave could be
5558       influenced by a variable of the same name previously set by another
5559       thread).
5560       We create it like if it had been explicitly set with SET before.
5561       The 'new' mimics what sql_yacc.yy does when 'SET @a=10;'.
5562       sql_set_variables() is what is called from 'case SQLCOM_SET_OPTION'
5563       in dispatch_command()). Instead of building a one-element list to pass to
5564       sql_set_variables(), we could instead manually call check() and update();
5565       this would save memory and time; but calling sql_set_variables() makes
5566       one unique place to maintain (sql_set_variables()).
5567 
5568       Manipulation with lex is necessary since free_underlaid_joins
5569       is going to release memory belonging to the main query.
5570     */
5571 
5572     List<set_var_base> tmp_var_list;
5573     LEX *sav_lex= thd->lex, lex_tmp;
5574     thd->lex= &lex_tmp;
5575     lex_start(thd);
5576     tmp_var_list.push_back(new (thd->mem_root)
5577                            set_var_user(new (thd->mem_root)
5578                                         Item_func_set_user_var(thd, name,
5579                                                                new (thd->mem_root) Item_null(thd))),
5580                            thd->mem_root);
5581     /* Create the variable if the above allocations succeeded */
5582     if (unlikely(thd->is_fatal_error) ||
5583         unlikely(sql_set_variables(thd, &tmp_var_list, false)))
5584     {
5585       thd->lex= sav_lex;
5586       goto err;
5587     }
5588     thd->lex= sav_lex;
5589     if (unlikely(!(var_entry= get_variable(&thd->user_vars, name, 0))))
5590       goto err;
5591   }
5592   else if (var_entry->used_query_id == thd->query_id ||
5593            mysql_bin_log.is_query_in_union(thd, var_entry->used_query_id))
5594   {
5595     /*
5596        If this variable was already stored in user_var_events by this query
5597        (because it's used in more than one place in the query), don't store
5598        it.
5599     */
5600     *out_entry= var_entry;
5601     return 0;
5602   }
5603 
5604   size_t size;
5605   /*
5606     First we need to store value of var_entry, when the next situation
5607     appears:
5608     > set @a:=1;
5609     > insert into t1 values (@a), (@a:=@a+1), (@a:=@a+1);
5610     We have to write to binlog value @a= 1.
5611 
5612     We allocate the user_var_event on user_var_events_alloc pool, not on
5613     the this-statement-execution pool because in SPs user_var_event objects
5614     may need to be valid after current [SP] statement execution pool is
5615     destroyed.
5616   */
5617   size= ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT)) + var_entry->length;
5618   if (unlikely(!(user_var_event= (BINLOG_USER_VAR_EVENT *)
5619                  alloc_root(thd->user_var_events_alloc, size))))
5620     goto err;
5621 
5622   user_var_event->value= (char*) user_var_event +
5623     ALIGN_SIZE(sizeof(BINLOG_USER_VAR_EVENT));
5624   user_var_event->user_var_event= var_entry;
5625   user_var_event->type= var_entry->type;
5626   user_var_event->charset_number= var_entry->charset()->number;
5627   user_var_event->unsigned_flag= var_entry->unsigned_flag;
5628   if (!var_entry->value)
5629   {
5630     /* NULL value*/
5631     user_var_event->length= 0;
5632     user_var_event->value= 0;
5633   }
5634   else
5635   {
5636     user_var_event->length= var_entry->length;
5637     memcpy(user_var_event->value, var_entry->value,
5638            var_entry->length);
5639   }
5640   /* Mark that this variable has been used by this query */
5641   var_entry->used_query_id= thd->query_id;
5642   if (insert_dynamic(&thd->user_var_events, (uchar*) &user_var_event))
5643     goto err;
5644 
5645   *out_entry= var_entry;
5646   return 0;
5647 
5648 err:
5649   *out_entry= var_entry;
5650   return 1;
5651 }
5652 
fix_length_and_dec()5653 bool Item_func_get_user_var::fix_length_and_dec()
5654 {
5655   THD *thd=current_thd;
5656   int error;
5657   maybe_null=1;
5658   decimals=NOT_FIXED_DEC;
5659   max_length=MAX_BLOB_WIDTH;
5660 
5661   error= get_var_with_binlog(thd, thd->lex->sql_command, &name, &m_var_entry);
5662 
5663   /*
5664     If the variable didn't exist it has been created as a STRING-type.
5665     'm_var_entry' is NULL only if there occurred an error during the call to
5666     get_var_with_binlog.
5667   */
5668   if (likely(!error && m_var_entry))
5669   {
5670     unsigned_flag= m_var_entry->unsigned_flag;
5671     max_length= (uint32)m_var_entry->length;
5672     switch (m_var_entry->type) {
5673     case REAL_RESULT:
5674       collation.set(&my_charset_numeric, DERIVATION_NUMERIC);
5675       fix_char_length(DBL_DIG + 8);
5676       set_handler(&type_handler_double);
5677       break;
5678     case INT_RESULT:
5679       collation.set(&my_charset_numeric, DERIVATION_NUMERIC);
5680       fix_char_length(MAX_BIGINT_WIDTH);
5681       decimals=0;
5682       if (unsigned_flag)
5683         set_handler(&type_handler_ulonglong);
5684       else
5685         set_handler(&type_handler_slonglong);
5686       break;
5687     case STRING_RESULT:
5688       collation.set(m_var_entry->charset(), DERIVATION_IMPLICIT);
5689       max_length= MAX_BLOB_WIDTH - 1;
5690       set_handler(&type_handler_long_blob);
5691       break;
5692     case DECIMAL_RESULT:
5693       collation.set(&my_charset_numeric, DERIVATION_NUMERIC);
5694       fix_char_length(DECIMAL_MAX_STR_LENGTH);
5695       decimals= DECIMAL_MAX_SCALE;
5696       set_handler(&type_handler_newdecimal);
5697       break;
5698     case ROW_RESULT:                            // Keep compiler happy
5699     case TIME_RESULT:
5700       DBUG_ASSERT(0);                // This case should never be chosen
5701       break;
5702     }
5703   }
5704   else
5705   {
5706     collation.set(&my_charset_bin, DERIVATION_IMPLICIT);
5707     null_value= 1;
5708     set_handler(&type_handler_long_blob);
5709     max_length= MAX_BLOB_WIDTH;
5710   }
5711   return false;
5712 }
5713 
5714 
const_item() const5715 bool Item_func_get_user_var::const_item() const
5716 {
5717   return (!m_var_entry ||
5718           current_thd->query_id != m_var_entry->update_query_id);
5719 }
5720 
5721 
print(String * str,enum_query_type query_type)5722 void Item_func_get_user_var::print(String *str, enum_query_type query_type)
5723 {
5724   str->append(STRING_WITH_LEN("@"));
5725   append_identifier(current_thd, str, &name);
5726 }
5727 
5728 
eq(const Item * item,bool binary_cmp) const5729 bool Item_func_get_user_var::eq(const Item *item, bool binary_cmp) const
5730 {
5731   /* Assume we don't have rtti */
5732   if (this == item)
5733     return 1;					// Same item is same.
5734   /* Check if other type is also a get_user_var() object */
5735   if (item->type() != FUNC_ITEM ||
5736       ((Item_func*) item)->functype() != functype())
5737     return 0;
5738   Item_func_get_user_var *other=(Item_func_get_user_var*) item;
5739   return (name.length == other->name.length &&
5740 	  !memcmp(name.str, other->name.str, name.length));
5741 }
5742 
5743 
set_value(THD * thd,sp_rcontext *,Item ** it)5744 bool Item_func_get_user_var::set_value(THD *thd,
5745                                        sp_rcontext * /*ctx*/, Item **it)
5746 {
5747   LEX_CSTRING tmp_name= get_name();
5748   Item_func_set_user_var *suv= new (thd->mem_root) Item_func_set_user_var(thd, &tmp_name, *it);
5749   /*
5750     Item_func_set_user_var is not fixed after construction, call
5751     fix_fields().
5752   */
5753   return (!suv || suv->fix_fields(thd, it) || suv->check(0) || suv->update());
5754 }
5755 
5756 
fix_fields(THD * thd,Item ** ref)5757 bool Item_user_var_as_out_param::fix_fields(THD *thd, Item **ref)
5758 {
5759   DBUG_ASSERT(!is_fixed());
5760   DBUG_ASSERT(thd->lex->exchange);
5761   if (!(entry= get_variable(&thd->user_vars, &org_name, 1)))
5762     return TRUE;
5763   entry->type= STRING_RESULT;
5764   /*
5765     Let us set the same collation which is used for loading
5766     of fields in LOAD DATA INFILE.
5767     (Since Item_user_var_as_out_param is used only there).
5768   */
5769   entry->set_charset(thd->lex->exchange->cs ?
5770                      thd->lex->exchange->cs :
5771                      thd->variables.collation_database);
5772   entry->update_query_id= thd->query_id;
5773   return FALSE;
5774 }
5775 
5776 
set_null_value(CHARSET_INFO * cs)5777 void Item_user_var_as_out_param::set_null_value(CHARSET_INFO* cs)
5778 {
5779   ::update_hash(entry, TRUE, 0, 0, STRING_RESULT, cs, 0 /* unsigned_arg */);
5780 }
5781 
5782 
set_value(const char * str,uint length,CHARSET_INFO * cs)5783 void Item_user_var_as_out_param::set_value(const char *str, uint length,
5784                                            CHARSET_INFO* cs)
5785 {
5786   ::update_hash(entry, FALSE, (void*)str, length, STRING_RESULT, cs,
5787                 0 /* unsigned_arg */);
5788 }
5789 
5790 
val_real()5791 double Item_user_var_as_out_param::val_real()
5792 {
5793   DBUG_ASSERT(0);
5794   return 0.0;
5795 }
5796 
5797 
val_int()5798 longlong Item_user_var_as_out_param::val_int()
5799 {
5800   DBUG_ASSERT(0);
5801   return 0;
5802 }
5803 
5804 
val_str(String * str)5805 String* Item_user_var_as_out_param::val_str(String *str)
5806 {
5807   DBUG_ASSERT(0);
5808   return 0;
5809 }
5810 
5811 
val_decimal(my_decimal * decimal_buffer)5812 my_decimal* Item_user_var_as_out_param::val_decimal(my_decimal *decimal_buffer)
5813 {
5814   DBUG_ASSERT(0);
5815   return 0;
5816 }
5817 
5818 
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)5819 bool Item_user_var_as_out_param::get_date(THD *thd, MYSQL_TIME *ltime,
5820                                           date_mode_t fuzzydate)
5821 {
5822   DBUG_ASSERT(0);
5823   return true;
5824 }
5825 
5826 
load_data_print_for_log_event(THD * thd,String * str) const5827 void Item_user_var_as_out_param::load_data_print_for_log_event(THD *thd,
5828                                                                String *str)
5829                                                                const
5830 {
5831   str->append('@');
5832   append_identifier(thd, str, &org_name);
5833 }
5834 
5835 
5836 Item_func_get_system_var::
Item_func_get_system_var(THD * thd,sys_var * var_arg,enum_var_type var_type_arg,LEX_CSTRING * component_arg,const char * name_arg,size_t name_len_arg)5837 Item_func_get_system_var(THD *thd, sys_var *var_arg, enum_var_type var_type_arg,
5838                        LEX_CSTRING *component_arg, const char *name_arg,
5839                        size_t name_len_arg):
5840   Item_func(thd), var(var_arg), var_type(var_type_arg),
5841   orig_var_type(var_type_arg), component(*component_arg), cache_present(0)
5842 {
5843   /* set_name() will allocate the name */
5844   set_name(thd, name_arg, (uint) name_len_arg, system_charset_info);
5845 }
5846 
5847 
is_written_to_binlog()5848 bool Item_func_get_system_var::is_written_to_binlog()
5849 {
5850   return var->is_written_to_binlog(var_type);
5851 }
5852 
5853 
update_null_value()5854 void Item_func_get_system_var::update_null_value()
5855 {
5856   THD *thd= current_thd;
5857   int save_no_errors= thd->no_errors;
5858   thd->no_errors= TRUE;
5859   type_handler()->Item_update_null_value(this);
5860   thd->no_errors= save_no_errors;
5861 }
5862 
5863 
fix_length_and_dec()5864 bool Item_func_get_system_var::fix_length_and_dec()
5865 {
5866   const char *cptr;
5867   maybe_null= TRUE;
5868   max_length= 0;
5869 
5870   if (var->check_type(var_type))
5871   {
5872     if (var_type != OPT_DEFAULT)
5873     {
5874       my_error(ER_INCORRECT_GLOBAL_LOCAL_VAR, MYF(0),
5875                var->name.str, var_type == OPT_GLOBAL ? "SESSION" : "GLOBAL");
5876       return TRUE;
5877     }
5878     /* As there was no local variable, return the global value */
5879     var_type= OPT_GLOBAL;
5880   }
5881 
5882   switch (var->show_type())
5883   {
5884     case SHOW_HA_ROWS:
5885     case SHOW_UINT:
5886     case SHOW_ULONG:
5887     case SHOW_ULONGLONG:
5888       unsigned_flag= TRUE;
5889       /* fall through */
5890     case SHOW_SINT:
5891     case SHOW_SLONG:
5892     case SHOW_SLONGLONG:
5893       collation= DTCollation_numeric();
5894       fix_char_length(MY_INT64_NUM_DECIMAL_DIGITS);
5895       decimals=0;
5896       break;
5897     case SHOW_CHAR:
5898     case SHOW_CHAR_PTR:
5899       mysql_mutex_lock(&LOCK_global_system_variables);
5900       cptr= var->show_type() == SHOW_CHAR ?
5901           reinterpret_cast<const char*>(var->value_ptr(current_thd, var_type,
5902                                                        &component)) :
5903           *reinterpret_cast<const char* const*>(var->value_ptr(current_thd,
5904                                                                var_type,
5905                                                                &component));
5906       if (cptr)
5907         max_length= (uint32) system_charset_info->numchars(cptr,
5908                                                            cptr + strlen(cptr));
5909       mysql_mutex_unlock(&LOCK_global_system_variables);
5910       collation.set(system_charset_info, DERIVATION_SYSCONST);
5911       max_length*= system_charset_info->mbmaxlen;
5912       decimals=NOT_FIXED_DEC;
5913       break;
5914     case SHOW_LEX_STRING:
5915       {
5916         mysql_mutex_lock(&LOCK_global_system_variables);
5917         const LEX_STRING *ls=
5918                 reinterpret_cast<const LEX_STRING*>(var->value_ptr(current_thd,
5919                                                                    var_type,
5920                                                                    &component));
5921         max_length= (uint32) system_charset_info->numchars(ls->str,
5922                                                            ls->str + ls->length);
5923         mysql_mutex_unlock(&LOCK_global_system_variables);
5924         collation.set(system_charset_info, DERIVATION_SYSCONST);
5925         max_length*= system_charset_info->mbmaxlen;
5926         decimals=NOT_FIXED_DEC;
5927       }
5928       break;
5929     case SHOW_BOOL:
5930     case SHOW_MY_BOOL:
5931       collation= DTCollation_numeric();
5932       fix_char_length(1);
5933       decimals=0;
5934       break;
5935     case SHOW_DOUBLE:
5936       decimals= 6;
5937       collation= DTCollation_numeric();
5938       fix_char_length(DBL_DIG + 6);
5939       break;
5940     default:
5941       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
5942       break;
5943   }
5944   return FALSE;
5945 }
5946 
5947 
print(String * str,enum_query_type query_type)5948 void Item_func_get_system_var::print(String *str, enum_query_type query_type)
5949 {
5950   if (name.length)
5951     str->append(&name);
5952   else
5953   {
5954     str->append(STRING_WITH_LEN("@@"));
5955     if (component.length)
5956     {
5957       str->append(&component);
5958       str->append('.');
5959     }
5960     else if (var_type == SHOW_OPT_GLOBAL && var->scope() != sys_var::GLOBAL)
5961     {
5962       str->append(STRING_WITH_LEN("global."));
5963     }
5964     str->append(&var->name);
5965   }
5966 }
5967 
check_vcol_func_processor(void * arg)5968 bool Item_func_get_system_var::check_vcol_func_processor(void *arg)
5969 {
5970   return mark_unsupported_function("@@", var->name.str, arg, VCOL_SESSION_FUNC);
5971 }
5972 
5973 
type_handler() const5974 const Type_handler *Item_func_get_system_var::type_handler() const
5975 {
5976   switch (var->show_type())
5977   {
5978     case SHOW_BOOL:
5979     case SHOW_MY_BOOL:
5980     case SHOW_SINT:
5981     case SHOW_SLONG:
5982     case SHOW_SLONGLONG:
5983       return &type_handler_slonglong;
5984     case SHOW_UINT:
5985     case SHOW_ULONG:
5986     case SHOW_ULONGLONG:
5987     case SHOW_HA_ROWS:
5988       return &type_handler_ulonglong;
5989     case SHOW_CHAR:
5990     case SHOW_CHAR_PTR:
5991     case SHOW_LEX_STRING:
5992       return &type_handler_varchar;
5993     case SHOW_DOUBLE:
5994       return &type_handler_double;
5995     default:
5996       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
5997       return &type_handler_varchar;              // keep the compiler happy
5998   }
5999 }
6000 
6001 
val_int()6002 longlong Item_func_get_system_var::val_int()
6003 {
6004   THD *thd= current_thd;
6005 
6006   DBUG_EXECUTE_IF("simulate_non_gtid_aware_master",
6007                   {
6008                     if (0 == strcmp("gtid_domain_id", var->name.str))
6009                     {
6010                       my_error(ER_VAR_CANT_BE_READ, MYF(0), var->name.str);
6011                       return 0;
6012                     }
6013                   });
6014   if (cache_present && thd->query_id == used_query_id)
6015   {
6016     if (cache_present & GET_SYS_VAR_CACHE_LONG)
6017     {
6018       null_value= cached_null_value;
6019       return cached_llval;
6020     }
6021     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
6022     {
6023       null_value= cached_null_value;
6024       cached_llval= (longlong) cached_dval;
6025       cache_present|= GET_SYS_VAR_CACHE_LONG;
6026       return cached_llval;
6027     }
6028     else if (cache_present & GET_SYS_VAR_CACHE_STRING)
6029     {
6030       null_value= cached_null_value;
6031       if (!null_value)
6032         cached_llval= longlong_from_string_with_check(&cached_strval);
6033       else
6034         cached_llval= 0;
6035       cache_present|= GET_SYS_VAR_CACHE_LONG;
6036       return cached_llval;
6037     }
6038   }
6039 
6040   cached_llval= var->val_int(&null_value, thd, var_type, &component);
6041   cache_present |= GET_SYS_VAR_CACHE_LONG;
6042   used_query_id= thd->query_id;
6043   cached_null_value= null_value;
6044   return cached_llval;
6045 }
6046 
6047 
val_str(String * str)6048 String* Item_func_get_system_var::val_str(String* str)
6049 {
6050   THD *thd= current_thd;
6051 
6052   if (cache_present && thd->query_id == used_query_id)
6053   {
6054     if (cache_present & GET_SYS_VAR_CACHE_STRING)
6055     {
6056       null_value= cached_null_value;
6057       return null_value ? NULL : &cached_strval;
6058     }
6059     else if (cache_present & GET_SYS_VAR_CACHE_LONG)
6060     {
6061       null_value= cached_null_value;
6062       if (!null_value)
6063         cached_strval.set (cached_llval, collation.collation);
6064       cache_present|= GET_SYS_VAR_CACHE_STRING;
6065       return null_value ? NULL : &cached_strval;
6066     }
6067     else if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
6068     {
6069       null_value= cached_null_value;
6070       if (!null_value)
6071         cached_strval.set_real (cached_dval, decimals, collation.collation);
6072       cache_present|= GET_SYS_VAR_CACHE_STRING;
6073       return null_value ? NULL : &cached_strval;
6074     }
6075   }
6076 
6077   str= var->val_str(&cached_strval, thd, var_type, &component);
6078   cache_present|= GET_SYS_VAR_CACHE_STRING;
6079   used_query_id= thd->query_id;
6080   cached_null_value= null_value= !str;
6081   return str;
6082 }
6083 
6084 
val_real()6085 double Item_func_get_system_var::val_real()
6086 {
6087   THD *thd= current_thd;
6088 
6089   if (cache_present && thd->query_id == used_query_id)
6090   {
6091     if (cache_present & GET_SYS_VAR_CACHE_DOUBLE)
6092     {
6093       null_value= cached_null_value;
6094       return cached_dval;
6095     }
6096     else if (cache_present & GET_SYS_VAR_CACHE_LONG)
6097     {
6098       null_value= cached_null_value;
6099       cached_dval= (double)cached_llval;
6100       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
6101       return cached_dval;
6102     }
6103     else if (cache_present & GET_SYS_VAR_CACHE_STRING)
6104     {
6105       null_value= cached_null_value;
6106       if (!null_value)
6107         cached_dval= double_from_string_with_check(&cached_strval);
6108       else
6109         cached_dval= 0;
6110       cache_present|= GET_SYS_VAR_CACHE_DOUBLE;
6111       return cached_dval;
6112     }
6113   }
6114 
6115   cached_dval= var->val_real(&null_value, thd, var_type, &component);
6116   cache_present |= GET_SYS_VAR_CACHE_DOUBLE;
6117   used_query_id= thd->query_id;
6118   cached_null_value= null_value;
6119   return cached_dval;
6120 }
6121 
6122 
eq(const Item * item,bool binary_cmp) const6123 bool Item_func_get_system_var::eq(const Item *item, bool binary_cmp) const
6124 {
6125   /* Assume we don't have rtti */
6126   if (this == item)
6127     return 1;					// Same item is same.
6128   /* Check if other type is also a get_user_var() object */
6129   if (item->type() != FUNC_ITEM ||
6130       ((Item_func*) item)->functype() != functype())
6131     return 0;
6132   Item_func_get_system_var *other=(Item_func_get_system_var*) item;
6133   return (var == other->var && var_type == other->var_type);
6134 }
6135 
6136 
cleanup()6137 void Item_func_get_system_var::cleanup()
6138 {
6139   Item_func::cleanup();
6140   cache_present= 0;
6141   var_type= orig_var_type;
6142   cached_strval.free();
6143 }
6144 
6145 /**
6146    @retval
6147    0 ok
6148    1 OOM error
6149 */
6150 
init_search(THD * thd,bool no_order)6151 bool Item_func_match::init_search(THD *thd, bool no_order)
6152 {
6153   DBUG_ENTER("Item_func_match::init_search");
6154 
6155   if (!table->file->is_open())
6156     DBUG_RETURN(0);
6157 
6158   /* Check if init_search() has been called before */
6159   if (ft_handler)
6160   {
6161     if (join_key)
6162       table->file->ft_handler= ft_handler;
6163     DBUG_RETURN(0);
6164   }
6165 
6166   if (key == NO_SUCH_KEY)
6167   {
6168     List<Item> fields;
6169     fields.push_back(new (thd->mem_root)
6170                      Item_string(thd, " ", 1, cmp_collation.collation),
6171                      thd->mem_root);
6172     for (uint i= 1; i < arg_count; i++)
6173       fields.push_back(args[i]);
6174     concat_ws= new (thd->mem_root) Item_func_concat_ws(thd, fields);
6175     if (unlikely(thd->is_fatal_error))
6176       DBUG_RETURN(1);                           // OOM in new or push_back
6177     /*
6178       Above function used only to get value and do not need fix_fields for it:
6179       Item_string - basic constant
6180       fields - fix_fields() was already called for this arguments
6181       Item_func_concat_ws - do not need fix_fields() to produce value
6182     */
6183     concat_ws->quick_fix_field();
6184   }
6185 
6186   if (master)
6187   {
6188     join_key= master->join_key= join_key | master->join_key;
6189     if (master->init_search(thd, no_order))
6190       DBUG_RETURN(1);
6191     ft_handler= master->ft_handler;
6192     join_key= master->join_key;
6193     DBUG_RETURN(0);
6194   }
6195 
6196   String *ft_tmp= 0;
6197 
6198   // MATCH ... AGAINST (NULL) is meaningless, but possible
6199   if (!(ft_tmp=key_item()->val_str(&value)))
6200   {
6201     ft_tmp= &value;
6202     value.set("", 0, cmp_collation.collation);
6203   }
6204 
6205   if (ft_tmp->charset() != cmp_collation.collation)
6206   {
6207     uint dummy_errors;
6208     if (search_value.copy(ft_tmp->ptr(), ft_tmp->length(), ft_tmp->charset(),
6209                           cmp_collation.collation, &dummy_errors))
6210       DBUG_RETURN(1);
6211     ft_tmp= &search_value;
6212   }
6213 
6214   if (join_key && !no_order)
6215     flags|=FT_SORTED;
6216 
6217   if (key != NO_SUCH_KEY)
6218     THD_STAGE_INFO(table->in_use, stage_fulltext_initialization);
6219 
6220   ft_handler= table->file->ft_init_ext(flags, key, ft_tmp);
6221 
6222   if (join_key)
6223     table->file->ft_handler=ft_handler;
6224 
6225   DBUG_RETURN(0);
6226 }
6227 
6228 
fix_fields(THD * thd,Item ** ref)6229 bool Item_func_match::fix_fields(THD *thd, Item **ref)
6230 {
6231   DBUG_ASSERT(fixed == 0);
6232   Item *UNINIT_VAR(item);                        // Safe as arg_count is > 1
6233 
6234   status_var_increment(thd->status_var.feature_fulltext);
6235 
6236   maybe_null=1;
6237   join_key=0;
6238 
6239   /*
6240     const_item is assumed in quite a bit of places, so it would be difficult
6241     to remove;  If it would ever to be removed, this should include
6242     modifications to find_best and auto_close as complement to auto_init code
6243     above.
6244    */
6245   if (Item_func::fix_fields(thd, ref) ||
6246       !args[0]->const_during_execution())
6247   {
6248     my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST");
6249     return TRUE;
6250   }
6251 
6252   bool allows_multi_table_search= true;
6253   const_item_cache=0;
6254   table= 0;
6255   for (uint i=1 ; i < arg_count ; i++)
6256   {
6257     item= args[i]= args[i]->real_item();
6258     /*
6259       When running in PS mode, some Item_field's can already be replaced
6260       to Item_func_conv_charset during PREPARE time. This is possible
6261       in case of "MATCH (f1,..,fN) AGAINST (... IN BOOLEAN MODE)"
6262       when running without any fulltext indexes and when fields f1..fN
6263       have different character sets.
6264       So we check for FIELD_ITEM only during prepare time and in non-PS mode,
6265       and do not check in PS execute time.
6266     */
6267     if (!thd->stmt_arena->is_stmt_execute() &&
6268         item->type() != Item::FIELD_ITEM)
6269     {
6270       my_error(ER_WRONG_ARGUMENTS, MYF(0), "MATCH");
6271       return TRUE;
6272     }
6273     /*
6274       During the prepare-time execution of fix_fields() of a PS query some
6275       Item_fields's could have been already replaced to Item_func_conv_charset
6276       (by the call for agg_arg_charsets_for_comparison below()).
6277       But agg_arg_charsets_for_comparison() is written in a way that
6278       at least *one* of the Item_field's is not replaced.
6279       This makes sure that "table" gets initialized during PS execution time.
6280     */
6281     if (item->type() == Item::FIELD_ITEM)
6282       table= ((Item_field *)item)->field->table;
6283 
6284     allows_multi_table_search &= allows_search_on_non_indexed_columns(table);
6285   }
6286 
6287   /*
6288     Check that all columns come from the same table.
6289     We've already checked that columns in MATCH are fields so
6290     PARAM_TABLE_BIT can only appear from AGAINST argument.
6291   */
6292   if ((used_tables_cache & ~PARAM_TABLE_BIT) != item->used_tables())
6293     key=NO_SUCH_KEY;
6294 
6295   if (key == NO_SUCH_KEY && !allows_multi_table_search)
6296   {
6297     my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH");
6298     return TRUE;
6299   }
6300   if (!(table->file->ha_table_flags() & HA_CAN_FULLTEXT))
6301   {
6302     my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0), table->file->table_type());
6303     return 1;
6304   }
6305   table->fulltext_searched=1;
6306   return agg_arg_charsets_for_comparison(cmp_collation, args+1, arg_count-1);
6307 }
6308 
fix_index()6309 bool Item_func_match::fix_index()
6310 {
6311   Item_field *item;
6312   uint ft_to_key[MAX_KEY], ft_cnt[MAX_KEY], fts=0, keynr;
6313   uint max_cnt=0, mkeys=0, i;
6314 
6315   /*
6316     We will skip execution if the item is not fixed
6317     with fix_field
6318   */
6319   if (!fixed)
6320     return false;
6321 
6322   if (key == NO_SUCH_KEY)
6323     return 0;
6324 
6325   if (!table)
6326     goto err;
6327 
6328   for (keynr=0 ; keynr < table->s->keys ; keynr++)
6329   {
6330     if ((table->key_info[keynr].flags & HA_FULLTEXT) &&
6331         (flags & FT_BOOL ? table->keys_in_use_for_query.is_set(keynr) :
6332                            table->s->keys_in_use.is_set(keynr)))
6333 
6334     {
6335       ft_to_key[fts]=keynr;
6336       ft_cnt[fts]=0;
6337       fts++;
6338     }
6339   }
6340 
6341   if (!fts)
6342     goto err;
6343 
6344   for (i=1; i < arg_count; i++)
6345   {
6346     if (args[i]->type() != FIELD_ITEM)
6347       goto err;
6348     item=(Item_field*)args[i];
6349     for (keynr=0 ; keynr < fts ; keynr++)
6350     {
6351       KEY *ft_key=&table->key_info[ft_to_key[keynr]];
6352       uint key_parts=ft_key->user_defined_key_parts;
6353 
6354       for (uint part=0 ; part < key_parts ; part++)
6355       {
6356 	if (item->field->eq(ft_key->key_part[part].field))
6357 	  ft_cnt[keynr]++;
6358       }
6359     }
6360   }
6361 
6362   for (keynr=0 ; keynr < fts ; keynr++)
6363   {
6364     if (ft_cnt[keynr] > max_cnt)
6365     {
6366       mkeys=0;
6367       max_cnt=ft_cnt[mkeys]=ft_cnt[keynr];
6368       ft_to_key[mkeys]=ft_to_key[keynr];
6369       continue;
6370     }
6371     if (max_cnt && ft_cnt[keynr] == max_cnt)
6372     {
6373       mkeys++;
6374       ft_cnt[mkeys]=ft_cnt[keynr];
6375       ft_to_key[mkeys]=ft_to_key[keynr];
6376       continue;
6377     }
6378   }
6379 
6380   for (keynr=0 ; keynr <= mkeys ; keynr++)
6381   {
6382     // partial keys doesn't work
6383     if (max_cnt < arg_count-1 ||
6384         max_cnt < table->key_info[ft_to_key[keynr]].user_defined_key_parts)
6385       continue;
6386 
6387     key=ft_to_key[keynr];
6388 
6389     return 0;
6390   }
6391 
6392 err:
6393   if (allows_search_on_non_indexed_columns(table))
6394   {
6395     key=NO_SUCH_KEY;
6396     return 0;
6397   }
6398   my_message(ER_FT_MATCHING_KEY_NOT_FOUND,
6399              ER(ER_FT_MATCHING_KEY_NOT_FOUND), MYF(0));
6400   return 1;
6401 }
6402 
6403 
eq(const Item * item,bool binary_cmp) const6404 bool Item_func_match::eq(const Item *item, bool binary_cmp) const
6405 {
6406   if (item->type() != FUNC_ITEM ||
6407       ((Item_func*)item)->functype() != FT_FUNC ||
6408       flags != ((Item_func_match*)item)->flags)
6409     return 0;
6410 
6411   Item_func_match *ifm=(Item_func_match*) item;
6412 
6413   if (key == ifm->key && table == ifm->table &&
6414       key_item()->eq(ifm->key_item(), binary_cmp))
6415     return 1;
6416 
6417   return 0;
6418 }
6419 
6420 
val_real()6421 double Item_func_match::val_real()
6422 {
6423   DBUG_ASSERT(fixed == 1);
6424   DBUG_ENTER("Item_func_match::val");
6425   if (ft_handler == NULL)
6426     DBUG_RETURN(-1.0);
6427 
6428   if (key != NO_SUCH_KEY && table->null_row) /* NULL row from an outer join */
6429     DBUG_RETURN(0.0);
6430 
6431   if (join_key)
6432   {
6433     if (table->file->ft_handler)
6434       DBUG_RETURN(ft_handler->please->get_relevance(ft_handler));
6435     join_key=0;
6436   }
6437 
6438   if (key == NO_SUCH_KEY)
6439   {
6440     String *a= concat_ws->val_str(&value);
6441     if ((null_value= (a == 0)) || !a->length())
6442       DBUG_RETURN(0);
6443     DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
6444 				      (uchar *)a->ptr(), a->length()));
6445   }
6446   DBUG_RETURN(ft_handler->please->find_relevance(ft_handler,
6447                                                  table->record[0], 0));
6448 }
6449 
print(String * str,enum_query_type query_type)6450 void Item_func_match::print(String *str, enum_query_type query_type)
6451 {
6452   str->append(STRING_WITH_LEN("(match "));
6453   print_args(str, 1, query_type);
6454   str->append(STRING_WITH_LEN(" against ("));
6455   args[0]->print(str, query_type);
6456   if (flags & FT_BOOL)
6457     str->append(STRING_WITH_LEN(" in boolean mode"));
6458   else if (flags & FT_EXPAND)
6459     str->append(STRING_WITH_LEN(" with query expansion"));
6460   str->append(STRING_WITH_LEN("))"));
6461 }
6462 
6463 
6464 class Func_handler_bit_xor_int_to_ulonglong:
6465         public Item_handled_func::Handler_ulonglong
6466 {
6467 public:
to_longlong_null(Item_handled_func * item) const6468   Longlong_null to_longlong_null(Item_handled_func *item) const
6469   {
6470     DBUG_ASSERT(item->is_fixed());
6471     return item->arguments()[0]->to_longlong_null() ^
6472            item->arguments()[1]->to_longlong_null();
6473   }
6474 };
6475 
6476 
6477 class Func_handler_bit_xor_dec_to_ulonglong:
6478         public Item_handled_func::Handler_ulonglong
6479 {
6480 public:
to_longlong_null(Item_handled_func * item) const6481   Longlong_null to_longlong_null(Item_handled_func *item) const
6482   {
6483     DBUG_ASSERT(item->is_fixed());
6484     return VDec(item->arguments()[0]).to_xlonglong_null() ^
6485            VDec(item->arguments()[1]).to_xlonglong_null();
6486   }
6487 };
6488 
6489 
fix_length_and_dec()6490 bool Item_func_bit_xor::fix_length_and_dec()
6491 {
6492   static const Func_handler_bit_xor_int_to_ulonglong ha_int_to_ull;
6493   static const Func_handler_bit_xor_dec_to_ulonglong ha_dec_to_ull;
6494   return fix_length_and_dec_op2_std(&ha_int_to_ull, &ha_dec_to_ull);
6495 }
6496 
6497 
6498 /***************************************************************************
6499   System variables
6500 ****************************************************************************/
6501 
6502 /**
6503   Return value of an system variable base[.name] as a constant item.
6504 
6505   @param thd			Thread handler
6506   @param var_type		global / session
6507   @param name		        Name of base or system variable
6508   @param component		Component.
6509 
6510   @note
6511     If component.str = 0 then the variable name is in 'name'
6512 
6513   @return
6514     - 0  : error
6515     - #  : constant item
6516 */
6517 
6518 
get_system_var(THD * thd,enum_var_type var_type,const LEX_CSTRING * name,const LEX_CSTRING * component)6519 Item *get_system_var(THD *thd, enum_var_type var_type,
6520                      const LEX_CSTRING *name,
6521 		     const LEX_CSTRING *component)
6522 {
6523   sys_var *var;
6524   LEX_CSTRING base_name, component_name;
6525 
6526   if (component->str)
6527   {
6528     base_name= *component;
6529     component_name= *name;
6530   }
6531   else
6532   {
6533     base_name= *name;
6534     component_name= *component;			// Empty string
6535   }
6536 
6537   if (!(var= find_sys_var(thd, base_name.str, base_name.length)))
6538     return 0;
6539   if (component->str)
6540   {
6541     if (!var->is_struct())
6542     {
6543       my_error(ER_VARIABLE_IS_NOT_STRUCT, MYF(0), base_name.str);
6544       return 0;
6545     }
6546   }
6547   thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
6548 
6549   set_if_smaller(component_name.length, MAX_SYS_VAR_LENGTH);
6550 
6551   return new (thd->mem_root) Item_func_get_system_var(thd, var, var_type,
6552                                                       &component_name,
6553                                                       NULL, 0);
6554 }
6555 
6556 
val_int()6557 longlong Item_func_row_count::val_int()
6558 {
6559   DBUG_ASSERT(fixed == 1);
6560   THD *thd= current_thd;
6561 
6562   return thd->get_row_count_func();
6563 }
6564 
6565 
6566 
6567 
Item_func_sp(THD * thd,Name_resolution_context * context_arg,sp_name * name,const Sp_handler * sph)6568 Item_func_sp::Item_func_sp(THD *thd, Name_resolution_context *context_arg,
6569                            sp_name *name, const Sp_handler *sph):
6570   Item_func(thd), Item_sp(thd, context_arg, name), m_handler(sph)
6571 {
6572   maybe_null= 1;
6573 }
6574 
6575 
Item_func_sp(THD * thd,Name_resolution_context * context_arg,sp_name * name_arg,const Sp_handler * sph,List<Item> & list)6576 Item_func_sp::Item_func_sp(THD *thd, Name_resolution_context *context_arg,
6577                            sp_name *name_arg, const Sp_handler *sph,
6578                            List<Item> &list):
6579   Item_func(thd, list), Item_sp(thd, context_arg, name_arg), m_handler(sph)
6580 {
6581   maybe_null= 1;
6582 }
6583 
6584 
6585 void
cleanup()6586 Item_func_sp::cleanup()
6587 {
6588   Item_sp::cleanup();
6589   Item_func::cleanup();
6590 }
6591 
6592 const char *
func_name() const6593 Item_func_sp::func_name() const
6594 {
6595   THD *thd= current_thd;
6596   return Item_sp::func_name(thd);
6597 }
6598 
6599 
my_missing_function_error(const LEX_CSTRING & token,const char * func_name)6600 void my_missing_function_error(const LEX_CSTRING &token, const char *func_name)
6601 {
6602   if (token.length && is_lex_native_function (&token))
6603     my_error(ER_FUNC_INEXISTENT_NAME_COLLISION, MYF(0), func_name);
6604   else
6605     my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION", func_name);
6606 }
6607 
6608 
6609 /**
6610   @note
6611   Deterministic stored procedures are considered inexpensive.
6612   Consequently such procedures may be evaluated during optimization,
6613   if they are constant (checked by the optimizer).
6614 */
6615 
is_expensive()6616 bool Item_func_sp::is_expensive()
6617 {
6618   return !m_sp->detistic() ||
6619           current_thd->locked_tables_mode < LTM_LOCK_TABLES;
6620 }
6621 
6622 
6623 /**
6624   @brief Initialize local members with values from the Field interface.
6625 
6626   @note called from Item::fix_fields.
6627 */
6628 
fix_length_and_dec()6629 bool Item_func_sp::fix_length_and_dec()
6630 {
6631   DBUG_ENTER("Item_func_sp::fix_length_and_dec");
6632 
6633   DBUG_ASSERT(sp_result_field);
6634   Type_std_attributes::set(sp_result_field->type_std_attributes());
6635   // There is a bug in the line below. See MDEV-11292 for details.
6636   collation.derivation= DERIVATION_COERCIBLE;
6637   maybe_null= 1;
6638 
6639   DBUG_RETURN(FALSE);
6640 }
6641 
6642 
6643 bool
execute()6644 Item_func_sp::execute()
6645 {
6646   /* Execute function and store the return value in the field. */
6647   return Item_sp::execute(current_thd, &null_value, args, arg_count);
6648 }
6649 
6650 
6651 void
make_send_field(THD * thd,Send_field * tmp_field)6652 Item_func_sp::make_send_field(THD *thd, Send_field *tmp_field)
6653 {
6654   DBUG_ENTER("Item_func_sp::make_send_field");
6655   DBUG_ASSERT(sp_result_field);
6656   sp_result_field->make_send_field(tmp_field);
6657   if (name.str)
6658   {
6659     DBUG_ASSERT(name.length == strlen(name.str));
6660     tmp_field->col_name= name;
6661   }
6662   DBUG_VOID_RETURN;
6663 }
6664 
6665 
type_handler() const6666 const Type_handler *Item_func_sp::type_handler() const
6667 {
6668   DBUG_ENTER("Item_func_sp::type_handler");
6669   DBUG_PRINT("info", ("m_sp = %p", (void *) m_sp));
6670   DBUG_ASSERT(sp_result_field);
6671   // This converts ENUM/SET to STRING
6672   const Type_handler *handler= sp_result_field->type_handler();
6673   DBUG_RETURN(handler->type_handler_for_item_field());
6674 }
6675 
6676 
val_int()6677 longlong Item_func_found_rows::val_int()
6678 {
6679   DBUG_ASSERT(fixed == 1);
6680   return current_thd->found_rows();
6681 }
6682 
6683 
val_int()6684 longlong Item_func_oracle_sql_rowcount::val_int()
6685 {
6686   DBUG_ASSERT(fixed == 1);
6687   THD *thd= current_thd;
6688   /*
6689     In case when a query like this:
6690       INSERT a INTO @va FROM t1;
6691     returns multiple rows, SQL%ROWCOUNT should report 1 rather than -1.
6692   */
6693   longlong rows= thd->get_row_count_func();
6694   return rows != -1 ? rows :                   // ROW_COUNT()
6695                       thd->found_rows();       // FOUND_ROWS()
6696 }
6697 
6698 
val_int()6699 longlong Item_func_sqlcode::val_int()
6700 {
6701   DBUG_ASSERT(fixed);
6702   DBUG_ASSERT(!null_value);
6703   Diagnostics_area::Sql_condition_iterator it=
6704     current_thd->get_stmt_da()->sql_conditions();
6705   const Sql_condition *err;
6706   if ((err= it++))
6707     return err->get_sql_errno();
6708   return 0;
6709 }
6710 
6711 
6712 bool
fix_fields(THD * thd,Item ** ref)6713 Item_func_sp::fix_fields(THD *thd, Item **ref)
6714 {
6715   bool res;
6716   DBUG_ENTER("Item_func_sp::fix_fields");
6717   DBUG_ASSERT(fixed == 0);
6718   sp_head *sp= m_handler->sp_find_routine(thd, m_name, true);
6719 
6720   /*
6721     Checking privileges to execute the function while creating view and
6722     executing the function of select.
6723    */
6724   if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) ||
6725       (thd->lex->sql_command == SQLCOM_CREATE_VIEW))
6726   {
6727     Security_context *save_security_ctx= thd->security_ctx;
6728     if (context && context->security_ctx)
6729       thd->security_ctx= context->security_ctx;
6730 
6731     /*
6732       If the routine is not found, let's still check EXECUTE_ACL to decide
6733       whether to return "Access denied" or "Routine does not exist".
6734     */
6735     res= sp ? sp->check_execute_access(thd) :
6736               check_routine_access(thd, EXECUTE_ACL, &m_name->m_db,
6737                                    &m_name->m_name,
6738                                    &sp_handler_function, false);
6739     thd->security_ctx= save_security_ctx;
6740 
6741     if (res)
6742     {
6743       process_error(thd);
6744       DBUG_RETURN(res);
6745     }
6746   }
6747 
6748 
6749   /* Custom aggregates are transformed into an Item_sum_sp. We can not do this
6750      earlier as we have no way of knowing what kind of Item we should create
6751      when parsing the query.
6752 
6753      TODO(cvicentiu): See if this limitation can be lifted.
6754   */
6755 
6756   DBUG_ASSERT(m_sp == NULL);
6757   if (!(m_sp= sp))
6758   {
6759     my_missing_function_error(m_name->m_name, ErrConvDQName(m_name).ptr());
6760     process_error(thd);
6761     DBUG_RETURN(TRUE);
6762   }
6763 
6764   /*
6765     We must call init_result_field before Item_func::fix_fields()
6766     to make m_sp and result_field members available to fix_length_and_dec(),
6767     which is called from Item_func::fix_fields().
6768   */
6769   res= init_result_field(thd, max_length, maybe_null, &null_value, &name);
6770 
6771   if (res)
6772     DBUG_RETURN(TRUE);
6773 
6774   if (m_sp->agg_type() == GROUP_AGGREGATE)
6775   {
6776     Item_sum_sp *item_sp;
6777     Query_arena *arena, backup;
6778     arena= thd->activate_stmt_arena_if_needed(&backup);
6779 
6780     if (arg_count)
6781     {
6782       List<Item> list;
6783       for (uint i= 0; i < arg_count; i++)
6784         list.push_back(args[i]);
6785       item_sp= new (thd->mem_root) Item_sum_sp(thd, context, m_name, sp, list);
6786     }
6787     else
6788       item_sp= new (thd->mem_root) Item_sum_sp(thd, context, m_name, sp);
6789 
6790     if (arena)
6791       thd->restore_active_arena(arena, &backup);
6792     if (!item_sp)
6793       DBUG_RETURN(TRUE);
6794     *ref= item_sp;
6795     item_sp->name= name;
6796     bool err= item_sp->fix_fields(thd, ref);
6797     if (err)
6798       DBUG_RETURN(TRUE);
6799 
6800     DBUG_RETURN(FALSE);
6801   }
6802 
6803   res= Item_func::fix_fields(thd, ref);
6804 
6805   if (res)
6806     DBUG_RETURN(TRUE);
6807 
6808   if (thd->lex->is_view_context_analysis())
6809   {
6810     /*
6811       Here we check privileges of the stored routine only during view
6812       creation, in order to validate the view.  A runtime check is
6813       performed in Item_func_sp::execute(), and this method is not
6814       called during context analysis.  Notice, that during view
6815       creation we do not infer into stored routine bodies and do not
6816       check privileges of its statements, which would probably be a
6817       good idea especially if the view has SQL SECURITY DEFINER and
6818       the used stored procedure has SQL SECURITY DEFINER.
6819     */
6820     res= sp_check_access(thd);
6821 #ifndef NO_EMBEDDED_ACCESS_CHECKS
6822     /*
6823       Try to set and restore the security context to see whether it's valid
6824     */
6825     Security_context *save_secutiry_ctx;
6826     res= set_routine_security_ctx(thd, m_sp, &save_secutiry_ctx);
6827     if (!res)
6828       m_sp->m_security_ctx.restore_security_context(thd, save_secutiry_ctx);
6829 
6830 #endif /* ! NO_EMBEDDED_ACCESS_CHECKS */
6831   }
6832 
6833   if (!m_sp->detistic())
6834   {
6835     used_tables_cache |= RAND_TABLE_BIT;
6836     const_item_cache= FALSE;
6837   }
6838 
6839   DBUG_RETURN(res);
6840 }
6841 
6842 
update_used_tables()6843 void Item_func_sp::update_used_tables()
6844 {
6845   Item_func::update_used_tables();
6846 
6847   if (!m_sp->detistic())
6848   {
6849     used_tables_cache |= RAND_TABLE_BIT;
6850     const_item_cache= FALSE;
6851   }
6852 }
6853 
check_vcol_func_processor(void * arg)6854 bool Item_func_sp::check_vcol_func_processor(void *arg)
6855 {
6856   return mark_unsupported_function(func_name(), "()", arg, VCOL_IMPOSSIBLE);
6857 }
6858 
6859 /*
6860   uuid_short handling.
6861 
6862   The short uuid is defined as a longlong that contains the following bytes:
6863 
6864   Bytes  Comment
6865   1      Server_id & 255
6866   4      Startup time of server in seconds
6867   3      Incrementor
6868 
6869   This means that an uuid is guaranteed to be unique
6870   even in a replication environment if the following holds:
6871 
6872   - The last byte of the server id is unique
6873   - If you between two shutdown of the server don't get more than
6874     an average of 2^24 = 16M calls to uuid_short() per second.
6875 */
6876 
6877 ulonglong uuid_value;
6878 
uuid_short_init()6879 void uuid_short_init()
6880 {
6881   uuid_value= ((((ulonglong) global_system_variables.server_id) << 56) +
6882                (((ulonglong) server_start_time) << 24));
6883 }
6884 
6885 
val_int()6886 longlong Item_func_uuid_short::val_int()
6887 {
6888   ulonglong val;
6889   mysql_mutex_lock(&LOCK_short_uuid_generator);
6890   val= uuid_value++;
6891   mysql_mutex_unlock(&LOCK_short_uuid_generator);
6892   return (longlong) val;
6893 }
6894 
6895 
6896 /**
6897   Last_value - return last argument.
6898 */
6899 
evaluate_sideeffects()6900 void Item_func_last_value::evaluate_sideeffects()
6901 {
6902   DBUG_ASSERT(fixed == 1 && arg_count > 0);
6903   for (uint i= 0; i < arg_count-1 ; i++)
6904     args[i]->val_int();
6905 }
6906 
val_str(String * str)6907 String *Item_func_last_value::val_str(String *str)
6908 {
6909   String *tmp;
6910   evaluate_sideeffects();
6911   tmp= last_value->val_str(str);
6912   null_value= last_value->null_value;
6913   return tmp;
6914 }
6915 
6916 
val_native(THD * thd,Native * to)6917 bool Item_func_last_value::val_native(THD *thd, Native *to)
6918 {
6919   evaluate_sideeffects();
6920   return val_native_from_item(thd, last_value, to);
6921 }
6922 
6923 
val_int()6924 longlong Item_func_last_value::val_int()
6925 {
6926   longlong tmp;
6927   evaluate_sideeffects();
6928   tmp= last_value->val_int();
6929   null_value= last_value->null_value;
6930   return tmp;
6931 }
6932 
val_real()6933 double Item_func_last_value::val_real()
6934 {
6935   double tmp;
6936   evaluate_sideeffects();
6937   tmp= last_value->val_real();
6938   null_value= last_value->null_value;
6939   return tmp;
6940 }
6941 
val_decimal(my_decimal * decimal_value)6942 my_decimal *Item_func_last_value::val_decimal(my_decimal *decimal_value)
6943 {
6944   my_decimal *tmp;
6945   evaluate_sideeffects();
6946   tmp= last_value->val_decimal(decimal_value);
6947   null_value= last_value->null_value;
6948   return tmp;
6949 }
6950 
6951 
get_date(THD * thd,MYSQL_TIME * ltime,date_mode_t fuzzydate)6952 bool Item_func_last_value::get_date(THD *thd, MYSQL_TIME *ltime, date_mode_t fuzzydate)
6953 {
6954   evaluate_sideeffects();
6955   bool tmp= last_value->get_date(thd, ltime, fuzzydate);
6956   null_value= last_value->null_value;
6957   return tmp;
6958 }
6959 
6960 
fix_length_and_dec()6961 bool Item_func_last_value::fix_length_and_dec()
6962 {
6963   last_value=          args[arg_count -1];
6964   Type_std_attributes::set(last_value);
6965   maybe_null=          last_value->maybe_null;
6966   return FALSE;
6967 }
6968 
6969 
print_func(String * str,const char * func_name)6970 void Cursor_ref::print_func(String *str, const char *func_name)
6971 {
6972   append_identifier(current_thd, str, &m_cursor_name);
6973   str->append(func_name);
6974 }
6975 
6976 
get_open_cursor_or_error()6977 sp_cursor *Cursor_ref::get_open_cursor_or_error()
6978 {
6979   THD *thd= current_thd;
6980   sp_cursor *c= thd->spcont->get_cursor(m_cursor_offset);
6981   DBUG_ASSERT(c);
6982   if (!c/*safety*/ || !c->is_open())
6983   {
6984     my_message(ER_SP_CURSOR_NOT_OPEN, ER_THD(thd, ER_SP_CURSOR_NOT_OPEN),
6985                MYF(0));
6986     return NULL;
6987   }
6988   return c;
6989 }
6990 
6991 
val_int()6992 longlong Item_func_cursor_isopen::val_int()
6993 {
6994   sp_cursor *c= current_thd->spcont->get_cursor(m_cursor_offset);
6995   DBUG_ASSERT(c != NULL);
6996   return c ? c->is_open() : 0;
6997 }
6998 
6999 
val_int()7000 longlong Item_func_cursor_found::val_int()
7001 {
7002   sp_cursor *c= get_open_cursor_or_error();
7003   return !(null_value= (!c || c->fetch_count() == 0)) && c->found();
7004 }
7005 
7006 
val_int()7007 longlong Item_func_cursor_notfound::val_int()
7008 {
7009   sp_cursor *c= get_open_cursor_or_error();
7010   return !(null_value= (!c || c->fetch_count() == 0)) && !c->found();
7011 }
7012 
7013 
val_int()7014 longlong Item_func_cursor_rowcount::val_int()
7015 {
7016   sp_cursor *c= get_open_cursor_or_error();
7017   return !(null_value= !c) ? c->row_count() : 0;
7018 }
7019 
7020 /*****************************************************************************
7021   SEQUENCE functions
7022 *****************************************************************************/
7023 
val_int()7024 longlong Item_func_nextval::val_int()
7025 {
7026   longlong value;
7027   int error;
7028   const char *key;
7029   uint length= get_table_def_key(table_list, &key);
7030   THD *thd;
7031   SEQUENCE_LAST_VALUE *entry;
7032   char buff[80];
7033   String key_buff(buff,sizeof(buff), &my_charset_bin);
7034   DBUG_ENTER("Item_func_nextval::val_int");
7035   update_table();
7036   DBUG_ASSERT(table && table->s->sequence);
7037   thd= table->in_use;
7038 
7039   if (thd->count_cuted_fields == CHECK_FIELD_EXPRESSION)
7040   {
7041     /* Alter table checking if function works */
7042     null_value= 0;
7043     DBUG_RETURN(0);
7044   }
7045 
7046   if (table->s->tmp_table != NO_TMP_TABLE)
7047   {
7048     /*
7049       Temporary tables has an extra \0 at end to distinguish it from
7050       normal tables
7051     */
7052     key_buff.copy(key, length, &my_charset_bin);
7053     key_buff.append((char) 0);
7054     key= key_buff.ptr();
7055     length++;
7056   }
7057 
7058   if (!(entry= ((SEQUENCE_LAST_VALUE*)
7059                 my_hash_search(&thd->sequences, (uchar*) key, length))))
7060   {
7061     if (!(key= (char*) my_memdup(PSI_INSTRUMENT_ME, key, length, MYF(MY_WME))) ||
7062         !(entry= new SEQUENCE_LAST_VALUE((uchar*) key, length)))
7063     {
7064       /* EOM, error given */
7065       my_free((char*) key);
7066       delete entry;
7067       null_value= 1;
7068       DBUG_RETURN(0);
7069     }
7070     if (my_hash_insert(&thd->sequences, (uchar*) entry))
7071     {
7072       /* EOM, error given */
7073       delete entry;
7074       null_value= 1;
7075       DBUG_RETURN(0);
7076     }
7077   }
7078   entry->null_value= null_value= 0;
7079   value= table->s->sequence->next_value(table, 0, &error);
7080   entry->value= value;
7081   entry->set_version(table);
7082 
7083   if (unlikely(error))                          // Warning already printed
7084     entry->null_value= null_value= 1;           // For not strict mode
7085   DBUG_RETURN(value);
7086 }
7087 
7088 
7089 /* Print for nextval and lastval */
7090 
print(String * str,enum_query_type query_type)7091 void Item_func_nextval::print(String *str, enum_query_type query_type)
7092 {
7093   char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
7094   LEX_CSTRING d_name= table_list->db;
7095   LEX_CSTRING t_name= table_list->table_name;
7096   bool use_db_name= d_name.str && d_name.str[0];
7097   THD *thd= current_thd;                        // Don't trust 'table'
7098 
7099   str->append(func_name());
7100   str->append('(');
7101 
7102   /*
7103     for next_val we assume that table_list has been updated to contain
7104     the current db.
7105   */
7106 
7107   if (lower_case_table_names > 0)
7108   {
7109     strmake(t_name_buff, t_name.str, MAX_ALIAS_NAME-1);
7110     t_name.length= my_casedn_str(files_charset_info, t_name_buff);
7111     t_name.str= t_name_buff;
7112     if (use_db_name)
7113     {
7114       strmake(d_name_buff, d_name.str, MAX_ALIAS_NAME-1);
7115       d_name.length= my_casedn_str(files_charset_info, d_name_buff);
7116       d_name.str= d_name_buff;
7117     }
7118   }
7119 
7120   if (use_db_name)
7121   {
7122     append_identifier(thd, str, &d_name);
7123     str->append('.');
7124   }
7125   append_identifier(thd, str, &t_name);
7126   str->append(')');
7127 }
7128 
7129 
7130 /* Return last used value for sequence or NULL if sequence hasn't been used */
7131 
val_int()7132 longlong Item_func_lastval::val_int()
7133 {
7134   const char *key;
7135   SEQUENCE_LAST_VALUE *entry;
7136   uint length= get_table_def_key(table_list, &key);
7137   THD *thd;
7138   char buff[80];
7139   String key_buff(buff,sizeof(buff), &my_charset_bin);
7140   DBUG_ENTER("Item_func_lastval::val_int");
7141   update_table();
7142   thd= table->in_use;
7143 
7144   if (table->s->tmp_table != NO_TMP_TABLE)
7145   {
7146     /*
7147       Temporary tables has an extra \0 at end to distinguish it from
7148       normal tables
7149     */
7150     key_buff.copy(key, length, &my_charset_bin);
7151     key_buff.append((char) 0);
7152     key= key_buff.ptr();
7153     length++;
7154   }
7155 
7156   if (!(entry= ((SEQUENCE_LAST_VALUE*)
7157                 my_hash_search(&thd->sequences, (uchar*) key, length))))
7158   {
7159     /* Sequence not used */
7160     null_value= 1;
7161     DBUG_RETURN(0);
7162   }
7163   if (entry->check_version(table))
7164   {
7165     /* Table droped and re-created, remove current version */
7166     my_hash_delete(&thd->sequences, (uchar*) entry);
7167     null_value= 1;
7168     DBUG_RETURN(0);
7169   }
7170 
7171   null_value= entry->null_value;
7172   DBUG_RETURN(entry->value);
7173 }
7174 
7175 
7176 /*
7177   Sets next value to be returned from sequences
7178 
7179   SELECT setval(foo, 42, 0);           Next nextval will return 43
7180   SELECT setval(foo, 42, 0, true);     Same as above
7181   SELECT setval(foo, 42, 0, false);    Next nextval will return 42
7182 */
7183 
val_int()7184 longlong Item_func_setval::val_int()
7185 {
7186   longlong value;
7187   int error;
7188   THD *thd;
7189   DBUG_ENTER("Item_func_setval::val_int");
7190 
7191   update_table();
7192   DBUG_ASSERT(table && table->s->sequence);
7193   thd= table->in_use;
7194 
7195   if (unlikely(thd->count_cuted_fields == CHECK_FIELD_EXPRESSION))
7196   {
7197     /* Alter table checking if function works */
7198     null_value= 0;
7199     DBUG_RETURN(0);
7200   }
7201 
7202   value= nextval;
7203   error= table->s->sequence->set_value(table, nextval, round, is_used);
7204   if (unlikely(error))
7205   {
7206     null_value= 1;
7207     value= 0;
7208   }
7209   DBUG_RETURN(value);
7210 }
7211 
7212 
7213 /* Print for setval */
7214 
print(String * str,enum_query_type query_type)7215 void Item_func_setval::print(String *str, enum_query_type query_type)
7216 {
7217   char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
7218   LEX_CSTRING d_name= table_list->db;
7219   LEX_CSTRING t_name= table_list->table_name;
7220   bool use_db_name= d_name.str && d_name.str[0];
7221   THD *thd= current_thd;                        // Don't trust 'table'
7222 
7223   str->append(func_name());
7224   str->append('(');
7225 
7226   /*
7227     for next_val we assume that table_list has been updated to contain
7228     the current db.
7229   */
7230 
7231   if (lower_case_table_names > 0)
7232   {
7233     strmake(t_name_buff, t_name.str, MAX_ALIAS_NAME-1);
7234     t_name.length= my_casedn_str(files_charset_info, t_name_buff);
7235     t_name.str= t_name_buff;
7236     if (use_db_name)
7237     {
7238       strmake(d_name_buff, d_name.str, MAX_ALIAS_NAME-1);
7239       d_name.length= my_casedn_str(files_charset_info, d_name_buff);
7240       d_name.str= d_name_buff;
7241     }
7242   }
7243 
7244   if (use_db_name)
7245   {
7246     append_identifier(thd, str, &d_name);
7247     str->append('.');
7248   }
7249   append_identifier(thd, str, &t_name);
7250   str->append(',');
7251   str->append_longlong(nextval);
7252   str->append(',');
7253   str->append_longlong(is_used);
7254   str->append(',');
7255   str->append_ulonglong(round);
7256   str->append(')');
7257 }
7258