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