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