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