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