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