1/*
2 Copyright (c) 2000, 2016, Oracle and/or its affiliates.
3 Copyright (c) 2010, 2018, MariaDB Corporation
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; version 2 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
17
18
19#ifdef USE_PRAGMA_IMPLEMENTATION
20#pragma implementation // gcc: Class implementation
21#endif
22#include "mariadb.h" /* NO_EMBEDDED_ACCESS_CHECKS */
23#include "sql_priv.h"
24#include <mysql.h>
25#include <m_ctype.h>
26#include "my_dir.h"
27#include "sp_rcontext.h"
28#include "sp_head.h"
29#include "sql_trigger.h"
30#include "sql_select.h"
31#include "sql_show.h" // append_identifier
32#include "sql_view.h" // VIEW_ANY_SQL
33#include "sql_time.h" // str_to_datetime_with_warn,
34 // make_truncated_value_warning
35#include "sql_acl.h" // get_column_grant,
36 // SELECT_ACL, UPDATE_ACL,
37 // INSERT_ACL,
38 // check_grant_column
39#include "sql_base.h" // enum_resolution_type,
40 // REPORT_EXCEPT_NOT_FOUND,
41 // find_item_in_list,
42 // RESOLVED_AGAINST_ALIAS, ...
43#include "sql_expression_cache.h"
44
45const String my_null_string("NULL", 4, default_charset_info);
46const String my_default_string("DEFAULT", 7, default_charset_info);
47
48/*
49 item_empty_name is used when calling Item::set_name with NULL
50 pointer, to make it easier to use the name in printf.
51 item_used_name is used when calling Item::set_name with a 0 length
52 string.
53*/
54const char *item_empty_name="";
55const char *item_used_name= "\0";
56
57static int save_field_in_field(Field *, bool *, Field *, bool);
58
59
60/**
61 Compare two Items for List<Item>::add_unique()
62*/
63
64bool cmp_items(Item *a, Item *b)
65{
66 return a->eq(b, FALSE);
67}
68
69
70/**
71 Set max_sum_func_level if it is needed
72*/
73inline void set_max_sum_func_level(THD *thd, SELECT_LEX *select)
74{
75 if (thd->lex->in_sum_func &&
76 thd->lex->in_sum_func->nest_level >= select->nest_level)
77 set_if_bigger(thd->lex->in_sum_func->max_sum_func_level,
78 select->nest_level - 1);
79}
80
81
82MEM_ROOT *get_thd_memroot(THD *thd)
83{
84 return thd->mem_root;
85}
86
87/*****************************************************************************
88** Item functions
89*****************************************************************************/
90
91/**
92 Init all special items.
93*/
94
95void item_init(void)
96{
97 item_func_sleep_init();
98 uuid_short_init();
99}
100
101
102void Item::push_note_converted_to_negative_complement(THD *thd)
103{
104 push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_UNKNOWN_ERROR,
105 "Cast to signed converted positive out-of-range integer to "
106 "it's negative complement");
107}
108
109
110void Item::push_note_converted_to_positive_complement(THD *thd)
111{
112 push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_UNKNOWN_ERROR,
113 "Cast to unsigned converted negative integer to it's "
114 "positive complement");
115}
116
117
118longlong Item::val_datetime_packed_result()
119{
120 MYSQL_TIME ltime, tmp;
121 if (get_date_result(&ltime, TIME_FUZZY_DATES | TIME_INVALID_DATES))
122 return 0;
123 if (ltime.time_type != MYSQL_TIMESTAMP_TIME)
124 return pack_time(&ltime);
125 if ((null_value= time_to_datetime_with_warn(current_thd, &ltime, &tmp, 0)))
126 return 0;
127 return pack_time(&tmp);
128}
129
130
131/**
132 Get date/time/datetime.
133 If DATETIME or DATE result is returned, it's converted to TIME.
134*/
135bool Item::get_time_with_conversion(THD *thd, MYSQL_TIME *ltime,
136 ulonglong fuzzydate)
137{
138 if (get_date(ltime, fuzzydate))
139 return true;
140 if (ltime->time_type != MYSQL_TIMESTAMP_TIME)
141 {
142 MYSQL_TIME ltime2;
143 if ((thd->variables.old_behavior & OLD_MODE_ZERO_DATE_TIME_CAST) &&
144 (ltime->year || ltime->day || ltime->month))
145 {
146 /*
147 Old mode conversion from DATETIME with non-zero YYYYMMDD part
148 to TIME works very inconsistently. Possible variants:
149 - truncate the YYYYMMDD part
150 - add (MM*33+DD)*24 to hours
151 - add (MM*31+DD)*24 to hours
152 Let's return TRUE here, to disallow equal field propagation.
153 Note, If we start to use this method in more pieces of the code other
154 than equal field propagation, we should probably return
155 TRUE only if some flag in fuzzydate is set.
156 */
157 return true;
158 }
159 if (datetime_to_time_with_warn(thd, ltime, &ltime2, TIME_SECOND_PART_DIGITS))
160 {
161 /*
162 If the time difference between CURRENT_DATE and ltime
163 did not fit into the supported TIME range, then we set the
164 difference to the maximum possible value in the supported TIME range
165 */
166 DBUG_ASSERT(0);
167 return (null_value= true);
168 }
169 *ltime= ltime2;
170 }
171 return false;
172}
173
174
175/*
176 For the items which don't have its own fast val_str_ascii()
177 implementation we provide a generic slower version,
178 which converts from the Item character set to ASCII.
179 For better performance conversion happens only in
180 case of a "tricky" Item character set (e.g. UCS2).
181 Normally conversion does not happen.
182*/
183String *Item::val_str_ascii(String *str)
184{
185 DBUG_ASSERT(str != &str_value);
186
187 uint errors;
188 String *res= val_str(&str_value);
189 if (!res)
190 return 0;
191
192 if (!(res->charset()->state & MY_CS_NONASCII))
193 str= res;
194 else
195 {
196 if ((null_value= str->copy(res->ptr(), res->length(), collation.collation,
197 &my_charset_latin1, &errors)))
198 return 0;
199 }
200
201 return str;
202}
203
204
205String *Item::val_str(String *str, String *converter, CHARSET_INFO *cs)
206{
207 String *res= val_str(str);
208 if (null_value)
209 return (String *) 0;
210
211 if (!cs)
212 return res;
213
214 uint errors;
215 if ((null_value= converter->copy(res->ptr(), res->length(),
216 collation.collation, cs, &errors)))
217 return (String *) 0;
218
219 return converter;
220}
221
222
223String *Item::val_string_from_real(String *str)
224{
225 double nr= val_real();
226 if (null_value)
227 return 0; /* purecov: inspected */
228 str->set_real(nr,decimals, &my_charset_numeric);
229 return str;
230}
231
232
233String *Item::val_string_from_int(String *str)
234{
235 longlong nr= val_int();
236 if (null_value)
237 return 0;
238 str->set_int(nr, unsigned_flag, &my_charset_numeric);
239 return str;
240}
241
242
243String *Item::val_string_from_decimal(String *str)
244{
245 my_decimal dec_buf, *dec= val_decimal(&dec_buf);
246 if (null_value)
247 return 0;
248 my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
249 my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
250 return str;
251}
252
253
254/*
255 All val_xxx_from_date() must call this method, to expose consistent behaviour
256 regarding SQL_MODE when converting DATE/DATETIME to other data types.
257*/
258bool Item::get_temporal_with_sql_mode(MYSQL_TIME *ltime)
259{
260 return get_date(ltime, field_type() == MYSQL_TYPE_TIME
261 ? TIME_TIME_ONLY
262 : sql_mode_for_dates(current_thd));
263}
264
265
266bool Item::is_null_from_temporal()
267{
268 MYSQL_TIME ltime;
269 return get_temporal_with_sql_mode(&ltime);
270}
271
272
273longlong Item::val_int_from_str(int *error)
274{
275 char buff[MAX_FIELD_WIDTH];
276 String tmp(buff,sizeof(buff), &my_charset_bin), *res;
277
278 /*
279 For a string result, we must first get the string and then convert it
280 to a longlong
281 */
282 if (!(res= val_str(&tmp)))
283 {
284 *error= 0;
285 return 0;
286 }
287 Converter_strtoll10_with_warn cnv(NULL, Warn_filter_all(),
288 res->charset(), res->ptr(), res->length());
289 *error= cnv.error();
290 return cnv.result();
291}
292
293
294longlong Item::val_int_signed_typecast_from_str()
295{
296 int error;
297 longlong value= val_int_from_str(&error);
298 if (unlikely(!null_value && value < 0 && error == 0))
299 push_note_converted_to_negative_complement(current_thd);
300 return value;
301}
302
303
304longlong Item::val_int_unsigned_typecast_from_str()
305{
306 int error;
307 longlong value= val_int_from_str(&error);
308 if (unlikely(!null_value && error < 0))
309 push_note_converted_to_positive_complement(current_thd);
310 return value;
311}
312
313
314longlong Item::val_int_unsigned_typecast_from_int()
315{
316 longlong value= val_int();
317 if (!null_value && unsigned_flag == 0 && value < 0)
318 push_note_converted_to_positive_complement(current_thd);
319 return value;
320}
321
322
323String *Item::val_string_from_date(String *str)
324{
325 MYSQL_TIME ltime;
326 if (get_temporal_with_sql_mode(&ltime) ||
327 str->alloc(MAX_DATE_STRING_REP_LENGTH))
328 {
329 null_value= 1;
330 return (String *) 0;
331 }
332 str->length(my_TIME_to_str(&ltime, const_cast<char*>(str->ptr()), decimals));
333 str->set_charset(&my_charset_numeric);
334 return str;
335}
336
337
338my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
339{
340 double nr= val_real();
341 if (null_value)
342 return 0;
343 double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
344 return (decimal_value);
345}
346
347
348my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
349{
350 longlong nr= val_int();
351 if (null_value)
352 return 0;
353 int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
354 return decimal_value;
355}
356
357
358my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
359{
360 String *res;
361
362 if (!(res= val_str(&str_value)))
363 return 0;
364
365 return decimal_from_string_with_check(decimal_value, res);
366}
367
368
369my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value)
370{
371 DBUG_ASSERT(fixed == 1);
372 MYSQL_TIME ltime;
373 if (get_temporal_with_sql_mode(&ltime))
374 {
375 my_decimal_set_zero(decimal_value);
376 null_value= 1; // set NULL, stop processing
377 return 0;
378 }
379 return date2my_decimal(&ltime, decimal_value);
380}
381
382
383my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value)
384{
385 DBUG_ASSERT(fixed == 1);
386 MYSQL_TIME ltime;
387 if (get_time(&ltime))
388 {
389 my_decimal_set_zero(decimal_value);
390 return 0;
391 }
392 return date2my_decimal(&ltime, decimal_value);
393}
394
395
396longlong Item::val_int_from_date()
397{
398 DBUG_ASSERT(fixed == 1);
399 MYSQL_TIME ltime;
400 if (get_temporal_with_sql_mode(&ltime))
401 return 0;
402 longlong v= TIME_to_ulonglong(&ltime);
403 return ltime.neg ? -v : v;
404}
405
406
407double Item::val_real_from_date()
408{
409 DBUG_ASSERT(fixed == 1);
410 MYSQL_TIME ltime;
411 if (get_temporal_with_sql_mode(&ltime))
412 return 0;
413 return TIME_to_double(&ltime);
414}
415
416
417double Item::val_real_from_decimal()
418{
419 /* Note that fix_fields may not be called for Item_avg_field items */
420 double result;
421 my_decimal value_buff, *dec_val= val_decimal(&value_buff);
422 if (null_value)
423 return 0.0;
424 my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
425 return result;
426}
427
428
429longlong Item::val_int_from_decimal()
430{
431 /* Note that fix_fields may not be called for Item_avg_field items */
432 longlong result;
433 my_decimal value, *dec_val= val_decimal(&value);
434 if (null_value)
435 return 0;
436 my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result);
437 return result;
438}
439
440
441longlong Item::val_int_unsigned_typecast_from_decimal()
442{
443 longlong result;
444 my_decimal tmp, *dec= val_decimal(&tmp);
445 if (null_value)
446 return 0;
447 my_decimal2int(E_DEC_FATAL_ERROR, dec, 1, &result);
448 return result;
449}
450
451
452int Item::save_time_in_field(Field *field, bool no_conversions)
453{
454 MYSQL_TIME ltime;
455 if (get_time(&ltime))
456 return set_field_to_null_with_conversions(field, no_conversions);
457 field->set_notnull();
458 return field->store_time_dec(&ltime, decimals);
459}
460
461
462int Item::save_date_in_field(Field *field, bool no_conversions)
463{
464 MYSQL_TIME ltime;
465 if (get_date(&ltime, sql_mode_for_dates(field->table->in_use)))
466 return set_field_to_null_with_conversions(field, no_conversions);
467 field->set_notnull();
468 return field->store_time_dec(&ltime, decimals);
469}
470
471
472/*
473 Store the string value in field directly
474
475 SYNOPSIS
476 Item::save_str_value_in_field()
477 field a pointer to field where to store
478 result the pointer to the string value to be stored
479
480 DESCRIPTION
481 The method is used by Item_*::save_in_field implementations
482 when we don't need to calculate the value to store
483 See Item_string::save_in_field() implementation for example
484
485 IMPLEMENTATION
486 Check if the Item is null and stores the NULL or the
487 result value in the field accordingly.
488
489 RETURN
490 Nonzero value if error
491*/
492
493int Item::save_str_value_in_field(Field *field, String *result)
494{
495 if (null_value)
496 return set_field_to_null(field);
497 field->set_notnull();
498 return field->store(result->ptr(), result->length(),
499 collation.collation);
500}
501
502
503Item::Item(THD *thd):
504 is_expensive_cache(-1), rsize(0), name(null_clex_str), orig_name(0),
505 fixed(0), is_autogenerated_name(TRUE)
506{
507 DBUG_ASSERT(thd);
508 marker= 0;
509 maybe_null=null_value=with_sum_func=with_window_func=with_field=0;
510 in_rollup= 0;
511 with_param= 0;
512
513 /* Initially this item is not attached to any JOIN_TAB. */
514 join_tab_idx= MAX_TABLES;
515
516 /* Put item in free list so that we can free all items at end */
517 next= thd->free_list;
518 thd->free_list= this;
519 /*
520 Item constructor can be called during execution other then SQL_COM
521 command => we should check thd->lex->current_select on zero (thd->lex
522 can be uninitialised)
523 */
524 if (thd->lex->current_select)
525 {
526 enum_parsing_place place=
527 thd->lex->current_select->parsing_place;
528 if (place == SELECT_LIST || place == IN_HAVING)
529 thd->lex->current_select->select_n_having_items++;
530 }
531}
532
533
534/**
535 Constructor used by Item_field, Item_ref & aggregate (sum)
536 functions.
537
538 Used for duplicating lists in processing queries with temporary
539 tables.
540*/
541Item::Item(THD *thd, Item *item):
542 Type_all_attributes(item),
543 join_tab_idx(item->join_tab_idx),
544 is_expensive_cache(-1),
545 rsize(0),
546 str_value(item->str_value),
547 name(item->name),
548 orig_name(item->orig_name),
549 marker(item->marker),
550 maybe_null(item->maybe_null),
551 in_rollup(item->in_rollup),
552 null_value(item->null_value),
553 with_sum_func(item->with_sum_func),
554 with_param(item->with_param),
555 with_window_func(item->with_window_func),
556 with_field(item->with_field),
557 fixed(item->fixed),
558 is_autogenerated_name(item->is_autogenerated_name)
559{
560 next= thd->free_list; // Put in free list
561 thd->free_list= this;
562}
563
564
565void Item::print_parenthesised(String *str, enum_query_type query_type,
566 enum precedence parent_prec)
567{
568 bool need_parens= precedence() < parent_prec;
569 if (need_parens)
570 str->append('(');
571 print(str, query_type);
572 if (need_parens)
573 str->append(')');
574}
575
576
577void Item::print(String *str, enum_query_type query_type)
578{
579 str->append(full_name());
580}
581
582
583void Item::print_item_w_name(String *str, enum_query_type query_type)
584{
585 print(str, query_type);
586
587 if (name.str)
588 {
589 DBUG_ASSERT(name.length == strlen(name.str));
590 THD *thd= current_thd;
591 str->append(STRING_WITH_LEN(" AS "));
592 append_identifier(thd, str, &name);
593 }
594}
595
596
597void Item::print_value(String *str)
598{
599 char buff[MAX_FIELD_WIDTH];
600 String *ptr, tmp(buff,sizeof(buff),str->charset());
601 ptr= val_str(&tmp);
602 if (!ptr)
603 str->append("NULL");
604 else
605 {
606 switch (cmp_type()) {
607 case STRING_RESULT:
608 case TIME_RESULT:
609 append_unescaped(str, ptr->ptr(), ptr->length());
610 break;
611 case DECIMAL_RESULT:
612 case REAL_RESULT:
613 case INT_RESULT:
614 str->append(*ptr);
615 break;
616 case ROW_RESULT:
617 DBUG_ASSERT(0);
618 }
619 }
620}
621
622
623void Item::cleanup()
624{
625 DBUG_ENTER("Item::cleanup");
626 DBUG_PRINT("enter", ("this: %p", this));
627 fixed= 0;
628 marker= 0;
629 join_tab_idx= MAX_TABLES;
630 if (orig_name)
631 {
632 name.str= orig_name;
633 name.length= strlen(orig_name);
634 }
635 DBUG_VOID_RETURN;
636}
637
638
639/**
640 cleanup() item if it is 'fixed'.
641
642 @param arg a dummy parameter, is not used here
643*/
644
645bool Item::cleanup_processor(void *arg)
646{
647 if (fixed)
648 cleanup();
649 return FALSE;
650}
651
652
653/**
654 Traverse item tree possibly transforming it (replacing items).
655
656 This function is designed to ease transformation of Item trees.
657 Re-execution note: every such transformation is registered for
658 rollback by THD::change_item_tree() and is rolled back at the end
659 of execution by THD::rollback_item_tree_changes().
660
661 Therefore:
662 - this function can not be used at prepared statement prepare
663 (in particular, in fix_fields!), as only permanent
664 transformation of Item trees are allowed at prepare.
665 - the transformer function shall allocate new Items in execution
666 memory root (thd->mem_root) and not anywhere else: allocated
667 items will be gone in the end of execution.
668
669 If you don't need to transform an item tree, but only traverse
670 it, please use Item::walk() instead.
671
672
673 @param transformer functor that performs transformation of a subtree
674 @param arg opaque argument passed to the functor
675
676 @return
677 Returns pointer to the new subtree root. THD::change_item_tree()
678 should be called for it if transformation took place, i.e. if a
679 pointer to newly allocated item is returned.
680*/
681
682Item* Item::transform(THD *thd, Item_transformer transformer, uchar *arg)
683{
684 DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
685
686 return (this->*transformer)(thd, arg);
687}
688
689
690/**
691 Create and set up an expression cache for this item
692
693 @param thd Thread handle
694 @param depends_on List of the expression parameters
695
696 @details
697 The function creates an expression cache for an item and its parameters
698 specified by the 'depends_on' list. Then the expression cache is placed
699 into a cache wrapper that is returned as the result of the function.
700
701 @returns
702 A pointer to created wrapper item if successful, NULL - otherwise
703*/
704
705Item* Item::set_expr_cache(THD *thd)
706{
707 DBUG_ENTER("Item::set_expr_cache");
708 Item_cache_wrapper *wrapper;
709 if (likely((wrapper= new (thd->mem_root) Item_cache_wrapper(thd, this))) &&
710 likely(!wrapper->fix_fields(thd, (Item**)&wrapper)))
711 {
712 if (likely(!wrapper->set_cache(thd)))
713 DBUG_RETURN(wrapper);
714 }
715 DBUG_RETURN(NULL);
716}
717
718
719Item_ident::Item_ident(THD *thd, Name_resolution_context *context_arg,
720 const char *db_name_arg,const char *table_name_arg,
721 const LEX_CSTRING *field_name_arg)
722 :Item_result_field(thd), orig_db_name(db_name_arg),
723 orig_table_name(table_name_arg),
724 orig_field_name(*field_name_arg), context(context_arg),
725 db_name(db_name_arg), table_name(table_name_arg),
726 field_name(*field_name_arg),
727 alias_name_used(FALSE), cached_field_index(NO_CACHED_FIELD_INDEX),
728 cached_table(0), depended_from(0), can_be_depended(TRUE)
729{
730 name= *field_name_arg;
731}
732
733
734Item_ident::Item_ident(THD *thd, TABLE_LIST *view_arg,
735 const LEX_CSTRING *field_name_arg)
736 :Item_result_field(thd), orig_db_name(NullS),
737 orig_table_name(view_arg->table_name.str),
738 orig_field_name(*field_name_arg),
739 context(&view_arg->view->select_lex.context),
740 db_name(NullS), table_name(view_arg->alias.str),
741 field_name(*field_name_arg),
742 alias_name_used(FALSE), cached_field_index(NO_CACHED_FIELD_INDEX),
743 cached_table(NULL), depended_from(NULL), can_be_depended(TRUE)
744{
745 name= *field_name_arg;
746}
747
748
749/**
750 Constructor used by Item_field & Item_*_ref (see Item comment)
751*/
752
753Item_ident::Item_ident(THD *thd, Item_ident *item)
754 :Item_result_field(thd, item),
755 orig_db_name(item->orig_db_name),
756 orig_table_name(item->orig_table_name),
757 orig_field_name(item->orig_field_name),
758 context(item->context),
759 db_name(item->db_name),
760 table_name(item->table_name),
761 field_name(item->field_name),
762 alias_name_used(item->alias_name_used),
763 cached_field_index(item->cached_field_index),
764 cached_table(item->cached_table),
765 depended_from(item->depended_from),
766 can_be_depended(item->can_be_depended)
767{}
768
769void Item_ident::cleanup()
770{
771 DBUG_ENTER("Item_ident::cleanup");
772 bool was_fixed= fixed;
773 Item_result_field::cleanup();
774 db_name= orig_db_name;
775 table_name= orig_table_name;
776 field_name= orig_field_name;
777 /* Store if this Item was depended */
778 if (was_fixed)
779 {
780 /*
781 We can trust that depended_from set correctly only if this item
782 was fixed
783 */
784 can_be_depended= MY_TEST(depended_from);
785 }
786 DBUG_VOID_RETURN;
787}
788
789bool Item_ident::remove_dependence_processor(void * arg)
790{
791 DBUG_ENTER("Item_ident::remove_dependence_processor");
792 if (get_depended_from() == (st_select_lex *) arg)
793 depended_from= 0;
794 context= &((st_select_lex *) arg)->context;
795 DBUG_RETURN(0);
796}
797
798
799bool Item_ident::collect_outer_ref_processor(void *param)
800{
801 Collect_deps_prm *prm= (Collect_deps_prm *)param;
802 if (depended_from &&
803 depended_from->nest_level_base == prm->nest_level_base &&
804 depended_from->nest_level < prm->nest_level)
805 {
806 if (prm->collect)
807 prm->parameters->add_unique(this, &cmp_items);
808 else
809 prm->count++;
810 }
811 return FALSE;
812}
813
814
815/**
816 Store the pointer to this item field into a list if not already there.
817
818 The method is used by Item::walk to collect all unique Item_field objects
819 from a tree of Items into a set of items represented as a list.
820
821 Item_cond::walk() and Item_func::walk() stop the evaluation of the
822 processor function for its arguments once the processor returns
823 true.Therefore in order to force this method being called for all item
824 arguments in a condition the method must return false.
825
826 @param arg pointer to a List<Item_field>
827
828 @return
829 FALSE to force the evaluation of collect_item_field_processor
830 for the subsequent items.
831*/
832
833bool Item_field::collect_item_field_processor(void *arg)
834{
835 DBUG_ENTER("Item_field::collect_item_field_processor");
836 DBUG_PRINT("info", ("%s", field->field_name.str ?
837 field->field_name.str : "noname"));
838 List<Item_field> *item_list= (List<Item_field>*) arg;
839 List_iterator<Item_field> item_list_it(*item_list);
840 Item_field *curr_item;
841 while ((curr_item= item_list_it++))
842 {
843 if (curr_item->eq(this, 1))
844 DBUG_RETURN(FALSE); /* Already in the set. */
845 }
846 item_list->push_back(this);
847 DBUG_RETURN(FALSE);
848}
849
850
851bool Item_field::add_field_to_set_processor(void *arg)
852{
853 DBUG_ENTER("Item_field::add_field_to_set_processor");
854 DBUG_PRINT("info", ("%s", field->field_name.str ? field->field_name.str :
855 "noname"));
856 TABLE *table= (TABLE *) arg;
857 if (field->table == table)
858 bitmap_set_bit(&table->tmp_set, field->field_index);
859 DBUG_RETURN(FALSE);
860}
861
862
863/**
864 Rename fields in an expression to new field name as speficied by ALTER TABLE
865*/
866
867bool Item_field::rename_fields_processor(void *arg)
868{
869 Item::func_processor_rename *rename= (Item::func_processor_rename*) arg;
870 List_iterator<Create_field> def_it(rename->fields);
871 Create_field *def;
872
873 while ((def=def_it++))
874 {
875 if (def->change.str &&
876 (!db_name || !db_name[0] ||
877 !my_strcasecmp(table_alias_charset, db_name, rename->db_name.str)) &&
878 (!table_name || !table_name[0] ||
879 !my_strcasecmp(table_alias_charset, table_name, rename->table_name.str)) &&
880 !my_strcasecmp(system_charset_info, field_name.str, def->change.str))
881 {
882 field_name= def->field_name;
883 break;
884 }
885 }
886 return 0;
887}
888
889
890/**
891 Check if an Item_field references some field from a list of fields.
892
893 Check whether the Item_field represented by 'this' references any
894 of the fields in the keyparts passed via 'arg'. Used with the
895 method Item::walk() to test whether any keypart in a sequence of
896 keyparts is referenced in an expression.
897
898 @param arg Field being compared, arg must be of type Field
899
900 @retval
901 TRUE if 'this' references the field 'arg'
902 @retval
903 FALSE otherwise
904*/
905
906bool Item_field::find_item_in_field_list_processor(void *arg)
907{
908 KEY_PART_INFO *first_non_group_part= *((KEY_PART_INFO **) arg);
909 KEY_PART_INFO *last_part= *(((KEY_PART_INFO **) arg) + 1);
910 KEY_PART_INFO *cur_part;
911
912 for (cur_part= first_non_group_part; cur_part != last_part; cur_part++)
913 {
914 if (field->eq(cur_part->field))
915 return TRUE;
916 }
917 return FALSE;
918}
919
920
921/*
922 Mark field in read_map
923
924 NOTES
925 This is used by filesort to register used fields in a a temporary
926 column read set or to register used fields in a view or check constraint
927*/
928
929bool Item_field::register_field_in_read_map(void *arg)
930{
931 TABLE *table= (TABLE *) arg;
932 int res= 0;
933 if (field->vcol_info &&
934 !bitmap_fast_test_and_set(field->table->vcol_set, field->field_index))
935 {
936 res= field->vcol_info->expr->walk(&Item::register_field_in_read_map,1,arg);
937 }
938 if (field->table == table || !table)
939 bitmap_set_bit(field->table->read_set, field->field_index);
940 return res;
941}
942
943/*
944 @brief
945 Mark field in bitmap supplied as *arg
946*/
947
948bool Item_field::register_field_in_bitmap(void *arg)
949{
950 MY_BITMAP *bitmap= (MY_BITMAP *) arg;
951 DBUG_ASSERT(bitmap);
952 bitmap_set_bit(bitmap, field->field_index);
953 return 0;
954}
955
956
957/*
958 Mark field in write_map
959
960 NOTES
961 This is used by UPDATE to register underlying fields of used view fields.
962*/
963
964bool Item_field::register_field_in_write_map(void *arg)
965{
966 TABLE *table= (TABLE *) arg;
967 if (field->table == table || !table)
968 bitmap_set_bit(field->table->write_set, field->field_index);
969 return 0;
970}
971
972/**
973 Check that we are not refering to any not yet initialized fields
974
975 Fields are initialized in this order:
976 - All fields that have default value as a constant are initialized first.
977 - Then user-specified values from the INSERT list
978 - Then all fields that has a default expression, in field_index order.
979 - Then all virtual fields, in field_index order.
980 - Then auto-increment values
981
982 This means:
983 - For default fields we can't access the same field or a field after
984 itself that doesn't have a non-constant default value.
985 - A virtual field can't access itself or a virtual field after itself.
986 - user-specified values will not see virtual fields or default expressions,
987 as in INSERT t1 (a) VALUES (b);
988 - no virtual fields can access auto-increment values
989
990 This is used by fix_vcol_expr() when a table is opened
991
992 We don't have to check fields that are marked as NO_DEFAULT_VALUE
993 as the upper level will ensure that all these will be given a value.
994*/
995
996bool Item_field::check_field_expression_processor(void *arg)
997{
998 Field *org_field= (Field*) arg;
999 if (field->flags & NO_DEFAULT_VALUE_FLAG)
1000 return 0;
1001 if ((field->default_value && field->default_value->flags) || field->vcol_info)
1002 {
1003 if (field == org_field ||
1004 (!org_field->vcol_info && field->vcol_info) ||
1005 (((field->vcol_info && org_field->vcol_info) ||
1006 (!field->vcol_info && !org_field->vcol_info)) &&
1007 field->field_index >= org_field->field_index))
1008 {
1009 my_error(ER_EXPRESSION_REFERS_TO_UNINIT_FIELD,
1010 MYF(0),
1011 org_field->field_name.str, field->field_name.str);
1012 return 1;
1013 }
1014 }
1015 return 0;
1016}
1017
1018bool Item_field::update_vcol_processor(void *arg)
1019{
1020 MY_BITMAP *map= (MY_BITMAP *) arg;
1021 if (field->vcol_info &&
1022 !bitmap_fast_test_and_set(map, field->field_index))
1023 {
1024 field->vcol_info->expr->walk(&Item::update_vcol_processor, 0, arg);
1025 field->vcol_info->expr->save_in_field(field, 0);
1026 }
1027 return 0;
1028}
1029
1030
1031bool Item::check_cols(uint c)
1032{
1033 if (c != 1)
1034 {
1035 my_error(ER_OPERAND_COLUMNS, MYF(0), c);
1036 return 1;
1037 }
1038 return 0;
1039}
1040
1041
1042bool Item::check_type_or_binary(const char *opname,
1043 const Type_handler *expect) const
1044{
1045 const Type_handler *handler= type_handler();
1046 if (handler == expect ||
1047 (handler->is_general_purpose_string_type() &&
1048 collation.collation == &my_charset_bin))
1049 return false;
1050 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1051 handler->name().ptr(), opname);
1052 return true;
1053}
1054
1055
1056bool Item::check_type_general_purpose_string(const char *opname) const
1057{
1058 const Type_handler *handler= type_handler();
1059 if (handler->is_general_purpose_string_type())
1060 return false;
1061 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1062 handler->name().ptr(), opname);
1063 return true;
1064}
1065
1066
1067bool Item::check_type_traditional_scalar(const char *opname) const
1068{
1069 const Type_handler *handler= type_handler();
1070 if (handler->is_traditional_type() && handler->is_scalar_type())
1071 return false;
1072 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1073 handler->name().ptr(), opname);
1074 return true;
1075}
1076
1077
1078bool Item::check_type_can_return_int(const char *opname) const
1079{
1080 const Type_handler *handler= type_handler();
1081 if (handler->can_return_int())
1082 return false;
1083 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1084 handler->name().ptr(), opname);
1085 return true;
1086}
1087
1088
1089bool Item::check_type_can_return_decimal(const char *opname) const
1090{
1091 const Type_handler *handler= type_handler();
1092 if (handler->can_return_decimal())
1093 return false;
1094 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1095 handler->name().ptr(), opname);
1096 return true;
1097}
1098
1099
1100bool Item::check_type_can_return_real(const char *opname) const
1101{
1102 const Type_handler *handler= type_handler();
1103 if (handler->can_return_real())
1104 return false;
1105 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1106 handler->name().ptr(), opname);
1107 return true;
1108}
1109
1110
1111bool Item::check_type_can_return_date(const char *opname) const
1112{
1113 const Type_handler *handler= type_handler();
1114 if (handler->can_return_date())
1115 return false;
1116 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1117 handler->name().ptr(), opname);
1118 return true;
1119}
1120
1121
1122bool Item::check_type_can_return_time(const char *opname) const
1123{
1124 const Type_handler *handler= type_handler();
1125 if (handler->can_return_time())
1126 return false;
1127 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1128 handler->name().ptr(), opname);
1129 return true;
1130}
1131
1132
1133bool Item::check_type_can_return_str(const char *opname) const
1134{
1135 const Type_handler *handler= type_handler();
1136 if (handler->can_return_str())
1137 return false;
1138 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1139 handler->name().ptr(), opname);
1140 return true;
1141}
1142
1143
1144bool Item::check_type_can_return_text(const char *opname) const
1145{
1146 const Type_handler *handler= type_handler();
1147 if (handler->can_return_text())
1148 return false;
1149 my_error(ER_ILLEGAL_PARAMETER_DATA_TYPE_FOR_OPERATION, MYF(0),
1150 handler->name().ptr(), opname);
1151 return true;
1152}
1153
1154
1155bool Item::check_type_scalar(const char *opname) const
1156{
1157 /*
1158 fixed==true usually means than the Item has an initialized
1159 and reliable data type handler and attributes.
1160 Item_outer_ref is an exception. It copies the data type and the attributes
1161 from the referenced Item in the constructor, but then sets "fixed" to false,
1162 and re-fixes itself again in fix_inner_refs().
1163 This hack in Item_outer_ref should probably be refactored eventually.
1164 Discuss with Sanja.
1165 */
1166 DBUG_ASSERT(fixed || type() == REF_ITEM);
1167 const Type_handler *handler= type_handler();
1168 if (handler->is_scalar_type())
1169 return false;
1170 my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
1171 return true;
1172}
1173
1174
1175void Item::set_name(THD *thd, const char *str, size_t length, CHARSET_INFO *cs)
1176{
1177 if (!length)
1178 {
1179 /*
1180 Null string are replaced by item_empty_name. This is used by AS or
1181 internal function like last_insert_id() to detect if we need to
1182 change the name later.
1183 Used by sql_yacc.yy in select_alias handling
1184 */
1185 name.str= str ? item_used_name : item_empty_name;
1186 name.length= 0;
1187 return;
1188 }
1189
1190 const char *str_start= str;
1191 if (!cs->ctype || cs->mbminlen > 1)
1192 {
1193 str+= cs->cset->scan(cs, str, str + length, MY_SEQ_SPACES);
1194 length-= (uint)(str - str_start);
1195 }
1196 else
1197 {
1198 /*
1199 This will probably need a better implementation in the future:
1200 a function in CHARSET_INFO structure.
1201 */
1202 while (length && !my_isgraph(cs,*str))
1203 { // Fix problem with yacc
1204 length--;
1205 str++;
1206 }
1207 }
1208 if (str != str_start && !is_autogenerated_name)
1209 {
1210 char buff[SAFE_NAME_LEN];
1211
1212 strmake(buff, str_start,
1213 MY_MIN(sizeof(buff)-1, length + (int) (str-str_start)));
1214
1215 if (length == 0)
1216 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1217 ER_NAME_BECOMES_EMPTY,
1218 ER_THD(thd, ER_NAME_BECOMES_EMPTY),
1219 buff);
1220 else
1221 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1222 ER_REMOVED_SPACES, ER_THD(thd, ER_REMOVED_SPACES),
1223 buff);
1224 }
1225 if (!my_charset_same(cs, system_charset_info))
1226 {
1227 size_t res_length;
1228 name.str= sql_strmake_with_convert(thd, str, length, cs,
1229 MAX_ALIAS_NAME, system_charset_info,
1230 &res_length);
1231 name.length= res_length;
1232 }
1233 else
1234 name.str= thd->strmake(str, (name.length= MY_MIN(length,MAX_ALIAS_NAME)));
1235}
1236
1237
1238void Item::set_name_no_truncate(THD *thd, const char *str, uint length,
1239 CHARSET_INFO *cs)
1240{
1241 if (!my_charset_same(cs, system_charset_info))
1242 {
1243 size_t res_length;
1244 name.str= sql_strmake_with_convert(thd, str, length, cs,
1245 UINT_MAX, system_charset_info,
1246 &res_length);
1247 name.length= res_length;
1248 }
1249 else
1250 name.str= thd->strmake(str, (name.length= length));
1251}
1252
1253
1254/**
1255 @details
1256 This function is called when:
1257 - Comparing items in the WHERE clause (when doing where optimization)
1258 - When trying to find an ORDER BY/GROUP BY item in the SELECT part
1259*/
1260
1261bool Item::eq(const Item *item, bool binary_cmp) const
1262{
1263 /*
1264 Note, that this is never TRUE if item is a Item_param:
1265 for all basic constants we have special checks, and Item_param's
1266 type() can be only among basic constant types.
1267 */
1268 return type() == item->type() && name.str && item->name.str &&
1269 !lex_string_cmp(system_charset_info, &name, &item->name);
1270}
1271
1272
1273Item *Item::safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
1274{
1275 if (!needs_charset_converter(tocs))
1276 return this;
1277 Item_func_conv_charset *conv= new (thd->mem_root) Item_func_conv_charset(thd, this, tocs, 1);
1278 return conv && conv->safe ? conv : NULL;
1279}
1280
1281
1282/**
1283 Some pieces of the code do not support changing of
1284 Item_cache to other Item types.
1285
1286 Example:
1287 Item_singlerow_subselect has "Item_cache **row".
1288 Creating of Item_func_conv_charset followed by THD::change_item_tree()
1289 should not change row[i] from Item_cache directly to Item_func_conv_charset,
1290 because Item_singlerow_subselect later calls Item_cache-specific methods,
1291 e.g. row[i]->store() and row[i]->cache_value().
1292
1293 Let's wrap Item_func_conv_charset in a new Item_cache,
1294 so the Item_cache-specific methods can still be used for
1295 Item_singlerow_subselect::row[i] safely.
1296
1297 As a bonus we cache the converted value, instead of converting every time
1298
1299 TODO: we should eventually check all other use cases of change_item_tree().
1300 Perhaps some more potentially dangerous substitution examples exist.
1301*/
1302
1303Item *Item_cache::safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
1304{
1305 if (!example)
1306 return Item::safe_charset_converter(thd, tocs);
1307 Item *conv= example->safe_charset_converter(thd, tocs);
1308 if (conv == example)
1309 return this;
1310 Item_cache *cache;
1311 if (!conv || conv->fix_fields(thd, (Item **) NULL) ||
1312 unlikely(!(cache= new (thd->mem_root) Item_cache_str(thd, conv))))
1313 return NULL; // Safe conversion is not possible, or OEM
1314 cache->setup(thd, conv);
1315 cache->fixed= false; // Make Item::fix_fields() happy
1316 return cache;
1317}
1318
1319
1320/**
1321 @details
1322 Created mostly for mysql_prepare_table(). Important
1323 when a string ENUM/SET column is described with a numeric default value:
1324
1325 CREATE TABLE t1(a SET('a') DEFAULT 1);
1326
1327 We cannot use generic Item::safe_charset_converter(), because
1328 the latter returns a non-fixed Item, so val_str() crashes afterwards.
1329 Override Item_num method, to return a fixed item.
1330*/
1331
1332Item *Item_num::safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
1333{
1334 /*
1335 Item_num returns pure ASCII result,
1336 so conversion is needed only in case of "tricky" character
1337 sets like UCS2. If tocs is not "tricky", return the item itself.
1338 */
1339 if (!(tocs->state & MY_CS_NONASCII))
1340 return this;
1341
1342 Item *conv;
1343 if ((conv= const_charset_converter(thd, tocs, true)))
1344 conv->fix_char_length(max_char_length());
1345 return conv;
1346}
1347
1348
1349/**
1350 Create character set converter for constant items
1351 using Item_null, Item_string or Item_static_string_func.
1352
1353 @param tocs Character set to to convert the string to.
1354 @param lossless Whether data loss is acceptable.
1355 @param func_name Function name, or NULL.
1356
1357 @return this, if conversion is not needed,
1358 NULL, if safe conversion is not possible, or
1359 a new item representing the converted constant.
1360*/
1361Item *Item::const_charset_converter(THD *thd, CHARSET_INFO *tocs,
1362 bool lossless,
1363 const char *func_name)
1364{
1365 DBUG_ASSERT(const_item());
1366 DBUG_ASSERT(fixed);
1367 StringBuffer<64>tmp;
1368 String *s= val_str(&tmp);
1369 MEM_ROOT *mem_root= thd->mem_root;
1370
1371 if (!s)
1372 return new (mem_root) Item_null(thd, (char *) func_name, tocs);
1373
1374 if (!needs_charset_converter(s->length(), tocs))
1375 {
1376 if (collation.collation == &my_charset_bin && tocs != &my_charset_bin &&
1377 !this->check_well_formed_result(s, true))
1378 return NULL;
1379 return this;
1380 }
1381
1382 uint conv_errors;
1383 Item_string *conv= (func_name ?
1384 new (mem_root)
1385 Item_static_string_func(thd, func_name,
1386 s, tocs, &conv_errors,
1387 collation.derivation,
1388 collation.repertoire) :
1389 new (mem_root)
1390 Item_string(thd, s, tocs, &conv_errors,
1391 collation.derivation,
1392 collation.repertoire));
1393
1394 if (unlikely(!conv || (conv_errors && lossless)))
1395 {
1396 /*
1397 Safe conversion is not possible (or EOM).
1398 We could not convert a string into the requested character set
1399 without data loss. The target charset does not cover all the
1400 characters from the string. Operation cannot be done correctly.
1401 */
1402 return NULL;
1403 }
1404 if (s->charset() == &my_charset_bin && tocs != &my_charset_bin &&
1405 !conv->check_well_formed_result(true))
1406 return NULL;
1407 return conv;
1408}
1409
1410
1411Item *Item_param::safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
1412{
1413 /*
1414 Return "this" if in prepare. result_type may change at execition time,
1415 to it's possible that the converter will not be needed at all:
1416
1417 PREPARE stmt FROM 'SELECT * FROM t1 WHERE field = ?';
1418 SET @arg= 1;
1419 EXECUTE stmt USING @arg;
1420
1421 In the above example result_type is STRING_RESULT at prepare time,
1422 and INT_RESULT at execution time.
1423 */
1424 return !const_item() || state == NULL_VALUE ?
1425 this : const_charset_converter(thd, tocs, true);
1426}
1427
1428
1429/**
1430 Get the value of the function as a MYSQL_TIME structure.
1431 As a extra convenience the time structure is reset on error or NULL values!
1432*/
1433
1434bool Item::get_date_from_int(MYSQL_TIME *ltime, ulonglong fuzzydate)
1435{
1436 longlong value= val_int();
1437 bool neg= !unsigned_flag && value < 0;
1438 if (null_value || int_to_datetime_with_warn(neg, neg ? -value : value,
1439 ltime, fuzzydate,
1440 field_name_or_null()))
1441 return null_value|= make_zero_date(ltime, fuzzydate);
1442 return null_value= false;
1443}
1444
1445
1446bool Item::get_date_from_year(MYSQL_TIME *ltime, ulonglong fuzzydate)
1447{
1448 longlong value= val_int();
1449 DBUG_ASSERT(unsigned_flag || value >= 0);
1450 if (max_length == 2)
1451 {
1452 if (value < 70)
1453 value+= 2000;
1454 else if (value <= 1900)
1455 value+= 1900;
1456 }
1457 value*= 10000; /* make it YYYYMMHH */
1458 if (null_value || int_to_datetime_with_warn(false, value,
1459 ltime, fuzzydate,
1460 field_name_or_null()))
1461 return null_value|= make_zero_date(ltime, fuzzydate);
1462 return null_value= false;
1463}
1464
1465
1466bool Item::get_date_from_real(MYSQL_TIME *ltime, ulonglong fuzzydate)
1467{
1468 double value= val_real();
1469 if (null_value || double_to_datetime_with_warn(value, ltime, fuzzydate,
1470 field_name_or_null()))
1471 return null_value|= make_zero_date(ltime, fuzzydate);
1472 return null_value= false;
1473}
1474
1475
1476bool Item::get_date_from_decimal(MYSQL_TIME *ltime, ulonglong fuzzydate)
1477{
1478 my_decimal value, *res;
1479 if (!(res= val_decimal(&value)) ||
1480 decimal_to_datetime_with_warn(res, ltime, fuzzydate,
1481 field_name_or_null()))
1482 return null_value|= make_zero_date(ltime, fuzzydate);
1483 return null_value= false;
1484}
1485
1486
1487bool Item::get_date_from_string(MYSQL_TIME *ltime, ulonglong fuzzydate)
1488{
1489 char buff[40];
1490 String tmp(buff,sizeof(buff), &my_charset_bin),*res;
1491 if (!(res=val_str(&tmp)) ||
1492 str_to_datetime_with_warn(res->charset(), res->ptr(), res->length(),
1493 ltime, fuzzydate))
1494 return null_value|= make_zero_date(ltime, fuzzydate);
1495 return null_value= false;
1496}
1497
1498
1499bool Item::make_zero_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
1500{
1501 /*
1502 if the item was not null and convertion failed, we return a zero date
1503 if allowed, otherwise - null.
1504 */
1505 bzero((char*) ltime,sizeof(*ltime));
1506 if (fuzzydate & TIME_TIME_ONLY)
1507 {
1508 /*
1509 In the following scenario:
1510 - The caller expected to get a TIME value
1511 - Item returned a not NULL string or numeric value
1512 - But then conversion from string or number to TIME failed
1513 we need to change the default time_type from MYSQL_TIMESTAMP_DATE
1514 (which was set in bzero) to MYSQL_TIMESTAMP_TIME and therefore
1515 return TIME'00:00:00' rather than DATE'0000-00-00'.
1516 If we don't do this, methods like Item::get_time_with_conversion()
1517 will erroneously subtract CURRENT_DATE from '0000-00-00 00:00:00'
1518 and return TIME'-838:59:59' instead of TIME'00:00:00' as a result.
1519 */
1520 ltime->time_type= MYSQL_TIMESTAMP_TIME;
1521 }
1522 return !(fuzzydate & TIME_FUZZY_DATES);
1523}
1524
1525bool Item::get_seconds(ulonglong *sec, ulong *sec_part)
1526{
1527 if (decimals == 0)
1528 { // optimize for an important special case
1529 longlong val= val_int();
1530 bool neg= val < 0 && !unsigned_flag;
1531 *sec= neg ? -val : val;
1532 *sec_part= 0;
1533 return neg;
1534 }
1535 my_decimal tmp, *dec= val_decimal(&tmp);
1536 if (!dec)
1537 return 0;
1538 return my_decimal2seconds(dec, sec, sec_part);
1539}
1540
1541const MY_LOCALE *Item::locale_from_val_str()
1542{
1543 StringBuffer<MAX_FIELD_WIDTH> tmp;
1544 String *locale_name= val_str_ascii(&tmp);
1545 const MY_LOCALE *lc;
1546 if (!locale_name ||
1547 !(lc= my_locale_by_name(locale_name->c_ptr_safe())))
1548 {
1549 THD *thd= current_thd;
1550 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
1551 ER_UNKNOWN_LOCALE,
1552 ER_THD(thd, ER_UNKNOWN_LOCALE),
1553 locale_name ? locale_name->c_ptr_safe() : "NULL");
1554 lc= &my_locale_en_US;
1555 }
1556 return lc;
1557}
1558
1559
1560CHARSET_INFO *Item::default_charset()
1561{
1562 return current_thd->variables.collation_connection;
1563}
1564
1565
1566/*
1567 Save value in field, but don't give any warnings
1568
1569 NOTES
1570 This is used to temporary store and retrieve a value in a column,
1571 for example in opt_range to adjust the key value to fit the column.
1572*/
1573
1574int Item::save_in_field_no_warnings(Field *field, bool no_conversions)
1575{
1576 int res;
1577 TABLE *table= field->table;
1578 THD *thd= table->in_use;
1579 enum_check_fields tmp= thd->count_cuted_fields;
1580 my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
1581 sql_mode_t sql_mode= thd->variables.sql_mode;
1582 thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
1583 thd->variables.sql_mode|= MODE_INVALID_DATES;
1584 thd->count_cuted_fields= CHECK_FIELD_IGNORE;
1585
1586 res= save_in_field(field, no_conversions);
1587
1588 thd->count_cuted_fields= tmp;
1589 dbug_tmp_restore_column_map(table->write_set, old_map);
1590 thd->variables.sql_mode= sql_mode;
1591 return res;
1592}
1593
1594#ifndef DBUG_OFF
1595static inline
1596void mark_unsupported_func(const char *where, const char *processor_name)
1597{
1598 char buff[64];
1599 my_snprintf(buff, sizeof(buff), "%s::%s", where ? where: "", processor_name);
1600 DBUG_ENTER(buff);
1601 my_snprintf(buff, sizeof(buff), "%s returns TRUE: unsupported function", processor_name);
1602 DBUG_PRINT("info", ("%s", buff));
1603 DBUG_VOID_RETURN;
1604}
1605#else
1606#define mark_unsupported_func(X,Y) {}
1607#endif
1608
1609bool mark_unsupported_function(const char *where, void *store, uint result)
1610{
1611 Item::vcol_func_processor_result *res=
1612 (Item::vcol_func_processor_result*) store;
1613 uint old_errors= res->errors;
1614 mark_unsupported_func(where, "check_vcol_func_processor");
1615 res->errors|= result; /* Store type of expression */
1616 /* Store the name to the highest violation (normally VCOL_IMPOSSIBLE) */
1617 if (result > old_errors)
1618 res->name= where ? where : "";
1619 return false;
1620}
1621
1622/* convenience helper for mark_unsupported_function() above */
1623bool mark_unsupported_function(const char *w1, const char *w2,
1624 void *store, uint result)
1625{
1626 char *ptr= (char*)current_thd->alloc(strlen(w1) + strlen(w2) + 1);
1627 if (ptr)
1628 strxmov(ptr, w1, w2, NullS);
1629 return mark_unsupported_function(ptr, store, result);
1630}
1631
1632
1633Query_fragment::Query_fragment(THD *thd, sp_head *sphead,
1634 const char *start, const char *end)
1635{
1636 DBUG_ASSERT(start <= end);
1637 if (sphead)
1638 {
1639 if (sphead->m_tmp_query)
1640 {
1641 // Normal SP statement
1642 DBUG_ASSERT(sphead->m_tmp_query <= start);
1643 set(start - sphead->m_tmp_query, end - start);
1644 }
1645 else
1646 {
1647 /*
1648 We're in the "if" expression of a compound query:
1649 if (expr)
1650 do_something;
1651 end if;
1652 sphead->m_tmp_query is not set yet at this point, because
1653 the "if" part of such statements is never put into the binary log.
1654 Values of Rewritable_query_parameter::pos_in_query and
1655 Rewritable_query_parameter:len_in_query will not be important,
1656 so setting both to 0 should be fine.
1657 */
1658 set(0, 0);
1659 }
1660 }
1661 else
1662 {
1663 // Non-SP statement
1664 DBUG_ASSERT(thd->query() <= start);
1665 DBUG_ASSERT(end <= thd->query_end());
1666 set(start - thd->query(), end - start);
1667 }
1668}
1669
1670
1671/*****************************************************************************
1672 Item_sp_variable methods
1673*****************************************************************************/
1674
1675Item_sp_variable::Item_sp_variable(THD *thd, const LEX_CSTRING *sp_var_name)
1676 :Item(thd), m_thd(0), m_name(*sp_var_name)
1677#ifndef DBUG_OFF
1678 , m_sp(0)
1679#endif
1680{
1681}
1682
1683
1684bool Item_sp_variable::fix_fields_from_item(THD *thd, Item **, const Item *it)
1685{
1686 m_thd= thd; /* NOTE: this must be set before any this_xxx() */
1687
1688 DBUG_ASSERT(it->fixed);
1689
1690 max_length= it->max_length;
1691 decimals= it->decimals;
1692 unsigned_flag= it->unsigned_flag;
1693 with_param= 1;
1694 if (thd->lex->current_select && thd->lex->current_select->master_unit()->item)
1695 thd->lex->current_select->master_unit()->item->with_param= 1;
1696 fixed= 1;
1697 collation.set(it->collation.collation, it->collation.derivation);
1698
1699 return FALSE;
1700}
1701
1702
1703double Item_sp_variable::val_real()
1704{
1705 DBUG_ASSERT(fixed);
1706 Item *it= this_item();
1707 double ret= it->val_real();
1708 null_value= it->null_value;
1709 return ret;
1710}
1711
1712
1713longlong Item_sp_variable::val_int()
1714{
1715 DBUG_ASSERT(fixed);
1716 Item *it= this_item();
1717 longlong ret= it->val_int();
1718 null_value= it->null_value;
1719 return ret;
1720}
1721
1722
1723String *Item_sp_variable::val_str(String *sp)
1724{
1725 DBUG_ASSERT(fixed);
1726 Item *it= this_item();
1727 String *res= it->val_str(sp);
1728
1729 null_value= it->null_value;
1730
1731 if (!res)
1732 return NULL;
1733
1734 /*
1735 This way we mark returned value of val_str as const,
1736 so that various functions (e.g. CONCAT) won't try to
1737 modify the value of the Item. Analogous mechanism is
1738 implemented for Item_param.
1739 Without this trick Item_splocal could be changed as a
1740 side-effect of expression computation. Here is an example
1741 of what happens without it: suppose x is varchar local
1742 variable in a SP with initial value 'ab' Then
1743 select concat(x,'c');
1744 would change x's value to 'abc', as Item_func_concat::val_str()
1745 would use x's internal buffer to compute the result.
1746 This is intended behaviour of Item_func_concat. Comments to
1747 Item_param class contain some more details on the topic.
1748 */
1749
1750 if (res != &str_value)
1751 str_value.set(res->ptr(), res->length(), res->charset());
1752 else
1753 res->mark_as_const();
1754
1755 return &str_value;
1756}
1757
1758
1759my_decimal *Item_sp_variable::val_decimal(my_decimal *decimal_value)
1760{
1761 DBUG_ASSERT(fixed);
1762 Item *it= this_item();
1763 my_decimal *val= it->val_decimal(decimal_value);
1764 null_value= it->null_value;
1765 return val;
1766}
1767
1768
1769bool Item_sp_variable::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
1770{
1771 DBUG_ASSERT(fixed);
1772 Item *it= this_item();
1773 bool val= it->get_date(ltime, fuzzydate);
1774 null_value= it->null_value;
1775 return val;
1776}
1777
1778
1779bool Item_sp_variable::is_null()
1780{
1781 return this_item()->is_null();
1782}
1783
1784void Item_sp_variable::make_send_field(THD *thd, Send_field *field)
1785{
1786 Item *it= this_item();
1787
1788 it->make_send_field(thd, field);
1789 if (name.str)
1790 field->col_name= name;
1791 else
1792 field->col_name= m_name;
1793}
1794
1795/*****************************************************************************
1796 Item_splocal methods
1797*****************************************************************************/
1798
1799Item_splocal::Item_splocal(THD *thd,
1800 const Sp_rcontext_handler *rh,
1801 const LEX_CSTRING *sp_var_name,
1802 uint sp_var_idx,
1803 const Type_handler *handler,
1804 uint pos_in_q, uint len_in_q):
1805 Item_sp_variable(thd, sp_var_name),
1806 Rewritable_query_parameter(pos_in_q, len_in_q),
1807 Type_handler_hybrid_field_type(handler),
1808 m_rcontext_handler(rh),
1809 m_var_idx(sp_var_idx)
1810{
1811 maybe_null= TRUE;
1812 m_type= sp_map_item_type(handler);
1813}
1814
1815
1816sp_rcontext *Item_splocal::get_rcontext(sp_rcontext *local_ctx) const
1817{
1818 return m_rcontext_handler->get_rcontext(local_ctx);
1819}
1820
1821
1822Item_field *Item_splocal::get_variable(sp_rcontext *ctx) const
1823{
1824 return get_rcontext(ctx)->get_variable(m_var_idx);
1825}
1826
1827
1828bool Item_splocal::fix_fields(THD *thd, Item **ref)
1829{
1830 Item *item= get_variable(thd->spcont);
1831 set_handler(item->type_handler());
1832 return fix_fields_from_item(thd, ref, item);
1833}
1834
1835
1836Item *
1837Item_splocal::this_item()
1838{
1839 DBUG_ASSERT(m_sp == m_thd->spcont->m_sp);
1840 DBUG_ASSERT(fixed);
1841 return get_variable(m_thd->spcont);
1842}
1843
1844const Item *
1845Item_splocal::this_item() const
1846{
1847 DBUG_ASSERT(m_sp == m_thd->spcont->m_sp);
1848 DBUG_ASSERT(fixed);
1849 return get_variable(m_thd->spcont);
1850}
1851
1852
1853Item **
1854Item_splocal::this_item_addr(THD *thd, Item **)
1855{
1856 DBUG_ASSERT(m_sp == thd->spcont->m_sp);
1857 DBUG_ASSERT(fixed);
1858 return get_rcontext(thd->spcont)->get_variable_addr(m_var_idx);
1859}
1860
1861
1862void Item_splocal::print(String *str, enum_query_type)
1863{
1864 const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix();
1865 str->reserve(m_name.length + 8 + prefix->length);
1866 str->append(prefix);
1867 str->append(&m_name);
1868 str->append('@');
1869 str->qs_append(m_var_idx);
1870}
1871
1872
1873bool Item_splocal::set_value(THD *thd, sp_rcontext *ctx, Item **it)
1874{
1875 return get_rcontext(ctx)->set_variable(thd, get_var_idx(), it);
1876}
1877
1878
1879/**
1880 These two declarations are different:
1881 x INT;
1882 ROW(x INT);
1883 A ROW with one elements should not be comparable to scalar value.
1884
1885 TODO: Currently we don't support one argument with the function ROW(), so
1886 this query returns a syntax error, meaning that more arguments are expected:
1887 SELECT ROW(1);
1888
1889 Therefore, all around the code we assume that cols()==1 means a scalar value
1890 and cols()>1 means a ROW value. With adding ROW SP variables this
1891 assumption is not true any more. ROW variables with one element are
1892 now possible.
1893
1894 To implement Item::check_cols() correctly, we now should extend it to
1895 know if a ROW or a scalar value is being tested. For example,
1896 these new prototypes should work:
1897 virtual bool check_cols(Item_result result, uint c);
1898 or
1899 virtual bool check_cols(const Type_handler *type, uint c);
1900
1901 The current implementation of Item_splocal::check_cols() is a compromise
1902 that should be more or less fine until we extend check_cols().
1903 It disallows ROW variables to appear in a scalar context.
1904 The "|| n == 1" part of the conditon is responsible for this.
1905 For example, it disallows ROW variables to appear in SELECT list:
1906
1907DELIMITER $$;
1908CREATE PROCEDURE p1()
1909AS
1910 a ROW (a INT);
1911BEGIN
1912 SELECT a;
1913END;
1914$$
1915DELIMITER ;$$
1916--error ER_OPERAND_COLUMNS
1917CALL p1();
1918
1919 But is produces false negatives with ROW variables consisting of one element.
1920 For example, this script fails:
1921
1922SET sql_mode=ORACLE;
1923DROP PROCEDURE IF EXISTS p1;
1924DELIMITER $$
1925CREATE PROCEDURE p1
1926AS
1927 a ROW(a INT);
1928 b ROW(a INT);
1929BEGIN
1930 SELECT a=b;
1931END;
1932$$
1933DELIMITER ;
1934CALL p1();
1935
1936 and returns "ERROR 1241 (21000): Operand should contain 1 column(s)".
1937 This will be fixed that we change check_cols().
1938*/
1939
1940bool Item_splocal::check_cols(uint n)
1941{
1942 DBUG_ASSERT(m_thd->spcont);
1943 if (Type_handler_hybrid_field_type::cmp_type() != ROW_RESULT)
1944 return Item::check_cols(n);
1945
1946 if (n != this_item()->cols() || n == 1)
1947 {
1948 my_error(ER_OPERAND_COLUMNS, MYF(0), n);
1949 return true;
1950 }
1951 return false;
1952}
1953
1954
1955bool Item_splocal_row_field::fix_fields(THD *thd, Item **ref)
1956{
1957 Item *item= get_variable(thd->spcont)->element_index(m_field_idx);
1958 return fix_fields_from_item(thd, ref, item);
1959}
1960
1961
1962Item *
1963Item_splocal_row_field::this_item()
1964{
1965 DBUG_ASSERT(m_sp == m_thd->spcont->m_sp);
1966 DBUG_ASSERT(fixed);
1967 return get_variable(m_thd->spcont)->element_index(m_field_idx);
1968}
1969
1970
1971const Item *
1972Item_splocal_row_field::this_item() const
1973{
1974 DBUG_ASSERT(m_sp == m_thd->spcont->m_sp);
1975 DBUG_ASSERT(fixed);
1976 return get_variable(m_thd->spcont)->element_index(m_field_idx);
1977}
1978
1979
1980Item **
1981Item_splocal_row_field::this_item_addr(THD *thd, Item **)
1982{
1983 DBUG_ASSERT(m_sp == thd->spcont->m_sp);
1984 DBUG_ASSERT(fixed);
1985 return get_variable(thd->spcont)->addr(m_field_idx);
1986}
1987
1988
1989void Item_splocal_row_field::print(String *str, enum_query_type)
1990{
1991 const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix();
1992 str->reserve(m_name.length + m_field_name.length + 8 + prefix->length);
1993 str->append(prefix);
1994 str->append(&m_name);
1995 str->append('.');
1996 str->append(&m_field_name);
1997 str->append('@');
1998 str->qs_append(m_var_idx);
1999 str->append('[');
2000 str->qs_append(m_field_idx);
2001 str->append(']');
2002}
2003
2004
2005bool Item_splocal_row_field::set_value(THD *thd, sp_rcontext *ctx, Item **it)
2006{
2007 return get_rcontext(ctx)->set_variable_row_field(thd, m_var_idx, m_field_idx,
2008 it);
2009}
2010
2011
2012bool Item_splocal_row_field_by_name::fix_fields(THD *thd, Item **it)
2013{
2014 m_thd= thd;
2015 if (get_rcontext(thd->spcont)->find_row_field_by_name_or_error(&m_field_idx,
2016 m_var_idx,
2017 m_field_name))
2018 return true;
2019 Item *item= get_variable(thd->spcont)->element_index(m_field_idx);
2020 set_handler(item->type_handler());
2021 return fix_fields_from_item(thd, it, item);
2022}
2023
2024
2025void Item_splocal_row_field_by_name::print(String *str, enum_query_type)
2026{
2027 const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix();
2028 // +16 should be enough for .NNN@[""]
2029 if (str->reserve(m_name.length + 2 * m_field_name.length +
2030 prefix->length + 16))
2031 return;
2032 str->qs_append(prefix);
2033 str->qs_append(&m_name);
2034 str->qs_append('.');
2035 str->qs_append(&m_field_name);
2036 str->qs_append('@');
2037 str->qs_append(m_var_idx);
2038 str->qs_append("[\"", 2);
2039 str->qs_append(&m_field_name);
2040 str->qs_append("\"]", 2);
2041}
2042
2043
2044bool Item_splocal_row_field_by_name::set_value(THD *thd, sp_rcontext *ctx, Item **it)
2045{
2046 DBUG_ASSERT(fixed); // Make sure m_field_idx is already set
2047 return Item_splocal_row_field::set_value(thd, ctx, it);
2048}
2049
2050
2051/*****************************************************************************
2052 Item_case_expr methods
2053*****************************************************************************/
2054
2055LEX_CSTRING str_case_expr= { STRING_WITH_LEN("case_expr") };
2056
2057Item_case_expr::Item_case_expr(THD *thd, uint case_expr_id):
2058 Item_sp_variable(thd, &str_case_expr),
2059 m_case_expr_id(case_expr_id)
2060{
2061}
2062
2063
2064bool Item_case_expr::fix_fields(THD *thd, Item **ref)
2065{
2066 Item *item= thd->spcont->get_case_expr(m_case_expr_id);
2067 return fix_fields_from_item(thd, ref, item);
2068}
2069
2070
2071Item *
2072Item_case_expr::this_item()
2073{
2074 DBUG_ASSERT(m_sp == m_thd->spcont->m_sp);
2075
2076 return m_thd->spcont->get_case_expr(m_case_expr_id);
2077}
2078
2079
2080
2081const Item *
2082Item_case_expr::this_item() const
2083{
2084 DBUG_ASSERT(m_sp == m_thd->spcont->m_sp);
2085
2086 return m_thd->spcont->get_case_expr(m_case_expr_id);
2087}
2088
2089
2090Item **
2091Item_case_expr::this_item_addr(THD *thd, Item **)
2092{
2093 DBUG_ASSERT(m_sp == thd->spcont->m_sp);
2094
2095 return thd->spcont->get_case_expr_addr(m_case_expr_id);
2096}
2097
2098
2099void Item_case_expr::print(String *str, enum_query_type)
2100{
2101 if (str->reserve(MAX_INT_WIDTH + sizeof("case_expr@")))
2102 return; /* purecov: inspected */
2103 (void) str->append(STRING_WITH_LEN("case_expr@"));
2104 str->qs_append(m_case_expr_id);
2105}
2106
2107
2108/*****************************************************************************
2109 Item_name_const methods
2110*****************************************************************************/
2111
2112double Item_name_const::val_real()
2113{
2114 DBUG_ASSERT(fixed);
2115 double ret= value_item->val_real();
2116 null_value= value_item->null_value;
2117 return ret;
2118}
2119
2120
2121longlong Item_name_const::val_int()
2122{
2123 DBUG_ASSERT(fixed);
2124 longlong ret= value_item->val_int();
2125 null_value= value_item->null_value;
2126 return ret;
2127}
2128
2129
2130String *Item_name_const::val_str(String *sp)
2131{
2132 DBUG_ASSERT(fixed);
2133 String *ret= value_item->val_str(sp);
2134 null_value= value_item->null_value;
2135 return ret;
2136}
2137
2138
2139my_decimal *Item_name_const::val_decimal(my_decimal *decimal_value)
2140{
2141 DBUG_ASSERT(fixed);
2142 my_decimal *val= value_item->val_decimal(decimal_value);
2143 null_value= value_item->null_value;
2144 return val;
2145}
2146
2147bool Item_name_const::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
2148{
2149 DBUG_ASSERT(fixed);
2150 bool rc= value_item->get_date(ltime, fuzzydate);
2151 null_value= value_item->null_value;
2152 return rc;
2153}
2154
2155bool Item_name_const::is_null()
2156{
2157 return value_item->is_null();
2158}
2159
2160
2161Item_name_const::Item_name_const(THD *thd, Item *name_arg, Item *val):
2162 Item(thd), value_item(val), name_item(name_arg)
2163{
2164 Item::maybe_null= TRUE;
2165 valid_args= true;
2166 if (!name_item->basic_const_item())
2167 goto err;
2168
2169 if (value_item->basic_const_item())
2170 return; // ok
2171
2172 if (value_item->type() == FUNC_ITEM)
2173 {
2174 Item_func *value_func= (Item_func *) value_item;
2175 if (value_func->functype() != Item_func::COLLATE_FUNC &&
2176 value_func->functype() != Item_func::NEG_FUNC)
2177 goto err;
2178
2179 if (value_func->key_item()->basic_const_item())
2180 return; // ok
2181 }
2182
2183err:
2184 valid_args= false;
2185 my_error(ER_WRONG_ARGUMENTS, MYF(0), "NAME_CONST");
2186}
2187
2188
2189Item::Type Item_name_const::type() const
2190{
2191 /*
2192 As
2193 1. one can try to create the Item_name_const passing non-constant
2194 arguments, although it's incorrect and
2195 2. the type() method can be called before the fix_fields() to get
2196 type information for a further type cast, e.g.
2197 if (item->type() == FIELD_ITEM)
2198 ((Item_field *) item)->...
2199 we return NULL_ITEM in the case to avoid wrong casting.
2200
2201 valid_args guarantees value_item->basic_const_item(); if type is
2202 FUNC_ITEM, then we have a fudged item_func_neg() on our hands
2203 and return the underlying type.
2204 For Item_func_set_collation()
2205 e.g. NAME_CONST('name', 'value' COLLATE collation) we return its
2206 'value' argument type.
2207 */
2208 if (!valid_args)
2209 return NULL_ITEM;
2210 Item::Type value_type= value_item->type();
2211 if (value_type == FUNC_ITEM)
2212 {
2213 /*
2214 The second argument of NAME_CONST('name', 'value') must be
2215 a simple constant item or a NEG_FUNC/COLLATE_FUNC.
2216 */
2217 DBUG_ASSERT(((Item_func *) value_item)->functype() ==
2218 Item_func::NEG_FUNC ||
2219 ((Item_func *) value_item)->functype() ==
2220 Item_func::COLLATE_FUNC);
2221 return ((Item_func *) value_item)->key_item()->type();
2222 }
2223 return value_type;
2224}
2225
2226
2227bool Item_name_const::fix_fields(THD *thd, Item **ref)
2228{
2229 char buf[128];
2230 String *item_name;
2231 String s(buf, sizeof(buf), &my_charset_bin);
2232 s.length(0);
2233
2234 if ((!value_item->fixed &&
2235 value_item->fix_fields(thd, &value_item)) ||
2236 (!name_item->fixed &&
2237 name_item->fix_fields(thd, &name_item)) ||
2238 !value_item->const_item() ||
2239 !name_item->const_item() ||
2240 !(item_name= name_item->val_str(&s))) // Can't have a NULL name
2241 {
2242 my_error(ER_RESERVED_SYNTAX, MYF(0), "NAME_CONST");
2243 return TRUE;
2244 }
2245 if (is_autogenerated_name)
2246 {
2247 set_name(thd, item_name->c_ptr(), (uint) item_name->length(),
2248 system_charset_info);
2249 }
2250 if (value_item->collation.derivation == DERIVATION_NUMERIC)
2251 collation.set_numeric();
2252 else
2253 collation.set(value_item->collation.collation, DERIVATION_IMPLICIT);
2254 max_length= value_item->max_length;
2255 decimals= value_item->decimals;
2256 fixed= 1;
2257 return FALSE;
2258}
2259
2260
2261void Item_name_const::print(String *str, enum_query_type query_type)
2262{
2263 str->append(STRING_WITH_LEN("NAME_CONST("));
2264 name_item->print(str, query_type);
2265 str->append(',');
2266 value_item->print(str, query_type);
2267 str->append(')');
2268}
2269
2270
2271/*
2272 need a special class to adjust printing : references to aggregate functions
2273 must not be printed as refs because the aggregate functions that are added to
2274 the front of select list are not printed as well.
2275*/
2276class Item_aggregate_ref : public Item_ref
2277{
2278public:
2279 Item_aggregate_ref(THD *thd, Name_resolution_context *context_arg,
2280 Item **item, const char *table_name_arg,
2281 const LEX_CSTRING *field_name_arg):
2282 Item_ref(thd, context_arg, item, table_name_arg, field_name_arg) {}
2283
2284 virtual inline void print (String *str, enum_query_type query_type)
2285 {
2286 if (ref)
2287 (*ref)->print(str, query_type);
2288 else
2289 Item_ident::print(str, query_type);
2290 }
2291 virtual Ref_Type ref_type() { return AGGREGATE_REF; }
2292};
2293
2294
2295/**
2296 Move SUM items out from item tree and replace with reference.
2297
2298 @param thd Thread handler
2299 @param ref_pointer_array Pointer to array of reference fields
2300 @param fields All fields in select
2301 @param ref Pointer to item
2302 @param split_flags Zero or more of the following flags
2303 SPLIT_FUNC_SKIP_REGISTERED:
2304 Function be must skipped for registered SUM
2305 SUM items
2306 SPLIT_SUM_SELECT
2307 We are called on the select level and have to
2308 register items operated on sum function
2309
2310 @note
2311 All found SUM items are added FIRST in the fields list and
2312 we replace the item with a reference.
2313
2314 If this is an item in the SELECT list then we also have to split out
2315 all arguments to functions used together with the sum function.
2316 For example in case of SELECT A*sum(B) we have to split out both
2317 A and sum(B).
2318 This is not needed for ORDER BY, GROUP BY or HAVING as all references
2319 to items in the select list are already of type REF
2320
2321 thd->fatal_error() may be called if we are out of memory
2322*/
2323
2324void Item::split_sum_func2(THD *thd, Ref_ptr_array ref_pointer_array,
2325 List<Item> &fields, Item **ref,
2326 uint split_flags)
2327{
2328 if (unlikely(type() == SUM_FUNC_ITEM))
2329 {
2330 /* An item of type Item_sum is registered if ref_by != 0 */
2331 if ((split_flags & SPLIT_SUM_SKIP_REGISTERED) &&
2332 ((Item_sum *) this)->ref_by)
2333 return;
2334 }
2335 else if (type() == WINDOW_FUNC_ITEM || with_window_func)
2336 {
2337 /*
2338 Skip the else part, window functions are very special functions:
2339 they need to have their own fields in the temp. table, but they
2340 need to be proceessed differently than regular aggregate functions
2341
2342 Call split_sum_func here so that each argument gets its fields to
2343 point to the temporary table.
2344 */
2345 split_sum_func(thd, ref_pointer_array, fields, split_flags);
2346 if (type() == FUNC_ITEM) {
2347 return;
2348 }
2349 }
2350 else
2351 {
2352 /* Not a SUM() function */
2353 if (unlikely((!with_sum_func && !(split_flags & SPLIT_SUM_SELECT))))
2354 {
2355 /*
2356 This is not a SUM function and there are no SUM functions inside.
2357 Nothing more to do.
2358 */
2359 return;
2360 }
2361 if (likely(with_sum_func ||
2362 (type() == FUNC_ITEM &&
2363 (((Item_func *) this)->functype() ==
2364 Item_func::ISNOTNULLTEST_FUNC ||
2365 ((Item_func *) this)->functype() ==
2366 Item_func::TRIG_COND_FUNC))))
2367 {
2368 /* Will call split_sum_func2() for all items */
2369 split_sum_func(thd, ref_pointer_array, fields, split_flags);
2370 return;
2371 }
2372
2373 if (unlikely((!(used_tables() & ~PARAM_TABLE_BIT) ||
2374 type() == SUBSELECT_ITEM ||
2375 (type() == REF_ITEM &&
2376 ((Item_ref*)this)->ref_type() != Item_ref::VIEW_REF))))
2377 return;
2378 }
2379
2380 /*
2381 Replace item with a reference so that we can easily calculate
2382 it (in case of sum functions) or copy it (in case of fields)
2383
2384 The test above is to ensure we don't do a reference for things
2385 that are constants (PARAM_TABLE_BIT is in effect a constant)
2386 or already referenced (for example an item in HAVING)
2387 Exception is Item_direct_view_ref which we need to convert to
2388 Item_ref to allow fields from view being stored in tmp table.
2389 */
2390 Item_ref *item_ref;
2391 uint el= fields.elements;
2392 /*
2393 If this is an item_ref, get the original item
2394 This is a safety measure if this is called for things that is
2395 already a reference.
2396 */
2397 Item *real_itm= real_item();
2398 ref_pointer_array[el]= real_itm;
2399 if (type() == WINDOW_FUNC_ITEM)
2400 {
2401 if (!(item_ref= (new (thd->mem_root)
2402 Item_direct_ref(thd,
2403 &thd->lex->current_select->context,
2404 &ref_pointer_array[el], 0,
2405 &name))))
2406 return; // fatal_error is set
2407 }
2408 else
2409 {
2410 if (!(item_ref= (new (thd->mem_root)
2411 Item_aggregate_ref(thd,
2412 &thd->lex->current_select->context,
2413 &ref_pointer_array[el], 0,
2414 &name))))
2415 return; // fatal_error is set
2416 }
2417 if (type() == SUM_FUNC_ITEM)
2418 item_ref->depended_from= ((Item_sum *) this)->depended_from();
2419 fields.push_front(real_itm);
2420 thd->change_item_tree(ref, item_ref);
2421}
2422
2423
2424static bool
2425left_is_superset(const DTCollation *left, const DTCollation *right)
2426{
2427 /* Allow convert to Unicode */
2428 if (left->collation->state & MY_CS_UNICODE &&
2429 (left->derivation < right->derivation ||
2430 (left->derivation == right->derivation &&
2431 (!(right->collation->state & MY_CS_UNICODE) ||
2432 /* The code below makes 4-byte utf8 a superset over 3-byte utf8 */
2433 (left->collation->state & MY_CS_UNICODE_SUPPLEMENT &&
2434 !(right->collation->state & MY_CS_UNICODE_SUPPLEMENT) &&
2435 left->collation->mbmaxlen > right->collation->mbmaxlen &&
2436 left->collation->mbminlen == right->collation->mbminlen)))))
2437 return TRUE;
2438 /* Allow convert from ASCII */
2439 if (right->repertoire == MY_REPERTOIRE_ASCII &&
2440 (left->derivation < right->derivation ||
2441 (left->derivation == right->derivation &&
2442 !(left->repertoire == MY_REPERTOIRE_ASCII))))
2443 return TRUE;
2444 /* Disallow conversion otherwise */
2445 return FALSE;
2446}
2447
2448/**
2449 Aggregate two collations together taking
2450 into account their coercibility (aka derivation):.
2451
2452 0 == DERIVATION_EXPLICIT - an explicitly written COLLATE clause @n
2453 1 == DERIVATION_NONE - a mix of two different collations @n
2454 2 == DERIVATION_IMPLICIT - a column @n
2455 3 == DERIVATION_COERCIBLE - a string constant.
2456
2457 The most important rules are:
2458 -# If collations are the same:
2459 chose this collation, and the strongest derivation.
2460 -# If collations are different:
2461 - Character sets may differ, but only if conversion without
2462 data loss is possible. The caller provides flags whether
2463 character set conversion attempts should be done. If no
2464 flags are substituted, then the character sets must be the same.
2465 Currently processed flags are:
2466 MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset
2467 MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
2468 - two EXPLICIT collations produce an error, e.g. this is wrong:
2469 CONCAT(expr1 collate latin1_swedish_ci, expr2 collate latin1_german_ci)
2470 - the side with smaller derivation value wins,
2471 i.e. a column is stronger than a string constant,
2472 an explicit COLLATE clause is stronger than a column.
2473 - if derivations are the same, we have DERIVATION_NONE,
2474 we'll wait for an explicit COLLATE clause which possibly can
2475 come from another argument later: for example, this is valid,
2476 but we don't know yet when collecting the first two arguments:
2477 @code
2478 CONCAT(latin1_swedish_ci_column,
2479 latin1_german1_ci_column,
2480 expr COLLATE latin1_german2_ci)
2481 @endcode
2482*/
2483
2484bool DTCollation::aggregate(const DTCollation &dt, uint flags)
2485{
2486 if (!my_charset_same(collation, dt.collation))
2487 {
2488 /*
2489 We do allow to use binary strings (like BLOBS)
2490 together with character strings.
2491 Binaries have more precedence than a character
2492 string of the same derivation.
2493 */
2494 if (collation == &my_charset_bin)
2495 {
2496 if (derivation <= dt.derivation)
2497 {
2498 /* Do nothing */
2499 }
2500 else
2501 {
2502 set(dt);
2503 }
2504 }
2505 else if (dt.collation == &my_charset_bin)
2506 {
2507 if (dt.derivation <= derivation)
2508 {
2509 set(dt);
2510 }
2511 }
2512 else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
2513 left_is_superset(this, &dt))
2514 {
2515 /* Do nothing */
2516 }
2517 else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
2518 left_is_superset(&dt, this))
2519 {
2520 set(dt);
2521 }
2522 else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
2523 derivation < dt.derivation &&
2524 dt.derivation >= DERIVATION_SYSCONST)
2525 {
2526 /* Do nothing */
2527 }
2528 else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
2529 dt.derivation < derivation &&
2530 derivation >= DERIVATION_SYSCONST)
2531 {
2532 set(dt);
2533 }
2534 else
2535 {
2536 // Cannot apply conversion
2537 set(&my_charset_bin, DERIVATION_NONE,
2538 (dt.repertoire|repertoire));
2539 return 1;
2540 }
2541 }
2542 else if (derivation < dt.derivation)
2543 {
2544 /* Do nothing */
2545 }
2546 else if (dt.derivation < derivation)
2547 {
2548 set(dt);
2549 }
2550 else
2551 {
2552 if (collation == dt.collation)
2553 {
2554 /* Do nothing */
2555 }
2556 else
2557 {
2558 if (derivation == DERIVATION_EXPLICIT)
2559 {
2560 set(0, DERIVATION_NONE, 0);
2561 return 1;
2562 }
2563 if (collation->state & MY_CS_BINSORT &&
2564 dt.collation->state & MY_CS_BINSORT)
2565 return 1;
2566 if (collation->state & MY_CS_BINSORT)
2567 return 0;
2568 if (dt.collation->state & MY_CS_BINSORT)
2569 {
2570 set(dt);
2571 return 0;
2572 }
2573 CHARSET_INFO *bin= get_charset_by_csname(collation->csname,
2574 MY_CS_BINSORT,MYF(0));
2575 set(bin, DERIVATION_NONE);
2576 }
2577 }
2578 repertoire|= dt.repertoire;
2579 return 0;
2580}
2581
2582/******************************/
2583static
2584void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname)
2585{
2586 my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
2587 c1.collation->name,c1.derivation_name(),
2588 c2.collation->name,c2.derivation_name(),
2589 fname);
2590}
2591
2592
2593static
2594void my_coll_agg_error(DTCollation &c1, DTCollation &c2, DTCollation &c3,
2595 const char *fname)
2596{
2597 my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0),
2598 c1.collation->name,c1.derivation_name(),
2599 c2.collation->name,c2.derivation_name(),
2600 c3.collation->name,c3.derivation_name(),
2601 fname);
2602}
2603
2604
2605static
2606void my_coll_agg_error(Item** args, uint count, const char *fname,
2607 int item_sep)
2608{
2609 if (count == 2)
2610 my_coll_agg_error(args[0]->collation, args[item_sep]->collation, fname);
2611 else if (count == 3)
2612 my_coll_agg_error(args[0]->collation, args[item_sep]->collation,
2613 args[2*item_sep]->collation, fname);
2614 else
2615 my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname);
2616}
2617
2618
2619bool Type_std_attributes::agg_item_collations(DTCollation &c, const char *fname,
2620 Item **av, uint count,
2621 uint flags, int item_sep)
2622{
2623 uint i;
2624 Item **arg;
2625 bool unknown_cs= 0;
2626
2627 c.set(av[0]->collation);
2628 for (i= 1, arg= &av[item_sep]; i < count; i++, arg+= item_sep)
2629 {
2630 if (c.aggregate((*arg)->collation, flags))
2631 {
2632 if (c.derivation == DERIVATION_NONE &&
2633 c.collation == &my_charset_bin)
2634 {
2635 unknown_cs= 1;
2636 continue;
2637 }
2638 my_coll_agg_error(av, count, fname, item_sep);
2639 return TRUE;
2640 }
2641 }
2642
2643 if (unknown_cs &&
2644 c.derivation != DERIVATION_EXPLICIT)
2645 {
2646 my_coll_agg_error(av, count, fname, item_sep);
2647 return TRUE;
2648 }
2649
2650 if ((flags & MY_COLL_DISALLOW_NONE) &&
2651 c.derivation == DERIVATION_NONE)
2652 {
2653 my_coll_agg_error(av, count, fname, item_sep);
2654 return TRUE;
2655 }
2656
2657 /* If all arguments where numbers, reset to @@collation_connection */
2658 if (flags & MY_COLL_ALLOW_NUMERIC_CONV &&
2659 c.derivation == DERIVATION_NUMERIC)
2660 c.set(Item::default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_NUMERIC);
2661
2662 return FALSE;
2663}
2664
2665
2666bool Type_std_attributes::agg_item_set_converter(const DTCollation &coll,
2667 const char *fname,
2668 Item **args, uint nargs,
2669 uint flags, int item_sep)
2670{
2671 THD *thd= current_thd;
2672 if (thd->lex->is_ps_or_view_context_analysis())
2673 return false;
2674 Item **arg, *safe_args[2]= {NULL, NULL};
2675
2676 /*
2677 For better error reporting: save the first and the second argument.
2678 We need this only if the the number of args is 3 or 2:
2679 - for a longer argument list, "Illegal mix of collations"
2680 doesn't display each argument's characteristics.
2681 - if nargs is 1, then this error cannot happen.
2682 */
2683 if (nargs >=2 && nargs <= 3)
2684 {
2685 safe_args[0]= args[0];
2686 safe_args[1]= args[item_sep];
2687 }
2688
2689 bool res= FALSE;
2690 uint i;
2691
2692 /*
2693 In case we're in statement prepare, create conversion item
2694 in its memory: it will be reused on each execute.
2695 */
2696 Query_arena backup;
2697 Query_arena *arena= thd->stmt_arena->is_stmt_prepare() ?
2698 thd->activate_stmt_arena_if_needed(&backup) :
2699 NULL;
2700
2701 for (i= 0, arg= args; i < nargs; i++, arg+= item_sep)
2702 {
2703 Item* conv= (*arg)->safe_charset_converter(thd, coll.collation);
2704 if (conv == *arg)
2705 continue;
2706 if (!conv && ((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII))
2707 conv= new (thd->mem_root) Item_func_conv_charset(thd, *arg, coll.collation, 1);
2708
2709 if (!conv)
2710 {
2711 if (nargs >=2 && nargs <= 3)
2712 {
2713 /* restore the original arguments for better error message */
2714 args[0]= safe_args[0];
2715 args[item_sep]= safe_args[1];
2716 }
2717 my_coll_agg_error(args, nargs, fname, item_sep);
2718 res= TRUE;
2719 break; // we cannot return here, we need to restore "arena".
2720 }
2721 /*
2722 If in statement prepare, then we create a converter for two
2723 constant items, do it once and then reuse it.
2724 If we're in execution of a prepared statement, arena is NULL,
2725 and the conv was created in runtime memory. This can be
2726 the case only if the argument is a parameter marker ('?'),
2727 because for all true constants the charset converter has already
2728 been created in prepare. In this case register the change for
2729 rollback.
2730 */
2731 if (thd->stmt_arena->is_stmt_prepare())
2732 *arg= conv;
2733 else
2734 thd->change_item_tree(arg, conv);
2735
2736 if (conv->fix_fields(thd, arg))
2737 {
2738 res= TRUE;
2739 break; // we cannot return here, we need to restore "arena".
2740 }
2741 }
2742 if (arena)
2743 thd->restore_active_arena(arena, &backup);
2744 return res;
2745}
2746
2747
2748/**
2749 @brief
2750 Building clone for Item_func_or_sum
2751
2752 @param thd thread handle
2753 @param mem_root part of the memory for the clone
2754
2755 @details
2756 This method gets copy of the current item and also
2757 build clones for its referencies. For the referencies
2758 build_copy is called again.
2759
2760 @retval
2761 clone of the item
2762 0 if an error occured
2763*/
2764
2765Item* Item_func_or_sum::build_clone(THD *thd)
2766{
2767 Item_func_or_sum *copy= (Item_func_or_sum *) get_copy(thd);
2768 if (unlikely(!copy))
2769 return 0;
2770 if (arg_count > 2)
2771 {
2772 copy->args=
2773 (Item**) alloc_root(thd->mem_root, sizeof(Item*) * arg_count);
2774 if (unlikely(!copy->args))
2775 return 0;
2776 }
2777 else if (arg_count > 0)
2778 copy->args= copy->tmp_arg;
2779
2780
2781 for (uint i= 0; i < arg_count; i++)
2782 {
2783 Item *arg_clone= args[i]->build_clone(thd);
2784 if (!arg_clone)
2785 return 0;
2786 copy->args[i]= arg_clone;
2787 }
2788 return copy;
2789}
2790
2791Item_sp::Item_sp(THD *thd, Name_resolution_context *context_arg,
2792 sp_name *name_arg) :
2793 context(context_arg), m_name(name_arg), m_sp(NULL), func_ctx(NULL),
2794 sp_result_field(NULL)
2795{
2796 dummy_table= (TABLE*) thd->calloc(sizeof(TABLE) + sizeof(TABLE_SHARE) +
2797 sizeof(Query_arena));
2798 dummy_table->s= (TABLE_SHARE*) (dummy_table + 1);
2799 /* TODO(cvicentiu) Move this sp_query_arena in the class as a direct member.
2800 Currently it can not be done due to header include dependencies. */
2801 sp_query_arena= (Query_arena *) (dummy_table->s + 1);
2802 memset(&sp_mem_root, 0, sizeof(sp_mem_root));
2803}
2804
2805Item_sp::Item_sp(THD *thd, Item_sp *item):
2806 context(item->context), m_name(item->m_name),
2807 m_sp(item->m_sp), func_ctx(NULL), sp_result_field(NULL)
2808{
2809 dummy_table= (TABLE*) thd->calloc(sizeof(TABLE)+ sizeof(TABLE_SHARE) +
2810 sizeof(Query_arena));
2811 dummy_table->s= (TABLE_SHARE*) (dummy_table+1);
2812 sp_query_arena= (Query_arena *) (dummy_table->s + 1);
2813 memset(&sp_mem_root, 0, sizeof(sp_mem_root));
2814}
2815
2816const char *
2817Item_sp::func_name(THD *thd) const
2818{
2819 /* Calculate length to avoid reallocation of string for sure */
2820 size_t len= (((m_name->m_explicit_name ? m_name->m_db.length : 0) +
2821 m_name->m_name.length)*2 + //characters*quoting
2822 2 + // ` and `
2823 (m_name->m_explicit_name ?
2824 3 : 0) + // '`', '`' and '.' for the db
2825 1 + // end of string
2826 ALIGN_SIZE(1)); // to avoid String reallocation
2827 String qname((char *)alloc_root(thd->mem_root, len), len,
2828 system_charset_info);
2829
2830 qname.length(0);
2831 if (m_name->m_explicit_name)
2832 {
2833 append_identifier(thd, &qname, &m_name->m_db);
2834 qname.append('.');
2835 }
2836 append_identifier(thd, &qname, &m_name->m_name);
2837 return qname.c_ptr_safe();
2838}
2839
2840void
2841Item_sp::cleanup()
2842{
2843 delete sp_result_field;
2844 sp_result_field= NULL;
2845 m_sp= NULL;
2846 delete func_ctx;
2847 func_ctx= NULL;
2848 free_root(&sp_mem_root, MYF(0));
2849 dummy_table->alias.free();
2850}
2851
2852/**
2853 @brief Checks if requested access to function can be granted to user.
2854 If function isn't found yet, it searches function first.
2855 If function can't be found or user don't have requested access
2856 error is raised.
2857
2858 @param thd thread handler
2859
2860 @return Indication if the access was granted or not.
2861 @retval FALSE Access is granted.
2862 @retval TRUE Requested access can't be granted or function doesn't exists.
2863
2864*/
2865bool
2866Item_sp::sp_check_access(THD *thd)
2867{
2868 DBUG_ENTER("Item_sp::sp_check_access");
2869 DBUG_ASSERT(m_sp);
2870 DBUG_RETURN(m_sp->check_execute_access(thd));
2871}
2872
2873/**
2874 @brief Execute function & store value in field.
2875
2876 @return Function returns error status.
2877 @retval FALSE on success.
2878 @retval TRUE if an error occurred.
2879*/
2880bool Item_sp::execute(THD *thd, bool *null_value, Item **args, uint arg_count)
2881{
2882 if (unlikely(execute_impl(thd, args, arg_count)))
2883 {
2884 *null_value= 1;
2885 context->process_error(thd);
2886 if (thd->killed)
2887 thd->send_kill_message();
2888 return true;
2889 }
2890
2891 /* Check that the field (the value) is not NULL. */
2892
2893 *null_value= sp_result_field->is_null();
2894 return (*null_value);
2895}
2896
2897/**
2898 @brief Execute function and store the return value in the field.
2899
2900 @note This function was intended to be the concrete implementation of
2901 the interface function execute. This was never realized.
2902
2903 @return The error state.
2904 @retval FALSE on success
2905 @retval TRUE if an error occurred.
2906*/
2907bool
2908Item_sp::execute_impl(THD *thd, Item **args, uint arg_count)
2909{
2910 Sub_statement_state statement_state;
2911 Security_context *save_security_ctx= thd->security_ctx;
2912 enum enum_sp_data_access access=
2913 (m_sp->daccess() == SP_DEFAULT_ACCESS) ?
2914 SP_DEFAULT_ACCESS_MAPPING : m_sp->daccess();
2915
2916 DBUG_ENTER("Item_sp::execute_impl");
2917
2918 if (context->security_ctx)
2919 {
2920 /* Set view definer security context */
2921 thd->security_ctx= context->security_ctx;
2922 }
2923
2924 if (unlikely(sp_check_access(thd)))
2925 {
2926 thd->security_ctx= save_security_ctx;
2927 DBUG_RETURN(TRUE);
2928 }
2929
2930 /*
2931 Throw an error if a non-deterministic function is called while
2932 statement-based replication (SBR) is active.
2933 */
2934
2935 if (unlikely(!m_sp->detistic() && !trust_function_creators &&
2936 (access == SP_CONTAINS_SQL || access == SP_MODIFIES_SQL_DATA) &&
2937 (mysql_bin_log.is_open() &&
2938 thd->variables.binlog_format == BINLOG_FORMAT_STMT)))
2939 {
2940 my_error(ER_BINLOG_UNSAFE_ROUTINE, MYF(0));
2941 thd->security_ctx= save_security_ctx;
2942 DBUG_RETURN(TRUE);
2943 }
2944
2945 /*
2946 Disable the binlogging if this is not a SELECT statement. If this is a
2947 SELECT, leave binlogging on, so execute_function() code writes the
2948 function call into binlog.
2949 */
2950 thd->reset_sub_statement_state(&statement_state, SUB_STMT_FUNCTION);
2951
2952 /*
2953 If this function is an aggregate function, we want to initialise the
2954 mem_root only once per group. For a regular stored function, we will
2955 initialise once for each call to execute_function.
2956 */
2957 m_sp->agg_type();
2958 DBUG_ASSERT(m_sp->agg_type() == GROUP_AGGREGATE ||
2959 (m_sp->agg_type() == NOT_AGGREGATE && !func_ctx));
2960 if (!func_ctx)
2961 {
2962 init_sql_alloc(&sp_mem_root, "Item_sp", MEM_ROOT_BLOCK_SIZE, 0, MYF(0));
2963 *sp_query_arena= Query_arena(&sp_mem_root,
2964 Query_arena::STMT_INITIALIZED_FOR_SP);
2965 }
2966
2967 bool err_status= m_sp->execute_function(thd, args, arg_count,
2968 sp_result_field, &func_ctx,
2969 sp_query_arena);
2970 /*
2971 We free the function context when the function finished executing normally
2972 (quit_func == TRUE) or the function has exited with an error.
2973 */
2974 if (err_status || func_ctx->quit_func)
2975 {
2976 /* Free Items allocated during function execution. */
2977 delete func_ctx;
2978 func_ctx= NULL;
2979 sp_query_arena->free_items();
2980 free_root(&sp_mem_root, MYF(0));
2981 memset(&sp_mem_root, 0, sizeof(sp_mem_root));
2982 }
2983 thd->restore_sub_statement_state(&statement_state);
2984
2985 thd->security_ctx= save_security_ctx;
2986 DBUG_RETURN(err_status);
2987}
2988
2989
2990/**
2991 @brief Initialize the result field by creating a temporary dummy table
2992 and assign it to a newly created field object. Meta data used to
2993 create the field is fetched from the sp_head belonging to the stored
2994 proceedure found in the stored procedure functon cache.
2995
2996 @note This function should be called from fix_fields to init the result
2997 field. It is some what related to Item_field.
2998
2999 @see Item_field
3000
3001 @param thd A pointer to the session and thread context.
3002
3003 @return Function return error status.
3004 @retval TRUE is returned on an error
3005 @retval FALSE is returned on success.
3006*/
3007
3008bool
3009Item_sp::init_result_field(THD *thd, uint max_length, uint maybe_null,
3010 bool *null_value, LEX_CSTRING *name)
3011{
3012 DBUG_ENTER("Item_sp::init_result_field");
3013
3014 DBUG_ASSERT(m_sp != NULL);
3015 DBUG_ASSERT(sp_result_field == NULL);
3016
3017 /*
3018 A Field needs to be attached to a Table.
3019 Below we "create" a dummy table by initializing
3020 the needed pointers.
3021 */
3022 dummy_table->alias.set("", 0, table_alias_charset);
3023 dummy_table->in_use= thd;
3024 dummy_table->copy_blobs= TRUE;
3025 dummy_table->s->table_cache_key= empty_clex_str;
3026 dummy_table->s->table_name= empty_clex_str;
3027 dummy_table->maybe_null= maybe_null;
3028
3029 if (!(sp_result_field= m_sp->create_result_field(max_length, name,
3030 dummy_table)))
3031 DBUG_RETURN(TRUE);
3032
3033 if (sp_result_field->pack_length() > sizeof(result_buf))
3034 {
3035 void *tmp;
3036 if (!(tmp= thd->alloc(sp_result_field->pack_length())))
3037 DBUG_RETURN(TRUE);
3038 sp_result_field->move_field((uchar*) tmp);
3039 }
3040 else
3041 sp_result_field->move_field(result_buf);
3042
3043 sp_result_field->null_ptr= (uchar *) null_value;
3044 sp_result_field->null_bit= 1;
3045
3046 DBUG_RETURN(FALSE);
3047}
3048
3049/**
3050 @brief
3051 Building clone for Item_ref
3052
3053 @param thd thread handle
3054 @param mem_root part of the memory for the clone
3055
3056 @details
3057 This method gets copy of the current item and also
3058 builds clone for its reference.
3059
3060 @retval
3061 clone of the item
3062 0 if an error occured
3063*/
3064
3065Item* Item_ref::build_clone(THD *thd)
3066{
3067 Item_ref *copy= (Item_ref *) get_copy(thd);
3068 if (unlikely(!copy) ||
3069 unlikely(!(copy->ref= (Item**) alloc_root(thd->mem_root,
3070 sizeof(Item*)))) ||
3071 unlikely(!(*copy->ref= (* ref)->build_clone(thd))))
3072 return 0;
3073 return copy;
3074}
3075
3076
3077void Item_ident_for_show::make_send_field(THD *thd, Send_field *tmp_field)
3078{
3079 tmp_field->table_name= tmp_field->org_table_name= table_name;
3080 tmp_field->db_name= db_name;
3081 tmp_field->col_name= tmp_field->org_col_name= field->field_name;
3082 tmp_field->length=field->field_length;
3083 tmp_field->type=field->type();
3084 tmp_field->flags= field->table->maybe_null ?
3085 (field->flags & ~NOT_NULL_FLAG) : field->flags;
3086 tmp_field->decimals= field->decimals();
3087}
3088
3089/**********************************************/
3090
3091Item_field::Item_field(THD *thd, Field *f)
3092 :Item_ident(thd, 0, NullS, *f->table_name, &f->field_name),
3093 item_equal(0),
3094 have_privileges(0), any_privileges(0)
3095{
3096 set_field(f);
3097
3098 orig_table_name= table_name;
3099 orig_field_name= field_name;
3100 with_field= 1;
3101}
3102
3103
3104/**
3105 Constructor used inside setup_wild().
3106
3107 Ensures that field, table, and database names will live as long as
3108 Item_field (this is important in prepared statements).
3109*/
3110
3111Item_field::Item_field(THD *thd, Name_resolution_context *context_arg,
3112 Field *f)
3113 :Item_ident(thd, context_arg, f->table->s->db.str, *f->table_name,
3114 &f->field_name),
3115 item_equal(0),
3116 have_privileges(0), any_privileges(0)
3117{
3118 /*
3119 We always need to provide Item_field with a fully qualified field
3120 name to avoid ambiguity when executing prepared statements like
3121 SELECT * from d1.t1, d2.t1; (assuming d1.t1 and d2.t1 have columns
3122 with same names).
3123 This is because prepared statements never deal with wildcards in
3124 select list ('*') and always fix fields using fully specified path
3125 (i.e. db.table.column).
3126 No check for OOM: if db_name is NULL, we'll just get
3127 "Field not found" error.
3128 We need to copy db_name, table_name and field_name because they must
3129 be allocated in the statement memory, not in table memory (the table
3130 structure can go away and pop up again between subsequent executions
3131 of a prepared statement or after the close_tables_for_reopen() call
3132 in mysql_multi_update_prepare() or due to wildcard expansion in stored
3133 procedures).
3134 */
3135 {
3136 if (db_name)
3137 orig_db_name= thd->strdup(db_name);
3138 if (table_name)
3139 orig_table_name= thd->strdup(table_name);
3140 if (field_name.str)
3141 thd->make_lex_string(&orig_field_name, field_name.str,
3142 field_name.length);
3143 /*
3144 We don't restore 'name' in cleanup because it's not changed
3145 during execution. Still we need it to point to persistent
3146 memory if this item is to be reused.
3147 */
3148 name= orig_field_name;
3149 }
3150 set_field(f);
3151 with_field= 1;
3152}
3153
3154
3155Item_field::Item_field(THD *thd, Name_resolution_context *context_arg,
3156 const char *db_arg,const char *table_name_arg,
3157 const LEX_CSTRING *field_name_arg)
3158 :Item_ident(thd, context_arg, db_arg, table_name_arg, field_name_arg),
3159 field(0), item_equal(0),
3160 have_privileges(0), any_privileges(0)
3161{
3162 SELECT_LEX *select= thd->lex->current_select;
3163 collation.set(DERIVATION_IMPLICIT);
3164 if (select && select->parsing_place != IN_HAVING)
3165 select->select_n_where_fields++;
3166 with_field= 1;
3167}
3168
3169/**
3170 Constructor need to process subselect with temporary tables (see Item)
3171*/
3172
3173Item_field::Item_field(THD *thd, Item_field *item)
3174 :Item_ident(thd, item),
3175 field(item->field),
3176 item_equal(item->item_equal),
3177 have_privileges(item->have_privileges),
3178 any_privileges(item->any_privileges)
3179{
3180 collation.set(DERIVATION_IMPLICIT);
3181 with_field= 1;
3182}
3183
3184
3185void Item_field::set_field(Field *field_par)
3186{
3187 field=result_field=field_par; // for easy coding with fields
3188 maybe_null=field->maybe_null();
3189 Type_std_attributes::set(field_par->type_std_attributes());
3190 table_name= *field_par->table_name;
3191 field_name= field_par->field_name;
3192 db_name= field_par->table->s->db.str;
3193 alias_name_used= field_par->table->alias_name_used;
3194
3195 fixed= 1;
3196 if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
3197 any_privileges= 0;
3198}
3199
3200
3201/**
3202 Reset this item to point to a field from the new temporary table.
3203 This is used when we create a new temporary table for each execution
3204 of prepared statement.
3205*/
3206
3207void Item_field::reset_field(Field *f)
3208{
3209 set_field(f);
3210 /* 'name' is pointing at field->field_name of old field */
3211 name= f->field_name;
3212}
3213
3214
3215void Item_field::load_data_print_for_log_event(THD *thd, String *to) const
3216{
3217 append_identifier(thd, to, name.str, name.length);
3218}
3219
3220
3221bool Item_field::load_data_set_no_data(THD *thd, const Load_data_param *param)
3222{
3223 if (field->load_data_set_no_data(thd, param->is_fixed_length()))
3224 return true;
3225 /*
3226 TODO: We probably should not throw warning for each field.
3227 But how about intention to always have the same number
3228 of warnings in THD::cuted_fields (and get rid of cuted_fields
3229 in the end ?)
3230 */
3231 thd->cuted_fields++;
3232 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
3233 ER_WARN_TOO_FEW_RECORDS,
3234 ER_THD(thd, ER_WARN_TOO_FEW_RECORDS),
3235 thd->get_stmt_da()->current_row_for_warning());
3236 return false;
3237}
3238
3239
3240bool Item_field::enumerate_field_refs_processor(void *arg)
3241{
3242 Field_enumerator *fe= (Field_enumerator*)arg;
3243 fe->visit_field(this);
3244 return FALSE;
3245}
3246
3247bool Item_field::update_table_bitmaps_processor(void *arg)
3248{
3249 update_table_bitmaps();
3250 return FALSE;
3251}
3252
3253static inline void set_field_to_new_field(Field **field, Field **new_field)
3254{
3255 if (*field && (*field)->table == new_field[0]->table)
3256 {
3257 Field *newf= new_field[(*field)->field_index];
3258 if ((*field)->ptr == newf->ptr)
3259 *field= newf;
3260 }
3261}
3262
3263bool Item_field::switch_to_nullable_fields_processor(void *arg)
3264{
3265 Field **new_fields= (Field **)arg;
3266 set_field_to_new_field(&field, new_fields);
3267 set_field_to_new_field(&result_field, new_fields);
3268 maybe_null= field && field->maybe_null();
3269 return 0;
3270}
3271
3272const char *Item_ident::full_name() const
3273{
3274 char *tmp;
3275 if (!table_name || !field_name.str)
3276 return field_name.str ? field_name.str : name.str ? name.str : "tmp_field";
3277
3278 if (db_name && db_name[0])
3279 {
3280 THD *thd= current_thd;
3281 tmp=(char*) thd->alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
3282 (uint) field_name.length+3);
3283 strxmov(tmp,db_name,".",table_name,".",field_name.str,NullS);
3284 }
3285 else
3286 {
3287 if (table_name[0])
3288 {
3289 THD *thd= current_thd;
3290 tmp= (char*) thd->alloc((uint) strlen(table_name) +
3291 field_name.length + 2);
3292 strxmov(tmp, table_name, ".", field_name.str, NullS);
3293 }
3294 else
3295 return field_name.str;
3296 }
3297 return tmp;
3298}
3299
3300void Item_ident::print(String *str, enum_query_type query_type)
3301{
3302 THD *thd= current_thd;
3303 char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
3304 const char *d_name= db_name, *t_name= table_name;
3305 bool use_table_name= table_name && table_name[0];
3306 bool use_db_name= use_table_name && db_name && db_name[0] && !alias_name_used;
3307
3308 if (use_db_name && (query_type & QT_ITEM_IDENT_SKIP_DB_NAMES))
3309 use_db_name= !thd->db.str || strcmp(thd->db.str, db_name);
3310
3311 if (use_db_name)
3312 use_db_name= !(cached_table && cached_table->belong_to_view &&
3313 cached_table->belong_to_view->compact_view_format);
3314
3315 if (use_table_name && (query_type & QT_ITEM_IDENT_SKIP_TABLE_NAMES))
3316 {
3317 /*
3318 Don't print the table name if it's the only table in the context
3319 XXX technically, that's a sufficient, but too strong condition
3320 */
3321 if (!context)
3322 use_db_name= use_table_name= false;
3323 else if (context->outer_context)
3324 use_table_name= true;
3325 else if (context->last_name_resolution_table == context->first_name_resolution_table)
3326 use_db_name= use_table_name= false;
3327 else if (!context->last_name_resolution_table &&
3328 !context->first_name_resolution_table->next_name_resolution_table)
3329 use_db_name= use_table_name= false;
3330 }
3331
3332 if (!field_name.str || !field_name.str[0])
3333 {
3334 append_identifier(thd, str, STRING_WITH_LEN("tmp_field"));
3335 return;
3336 }
3337
3338 if (lower_case_table_names== 1 ||
3339 (lower_case_table_names == 2 && !alias_name_used))
3340 {
3341 if (use_table_name)
3342 {
3343 strmov(t_name_buff, table_name);
3344 my_casedn_str(files_charset_info, t_name_buff);
3345 t_name= t_name_buff;
3346 }
3347 if (use_db_name)
3348 {
3349 strmov(d_name_buff, db_name);
3350 my_casedn_str(files_charset_info, d_name_buff);
3351 d_name= d_name_buff;
3352 }
3353 }
3354
3355 if (use_db_name)
3356 {
3357 append_identifier(thd, str, d_name, (uint)strlen(d_name));
3358 str->append('.');
3359 DBUG_ASSERT(use_table_name);
3360 }
3361 if (use_table_name)
3362 {
3363 append_identifier(thd, str, t_name, (uint) strlen(t_name));
3364 str->append('.');
3365 }
3366 append_identifier(thd, str, &field_name);
3367}
3368
3369/* ARGSUSED */
3370String *Item_field::val_str(String *str)
3371{
3372 DBUG_ASSERT(fixed == 1);
3373 if ((null_value=field->is_null()))
3374 return 0;
3375 str->set_charset(str_value.charset());
3376 return field->val_str(str,&str_value);
3377}
3378
3379
3380double Item_field::val_real()
3381{
3382 DBUG_ASSERT(fixed == 1);
3383 if ((null_value=field->is_null()))
3384 return 0.0;
3385 return field->val_real();
3386}
3387
3388
3389longlong Item_field::val_int()
3390{
3391 DBUG_ASSERT(fixed == 1);
3392 if ((null_value=field->is_null()))
3393 return 0;
3394 return field->val_int();
3395}
3396
3397
3398my_decimal *Item_field::val_decimal(my_decimal *decimal_value)
3399{
3400 if ((null_value= field->is_null()))
3401 return 0;
3402 return field->val_decimal(decimal_value);
3403}
3404
3405
3406String *Item_field::str_result(String *str)
3407{
3408 if ((null_value=result_field->is_null()))
3409 return 0;
3410 str->set_charset(str_value.charset());
3411 return result_field->val_str(str,&str_value);
3412}
3413
3414bool Item_field::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
3415{
3416 if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
3417 {
3418 bzero((char*) ltime,sizeof(*ltime));
3419 return 1;
3420 }
3421 return 0;
3422}
3423
3424bool Item_field::get_date_result(MYSQL_TIME *ltime, ulonglong fuzzydate)
3425{
3426 if (result_field->is_null() || result_field->get_date(ltime,fuzzydate))
3427 {
3428 bzero((char*) ltime,sizeof(*ltime));
3429 return (null_value= 1);
3430 }
3431 return (null_value= 0);
3432}
3433
3434
3435void Item_field::save_result(Field *to)
3436{
3437 save_field_in_field(result_field, &null_value, to, TRUE);
3438}
3439
3440
3441double Item_field::val_result()
3442{
3443 if ((null_value=result_field->is_null()))
3444 return 0.0;
3445 return result_field->val_real();
3446}
3447
3448longlong Item_field::val_int_result()
3449{
3450 if ((null_value=result_field->is_null()))
3451 return 0;
3452 return result_field->val_int();
3453}
3454
3455
3456my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value)
3457{
3458 if ((null_value= result_field->is_null()))
3459 return 0;
3460 return result_field->val_decimal(decimal_value);
3461}
3462
3463
3464bool Item_field::val_bool_result()
3465{
3466 if ((null_value= result_field->is_null()))
3467 return false;
3468 return result_field->val_bool();
3469}
3470
3471
3472bool Item_field::is_null_result()
3473{
3474 return (null_value=result_field->is_null());
3475}
3476
3477
3478bool Item_field::eq(const Item *item, bool binary_cmp) const
3479{
3480 Item *real_item2= ((Item *) item)->real_item();
3481 if (real_item2->type() != FIELD_ITEM)
3482 return 0;
3483
3484 Item_field *item_field= (Item_field*) real_item2;
3485 if (item_field->field && field)
3486 return item_field->field == field;
3487 /*
3488 We may come here when we are trying to find a function in a GROUP BY
3489 clause from the select list.
3490 In this case the '100 % correct' way to do this would be to first
3491 run fix_fields() on the GROUP BY item and then retry this function, but
3492 I think it's better to relax the checking a bit as we will in
3493 most cases do the correct thing by just checking the field name.
3494 (In cases where we would choose wrong we would have to generate a
3495 ER_NON_UNIQ_ERROR).
3496 */
3497 return (!lex_string_cmp(system_charset_info, &item_field->name,
3498 &field_name) &&
3499 (!item_field->table_name || !table_name ||
3500 (!my_strcasecmp(table_alias_charset, item_field->table_name,
3501 table_name) &&
3502 (!item_field->db_name || !db_name ||
3503 (item_field->db_name && !strcmp(item_field->db_name,
3504 db_name))))));
3505}
3506
3507
3508table_map Item_field::used_tables() const
3509{
3510 if (field->table->const_table)
3511 return 0; // const item
3512 return (get_depended_from() ? OUTER_REF_TABLE_BIT : field->table->map);
3513}
3514
3515table_map Item_field::all_used_tables() const
3516{
3517 return (get_depended_from() ? OUTER_REF_TABLE_BIT : field->table->map);
3518}
3519
3520
3521/*
3522 @Note thd->fatal_error can be set in case of OOM
3523*/
3524
3525void Item_field::fix_after_pullout(st_select_lex *new_parent, Item **ref,
3526 bool merge)
3527{
3528 if (new_parent == get_depended_from())
3529 depended_from= NULL;
3530 if (context)
3531 {
3532 bool need_change= false;
3533 /*
3534 Suppose there are nested selects:
3535
3536 select_id=1
3537 select_id=2
3538 select_id=3 <----+
3539 select_id=4 -+
3540 select_id=5 --+
3541
3542 Suppose, pullout operation has moved anything that had select_id=4 or 5
3543 in to select_id=3.
3544
3545 If this Item_field had a name resolution context pointing into select_lex
3546 with id=4 or id=5, it needs a new name resolution context.
3547
3548 However, it could also be that this object is a part of outer reference:
3549 Item_ref(Item_field(field in select with select_id=1))).
3550 - The Item_ref object has a context with select_id=5, and so needs a new
3551 name resolution context.
3552 - The Item_field object has a context with select_id=1, and doesn't need
3553 a new name resolution context.
3554
3555 So, the following loop walks from Item_field's current context upwards.
3556 If we find that the select we've been pulled out to is up there, we
3557 create the new name resolution context. Otherwise, we don't.
3558 */
3559 for (Name_resolution_context *ct= context; ct; ct= ct->outer_context)
3560 {
3561 if (new_parent == ct->select_lex)
3562 {
3563 need_change= true;
3564 break;
3565 }
3566 }
3567 if (!need_change)
3568 return;
3569
3570 if (!merge)
3571 {
3572 /*
3573 It is transformation without merge.
3574 This field was "outer" for the inner SELECT where it was taken and
3575 moved up.
3576 "Outer" fields uses normal SELECT_LEX context of upper SELECTs for
3577 name resolution, so we can switch everything to it safely.
3578 */
3579 this->context= &new_parent->context;
3580 return;
3581 }
3582
3583 Name_resolution_context *ctx= new Name_resolution_context();
3584 if (!ctx)
3585 return; // Fatal error set
3586 if (context->select_lex == new_parent)
3587 {
3588 /*
3589 This field was pushed in then pulled out
3590 (for example left part of IN)
3591 */
3592 ctx->outer_context= context->outer_context;
3593 }
3594 else if (context->outer_context)
3595 {
3596 /* just pull to the upper context */
3597 ctx->outer_context= context->outer_context->outer_context;
3598 }
3599 else
3600 {
3601 /* No upper context (merging Derived/VIEW where context chain ends) */
3602 ctx->outer_context= NULL;
3603 }
3604 ctx->table_list= context->first_name_resolution_table;
3605 ctx->select_lex= new_parent;
3606 if (context->select_lex == NULL)
3607 ctx->select_lex= NULL;
3608 ctx->first_name_resolution_table= context->first_name_resolution_table;
3609 ctx->last_name_resolution_table= context->last_name_resolution_table;
3610 ctx->error_processor= context->error_processor;
3611 ctx->error_processor_data= context->error_processor_data;
3612 ctx->resolve_in_select_list= context->resolve_in_select_list;
3613 ctx->security_ctx= context->security_ctx;
3614 this->context=ctx;
3615 }
3616}
3617
3618
3619Item *Item_field::get_tmp_table_item(THD *thd)
3620{
3621 Item_field *new_item= new (thd->mem_root) Item_temptable_field(thd, this);
3622 if (new_item)
3623 new_item->field= new_item->result_field;
3624 return new_item;
3625}
3626
3627longlong Item_field::val_int_endpoint(bool left_endp, bool *incl_endp)
3628{
3629 longlong res= val_int();
3630 return null_value? LONGLONG_MIN : res;
3631}
3632
3633/**
3634 Create an item from a string we KNOW points to a valid longlong
3635 end \\0 terminated number string.
3636 This is always 'signed'. Unsigned values are created with Item_uint()
3637*/
3638
3639Item_int::Item_int(THD *thd, const char *str_arg, size_t length):
3640 Item_num(thd)
3641{
3642 char *end_ptr= (char*) str_arg + length;
3643 int error;
3644 value= my_strtoll10(str_arg, &end_ptr, &error);
3645 max_length= (uint) (end_ptr - str_arg);
3646 name.str= str_arg;
3647 /*
3648 We can't trust max_length as in show_routine_code we are using "Pos" as
3649 the field name.
3650 */
3651 name.length= !str_arg[max_length] ? max_length : strlen(str_arg);
3652 fixed= 1;
3653}
3654
3655
3656my_decimal *Item_int::val_decimal(my_decimal *decimal_value)
3657{
3658 int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_value);
3659 return decimal_value;
3660}
3661
3662String *Item_int::val_str(String *str)
3663{
3664 // following assert is redundant, because fixed=1 assigned in constructor
3665 DBUG_ASSERT(fixed == 1);
3666 str->set_int(value, unsigned_flag, collation.collation);
3667 return str;
3668}
3669
3670void Item_int::print(String *str, enum_query_type query_type)
3671{
3672 // my_charset_bin is good enough for numbers
3673 str_value.set_int(value, unsigned_flag, &my_charset_bin);
3674 str->append(str_value);
3675}
3676
3677
3678Item *Item_bool::neg_transformer(THD *thd)
3679{
3680 value= !value;
3681 name= null_clex_str;
3682 return this;
3683}
3684
3685
3686Item_uint::Item_uint(THD *thd, const char *str_arg, size_t length):
3687 Item_int(thd, str_arg, length)
3688{
3689 unsigned_flag= 1;
3690}
3691
3692
3693Item_uint::Item_uint(THD *thd, const char *str_arg, longlong i, uint length):
3694 Item_int(thd, str_arg, i, length)
3695{
3696 unsigned_flag= 1;
3697}
3698
3699
3700String *Item_uint::val_str(String *str)
3701{
3702 // following assert is redundant, because fixed=1 assigned in constructor
3703 DBUG_ASSERT(fixed == 1);
3704 str->set((ulonglong) value, collation.collation);
3705 return str;
3706}
3707
3708
3709void Item_uint::print(String *str, enum_query_type query_type)
3710{
3711 // latin1 is good enough for numbers
3712 str_value.set((ulonglong) value, default_charset());
3713 str->append(str_value);
3714}
3715
3716
3717Item_decimal::Item_decimal(THD *thd, const char *str_arg, size_t length,
3718 CHARSET_INFO *charset):
3719 Item_num(thd)
3720{
3721 str2my_decimal(E_DEC_FATAL_ERROR, str_arg, length, charset, &decimal_value);
3722 name.str= str_arg;
3723 name.length= safe_strlen(str_arg);
3724 decimals= (uint8) decimal_value.frac;
3725 fixed= 1;
3726 max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3727 decimals,
3728 decimals,
3729 unsigned_flag);
3730}
3731
3732Item_decimal::Item_decimal(THD *thd, longlong val, bool unsig):
3733 Item_num(thd)
3734{
3735 int2my_decimal(E_DEC_FATAL_ERROR, val, unsig, &decimal_value);
3736 decimals= (uint8) decimal_value.frac;
3737 fixed= 1;
3738 max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3739 decimals,
3740 decimals,
3741 unsigned_flag);
3742}
3743
3744
3745Item_decimal::Item_decimal(THD *thd, double val, int precision, int scale):
3746 Item_num(thd)
3747{
3748 double2my_decimal(E_DEC_FATAL_ERROR, val, &decimal_value);
3749 decimals= (uint8) decimal_value.frac;
3750 fixed= 1;
3751 max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3752 decimals,
3753 decimals,
3754 unsigned_flag);
3755}
3756
3757
3758Item_decimal::Item_decimal(THD *thd, const char *str, const my_decimal *val_arg,
3759 uint decimal_par, uint length):
3760 Item_num(thd)
3761{
3762 my_decimal2decimal(val_arg, &decimal_value);
3763 name.str= str;
3764 name.length= safe_strlen(str);
3765 decimals= (uint8) decimal_par;
3766 max_length= length;
3767 fixed= 1;
3768}
3769
3770
3771Item_decimal::Item_decimal(THD *thd, my_decimal *value_par):
3772 Item_num(thd)
3773{
3774 my_decimal2decimal(value_par, &decimal_value);
3775 decimals= (uint8) decimal_value.frac;
3776 fixed= 1;
3777 max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3778 decimals,
3779 decimals,
3780 unsigned_flag);
3781}
3782
3783
3784Item_decimal::Item_decimal(THD *thd, const uchar *bin, int precision, int scale):
3785 Item_num(thd)
3786{
3787 binary2my_decimal(E_DEC_FATAL_ERROR, bin,
3788 &decimal_value, precision, scale);
3789 decimals= (uint8) decimal_value.frac;
3790 fixed= 1;
3791 max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
3792 unsigned_flag);
3793}
3794
3795
3796longlong Item_decimal::val_int()
3797{
3798 longlong result;
3799 my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &result);
3800 return result;
3801}
3802
3803double Item_decimal::val_real()
3804{
3805 double result;
3806 my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
3807 return result;
3808}
3809
3810String *Item_decimal::val_str(String *result)
3811{
3812 result->set_charset(&my_charset_numeric);
3813 my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, result);
3814 return result;
3815}
3816
3817void Item_decimal::print(String *str, enum_query_type query_type)
3818{
3819 my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, &str_value);
3820 str->append(str_value);
3821}
3822
3823
3824bool Item_decimal::eq(const Item *item, bool binary_cmp) const
3825{
3826 if (type() == item->type() && item->basic_const_item())
3827 {
3828 /*
3829 We need to cast off const to call val_decimal(). This should
3830 be OK for a basic constant. Additionally, we can pass 0 as
3831 a true decimal constant will return its internal decimal
3832 storage and ignore the argument.
3833 */
3834 Item *arg= (Item*) item;
3835 my_decimal *value= arg->val_decimal(0);
3836 return !my_decimal_cmp(&decimal_value, value);
3837 }
3838 return 0;
3839}
3840
3841
3842void Item_decimal::set_decimal_value(my_decimal *value_par)
3843{
3844 my_decimal2decimal(value_par, &decimal_value);
3845 decimals= (uint8) decimal_value.frac;
3846 unsigned_flag= !decimal_value.sign();
3847 max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3848 decimals,
3849 decimals,
3850 unsigned_flag);
3851}
3852
3853
3854Item *Item_decimal::clone_item(THD *thd)
3855{
3856 return new (thd->mem_root) Item_decimal(thd, name.str, &decimal_value, decimals,
3857 max_length);
3858}
3859
3860
3861String *Item_float::val_str(String *str)
3862{
3863 // following assert is redundant, because fixed=1 assigned in constructor
3864 DBUG_ASSERT(fixed == 1);
3865 str->set_real(value, decimals, &my_charset_numeric);
3866 return str;
3867}
3868
3869
3870my_decimal *Item_float::val_decimal(my_decimal *decimal_value)
3871{
3872 // following assert is redundant, because fixed=1 assigned in constructor
3873 DBUG_ASSERT(fixed == 1);
3874 double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_value);
3875 return (decimal_value);
3876}
3877
3878
3879Item *Item_float::clone_item(THD *thd)
3880{
3881 return new (thd->mem_root) Item_float(thd, name.str, value, decimals,
3882 max_length);
3883}
3884
3885
3886void Item_string::print(String *str, enum_query_type query_type)
3887{
3888 const bool print_introducer=
3889 !(query_type & QT_WITHOUT_INTRODUCERS) && is_cs_specified();
3890 if (print_introducer)
3891 {
3892 str->append('_');
3893 str->append(collation.collation->csname);
3894 }
3895
3896 str->append('\'');
3897
3898 if (query_type & QT_TO_SYSTEM_CHARSET)
3899 {
3900 if (print_introducer)
3901 {
3902 /*
3903 Because we wrote an introducer, we must print str_value in its
3904 charset, and the resulting bytes must not be changed until they
3905 reach the end client.
3906 But the caller is asking for system_charset_info, and may later
3907 convert into character_set_results. That means two conversions: we
3908 must ensure that they don't change our printed bytes.
3909 So we print str_value in the least common denominator of the three
3910 charsets involved: ASCII. Non-ASCII characters are printed as \xFF
3911 sequences (which is ASCII too). This way, our bytes will not be
3912 changed.
3913 */
3914 ErrConvString tmp(str_value.ptr(), str_value.length(), &my_charset_bin);
3915 str->append(tmp.ptr());
3916 }
3917 else
3918 {
3919 str_value.print(str, system_charset_info);
3920 }
3921 }
3922 else
3923 {
3924 // Caller wants a result in the charset of str_value.
3925 str_value.print(str);
3926 }
3927
3928 str->append('\'');
3929}
3930
3931
3932double Item_string::val_real()
3933{
3934 DBUG_ASSERT(fixed == 1);
3935 return double_from_string_with_check(&str_value);
3936}
3937
3938
3939/**
3940 @todo
3941 Give error if we wanted a signed integer and we got an unsigned one
3942*/
3943longlong Item_string::val_int()
3944{
3945 DBUG_ASSERT(fixed == 1);
3946 return longlong_from_string_with_check(&str_value);
3947}
3948
3949
3950my_decimal *Item_string::val_decimal(my_decimal *decimal_value)
3951{
3952 return val_decimal_from_string(decimal_value);
3953}
3954
3955
3956double Item_null::val_real()
3957{
3958 // following assert is redundant, because fixed=1 assigned in constructor
3959 DBUG_ASSERT(fixed == 1);
3960 null_value=1;
3961 return 0.0;
3962}
3963longlong Item_null::val_int()
3964{
3965 // following assert is redundant, because fixed=1 assigned in constructor
3966 DBUG_ASSERT(fixed == 1);
3967 null_value=1;
3968 return 0;
3969}
3970/* ARGSUSED */
3971String *Item_null::val_str(String *str)
3972{
3973 // following assert is redundant, because fixed=1 assigned in constructor
3974 DBUG_ASSERT(fixed == 1);
3975 null_value=1;
3976 return 0;
3977}
3978
3979my_decimal *Item_null::val_decimal(my_decimal *decimal_value)
3980{
3981 return 0;
3982}
3983
3984
3985bool Item_null::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
3986{
3987 // following assert is redundant, because fixed=1 assigned in constructor
3988 DBUG_ASSERT(fixed == 1);
3989 make_zero_date(ltime, fuzzydate);
3990 return (null_value= true);
3991}
3992
3993
3994Item *Item_null::safe_charset_converter(THD *thd, CHARSET_INFO *tocs)
3995{
3996 return this;
3997}
3998
3999Item *Item_null::clone_item(THD *thd)
4000{
4001 return new (thd->mem_root) Item_null(thd, name.str);
4002}
4003
4004
4005Item_basic_constant *
4006Item_null::make_string_literal_concat(THD *thd, const LEX_CSTRING *str)
4007{
4008 DBUG_ASSERT(thd->variables.sql_mode & MODE_EMPTY_STRING_IS_NULL);
4009 if (str->length)
4010 {
4011 CHARSET_INFO *cs= thd->variables.collation_connection;
4012 uint repertoire= my_string_repertoire(cs, str->str, str->length);
4013 return new (thd->mem_root) Item_string(thd,
4014 str->str, (uint) str->length, cs,
4015 DERIVATION_COERCIBLE, repertoire);
4016 }
4017 return this;
4018}
4019
4020
4021/*********************** Item_param related ******************************/
4022
4023Item_param::Item_param(THD *thd, const LEX_CSTRING *name_arg,
4024 uint pos_in_query_arg, uint len_in_query_arg):
4025 Item_basic_value(thd),
4026 Rewritable_query_parameter(pos_in_query_arg, len_in_query_arg),
4027 /*
4028 Set handler to type_handler_null. Its data type test methods such as:
4029 - is_scalar_type()
4030 - can_return_int()
4031 - can_return_real(),
4032 - is_general_purpose_string_type()
4033 all return "true". This is needed to avoid any "illegal parameter type"
4034 errors in Item::check_type_xxx() at PS prepare time.
4035 */
4036 Type_handler_hybrid_field_type(&type_handler_null),
4037 state(NO_VALUE),
4038 /* Don't pretend to be a literal unless value for this item is set. */
4039 item_type(PARAM_ITEM),
4040 m_empty_string_is_null(false),
4041 indicator(STMT_INDICATOR_NONE),
4042 m_out_param_info(NULL),
4043 /*
4044 Set m_is_settable_routine_parameter to "true" by default.
4045 This is needed for client-server protocol,
4046 whose parameters are always settable.
4047 For dynamic SQL, settability depends on the type of Item passed
4048 as an actual parameter. See Item_param::set_from_item().
4049 */
4050 m_is_settable_routine_parameter(true)
4051{
4052 name= *name_arg;
4053 /*
4054 Since we can't say whenever this item can be NULL or cannot be NULL
4055 before mysql_stmt_execute(), so we assuming that it can be NULL until
4056 value is set.
4057 */
4058 maybe_null= 1;
4059}
4060
4061
4062void Item_param::set_null()
4063{
4064 DBUG_ENTER("Item_param::set_null");
4065 /*
4066 These are cleared after each execution by reset() method or by setting
4067 other value.
4068 */
4069 null_value= 1;
4070 /*
4071 Because of NULL and string values we need to set max_length for each new
4072 placeholder value: user can submit NULL for any placeholder type, and
4073 string length can be different in each execution.
4074 */
4075 max_length= 0;
4076 decimals= 0;
4077 state= NULL_VALUE;
4078 fix_type(Item::NULL_ITEM);
4079 DBUG_VOID_RETURN;
4080}
4081
4082void Item_param::set_int(longlong i, uint32 max_length_arg)
4083{
4084 DBUG_ENTER("Item_param::set_int");
4085 DBUG_ASSERT(value.type_handler()->cmp_type() == INT_RESULT);
4086 value.integer= (longlong) i;
4087 state= SHORT_DATA_VALUE;
4088 collation.set_numeric();
4089 max_length= max_length_arg;
4090 decimals= 0;
4091 maybe_null= 0;
4092 null_value= 0;
4093 fix_type(Item::INT_ITEM);
4094 DBUG_VOID_RETURN;
4095}
4096
4097void Item_param::set_double(double d)
4098{
4099 DBUG_ENTER("Item_param::set_double");
4100 DBUG_ASSERT(value.type_handler()->cmp_type() == REAL_RESULT);
4101 value.real= d;
4102 state= SHORT_DATA_VALUE;
4103 collation.set_numeric();
4104 max_length= DBL_DIG + 8;
4105 decimals= NOT_FIXED_DEC;
4106 maybe_null= 0;
4107 null_value= 0;
4108 fix_type(Item::REAL_ITEM);
4109 DBUG_VOID_RETURN;
4110}
4111
4112
4113/**
4114 Set decimal parameter value from string.
4115
4116 @param str character string
4117 @param length string length
4118
4119 @note
4120 As we use character strings to send decimal values in
4121 binary protocol, we use str2my_decimal to convert it to
4122 internal decimal value.
4123*/
4124
4125void Item_param::set_decimal(const char *str, ulong length)
4126{
4127 char *end;
4128 DBUG_ENTER("Item_param::set_decimal");
4129 DBUG_ASSERT(value.type_handler()->cmp_type() == DECIMAL_RESULT);
4130
4131 end= (char*) str+length;
4132 str2my_decimal(E_DEC_FATAL_ERROR, str, &value.m_decimal, &end);
4133 state= SHORT_DATA_VALUE;
4134 decimals= value.m_decimal.frac;
4135 collation.set_numeric();
4136 max_length=
4137 my_decimal_precision_to_length_no_truncation(value.m_decimal.precision(),
4138 decimals, unsigned_flag);
4139 maybe_null= 0;
4140 null_value= 0;
4141 fix_type(Item::DECIMAL_ITEM);
4142 DBUG_VOID_RETURN;
4143}
4144
4145void Item_param::set_decimal(const my_decimal *dv, bool unsigned_arg)
4146{
4147 DBUG_ASSERT(value.type_handler()->cmp_type() == DECIMAL_RESULT);
4148 state= SHORT_DATA_VALUE;
4149
4150 my_decimal2decimal(dv, &value.m_decimal);
4151
4152 decimals= (uint8) value.m_decimal.frac;
4153 collation.set_numeric();
4154 unsigned_flag= unsigned_arg;
4155 max_length= my_decimal_precision_to_length(value.m_decimal.intg + decimals,
4156 decimals, unsigned_flag);
4157 maybe_null= 0;
4158 null_value= 0;
4159 fix_type(Item::DECIMAL_ITEM);
4160}
4161
4162
4163void Item_param::fix_temporal(uint32 max_length_arg, uint decimals_arg)
4164{
4165 state= SHORT_DATA_VALUE;
4166 collation.set_numeric();
4167 max_length= max_length_arg;
4168 decimals= decimals_arg;
4169 maybe_null= 0;
4170 null_value= 0;
4171 fix_type(Item::DATE_ITEM);
4172}
4173
4174
4175void Item_param::set_time(const MYSQL_TIME *tm,
4176 uint32 max_length_arg, uint decimals_arg)
4177{
4178 DBUG_ASSERT(value.type_handler()->cmp_type() == TIME_RESULT);
4179 value.time= *tm;
4180 maybe_null= 0;
4181 null_value= 0;
4182 fix_temporal(max_length_arg, decimals_arg);
4183}
4184
4185
4186/**
4187 Set parameter value from MYSQL_TIME value.
4188
4189 @param tm datetime value to set (time_type is ignored)
4190 @param type type of datetime value
4191 @param max_length_arg max length of datetime value as string
4192
4193 @note
4194 If we value to be stored is not normalized, zero value will be stored
4195 instead and proper warning will be produced. This function relies on
4196 the fact that even wrong value sent over binary protocol fits into
4197 MAX_DATE_STRING_REP_LENGTH buffer.
4198*/
4199void Item_param::set_time(MYSQL_TIME *tm, timestamp_type time_type,
4200 uint32 max_length_arg)
4201{
4202 DBUG_ENTER("Item_param::set_time");
4203 DBUG_ASSERT(value.type_handler()->cmp_type() == TIME_RESULT);
4204
4205 value.time= *tm;
4206 value.time.time_type= time_type;
4207
4208 if (check_datetime_range(&value.time))
4209 {
4210 ErrConvTime str(&value.time);
4211 make_truncated_value_warning(current_thd, Sql_condition::WARN_LEVEL_WARN,
4212 &str, time_type, 0);
4213 set_zero_time(&value.time, time_type);
4214 }
4215 maybe_null= 0;
4216 null_value= 0;
4217 fix_temporal(max_length_arg,
4218 tm->second_part > 0 ? TIME_SECOND_PART_DIGITS : 0);
4219 DBUG_VOID_RETURN;
4220}
4221
4222
4223bool Item_param::set_str(const char *str, ulong length,
4224 CHARSET_INFO *fromcs, CHARSET_INFO *tocs)
4225{
4226 DBUG_ENTER("Item_param::set_str");
4227 DBUG_ASSERT(value.type_handler()->cmp_type() == STRING_RESULT);
4228 /*
4229 Assign string with no conversion: data is converted only after it's
4230 been written to the binary log.
4231 */
4232 uint dummy_errors;
4233 if (unlikely(value.m_string.copy(str, length, fromcs, tocs, &dummy_errors)))
4234 DBUG_RETURN(TRUE);
4235 /*
4236 Set str_value_ptr to make sure it's in sync with str_value.
4237 This is needed in case if we're called from Item_param::set_value(),
4238 from the code responsible for setting OUT parameters in
4239 sp_head::execute_procedure(). This makes sure that
4240 Protocol_binary::send_out_parameters() later gets a valid value
4241 from Item_param::val_str().
4242 Note, for IN parameters, Item_param::convert_str_value() will be called
4243 later, which will convert the value from the client character set to the
4244 connection character set, and will reset both str_value and str_value_ptr.
4245 */
4246 value.m_string_ptr.set(value.m_string.ptr(),
4247 value.m_string.length(),
4248 value.m_string.charset());
4249 state= SHORT_DATA_VALUE;
4250 collation.set(tocs, DERIVATION_COERCIBLE);
4251 max_length= length;
4252 maybe_null= 0;
4253 null_value= 0;
4254 /* max_length and decimals are set after charset conversion */
4255 /* sic: str may be not null-terminated, don't add DBUG_PRINT here */
4256 fix_type(Item::STRING_ITEM);
4257 DBUG_RETURN(FALSE);
4258}
4259
4260
4261bool Item_param::set_longdata(const char *str, ulong length)
4262{
4263 DBUG_ENTER("Item_param::set_longdata");
4264 DBUG_ASSERT(value.type_handler()->cmp_type() == STRING_RESULT);
4265
4266 /*
4267 If client character set is multibyte, end of long data packet
4268 may hit at the middle of a multibyte character. Additionally,
4269 if binary log is open we must write long data value to the
4270 binary log in character set of client. This is why we can't
4271 convert long data to connection character set as it comes
4272 (here), and first have to concatenate all pieces together,
4273 write query to the binary log and only then perform conversion.
4274 */
4275 if (value.m_string.length() + length > max_long_data_size)
4276 {
4277 my_message(ER_UNKNOWN_ERROR,
4278 "Parameter of prepared statement which is set through "
4279 "mysql_send_long_data() is longer than "
4280 "'max_long_data_size' bytes",
4281 MYF(0));
4282 DBUG_RETURN(true);
4283 }
4284
4285 if (value.m_string.append(str, length, &my_charset_bin))
4286 DBUG_RETURN(TRUE);
4287 state= LONG_DATA_VALUE;
4288 maybe_null= 0;
4289 null_value= 0;
4290 fix_type(Item::STRING_ITEM);
4291
4292 DBUG_RETURN(FALSE);
4293}
4294
4295
4296void Item_param::CONVERSION_INFO::set(THD *thd, CHARSET_INFO *fromcs)
4297{
4298 CHARSET_INFO *tocs= thd->variables.collation_connection;
4299
4300 character_set_of_placeholder= fromcs;
4301 character_set_client= thd->variables.character_set_client;
4302 /*
4303 Setup source and destination character sets so that they
4304 are different only if conversion is necessary: this will
4305 make later checks easier.
4306 */
4307 uint32 dummy_offset;
4308 final_character_set_of_str_value=
4309 String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
4310 tocs : fromcs;
4311}
4312
4313
4314bool Item_param::CONVERSION_INFO::convert(THD *thd, String *str)
4315{
4316 return thd->convert_string(str,
4317 character_set_of_placeholder,
4318 final_character_set_of_str_value);
4319}
4320
4321
4322/**
4323 Set parameter value from Item.
4324
4325 @param thd Current thread
4326 @param item Item
4327
4328 @retval
4329 0 OK
4330 @retval
4331 1 Out of memory
4332*/
4333
4334bool Item_param::set_from_item(THD *thd, Item *item)
4335{
4336 DBUG_ENTER("Item_param::set_from_item");
4337 m_is_settable_routine_parameter= item->get_settable_routine_parameter();
4338 if (limit_clause_param)
4339 {
4340 longlong val= item->val_int();
4341 if (item->null_value)
4342 {
4343 set_null();
4344 DBUG_RETURN(false);
4345 }
4346 else
4347 {
4348 unsigned_flag= item->unsigned_flag;
4349 set_handler(item->type_handler());
4350 DBUG_RETURN(set_limit_clause_param(val));
4351 }
4352 }
4353 struct st_value tmp;
4354 if (!item->save_in_value(&tmp))
4355 {
4356 const Type_handler *h= item->type_handler();
4357 set_handler(h);
4358 DBUG_RETURN(set_value(thd, item, &tmp, h));
4359 }
4360 else
4361 set_null();
4362
4363 DBUG_RETURN(0);
4364}
4365
4366/**
4367 Resets parameter after execution.
4368
4369 @note
4370 We clear null_value here instead of setting it in set_* methods,
4371 because we want more easily handle case for long data.
4372*/
4373
4374void Item_param::reset()
4375{
4376 DBUG_ENTER("Item_param::reset");
4377 /* Shrink string buffer if it's bigger than max possible CHAR column */
4378 if (value.m_string.alloced_length() > MAX_CHAR_WIDTH)
4379 value.m_string.free();
4380 else
4381 value.m_string.length(0);
4382 value.m_string_ptr.length(0);
4383 /*
4384 We must prevent all charset conversions until data has been written
4385 to the binary log.
4386 */
4387 value.m_string.set_charset(&my_charset_bin);
4388 collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
4389 state= NO_VALUE;
4390 maybe_null= 1;
4391 null_value= 0;
4392 fixed= false;
4393 /*
4394 Don't reset item_type to PARAM_ITEM: it's only needed to guard
4395 us from item optimizations at prepare stage, when item doesn't yet
4396 contain a literal of some kind.
4397 In all other cases when this object is accessed its value is
4398 set (this assumption is guarded by 'state' and
4399 DBUG_ASSERTS(state != NO_VALUE) in all Item_param::get_*
4400 methods).
4401 */
4402 DBUG_VOID_RETURN;
4403}
4404
4405
4406int Item_param::save_in_field(Field *field, bool no_conversions)
4407{
4408 field->set_notnull();
4409
4410 /*
4411 There's no "default" intentionally, to make compiler complain
4412 when adding a new XXX_VALUE value.
4413 Garbage (e.g. in case of a memory overrun) is handled after the switch.
4414 */
4415 switch (state) {
4416 case SHORT_DATA_VALUE:
4417 case LONG_DATA_VALUE:
4418 return value.type_handler()->Item_save_in_field(this, field, no_conversions);
4419 case NULL_VALUE:
4420 return set_field_to_null_with_conversions(field, no_conversions);
4421 case DEFAULT_VALUE:
4422 return field->save_in_field_default_value(field->table->pos_in_table_list->
4423 top_table() !=
4424 field->table->pos_in_table_list);
4425 case IGNORE_VALUE:
4426 return field->save_in_field_ignore_value(field->table->pos_in_table_list->
4427 top_table() !=
4428 field->table->pos_in_table_list);
4429 case NO_VALUE:
4430 DBUG_ASSERT(0); // Should not be possible
4431 return true;
4432 }
4433 DBUG_ASSERT(0); // Garbage
4434 return 1;
4435}
4436
4437
4438bool Item_param::can_return_value() const
4439{
4440 // There's no "default". See comments in Item_param::save_in_field().
4441 switch (state) {
4442 case SHORT_DATA_VALUE:
4443 case LONG_DATA_VALUE:
4444 return true;
4445 case IGNORE_VALUE:
4446 case DEFAULT_VALUE:
4447 invalid_default_param();
4448 // fall through
4449 case NULL_VALUE:
4450 return false;
4451 case NO_VALUE:
4452 DBUG_ASSERT(0); // Should not be possible
4453 return false;
4454 }
4455 DBUG_ASSERT(0); // Garbage
4456 return false;
4457}
4458
4459
4460void Item_param::invalid_default_param() const
4461{
4462 my_message(ER_INVALID_DEFAULT_PARAM,
4463 ER_THD(current_thd, ER_INVALID_DEFAULT_PARAM), MYF(0));
4464}
4465
4466
4467bool Item_param::get_date(MYSQL_TIME *res, ulonglong fuzzydate)
4468{
4469 /*
4470 LIMIT clause parameter should not call get_date()
4471 For non-LIMIT parameters, handlers must be the same.
4472 */
4473 DBUG_ASSERT(type_handler()->result_type() ==
4474 value.type_handler()->result_type());
4475 if (state == SHORT_DATA_VALUE &&
4476 value.type_handler()->cmp_type() == TIME_RESULT)
4477 {
4478 *res= value.time;
4479 return 0;
4480 }
4481 return type_handler()->Item_get_date(this, res, fuzzydate);
4482}
4483
4484
4485double Item_param::PValue::val_real() const
4486{
4487 switch (type_handler()->cmp_type()) {
4488 case REAL_RESULT:
4489 return real;
4490 case INT_RESULT:
4491 return (double) integer;
4492 case DECIMAL_RESULT:
4493 {
4494 double result;
4495 my_decimal2double(E_DEC_FATAL_ERROR, &m_decimal, &result);
4496 return result;
4497 }
4498 case STRING_RESULT:
4499 return double_from_string_with_check(&m_string);
4500 case TIME_RESULT:
4501 /*
4502 This works for example when user says SELECT ?+0.0 and supplies
4503 time value for the placeholder.
4504 */
4505 return TIME_to_double(&time);
4506 case ROW_RESULT:
4507 DBUG_ASSERT(0);
4508 break;
4509 }
4510 return 0.0;
4511}
4512
4513
4514longlong Item_param::PValue::val_int(const Type_std_attributes *attr) const
4515{
4516 switch (type_handler()->cmp_type()) {
4517 case REAL_RESULT:
4518 return (longlong) rint(real);
4519 case INT_RESULT:
4520 return integer;
4521 case DECIMAL_RESULT:
4522 {
4523 longlong i;
4524 my_decimal2int(E_DEC_FATAL_ERROR, &m_decimal, attr->unsigned_flag, &i);
4525 return i;
4526 }
4527 case STRING_RESULT:
4528 return longlong_from_string_with_check(&m_string);
4529 case TIME_RESULT:
4530 return (longlong) TIME_to_ulonglong(&time);
4531 case ROW_RESULT:
4532 DBUG_ASSERT(0);
4533 break;
4534 }
4535 return 0;
4536}
4537
4538
4539my_decimal *Item_param::PValue::val_decimal(my_decimal *dec,
4540 const Type_std_attributes *attr)
4541{
4542 switch (type_handler()->cmp_type()) {
4543 case DECIMAL_RESULT:
4544 return &m_decimal;
4545 case REAL_RESULT:
4546 double2my_decimal(E_DEC_FATAL_ERROR, real, dec);
4547 return dec;
4548 case INT_RESULT:
4549 int2my_decimal(E_DEC_FATAL_ERROR, integer, attr->unsigned_flag, dec);
4550 return dec;
4551 case STRING_RESULT:
4552 return decimal_from_string_with_check(dec, &m_string);
4553 case TIME_RESULT:
4554 return TIME_to_my_decimal(&time, dec);
4555 case ROW_RESULT:
4556 DBUG_ASSERT(0);
4557 break;
4558 }
4559 return 0;
4560}
4561
4562
4563String *Item_param::PValue::val_str(String *str,
4564 const Type_std_attributes *attr)
4565{
4566 switch (type_handler()->cmp_type()) {
4567 case STRING_RESULT:
4568 return &m_string_ptr;
4569 case REAL_RESULT:
4570 str->set_real(real, NOT_FIXED_DEC, &my_charset_bin);
4571 return str;
4572 case INT_RESULT:
4573 str->set(integer, &my_charset_bin);
4574 return str;
4575 case DECIMAL_RESULT:
4576 if (my_decimal2string(E_DEC_FATAL_ERROR, &m_decimal, 0, 0, 0, str) <= 1)
4577 return str;
4578 return NULL;
4579 case TIME_RESULT:
4580 {
4581 if (str->reserve(MAX_DATE_STRING_REP_LENGTH))
4582 return NULL;
4583 str->length((uint) my_TIME_to_str(&time, (char*) str->ptr(),
4584 attr->decimals));
4585 str->set_charset(&my_charset_bin);
4586 return str;
4587 }
4588 case ROW_RESULT:
4589 DBUG_ASSERT(0);
4590 break;
4591 }
4592 return NULL;
4593}
4594
4595
4596/**
4597 Return Param item values in string format, for generating the dynamic
4598 query used in update/binary logs.
4599
4600 @todo
4601 - Change interface and implementation to fill log data in place
4602 and avoid one more memcpy/alloc between str and log string.
4603 - In case of error we need to notify replication
4604 that binary log contains wrong statement
4605*/
4606
4607const String *Item_param::value_query_val_str(THD *thd, String *str) const
4608{
4609 switch (value.type_handler()->cmp_type()) {
4610 case INT_RESULT:
4611 str->set_int(value.integer, unsigned_flag, &my_charset_bin);
4612 return str;
4613 case REAL_RESULT:
4614 str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
4615 return str;
4616 case DECIMAL_RESULT:
4617 if (my_decimal2string(E_DEC_FATAL_ERROR, &value.m_decimal,
4618 0, 0, 0, str) > 1)
4619 return &my_null_string;
4620 return str;
4621 case TIME_RESULT:
4622 {
4623 static const uint32 typelen= 9; // "TIMESTAMP" is the longest type name
4624 char *buf, *ptr;
4625 str->length(0);
4626 /*
4627 TODO: in case of error we need to notify replication
4628 that binary log contains wrong statement
4629 */
4630 if (str->reserve(MAX_DATE_STRING_REP_LENGTH + 3 + typelen))
4631 return NULL;
4632
4633 /* Create date string inplace */
4634 switch (value.time.time_type) {
4635 case MYSQL_TIMESTAMP_DATE:
4636 str->append(STRING_WITH_LEN("DATE"));
4637 break;
4638 case MYSQL_TIMESTAMP_TIME:
4639 str->append(STRING_WITH_LEN("TIME"));
4640 break;
4641 case MYSQL_TIMESTAMP_DATETIME:
4642 str->append(STRING_WITH_LEN("TIMESTAMP"));
4643 break;
4644 case MYSQL_TIMESTAMP_ERROR:
4645 case MYSQL_TIMESTAMP_NONE:
4646 break;
4647 }
4648 DBUG_ASSERT(str->length() <= typelen);
4649 buf= str->c_ptr_quick();
4650 ptr= buf + str->length();
4651 *ptr++= '\'';
4652 ptr+= (uint) my_TIME_to_str(&value.time, ptr, decimals);
4653 *ptr++= '\'';
4654 str->length((uint32) (ptr - buf));
4655 return str;
4656 }
4657 case STRING_RESULT:
4658 {
4659 str->length(0);
4660 append_query_string(value.cs_info.character_set_client, str,
4661 value.m_string.ptr(), value.m_string.length(),
4662 thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES);
4663 return str;
4664 }
4665 case ROW_RESULT:
4666 DBUG_ASSERT(0);
4667 break;
4668 }
4669 return NULL;
4670}
4671
4672
4673const String *Item_param::query_val_str(THD *thd, String* str) const
4674{
4675 // There's no "default". See comments in Item_param::save_in_field().
4676 switch (state) {
4677 case SHORT_DATA_VALUE:
4678 case LONG_DATA_VALUE:
4679 return value_query_val_str(thd, str);
4680 case IGNORE_VALUE:
4681 case DEFAULT_VALUE:
4682 return &my_default_string;
4683 case NULL_VALUE:
4684 return &my_null_string;
4685 case NO_VALUE:
4686 DBUG_ASSERT(0); // Should not be possible
4687 return NULL;
4688 }
4689 DBUG_ASSERT(0); // Garbage
4690 return NULL;
4691}
4692
4693
4694/**
4695 Convert string from client character set to the character set of
4696 connection.
4697*/
4698
4699bool Item_param::convert_str_value(THD *thd)
4700{
4701 bool rc= FALSE;
4702 if ((state == SHORT_DATA_VALUE || state == LONG_DATA_VALUE) &&
4703 value.type_handler()->cmp_type() == STRING_RESULT)
4704 {
4705 rc= value.cs_info.convert_if_needed(thd, &value.m_string);
4706 /* Here str_value is guaranteed to be in final_character_set_of_str_value */
4707
4708 /*
4709 str_value_ptr is returned from val_str(). It must be not alloced
4710 to prevent it's modification by val_str() invoker.
4711 */
4712 value.m_string_ptr.set(value.m_string.ptr(), value.m_string.length(),
4713 value.m_string.charset());
4714 /* Synchronize item charset and length with value charset */
4715 fix_charset_and_length_from_str_value(value.m_string, DERIVATION_COERCIBLE);
4716 }
4717 return rc;
4718}
4719
4720
4721bool Item_param::basic_const_item() const
4722{
4723 DBUG_ASSERT(fixed || state == NO_VALUE);
4724 if (state == NO_VALUE ||
4725 (state == SHORT_DATA_VALUE && type_handler()->cmp_type() == TIME_RESULT))
4726 return FALSE;
4727 return TRUE;
4728}
4729
4730
4731Item *Item_param::value_clone_item(THD *thd)
4732{
4733 MEM_ROOT *mem_root= thd->mem_root;
4734 switch (value.type_handler()->cmp_type()) {
4735 case INT_RESULT:
4736 return (unsigned_flag ?
4737 new (mem_root) Item_uint(thd, name.str, value.integer, max_length) :
4738 new (mem_root) Item_int(thd, name.str, value.integer, max_length));
4739 case REAL_RESULT:
4740 return new (mem_root) Item_float(thd, name.str, value.real, decimals,
4741 max_length);
4742 case DECIMAL_RESULT:
4743 return 0; // Should create Item_decimal. See MDEV-11361.
4744 case STRING_RESULT:
4745 return new (mem_root) Item_string(thd, name.str,
4746 value.m_string.c_ptr_quick(),
4747 value.m_string.length(),
4748 value.m_string.charset(),
4749 collation.derivation,
4750 collation.repertoire);
4751 case TIME_RESULT:
4752 break;
4753 case ROW_RESULT:
4754 DBUG_ASSERT(0);
4755 break;
4756 }
4757 return 0;
4758}
4759
4760
4761/* see comments in the header file */
4762
4763Item *
4764Item_param::clone_item(THD *thd)
4765{
4766 // There's no "default". See comments in Item_param::save_in_field().
4767 switch (state) {
4768 case IGNORE_VALUE:
4769 case DEFAULT_VALUE:
4770 invalid_default_param();
4771 // fall through
4772 case NULL_VALUE:
4773 return new (thd->mem_root) Item_null(thd, name.str);
4774 case SHORT_DATA_VALUE:
4775 case LONG_DATA_VALUE:
4776 {
4777 DBUG_ASSERT(type_handler()->cmp_type() == value.type_handler()->cmp_type());
4778 return value_clone_item(thd);
4779 }
4780 case NO_VALUE:
4781 return 0;
4782 }
4783 DBUG_ASSERT(0); // Garbage
4784 return 0;
4785}
4786
4787
4788bool Item_param::value_eq(const Item *item, bool binary_cmp) const
4789{
4790 switch (value.type_handler()->cmp_type()) {
4791 case INT_RESULT:
4792 return int_eq(value.integer, item);
4793 case REAL_RESULT:
4794 return real_eq(value.real, item);
4795 case STRING_RESULT:
4796 return str_eq(&value.m_string, item, binary_cmp);
4797 case DECIMAL_RESULT:
4798 case TIME_RESULT:
4799 case ROW_RESULT:
4800 break;
4801 }
4802 return false;
4803}
4804
4805
4806bool
4807Item_param::eq(const Item *item, bool binary_cmp) const
4808{
4809 if (!basic_const_item())
4810 return FALSE;
4811
4812 // There's no "default". See comments in Item_param::save_in_field().
4813 switch (state) {
4814 case IGNORE_VALUE:
4815 case DEFAULT_VALUE:
4816 invalid_default_param();
4817 return false;
4818 case NULL_VALUE:
4819 return null_eq(item);
4820 case SHORT_DATA_VALUE:
4821 case LONG_DATA_VALUE:
4822 return value_eq(item, binary_cmp);
4823 case NO_VALUE:
4824 return false;
4825 }
4826 DBUG_ASSERT(0); // Garbage
4827 return FALSE;
4828}
4829
4830/* End of Item_param related */
4831
4832void Item_param::print(String *str, enum_query_type query_type)
4833{
4834 if (state == NO_VALUE)
4835 {
4836 str->append('?');
4837 }
4838 else if (state == DEFAULT_VALUE)
4839 {
4840 str->append("default");
4841 }
4842 else if (state == IGNORE_VALUE)
4843 {
4844 str->append("ignore");
4845 }
4846 else
4847 {
4848 char buffer[STRING_BUFFER_USUAL_SIZE];
4849 String tmp(buffer, sizeof(buffer), &my_charset_bin);
4850 const String *res;
4851 res= query_val_str(current_thd, &tmp);
4852 str->append(*res);
4853 }
4854}
4855
4856
4857/**
4858 Preserve the original parameter types and values
4859 when re-preparing a prepared statement.
4860
4861 @details Copy parameter type information and conversion
4862 function pointers from a parameter of the old statement
4863 to the corresponding parameter of the new one.
4864
4865 Move parameter values from the old parameters to the new
4866 one. We simply "exchange" the values, which allows
4867 to save on allocation and character set conversion in
4868 case a parameter is a string or a blob/clob.
4869
4870 The old parameter gets the value of this one, which
4871 ensures that all memory of this parameter is freed
4872 correctly.
4873
4874 @param[in] src parameter item of the original
4875 prepared statement
4876*/
4877
4878void
4879Item_param::set_param_type_and_swap_value(Item_param *src)
4880{
4881 Type_std_attributes::set(src);
4882 set_handler(src->type_handler());
4883 item_type= src->item_type;
4884
4885 maybe_null= src->maybe_null;
4886 null_value= src->null_value;
4887 state= src->state;
4888 fixed= src->fixed;
4889
4890 value.swap(src->value);
4891}
4892
4893
4894void Item_param::set_default()
4895{
4896 m_is_settable_routine_parameter= false;
4897 state= DEFAULT_VALUE;
4898 fixed= true;
4899 /*
4900 When Item_param is set to DEFAULT_VALUE:
4901 - its val_str() and val_decimal() return NULL
4902 - get_date() returns true
4903 It's important also to have null_value==true for DEFAULT_VALUE.
4904 Otherwise the callers of val_xxx() and get_date(), e.g. Item::send(),
4905 can misbehave (e.g. crash on asserts).
4906 */
4907 null_value= true;
4908}
4909
4910void Item_param::set_ignore()
4911{
4912 m_is_settable_routine_parameter= false;
4913 state= IGNORE_VALUE;
4914 fixed= true;
4915 null_value= true;
4916}
4917
4918/**
4919 This operation is intended to store some item value in Item_param to be
4920 used later.
4921
4922 @param thd thread context
4923 @param ctx stored procedure runtime context
4924 @param it a pointer to an item in the tree
4925
4926 @return Error status
4927 @retval TRUE on error
4928 @retval FALSE on success
4929*/
4930
4931bool
4932Item_param::set_value(THD *thd, sp_rcontext *ctx, Item **it)
4933{
4934 Item *arg= *it;
4935 struct st_value tmp;
4936 /*
4937 The OUT parameter is bound to some data type.
4938 It's important not to touch m_type_handler,
4939 to make sure the next mysql_stmt_execute()
4940 correctly fetches the value from the client-server protocol,
4941 using set_param_func().
4942 */
4943 if (arg->save_in_value(&tmp) ||
4944 set_value(thd, arg, &tmp, arg->type_handler()))
4945 {
4946 set_null();
4947 return false;
4948 }
4949 /* It is wrapper => other set_* shoud set null_value */
4950 DBUG_ASSERT(null_value == false);
4951 return false;
4952}
4953
4954
4955/**
4956 Setter of Item_param::m_out_param_info.
4957
4958 m_out_param_info is used to store information about store routine
4959 OUT-parameters, such as stored routine name, database, stored routine
4960 variable name. It is supposed to be set in sp_head::execute() after
4961 Item_param::set_value() is called.
4962*/
4963
4964void
4965Item_param::set_out_param_info(Send_field *info)
4966{
4967 m_out_param_info= info;
4968 set_handler_by_field_type(m_out_param_info->type);
4969}
4970
4971
4972/**
4973 Getter of Item_param::m_out_param_info.
4974
4975 m_out_param_info is used to store information about store routine
4976 OUT-parameters, such as stored routine name, database, stored routine
4977 variable name. It is supposed to be retrieved in
4978 Protocol_binary::send_out_parameters() during creation of OUT-parameter
4979 result set.
4980*/
4981
4982const Send_field *
4983Item_param::get_out_param_info() const
4984{
4985 return m_out_param_info;
4986}
4987
4988
4989/**
4990 Fill meta-data information for the corresponding column in a result set.
4991 If this is an OUT-parameter of a stored procedure, preserve meta-data of
4992 stored-routine variable.
4993
4994 @param field container for meta-data to be filled
4995*/
4996
4997void Item_param::make_send_field(THD *thd, Send_field *field)
4998{
4999 Item::make_send_field(thd, field);
5000
5001 if (!m_out_param_info)
5002 return;
5003
5004 /*
5005 This is an OUT-parameter of stored procedure. We should use
5006 OUT-parameter info to fill out the names.
5007 */
5008
5009 field->db_name= m_out_param_info->db_name;
5010 field->table_name= m_out_param_info->table_name;
5011 field->org_table_name= m_out_param_info->org_table_name;
5012 field->col_name= m_out_param_info->col_name;
5013 field->org_col_name= m_out_param_info->org_col_name;
5014
5015 field->length= m_out_param_info->length;
5016 field->flags= m_out_param_info->flags;
5017 field->decimals= m_out_param_info->decimals;
5018 field->type= m_out_param_info->type;
5019}
5020
5021bool Item_param::append_for_log(THD *thd, String *str)
5022{
5023 StringBuffer<STRING_BUFFER_USUAL_SIZE> buf;
5024 const String *val= query_val_str(thd, &buf);
5025 return str->append(*val);
5026}
5027
5028/****************************************************************************
5029 Item_copy
5030****************************************************************************/
5031
5032Item_copy *Item_copy::create(THD *thd, Item *item)
5033{
5034 MEM_ROOT *mem_root= thd->mem_root;
5035 switch (item->result_type())
5036 {
5037 case STRING_RESULT:
5038 return new (mem_root) Item_copy_string(thd, item);
5039 case REAL_RESULT:
5040 return new (mem_root) Item_copy_float(thd, item);
5041 case INT_RESULT:
5042 return item->unsigned_flag ?
5043 new (mem_root) Item_copy_uint(thd, item) :
5044 new (mem_root) Item_copy_int(thd, item);
5045 case DECIMAL_RESULT:
5046 return new (mem_root) Item_copy_decimal(thd, item);
5047 case TIME_RESULT:
5048 case ROW_RESULT:
5049 DBUG_ASSERT (0);
5050 }
5051 /* should not happen */
5052 return NULL;
5053}
5054
5055/****************************************************************************
5056 Item_copy_string
5057****************************************************************************/
5058
5059double Item_copy_string::val_real()
5060{
5061 int err_not_used;
5062 char *end_not_used;
5063 return (null_value ? 0.0 :
5064 my_strntod(str_value.charset(), (char*) str_value.ptr(),
5065 str_value.length(), &end_not_used, &err_not_used));
5066}
5067
5068longlong Item_copy_string::val_int()
5069{
5070 int err;
5071 return null_value ? 0 : my_strntoll(str_value.charset(),str_value.ptr(),
5072 str_value.length(), 10, (char**) 0,
5073 &err);
5074}
5075
5076
5077int Item_copy_string::save_in_field(Field *field, bool no_conversions)
5078{
5079 return save_str_value_in_field(field, &str_value);
5080}
5081
5082
5083void Item_copy_string::copy()
5084{
5085 String *res=item->val_str(&str_value);
5086 if (res && res != &str_value)
5087 str_value.copy(*res);
5088 null_value=item->null_value;
5089}
5090
5091/* ARGSUSED */
5092String *Item_copy_string::val_str(String *str)
5093{
5094 // Item_copy_string is used without fix_fields call
5095 if (null_value)
5096 return (String*) 0;
5097 return &str_value;
5098}
5099
5100
5101my_decimal *Item_copy_string::val_decimal(my_decimal *decimal_value)
5102{
5103 // Item_copy_string is used without fix_fields call
5104 if (null_value)
5105 return (my_decimal *) 0;
5106 string2my_decimal(E_DEC_FATAL_ERROR, &str_value, decimal_value);
5107 return (decimal_value);
5108}
5109
5110
5111/****************************************************************************
5112 Item_copy_int
5113****************************************************************************/
5114
5115void Item_copy_int::copy()
5116{
5117 cached_value= item->val_int();
5118 null_value=item->null_value;
5119}
5120
5121static int save_int_value_in_field (Field *, longlong, bool, bool);
5122
5123int Item_copy_int::save_in_field(Field *field, bool no_conversions)
5124{
5125 return save_int_value_in_field(field, cached_value,
5126 null_value, unsigned_flag);
5127}
5128
5129
5130String *Item_copy_int::val_str(String *str)
5131{
5132 if (null_value)
5133 return (String *) 0;
5134
5135 str->set(cached_value, &my_charset_bin);
5136 return str;
5137}
5138
5139
5140my_decimal *Item_copy_int::val_decimal(my_decimal *decimal_value)
5141{
5142 if (null_value)
5143 return (my_decimal *) 0;
5144
5145 int2my_decimal(E_DEC_FATAL_ERROR, cached_value, unsigned_flag, decimal_value);
5146 return decimal_value;
5147}
5148
5149
5150/****************************************************************************
5151 Item_copy_uint
5152****************************************************************************/
5153
5154String *Item_copy_uint::val_str(String *str)
5155{
5156 if (null_value)
5157 return (String *) 0;
5158
5159 str->set((ulonglong) cached_value, &my_charset_bin);
5160 return str;
5161}
5162
5163
5164/****************************************************************************
5165 Item_copy_float
5166****************************************************************************/
5167
5168String *Item_copy_float::val_str(String *str)
5169{
5170 if (null_value)
5171 return (String *) 0;
5172 else
5173 {
5174 double nr= val_real();
5175 str->set_real(nr,decimals, &my_charset_bin);
5176 return str;
5177 }
5178}
5179
5180
5181my_decimal *Item_copy_float::val_decimal(my_decimal *decimal_value)
5182{
5183 if (null_value)
5184 return (my_decimal *) 0;
5185 else
5186 {
5187 double nr= val_real();
5188 double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
5189 return decimal_value;
5190 }
5191}
5192
5193
5194int Item_copy_float::save_in_field(Field *field, bool no_conversions)
5195{
5196 if (null_value)
5197 return set_field_to_null(field);
5198 field->set_notnull();
5199 return field->store(cached_value);
5200}
5201
5202
5203/****************************************************************************
5204 Item_copy_decimal
5205****************************************************************************/
5206
5207int Item_copy_decimal::save_in_field(Field *field, bool no_conversions)
5208{
5209 if (null_value)
5210 return set_field_to_null(field);
5211 field->set_notnull();
5212 return field->store_decimal(&cached_value);
5213}
5214
5215
5216String *Item_copy_decimal::val_str(String *result)
5217{
5218 if (null_value)
5219 return (String *) 0;
5220 result->set_charset(&my_charset_bin);
5221 my_decimal2string(E_DEC_FATAL_ERROR, &cached_value, 0, 0, 0, result);
5222 return result;
5223}
5224
5225
5226double Item_copy_decimal::val_real()
5227{
5228 if (null_value)
5229 return 0.0;
5230 else
5231 {
5232 double result;
5233 my_decimal2double(E_DEC_FATAL_ERROR, &cached_value, &result);
5234 return result;
5235 }
5236}
5237
5238
5239longlong Item_copy_decimal::val_int()
5240{
5241 if (null_value)
5242 return 0;
5243 else
5244 {
5245 longlong result;
5246 my_decimal2int(E_DEC_FATAL_ERROR, &cached_value, unsigned_flag, &result);
5247 return result;
5248 }
5249}
5250
5251
5252void Item_copy_decimal::copy()
5253{
5254 my_decimal *nr= item->val_decimal(&cached_value);
5255 if (nr && nr != &cached_value)
5256 my_decimal2decimal (nr, &cached_value);
5257 null_value= item->null_value;
5258}
5259
5260
5261/*
5262 Functions to convert item to field (for send_result_set_metadata)
5263*/
5264
5265/* ARGSUSED */
5266bool Item::fix_fields(THD *thd, Item **ref)
5267{
5268
5269 // We do not check fields which are fixed during construction
5270 DBUG_ASSERT(fixed == 0 || basic_const_item());
5271 fixed= 1;
5272 return FALSE;
5273}
5274
5275
5276void Item_ref_null_helper::save_val(Field *to)
5277{
5278 DBUG_ASSERT(fixed == 1);
5279 (*ref)->save_val(to);
5280 owner->was_null|= null_value= (*ref)->null_value;
5281}
5282
5283
5284double Item_ref_null_helper::val_real()
5285{
5286 DBUG_ASSERT(fixed == 1);
5287 double tmp= (*ref)->val_result();
5288 owner->was_null|= null_value= (*ref)->null_value;
5289 return tmp;
5290}
5291
5292
5293longlong Item_ref_null_helper::val_int()
5294{
5295 DBUG_ASSERT(fixed == 1);
5296 longlong tmp= (*ref)->val_int_result();
5297 owner->was_null|= null_value= (*ref)->null_value;
5298 return tmp;
5299}
5300
5301
5302my_decimal *Item_ref_null_helper::val_decimal(my_decimal *decimal_value)
5303{
5304 DBUG_ASSERT(fixed == 1);
5305 my_decimal *val= (*ref)->val_decimal_result(decimal_value);
5306 owner->was_null|= null_value= (*ref)->null_value;
5307 return val;
5308}
5309
5310
5311bool Item_ref_null_helper::val_bool()
5312{
5313 DBUG_ASSERT(fixed == 1);
5314 bool val= (*ref)->val_bool_result();
5315 owner->was_null|= null_value= (*ref)->null_value;
5316 return val;
5317}
5318
5319
5320String* Item_ref_null_helper::val_str(String* s)
5321{
5322 DBUG_ASSERT(fixed == 1);
5323 String* tmp= (*ref)->str_result(s);
5324 owner->was_null|= null_value= (*ref)->null_value;
5325 return tmp;
5326}
5327
5328
5329bool Item_ref_null_helper::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
5330{
5331 return (owner->was_null|= null_value= (*ref)->get_date_result(ltime, fuzzydate));
5332}
5333
5334
5335/**
5336 Mark item and SELECT_LEXs as dependent if item was resolved in
5337 outer SELECT.
5338
5339 @param thd thread handler
5340 @param last select from which current item depend
5341 @param current current select
5342 @param resolved_item item which was resolved in outer SELECT(for warning)
5343 @param mark_item item which should be marked (can be differ in case of
5344 substitution)
5345*/
5346
5347static bool mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current,
5348 Item_ident *resolved_item,
5349 Item_ident *mark_item)
5350{
5351 DBUG_ENTER("mark_as_dependent");
5352
5353 /* store pointer on SELECT_LEX from which item is dependent */
5354 if (mark_item && mark_item->can_be_depended)
5355 {
5356 DBUG_PRINT("info", ("mark_item: %p lex: %p", mark_item, last));
5357 mark_item->depended_from= last;
5358 }
5359 if (current->mark_as_dependent(thd, last,
5360 /** resolved_item psergey-thu **/ mark_item))
5361 DBUG_RETURN(TRUE);
5362 if (thd->lex->describe & DESCRIBE_EXTENDED)
5363 {
5364 const char *db_name= (resolved_item->db_name ?
5365 resolved_item->db_name : "");
5366 const char *table_name= (resolved_item->table_name ?
5367 resolved_item->table_name : "");
5368 push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
5369 ER_WARN_FIELD_RESOLVED,
5370 ER_THD(thd,ER_WARN_FIELD_RESOLVED),
5371 db_name, (db_name[0] ? "." : ""),
5372 table_name, (table_name [0] ? "." : ""),
5373 resolved_item->field_name.str,
5374 current->select_number, last->select_number);
5375 }
5376 DBUG_RETURN(FALSE);
5377}
5378
5379
5380/**
5381 Mark range of selects and resolved identifier (field/reference)
5382 item as dependent.
5383
5384 @param thd thread handler
5385 @param last_select select where resolved_item was resolved
5386 @param current_sel current select (select where resolved_item was placed)
5387 @param found_field field which was found during resolving
5388 @param found_item Item which was found during resolving (if resolved
5389 identifier belongs to VIEW)
5390 @param resolved_item Identifier which was resolved
5391
5392 @note
5393 We have to mark all items between current_sel (including) and
5394 last_select (excluding) as dependend (select before last_select should
5395 be marked with actual table mask used by resolved item, all other with
5396 OUTER_REF_TABLE_BIT) and also write dependence information to Item of
5397 resolved identifier.
5398*/
5399
5400void mark_select_range_as_dependent(THD *thd,
5401 SELECT_LEX *last_select,
5402 SELECT_LEX *current_sel,
5403 Field *found_field, Item *found_item,
5404 Item_ident *resolved_item)
5405{
5406 /*
5407 Go from current SELECT to SELECT where field was resolved (it
5408 have to be reachable from current SELECT, because it was already
5409 done once when we resolved this field and cached result of
5410 resolving)
5411 */
5412 SELECT_LEX *previous_select= current_sel;
5413 for (; previous_select->outer_select() != last_select;
5414 previous_select= previous_select->outer_select())
5415 {
5416 Item_subselect *prev_subselect_item=
5417 previous_select->master_unit()->item;
5418 prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
5419 prev_subselect_item->const_item_cache= 0;
5420 }
5421 {
5422 Item_subselect *prev_subselect_item=
5423 previous_select->master_unit()->item;
5424 Item_ident *dependent= resolved_item;
5425 if (found_field == view_ref_found)
5426 {
5427 Item::Type type= found_item->type();
5428 prev_subselect_item->used_tables_cache|=
5429 found_item->used_tables();
5430 dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
5431 (Item_ident*) found_item :
5432 0);
5433 }
5434 else
5435 prev_subselect_item->used_tables_cache|=
5436 found_field->table->map;
5437 prev_subselect_item->const_item_cache= 0;
5438 mark_as_dependent(thd, last_select, current_sel, resolved_item,
5439 dependent);
5440 }
5441}
5442
5443
5444/**
5445 Search a GROUP BY clause for a field with a certain name.
5446
5447 Search the GROUP BY list for a column named as find_item. When searching
5448 preference is given to columns that are qualified with the same table (and
5449 database) name as the one being searched for.
5450
5451 @param find_item the item being searched for
5452 @param group_list GROUP BY clause
5453
5454 @return
5455 - the found item on success
5456 - NULL if find_item is not in group_list
5457*/
5458
5459static Item** find_field_in_group_list(Item *find_item, ORDER *group_list)
5460{
5461 const char *db_name;
5462 const char *table_name;
5463 LEX_CSTRING *field_name;
5464 ORDER *found_group= NULL;
5465 int found_match_degree= 0;
5466 char name_buff[SAFE_NAME_LEN+1];
5467
5468 if (find_item->type() == Item::FIELD_ITEM ||
5469 find_item->type() == Item::REF_ITEM)
5470 {
5471 db_name= ((Item_ident*) find_item)->db_name;
5472 table_name= ((Item_ident*) find_item)->table_name;
5473 field_name= &((Item_ident*) find_item)->field_name;
5474 }
5475 else
5476 return NULL;
5477
5478 if (db_name && lower_case_table_names)
5479 {
5480 /* Convert database to lower case for comparison */
5481 strmake_buf(name_buff, db_name);
5482 my_casedn_str(files_charset_info, name_buff);
5483 db_name= name_buff;
5484 }
5485
5486 DBUG_ASSERT(field_name->str != 0);
5487
5488 for (ORDER *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
5489 {
5490 int cur_match_degree= 0;
5491
5492 /* SELECT list element with explicit alias */
5493 if ((*(cur_group->item))->name.str && !table_name &&
5494 !(*(cur_group->item))->is_autogenerated_name &&
5495 !lex_string_cmp(system_charset_info,
5496 &(*(cur_group->item))->name, field_name))
5497 {
5498 ++cur_match_degree;
5499 }
5500 /* Reference on the field or view/derived field. */
5501 else if ((*(cur_group->item))->type() == Item::FIELD_ITEM ||
5502 (*(cur_group->item))->type() == Item::REF_ITEM )
5503 {
5504 Item_ident *cur_field= (Item_ident*) *cur_group->item;
5505 const char *l_db_name= cur_field->db_name;
5506 const char *l_table_name= cur_field->table_name;
5507 LEX_CSTRING *l_field_name= &cur_field->field_name;
5508
5509 DBUG_ASSERT(l_field_name->str != 0);
5510
5511 if (!lex_string_cmp(system_charset_info,
5512 l_field_name, field_name))
5513 ++cur_match_degree;
5514 else
5515 continue;
5516
5517 if (l_table_name && table_name)
5518 {
5519 /* If field_name is qualified by a table name. */
5520 if (my_strcasecmp(table_alias_charset, l_table_name, table_name))
5521 /* Same field names, different tables. */
5522 return NULL;
5523
5524 ++cur_match_degree;
5525 if (l_db_name && db_name)
5526 {
5527 /* If field_name is also qualified by a database name. */
5528 if (strcmp(l_db_name, db_name))
5529 /* Same field names, different databases. */
5530 return NULL;
5531 ++cur_match_degree;
5532 }
5533 }
5534 }
5535 else
5536 continue;
5537
5538 if (cur_match_degree > found_match_degree)
5539 {
5540 found_match_degree= cur_match_degree;
5541 found_group= cur_group;
5542 }
5543 else if (found_group && (cur_match_degree == found_match_degree) &&
5544 !(*(found_group->item))->eq((*(cur_group->item)), 0))
5545 {
5546 /*
5547 If the current resolve candidate matches equally well as the current
5548 best match, they must reference the same column, otherwise the field
5549 is ambiguous.
5550 */
5551 my_error(ER_NON_UNIQ_ERROR, MYF(0),
5552 find_item->full_name(), current_thd->where);
5553 return NULL;
5554 }
5555 }
5556
5557 if (found_group)
5558 return found_group->item;
5559 else
5560 return NULL;
5561}
5562
5563
5564/**
5565 Resolve a column reference in a sub-select.
5566
5567 Resolve a column reference (usually inside a HAVING clause) against the
5568 SELECT and GROUP BY clauses of the query described by 'select'. The name
5569 resolution algorithm searches both the SELECT and GROUP BY clauses, and in
5570 case of a name conflict prefers GROUP BY column names over SELECT names. If
5571 both clauses contain different fields with the same names, a warning is
5572 issued that name of 'ref' is ambiguous. We extend ANSI SQL in that when no
5573 GROUP BY column is found, then a HAVING name is resolved as a possibly
5574 derived SELECT column. This extension is allowed only if the
5575 MODE_ONLY_FULL_GROUP_BY sql mode isn't enabled.
5576
5577 @param thd current thread
5578 @param ref column reference being resolved
5579 @param select the select that ref is resolved against
5580
5581 @note
5582 The resolution procedure is:
5583 - Search for a column or derived column named col_ref_i [in table T_j]
5584 in the SELECT clause of Q.
5585 - Search for a column named col_ref_i [in table T_j]
5586 in the GROUP BY clause of Q.
5587 - If found different columns with the same name in GROUP BY and SELECT
5588 - issue a warning and return the GROUP BY column,
5589 - otherwise
5590 - if the MODE_ONLY_FULL_GROUP_BY mode is enabled return error
5591 - else return the found SELECT column.
5592
5593
5594 @return
5595 - NULL - there was an error, and the error was already reported
5596 - not_found_item - the item was not resolved, no error was reported
5597 - resolved item - if the item was resolved
5598*/
5599
5600static Item**
5601resolve_ref_in_select_and_group(THD *thd, Item_ident *ref, SELECT_LEX *select)
5602{
5603 Item **group_by_ref= NULL;
5604 Item **select_ref= NULL;
5605 ORDER *group_list= select->group_list.first;
5606 bool ambiguous_fields= FALSE;
5607 uint counter;
5608 enum_resolution_type resolution;
5609
5610 /*
5611 Search for a column or derived column named as 'ref' in the SELECT
5612 clause of the current select.
5613 */
5614 if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()),
5615 &counter, REPORT_EXCEPT_NOT_FOUND,
5616 &resolution)))
5617 return NULL; /* Some error occurred. */
5618 if (resolution == RESOLVED_AGAINST_ALIAS)
5619 ref->alias_name_used= TRUE;
5620
5621 /* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
5622 if (select->having_fix_field && !ref->with_sum_func && group_list)
5623 {
5624 group_by_ref= find_field_in_group_list(ref, group_list);
5625
5626 /* Check if the fields found in SELECT and GROUP BY are the same field. */
5627 if (group_by_ref && (select_ref != not_found_item) &&
5628 !((*group_by_ref)->eq(*select_ref, 0)))
5629 {
5630 ambiguous_fields= TRUE;
5631 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
5632 ER_NON_UNIQ_ERROR,
5633 ER_THD(thd,ER_NON_UNIQ_ERROR), ref->full_name(),
5634 thd->where);
5635
5636 }
5637 }
5638
5639 if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
5640 select->having_fix_field &&
5641 select_ref != not_found_item && !group_by_ref &&
5642 !ref->alias_name_used)
5643 {
5644 /*
5645 Report the error if fields was found only in the SELECT item list and
5646 the strict mode is enabled.
5647 */
5648 my_error(ER_NON_GROUPING_FIELD_USED, MYF(0),
5649 ref->name.str, "HAVING");
5650 return NULL;
5651 }
5652 if (select_ref != not_found_item || group_by_ref)
5653 {
5654 if (select_ref != not_found_item && !ambiguous_fields)
5655 {
5656 DBUG_ASSERT(*select_ref != 0);
5657 if (!select->ref_pointer_array[counter])
5658 {
5659 my_error(ER_ILLEGAL_REFERENCE, MYF(0),
5660 ref->name.str, "forward reference in item list");
5661 return NULL;
5662 }
5663 DBUG_ASSERT((*select_ref)->fixed);
5664 return &select->ref_pointer_array[counter];
5665 }
5666 if (group_by_ref)
5667 return group_by_ref;
5668 DBUG_ASSERT(FALSE);
5669 return NULL; /* So there is no compiler warning. */
5670 }
5671
5672 return (Item**) not_found_item;
5673}
5674
5675
5676/*
5677 @brief
5678 Whether a table belongs to an outer select.
5679
5680 @param table table to check
5681 @param select current select
5682
5683 @details
5684 Try to find select the table belongs to by ascending the derived tables chain.
5685*/
5686
5687static
5688bool is_outer_table(TABLE_LIST *table, SELECT_LEX *select)
5689{
5690 DBUG_ASSERT(table->select_lex != select);
5691 TABLE_LIST *tl;
5692
5693 if (table->belong_to_view &&
5694 table->belong_to_view->select_lex == select)
5695 return FALSE;
5696
5697 for (tl= select->master_unit()->derived;
5698 tl && tl->is_merged_derived();
5699 select= tl->select_lex, tl= select->master_unit()->derived)
5700 {
5701 if (tl->select_lex == table->select_lex)
5702 return FALSE;
5703 }
5704 return TRUE;
5705}
5706
5707
5708/**
5709 Resolve the name of an outer select column reference.
5710
5711 @param[in] thd current thread
5712 @param[in,out] from_field found field reference or (Field*)not_found_field
5713 @param[in,out] reference view column if this item was resolved to a
5714 view column
5715
5716 @description
5717 The method resolves the column reference represented by 'this' as a column
5718 present in outer selects that contain current select.
5719
5720 In prepared statements, because of cache, find_field_in_tables()
5721 can resolve fields even if they don't belong to current context.
5722 In this case this method only finds appropriate context and marks
5723 current select as dependent. The found reference of field should be
5724 provided in 'from_field'.
5725
5726 The cache is critical for prepared statements of type:
5727
5728 SELECT a FROM (SELECT a FROM test.t1) AS s1 NATURAL JOIN t2 AS s2;
5729
5730 This is internally converted to a join similar to
5731
5732 SELECT a FROM t1 AS s1,t2 AS s2 WHERE t2.a=t1.a;
5733
5734 Without the cache, we would on re-prepare not know if 'a' did match
5735 s1.a or s2.a.
5736
5737 @note
5738 This is the inner loop of Item_field::fix_fields:
5739 @code
5740 for each outer query Q_k beginning from the inner-most one
5741 {
5742 search for a column or derived column named col_ref_i
5743 [in table T_j] in the FROM clause of Q_k;
5744
5745 if such a column is not found
5746 Search for a column or derived column named col_ref_i
5747 [in table T_j] in the SELECT and GROUP clauses of Q_k.
5748 }
5749 @endcode
5750
5751 @retval
5752 1 column succefully resolved and fix_fields() should continue.
5753 @retval
5754 0 column fully fixed and fix_fields() should return FALSE
5755 @retval
5756 -1 error occurred
5757*/
5758
5759int
5760Item_field::fix_outer_field(THD *thd, Field **from_field, Item **reference)
5761{
5762 enum_parsing_place place= NO_MATTER;
5763 bool field_found= (*from_field != not_found_field);
5764 bool upward_lookup= FALSE;
5765 TABLE_LIST *table_list;
5766
5767 /* Calulate the TABLE_LIST for the table */
5768 table_list= (cached_table ? cached_table :
5769 field_found && (*from_field) != view_ref_found ?
5770 (*from_field)->table->pos_in_table_list : 0);
5771 /*
5772 If there are outer contexts (outer selects, but current select is
5773 not derived table or view) try to resolve this reference in the
5774 outer contexts.
5775
5776 We treat each subselect as a separate namespace, so that different
5777 subselects may contain columns with the same names. The subselects
5778 are searched starting from the innermost.
5779 */
5780 Name_resolution_context *last_checked_context= context;
5781 Item **ref= (Item **) not_found_item;
5782 SELECT_LEX *current_sel= thd->lex->current_select;
5783 Name_resolution_context *outer_context= 0;
5784 SELECT_LEX *select= 0;
5785 /* Currently derived tables cannot be correlated */
5786 if (current_sel->master_unit()->first_select()->linkage !=
5787 DERIVED_TABLE_TYPE)
5788 outer_context= context->outer_context;
5789
5790 /*
5791 This assert is to ensure we have an outer contex when *from_field
5792 is set.
5793 If this would not be the case, we would assert in mark_as_dependent
5794 as last_checked_countex == context
5795 */
5796 DBUG_ASSERT(outer_context || !*from_field ||
5797 *from_field == not_found_field);
5798 for (;
5799 outer_context;
5800 outer_context= outer_context->outer_context)
5801 {
5802 select= outer_context->select_lex;
5803 Item_subselect *prev_subselect_item=
5804 last_checked_context->select_lex->master_unit()->item;
5805 last_checked_context= outer_context;
5806 upward_lookup= TRUE;
5807
5808 place= prev_subselect_item->parsing_place;
5809 /*
5810 If outer_field is set, field was already found by first call
5811 to find_field_in_tables(). Only need to find appropriate context.
5812 */
5813 if (field_found && outer_context->select_lex !=
5814 table_list->select_lex)
5815 continue;
5816 /*
5817 In case of a view, find_field_in_tables() writes the pointer to
5818 the found view field into '*reference', in other words, it
5819 substitutes this Item_field with the found expression.
5820 */
5821 if (field_found || (*from_field= find_field_in_tables(thd, this,
5822 outer_context->
5823 first_name_resolution_table,
5824 outer_context->
5825 last_name_resolution_table,
5826 reference,
5827 IGNORE_EXCEPT_NON_UNIQUE,
5828 TRUE, TRUE)) !=
5829 not_found_field)
5830 {
5831 if (*from_field)
5832 {
5833 if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
5834 select->cur_pos_in_select_list != UNDEF_POS)
5835 {
5836 /*
5837 As this is an outer field it should be added to the list of
5838 non aggregated fields of the outer select.
5839 */
5840 if (select->join)
5841 {
5842 marker= select->cur_pos_in_select_list;
5843 select->join->non_agg_fields.push_back(this, thd->mem_root);
5844 }
5845 else
5846 {
5847 /*
5848 join is absent if it is upper SELECT_LEX of non-select
5849 command
5850 */
5851 DBUG_ASSERT(select->master_unit()->outer_select() == NULL &&
5852 (thd->lex->sql_command != SQLCOM_SELECT &&
5853 thd->lex->sql_command != SQLCOM_UPDATE_MULTI &&
5854 thd->lex->sql_command != SQLCOM_DELETE_MULTI &&
5855 thd->lex->sql_command != SQLCOM_INSERT_SELECT &&
5856 thd->lex->sql_command != SQLCOM_REPLACE_SELECT));
5857 }
5858 }
5859 if (*from_field != view_ref_found)
5860 {
5861 prev_subselect_item->used_tables_cache|= (*from_field)->table->map;
5862 prev_subselect_item->const_item_cache= 0;
5863 set_field(*from_field);
5864 if (!last_checked_context->select_lex->having_fix_field &&
5865 select->group_list.elements &&
5866 (place == SELECT_LIST || place == IN_HAVING))
5867 {
5868 Item_outer_ref *rf;
5869 /*
5870 If an outer field is resolved in a grouping select then it
5871 is replaced for an Item_outer_ref object. Otherwise an
5872 Item_field object is used.
5873 The new Item_outer_ref object is saved in the inner_refs_list of
5874 the outer select. Here it is only created. It can be fixed only
5875 after the original field has been fixed and this is done in the
5876 fix_inner_refs() function.
5877 */
5878 ;
5879 if (!(rf= new (thd->mem_root) Item_outer_ref(thd, context, this)))
5880 return -1;
5881 thd->change_item_tree(reference, rf);
5882 select->inner_refs_list.push_back(rf, thd->mem_root);
5883 rf->in_sum_func= thd->lex->in_sum_func;
5884 }
5885 /*
5886 A reference is resolved to a nest level that's outer or the same as
5887 the nest level of the enclosing set function : adjust the value of
5888 max_arg_level for the function if it's needed.
5889 */
5890 if (thd->lex->in_sum_func &&
5891 thd->lex->in_sum_func->nest_level >= select->nest_level)
5892 {
5893 Item::Type ref_type= (*reference)->type();
5894 set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5895 select->nest_level);
5896 set_field(*from_field);
5897 fixed= 1;
5898 mark_as_dependent(thd, last_checked_context->select_lex,
5899 context->select_lex, this,
5900 ((ref_type == REF_ITEM ||
5901 ref_type == FIELD_ITEM) ?
5902 (Item_ident*) (*reference) : 0));
5903 return 0;
5904 }
5905 }
5906 else
5907 {
5908 Item::Type ref_type= (*reference)->type();
5909 prev_subselect_item->used_tables_and_const_cache_join(*reference);
5910 mark_as_dependent(thd, last_checked_context->select_lex,
5911 context->select_lex, this,
5912 ((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ?
5913 (Item_ident*) (*reference) :
5914 0));
5915 if (thd->lex->in_sum_func &&
5916 thd->lex->in_sum_func->nest_level >= select->nest_level)
5917 {
5918 set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5919 select->nest_level);
5920 }
5921 /*
5922 A reference to a view field had been found and we
5923 substituted it instead of this Item (find_field_in_tables
5924 does it by assigning the new value to *reference), so now
5925 we can return from this function.
5926 */
5927 return 0;
5928 }
5929 }
5930 break;
5931 }
5932
5933 /* Search in SELECT and GROUP lists of the outer select. */
5934 if (place != IN_WHERE && place != IN_ON)
5935 {
5936 if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
5937 return -1; /* Some error occurred (e.g. ambiguous names). */
5938 if (ref != not_found_item)
5939 {
5940 DBUG_ASSERT(*ref && (*ref)->fixed);
5941 prev_subselect_item->used_tables_and_const_cache_join(*ref);
5942 break;
5943 }
5944 }
5945
5946 /*
5947 Reference is not found in this select => this subquery depend on
5948 outer select (or we just trying to find wrong identifier, in this
5949 case it does not matter which used tables bits we set)
5950 */
5951 prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
5952 prev_subselect_item->const_item_cache= 0;
5953 }
5954
5955 DBUG_ASSERT(ref != 0);
5956 if (!*from_field)
5957 return -1;
5958 if (ref == not_found_item && *from_field == not_found_field)
5959 {
5960 if (upward_lookup)
5961 {
5962 // We can't say exactly what absent table or field
5963 my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where);
5964 }
5965 else
5966 {
5967 /* Call find_field_in_tables only to report the error */
5968 find_field_in_tables(thd, this,
5969 context->first_name_resolution_table,
5970 context->last_name_resolution_table,
5971 reference, REPORT_ALL_ERRORS,
5972 !any_privileges, TRUE);
5973 }
5974 return -1;
5975 }
5976 else if (ref != not_found_item)
5977 {
5978 Item *save;
5979 Item_ref *rf;
5980
5981 /* Should have been checked in resolve_ref_in_select_and_group(). */
5982 DBUG_ASSERT(*ref && (*ref)->fixed);
5983 /*
5984 Here, a subset of actions performed by Item_ref::set_properties
5985 is not enough. So we pass ptr to NULL into Item_[direct]_ref
5986 constructor, so no initialization is performed, and call
5987 fix_fields() below.
5988 */
5989 save= *ref;
5990 *ref= NULL; // Don't call set_properties()
5991 rf= (place == IN_HAVING ?
5992 new (thd->mem_root)
5993 Item_ref(thd, context, ref, table_name,
5994 &field_name, alias_name_used) :
5995 (!select->group_list.elements ?
5996 new (thd->mem_root)
5997 Item_direct_ref(thd, context, ref, table_name,
5998 &field_name, alias_name_used) :
5999 new (thd->mem_root)
6000 Item_outer_ref(thd, context, ref, table_name,
6001 &field_name, alias_name_used)));
6002 *ref= save;
6003 if (!rf)
6004 return -1;
6005
6006 if (place != IN_HAVING && select->group_list.elements)
6007 {
6008 outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf,
6009 thd->mem_root);
6010 ((Item_outer_ref*)rf)->in_sum_func= thd->lex->in_sum_func;
6011 }
6012 thd->change_item_tree(reference, rf);
6013 /*
6014 rf is Item_ref => never substitute other items (in this case)
6015 during fix_fields() => we can use rf after fix_fields()
6016 */
6017 DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
6018 if (rf->fix_fields(thd, reference) || rf->check_cols(1))
6019 return -1;
6020
6021 /*
6022 We can not "move" aggregate function in the place where
6023 its arguments are not defined.
6024 */
6025 set_max_sum_func_level(thd, select);
6026 mark_as_dependent(thd, last_checked_context->select_lex,
6027 context->select_lex, rf,
6028 rf);
6029
6030 return 0;
6031 }
6032 else
6033 {
6034 /*
6035 We can not "move" aggregate function in the place where
6036 its arguments are not defined.
6037 */
6038 set_max_sum_func_level(thd, select);
6039 mark_as_dependent(thd, last_checked_context->select_lex,
6040 context->select_lex,
6041 this, (Item_ident*)*reference);
6042 if (last_checked_context->select_lex->having_fix_field)
6043 {
6044 Item_ref *rf;
6045 rf= new (thd->mem_root) Item_ref(thd, context,
6046 (*from_field)->table->s->db.str,
6047 (*from_field)->table->alias.c_ptr(),
6048 &field_name);
6049 if (!rf)
6050 return -1;
6051 thd->change_item_tree(reference, rf);
6052 /*
6053 rf is Item_ref => never substitute other items (in this case)
6054 during fix_fields() => we can use rf after fix_fields()
6055 */
6056 DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
6057 if (rf->fix_fields(thd, reference) || rf->check_cols(1))
6058 return -1;
6059 return 0;
6060 }
6061 }
6062 return 1;
6063}
6064
6065
6066/**
6067 Resolve the name of a column reference.
6068
6069 The method resolves the column reference represented by 'this' as a column
6070 present in one of: FROM clause, SELECT clause, GROUP BY clause of a query
6071 Q, or in outer queries that contain Q.
6072
6073 The name resolution algorithm used is (where [T_j] is an optional table
6074 name that qualifies the column name):
6075
6076 @code
6077 resolve_column_reference([T_j].col_ref_i)
6078 {
6079 search for a column or derived column named col_ref_i
6080 [in table T_j] in the FROM clause of Q;
6081
6082 if such a column is NOT found AND // Lookup in outer queries.
6083 there are outer queries
6084 {
6085 for each outer query Q_k beginning from the inner-most one
6086 {
6087 search for a column or derived column named col_ref_i
6088 [in table T_j] in the FROM clause of Q_k;
6089
6090 if such a column is not found
6091 Search for a column or derived column named col_ref_i
6092 [in table T_j] in the SELECT and GROUP clauses of Q_k.
6093 }
6094 }
6095 }
6096 @endcode
6097
6098 Notice that compared to Item_ref::fix_fields, here we first search the FROM
6099 clause, and then we search the SELECT and GROUP BY clauses.
6100
6101 @param[in] thd current thread
6102 @param[in,out] reference view column if this item was resolved to a
6103 view column
6104
6105 @retval
6106 TRUE if error
6107 @retval
6108 FALSE on success
6109*/
6110
6111bool Item_field::fix_fields(THD *thd, Item **reference)
6112{
6113 DBUG_ASSERT(fixed == 0);
6114 Field *from_field= (Field *)not_found_field;
6115 bool outer_fixed= false;
6116 SELECT_LEX *select= thd->lex->current_select;
6117
6118 if (select && select->in_tvc)
6119 {
6120 my_error(ER_FIELD_REFERENCE_IN_TVC, MYF(0), full_name());
6121 return(1);
6122 }
6123
6124 if (!field) // If field is not checked
6125 {
6126 TABLE_LIST *table_list;
6127 /*
6128 In case of view, find_field_in_tables() write pointer to view field
6129 expression to 'reference', i.e. it substitute that expression instead
6130 of this Item_field
6131 */
6132 DBUG_ASSERT(context);
6133 if ((from_field= find_field_in_tables(thd, this,
6134 context->first_name_resolution_table,
6135 context->last_name_resolution_table,
6136 reference,
6137 thd->lex->use_only_table_context ?
6138 REPORT_ALL_ERRORS :
6139 IGNORE_EXCEPT_NON_UNIQUE,
6140 !any_privileges,
6141 TRUE)) ==
6142 not_found_field)
6143 {
6144 int ret;
6145
6146 /* Look up in current select's item_list to find aliased fields */
6147 if (select && select->is_item_list_lookup)
6148 {
6149 uint counter;
6150 enum_resolution_type resolution;
6151 Item** res= find_item_in_list(this,
6152 select->item_list,
6153 &counter, REPORT_EXCEPT_NOT_FOUND,
6154 &resolution);
6155 if (!res)
6156 return 1;
6157 if (resolution == RESOLVED_AGAINST_ALIAS)
6158 alias_name_used= TRUE;
6159 if (res != (Item **)not_found_item)
6160 {
6161 if ((*res)->type() == Item::FIELD_ITEM)
6162 {
6163 /*
6164 It's an Item_field referencing another Item_field in the select
6165 list.
6166 Use the field from the Item_field in the select list and leave
6167 the Item_field instance in place.
6168 */
6169
6170 Field *new_field= (*((Item_field**)res))->field;
6171
6172 if (unlikely(new_field == NULL))
6173 {
6174 /* The column to which we link isn't valid. */
6175 my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->name.str,
6176 thd->where);
6177 return(1);
6178 }
6179
6180 /*
6181 We can not "move" aggregate function in the place where
6182 its arguments are not defined.
6183 */
6184 set_max_sum_func_level(thd, select);
6185 set_field(new_field);
6186 return 0;
6187 }
6188 else
6189 {
6190 /*
6191 It's not an Item_field in the select list so we must make a new
6192 Item_ref to point to the Item in the select list and replace the
6193 Item_field created by the parser with the new Item_ref.
6194 */
6195 Item_ref *rf= new (thd->mem_root)
6196 Item_ref(thd, context, db_name, table_name, &field_name);
6197 if (!rf)
6198 return 1;
6199 bool err= rf->fix_fields(thd, (Item **) &rf) || rf->check_cols(1);
6200 if (err)
6201 return TRUE;
6202
6203 thd->change_item_tree(reference,
6204 select->context_analysis_place == IN_GROUP_BY &&
6205 alias_name_used ? *rf->ref : rf);
6206
6207 /*
6208 We can not "move" aggregate function in the place where
6209 its arguments are not defined.
6210 */
6211 set_max_sum_func_level(thd, select);
6212 return FALSE;
6213 }
6214 }
6215 }
6216
6217 if (unlikely(!select))
6218 {
6219 my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where);
6220 goto error;
6221 }
6222 if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
6223 goto error;
6224 outer_fixed= TRUE;
6225 if (!ret)
6226 goto mark_non_agg_field;
6227 }
6228 else if (!from_field)
6229 goto error;
6230
6231 table_list= (cached_table ? cached_table :
6232 from_field != view_ref_found ?
6233 from_field->table->pos_in_table_list : 0);
6234 if (!outer_fixed && table_list && table_list->select_lex &&
6235 context->select_lex &&
6236 table_list->select_lex != context->select_lex &&
6237 !context->select_lex->is_merged_child_of(table_list->select_lex) &&
6238 is_outer_table(table_list, context->select_lex))
6239 {
6240 int ret;
6241 if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
6242 goto error;
6243 outer_fixed= 1;
6244 if (!ret)
6245 goto mark_non_agg_field;
6246 }
6247
6248 if (thd->lex->in_sum_func &&
6249 thd->lex->in_sum_func->nest_level ==
6250 select->nest_level)
6251 set_if_bigger(thd->lex->in_sum_func->max_arg_level,
6252 select->nest_level);
6253 /*
6254 if it is not expression from merged VIEW we will set this field.
6255
6256 We can leave expression substituted from view for next PS/SP rexecution
6257 (i.e. do not register this substitution for reverting on cleanup()
6258 (register_item_tree_changing())), because this subtree will be
6259 fix_field'ed during setup_tables()->setup_underlying() (i.e. before
6260 all other expressions of query, and references on tables which do
6261 not present in query will not make problems.
6262
6263 Also we suppose that view can't be changed during PS/SP life.
6264 */
6265 if (from_field == view_ref_found)
6266 return FALSE;
6267
6268 set_field(from_field);
6269 }
6270 else if (should_mark_column(thd->column_usage))
6271 {
6272 TABLE *table= field->table;
6273 MY_BITMAP *current_bitmap, *other_bitmap;
6274 if (thd->column_usage == MARK_COLUMNS_READ)
6275 {
6276 current_bitmap= table->read_set;
6277 other_bitmap= table->write_set;
6278 }
6279 else
6280 {
6281 current_bitmap= table->write_set;
6282 other_bitmap= table->read_set;
6283 }
6284 if (!bitmap_fast_test_and_set(current_bitmap, field->field_index))
6285 {
6286 if (!bitmap_is_set(other_bitmap, field->field_index))
6287 {
6288 /* First usage of column */
6289 table->used_fields++; // Used to optimize loops
6290 /* purecov: begin inspected */
6291 table->covering_keys.intersect(field->part_of_key);
6292 /* purecov: end */
6293 }
6294 }
6295 }
6296#ifndef NO_EMBEDDED_ACCESS_CHECKS
6297 if (any_privileges)
6298 {
6299 const char *db, *tab;
6300 db= field->table->s->db.str;
6301 tab= field->table->s->table_name.str;
6302 if (!(have_privileges= (get_column_grant(thd, &field->table->grant,
6303 db, tab, field_name.str) &
6304 VIEW_ANY_ACL)))
6305 {
6306 my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
6307 "ANY", thd->security_ctx->priv_user,
6308 thd->security_ctx->host_or_ip, field_name.str, tab);
6309 goto error;
6310 }
6311 }
6312#endif
6313 fixed= 1;
6314 if (field->vcol_info)
6315 fix_session_vcol_expr_for_read(thd, field, field->vcol_info);
6316 if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
6317 !outer_fixed && !thd->lex->in_sum_func &&
6318 select &&
6319 select->cur_pos_in_select_list != UNDEF_POS &&
6320 select->join)
6321 {
6322 select->join->non_agg_fields.push_back(this, thd->mem_root);
6323 marker= select->cur_pos_in_select_list;
6324 }
6325mark_non_agg_field:
6326 /*
6327 table->pos_in_table_list can be 0 when fixing partition functions
6328 or virtual fields.
6329 */
6330 if (fixed && (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY) &&
6331 field->table->pos_in_table_list)
6332 {
6333 /*
6334 Mark selects according to presence of non aggregated fields.
6335 Fields from outer selects added to the aggregate function
6336 outer_fields list as it's unknown at the moment whether it's
6337 aggregated or not.
6338 We're using the select lex of the cached table (if present).
6339 */
6340 SELECT_LEX *select_lex;
6341 if (cached_table)
6342 select_lex= cached_table->select_lex;
6343 else if (!(select_lex= field->table->pos_in_table_list->select_lex))
6344 {
6345 /*
6346 This can only happen when there is no real table in the query.
6347 We are using the field's resolution context. context->select_lex is eee
6348 safe for use because it's either the SELECT we want to use
6349 (the current level) or a stub added by non-SELECT queries.
6350 */
6351 select_lex= context->select_lex;
6352 }
6353 if (!thd->lex->in_sum_func)
6354 select_lex->set_non_agg_field_used(true);
6355 else
6356 {
6357 if (outer_fixed)
6358 thd->lex->in_sum_func->outer_fields.push_back(this, thd->mem_root);
6359 else if (thd->lex->in_sum_func->nest_level !=
6360 select->nest_level)
6361 select_lex->set_non_agg_field_used(true);
6362 }
6363 }
6364 return FALSE;
6365
6366error:
6367 context->process_error(thd);
6368 return TRUE;
6369}
6370
6371bool Item_field::post_fix_fields_part_expr_processor(void *int_arg)
6372{
6373 DBUG_ASSERT(fixed);
6374 if (field->vcol_info)
6375 field->vcol_info->mark_as_in_partitioning_expr();
6376 /*
6377 Update table_name to be real table name, not the alias. Because alias is
6378 reallocated for every statement, and this item has a long life time */
6379 table_name= field->table->s->table_name.str;
6380 return FALSE;
6381}
6382
6383bool Item_field::check_valid_arguments_processor(void *bool_arg)
6384{
6385 Virtual_column_info *vcol= field->vcol_info;
6386 if (!vcol)
6387 return FALSE;
6388 return vcol->expr->walk(&Item::check_partition_func_processor, 0, NULL)
6389 || vcol->expr->walk(&Item::check_valid_arguments_processor, 0, NULL);
6390}
6391
6392void Item_field::cleanup()
6393{
6394 DBUG_ENTER("Item_field::cleanup");
6395 Item_ident::cleanup();
6396 depended_from= NULL;
6397 /*
6398 Even if this object was created by direct link to field in setup_wild()
6399 it will be linked correctly next time by name of field and table alias.
6400 I.e. we can drop 'field'.
6401 */
6402 field= 0;
6403 item_equal= NULL;
6404 null_value= FALSE;
6405 DBUG_VOID_RETURN;
6406}
6407
6408/**
6409 Find a field among specified multiple equalities.
6410
6411 The function first searches the field among multiple equalities
6412 of the current level (in the cond_equal->current_level list).
6413 If it fails, it continues searching in upper levels accessed
6414 through a pointer cond_equal->upper_levels.
6415 The search terminates as soon as a multiple equality containing
6416 the field is found.
6417
6418 @param cond_equal reference to list of multiple equalities where
6419 the field (this object) is to be looked for
6420
6421 @return
6422 - First Item_equal containing the field, if success
6423 - 0, otherwise
6424*/
6425
6426Item_equal *Item_field::find_item_equal(COND_EQUAL *cond_equal)
6427{
6428 Item_equal *item= 0;
6429 while (cond_equal)
6430 {
6431 List_iterator_fast<Item_equal> li(cond_equal->current_level);
6432 while ((item= li++))
6433 {
6434 if (item->contains(field))
6435 return item;
6436 }
6437 /*
6438 The field is not found in any of the multiple equalities
6439 of the current level. Look for it in upper levels
6440 */
6441 cond_equal= cond_equal->upper_levels;
6442 }
6443 return 0;
6444}
6445
6446
6447/**
6448 Set a pointer to the multiple equality the field reference belongs to
6449 (if any).
6450
6451 The function looks for a multiple equality containing the field item
6452 among those referenced by arg.
6453 In the case such equality exists the function does the following.
6454 If the found multiple equality contains a constant, then the field
6455 reference is substituted for this constant, otherwise it sets a pointer
6456 to the multiple equality in the field item.
6457
6458
6459 @param arg reference to list of multiple equalities where
6460 the field (this object) is to be looked for
6461
6462 @note
6463 This function is supposed to be called as a callback parameter in calls
6464 of the compile method.
6465
6466 @return
6467 - pointer to the replacing constant item, if the field item was substituted
6468 - pointer to the field item, otherwise.
6469*/
6470
6471Item *Item_field::propagate_equal_fields(THD *thd,
6472 const Context &ctx,
6473 COND_EQUAL *arg)
6474{
6475 if (!(item_equal= find_item_equal(arg)))
6476 return this;
6477 if (!field->can_be_substituted_to_equal_item(ctx, item_equal))
6478 {
6479 item_equal= NULL;
6480 return this;
6481 }
6482 Item *item= item_equal->get_const();
6483 if (!item)
6484 {
6485 /*
6486 The found Item_equal is Okey, but it does not have a constant
6487 item yet. Keep this->item_equal point to the found Item_equal.
6488 */
6489 return this;
6490 }
6491 if (!(item= field->get_equal_const_item(thd, ctx, item)))
6492 {
6493 /*
6494 Could not do safe conversion from the original constant item
6495 to a field-compatible constant item.
6496 For example, we tried to optimize:
6497 WHERE date_column=' garbage ' AND LENGTH(date_column)=8;
6498 to
6499 WHERE date_column=' garbage ' AND LENGTH(DATE'XXXX-YY-ZZ');
6500 but failed to create a valid DATE literal from the given string literal.
6501
6502 Do not do constant propagation in such cases and unlink
6503 "this" from the found Item_equal (as this equality not usefull).
6504 */
6505 item_equal= NULL;
6506 return this;
6507 }
6508 return item;
6509}
6510
6511
6512/**
6513 Replace an Item_field for an equal Item_field that evaluated earlier
6514 (if any).
6515
6516 If this->item_equal points to some item and coincides with arg then
6517 the function returns a pointer to an item that is taken from
6518 the very beginning of the item_equal list which the Item_field
6519 object refers to (belongs to) unless item_equal contains a constant
6520 item. In this case the function returns this constant item,
6521 (if the substitution does not require conversion).
6522 If the Item_field object does not refer any Item_equal object
6523 'this' is returned .
6524
6525 @param arg NULL or points to so some item of the Item_equal type
6526
6527
6528 @note
6529 This function is supposed to be called as a callback parameter in calls
6530 of the transformer method.
6531
6532 @return
6533 - pointer to a replacement Item_field if there is a better equal item or
6534 a pointer to a constant equal item;
6535 - this - otherwise.
6536*/
6537
6538Item *Item_field::replace_equal_field(THD *thd, uchar *arg)
6539{
6540 REPLACE_EQUAL_FIELD_ARG* param= (REPLACE_EQUAL_FIELD_ARG*)arg;
6541 if (item_equal && item_equal == param->item_equal)
6542 {
6543 Item *const_item2= item_equal->get_const();
6544 if (const_item2)
6545 {
6546 /*
6547 Currently we don't allow to create Item_equal with compare_type()
6548 different from its Item_field's cmp_type().
6549 Field_xxx::test_if_equality_guarantees_uniqueness() prevent this.
6550 Also, Item_field::propagate_equal_fields() does not allow to assign
6551 this->item_equal to any instances of Item_equal if "this" is used
6552 in a non-native comparison context, or with an incompatible collation.
6553 So the fact that we have (item_equal != NULL) means that the currently
6554 processed function (the owner of "this") uses the field in its native
6555 comparison context, and it's safe to replace it to the constant from
6556 item_equal.
6557 */
6558 DBUG_ASSERT(type_handler()->type_handler_for_comparison()->cmp_type() ==
6559 item_equal->compare_type_handler()->cmp_type());
6560 return const_item2;
6561 }
6562 Item_field *subst=
6563 (Item_field *)(item_equal->get_first(param->context_tab, this));
6564 if (subst)
6565 subst= (Item_field *) (subst->real_item());
6566 if (subst && !field->eq(subst->field))
6567 return subst;
6568 }
6569 return this;
6570}
6571
6572
6573void Item::init_make_send_field(Send_field *tmp_field,
6574 enum enum_field_types field_type_arg)
6575{
6576 tmp_field->db_name= "";
6577 tmp_field->org_table_name= "";
6578 tmp_field->org_col_name= empty_clex_str;
6579 tmp_field->table_name= "";
6580 tmp_field->col_name= name;
6581 tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
6582 (my_binary_compare(charset_for_protocol()) ?
6583 BINARY_FLAG : 0);
6584 tmp_field->type= field_type_arg;
6585 tmp_field->length=max_length;
6586 tmp_field->decimals=decimals;
6587 if (unsigned_flag)
6588 tmp_field->flags |= UNSIGNED_FLAG;
6589}
6590
6591void Item::make_send_field(THD *thd, Send_field *tmp_field)
6592{
6593 init_make_send_field(tmp_field, field_type());
6594}
6595
6596
6597void Item_empty_string::make_send_field(THD *thd, Send_field *tmp_field)
6598{
6599 init_make_send_field(tmp_field, string_type_handler()->field_type());
6600}
6601
6602
6603/**
6604 Verifies that the input string is well-formed according to its character set.
6605 @param send_error If true, call my_error if string is not well-formed.
6606
6607 Will truncate input string if it is not well-formed.
6608
6609 @return
6610 If well-formed: input string.
6611 If not well-formed:
6612 if strict mode: NULL pointer and we set this Item's value to NULL
6613 if not strict mode: input string truncated up to last good character
6614 */
6615String *Item::check_well_formed_result(String *str, bool send_error)
6616{
6617 /* Check whether we got a well-formed string */
6618 CHARSET_INFO *cs= str->charset();
6619 uint wlen= str->well_formed_length();
6620 null_value= false;
6621 if (unlikely(wlen < str->length()))
6622 {
6623 THD *thd= current_thd;
6624 char hexbuf[7];
6625 uint diff= str->length() - wlen;
6626 set_if_smaller(diff, 3);
6627 octet2hex(hexbuf, str->ptr() + wlen, diff);
6628 if (send_error)
6629 {
6630 my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
6631 cs->csname, hexbuf);
6632 return 0;
6633 }
6634 if (thd->is_strict_mode())
6635 {
6636 null_value= 1;
6637 str= 0;
6638 }
6639 else
6640 {
6641 str->length(wlen);
6642 }
6643 push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN,
6644 ER_INVALID_CHARACTER_STRING,
6645 ER_THD(thd, ER_INVALID_CHARACTER_STRING), cs->csname,
6646 hexbuf);
6647 }
6648 return str;
6649}
6650
6651
6652/**
6653 Copy a string with optional character set conversion.
6654*/
6655bool
6656String_copier_for_item::copy_with_warn(CHARSET_INFO *dstcs, String *dst,
6657 CHARSET_INFO *srccs, const char *src,
6658 uint32 src_length, uint32 nchars)
6659{
6660 if (unlikely((dst->copy(dstcs, srccs, src, src_length, nchars, this))))
6661 return true; // EOM
6662 const char *pos;
6663 if (unlikely(pos= well_formed_error_pos()))
6664 {
6665 ErrConvString err(pos, src_length - (pos - src), &my_charset_bin);
6666 push_warning_printf(m_thd, Sql_condition::WARN_LEVEL_WARN,
6667 ER_INVALID_CHARACTER_STRING,
6668 ER_THD(m_thd, ER_INVALID_CHARACTER_STRING),
6669 srccs == &my_charset_bin ?
6670 dstcs->csname : srccs->csname,
6671 err.ptr());
6672 return false;
6673 }
6674 if (unlikely(pos= cannot_convert_error_pos()))
6675 {
6676 char buf[16];
6677 int mblen= my_charlen(srccs, pos, src + src_length);
6678 DBUG_ASSERT(mblen > 0 && mblen * 2 + 1 <= (int) sizeof(buf));
6679 octet2hex(buf, pos, mblen);
6680 push_warning_printf(m_thd, Sql_condition::WARN_LEVEL_WARN,
6681 ER_CANNOT_CONVERT_CHARACTER,
6682 ER_THD(m_thd, ER_CANNOT_CONVERT_CHARACTER),
6683 srccs->csname, buf, dstcs->csname);
6684 return false;
6685 }
6686 return false;
6687}
6688
6689
6690/*
6691 Compare two items using a given collation
6692
6693 SYNOPSIS
6694 eq_by_collation()
6695 item item to compare with
6696 binary_cmp TRUE <-> compare as binaries
6697 cs collation to use when comparing strings
6698
6699 DESCRIPTION
6700 This method works exactly as Item::eq if the collation cs coincides with
6701 the collation of the compared objects. Otherwise, first the collations that
6702 differ from cs are replaced for cs and then the items are compared by
6703 Item::eq. After the comparison the original collations of items are
6704 restored.
6705
6706 RETURN
6707 1 compared items has been detected as equal
6708 0 otherwise
6709*/
6710
6711bool Item::eq_by_collation(Item *item, bool binary_cmp, CHARSET_INFO *cs)
6712{
6713 CHARSET_INFO *save_cs= 0;
6714 CHARSET_INFO *save_item_cs= 0;
6715 if (collation.collation != cs)
6716 {
6717 save_cs= collation.collation;
6718 collation.collation= cs;
6719 }
6720 if (item->collation.collation != cs)
6721 {
6722 save_item_cs= item->collation.collation;
6723 item->collation.collation= cs;
6724 }
6725 bool res= eq(item, binary_cmp);
6726 if (save_cs)
6727 collation.collation= save_cs;
6728 if (save_item_cs)
6729 item->collation.collation= save_item_cs;
6730 return res;
6731}
6732
6733
6734/* ARGSUSED */
6735void Item_field::make_send_field(THD *thd, Send_field *tmp_field)
6736{
6737 field->make_send_field(tmp_field);
6738 DBUG_ASSERT(tmp_field->table_name != 0);
6739 if (name.str)
6740 {
6741 DBUG_ASSERT(name.length == strlen(name.str));
6742 tmp_field->col_name= name; // Use user supplied name
6743 }
6744 if (table_name)
6745 tmp_field->table_name= table_name;
6746 if (db_name)
6747 tmp_field->db_name= db_name;
6748}
6749
6750
6751/**
6752 Save a field value in another field
6753
6754 @param from Field to take the value from
6755 @param [out] null_value Pointer to the null_value flag to set
6756 @param to Field to save the value in
6757 @param no_conversions How to deal with NULL value
6758
6759 @details
6760 The function takes the value of the field 'from' and, if this value
6761 is not null, it saves in the field 'to' setting off the flag referenced
6762 by 'null_value'. Otherwise this flag is set on and field 'to' is
6763 also set to null possibly with conversion.
6764
6765 @note
6766 This function is used by the functions Item_field::save_in_field,
6767 Item_field::save_org_in_field and Item_ref::save_in_field
6768
6769 @retval FALSE OK
6770 @retval TRUE Error
6771
6772*/
6773
6774static int save_field_in_field(Field *from, bool *null_value,
6775 Field *to, bool no_conversions)
6776{
6777 int res;
6778 DBUG_ENTER("save_field_in_field");
6779 if (from->is_null())
6780 {
6781 (*null_value)= 1;
6782 DBUG_RETURN(set_field_to_null_with_conversions(to, no_conversions));
6783 }
6784 to->set_notnull();
6785
6786 /*
6787 If we're setting the same field as the one we're reading from there's
6788 nothing to do. This can happen in 'SET x = x' type of scenarios.
6789 */
6790 if (to == from)
6791 {
6792 (*null_value)= 0;
6793 DBUG_RETURN(0);
6794 }
6795
6796 res= field_conv(to, from);
6797 (*null_value)= 0;
6798 DBUG_RETURN(res);
6799}
6800
6801
6802fast_field_copier Item_field::setup_fast_field_copier(Field *to)
6803{
6804 return to->get_fast_field_copier(field);
6805}
6806
6807void Item_field::save_in_result_field(bool no_conversions)
6808{
6809 bool unused;
6810 save_field_in_field(field, &unused, result_field, no_conversions);
6811}
6812
6813/**
6814 Set a field's value from a item.
6815*/
6816
6817void Item_field::save_org_in_field(Field *to,
6818 fast_field_copier fast_field_copier_func)
6819{
6820 DBUG_ENTER("Item_field::save_org_in_field");
6821 DBUG_PRINT("enter", ("setup: %p data: %p",
6822 to, fast_field_copier_func));
6823 if (fast_field_copier_func)
6824 {
6825 if (field->is_null())
6826 {
6827 null_value= TRUE;
6828 set_field_to_null_with_conversions(to, TRUE);
6829 DBUG_VOID_RETURN;
6830 }
6831 to->set_notnull();
6832 if (to == field)
6833 {
6834 null_value= 0;
6835 DBUG_VOID_RETURN;
6836 }
6837 (*fast_field_copier_func)(to, field);
6838 }
6839 else
6840 save_field_in_field(field, &null_value, to, TRUE);
6841 DBUG_VOID_RETURN;
6842}
6843
6844
6845int Item_field::save_in_field(Field *to, bool no_conversions)
6846{
6847 return save_field_in_field(result_field, &null_value, to, no_conversions);
6848}
6849
6850
6851/**
6852 Store null in field.
6853
6854 This is used on INSERT.
6855 Allow NULL to be inserted in timestamp and auto_increment values.
6856
6857 @param field Field where we want to store NULL
6858
6859 @retval
6860 0 ok
6861 @retval
6862 1 Field doesn't support NULL values and can't handle 'field = NULL'
6863*/
6864
6865int Item_null::save_in_field(Field *field, bool no_conversions)
6866{
6867 return set_field_to_null_with_conversions(field, no_conversions);
6868}
6869
6870
6871/**
6872 Store null in field.
6873
6874 @param field Field where we want to store NULL
6875
6876 @retval
6877 0 OK
6878 @retval
6879 1 Field doesn't support NULL values
6880*/
6881
6882int Item_null::save_safe_in_field(Field *field)
6883{
6884 return set_field_to_null(field);
6885}
6886
6887
6888/*
6889 This implementation can lose str_value content, so if the
6890 Item uses str_value to store something, it should
6891 reimplement it's ::save_in_field() as Item_string, for example, does.
6892
6893 Note: all Item_XXX::val_str(str) methods must NOT assume that
6894 str != str_value. For example, see fix for bug #44743.
6895*/
6896int Item::save_str_in_field(Field *field, bool no_conversions)
6897{
6898 String *result;
6899 CHARSET_INFO *cs= collation.collation;
6900 char buff[MAX_FIELD_WIDTH]; // Alloc buffer for small columns
6901 str_value.set_quick(buff, sizeof(buff), cs);
6902 result=val_str(&str_value);
6903 if (null_value)
6904 {
6905 str_value.set_quick(0, 0, cs);
6906 return set_field_to_null_with_conversions(field, no_conversions);
6907 }
6908
6909 /* NOTE: If null_value == FALSE, "result" must be not NULL. */
6910
6911 field->set_notnull();
6912 int error= field->store(result->ptr(),result->length(),cs);
6913 str_value.set_quick(0, 0, cs);
6914 return error;
6915}
6916
6917
6918int Item::save_real_in_field(Field *field, bool no_conversions)
6919{
6920 double nr= val_real();
6921 if (null_value)
6922 return set_field_to_null_with_conversions(field, no_conversions);
6923 field->set_notnull();
6924 return field->store(nr);
6925}
6926
6927
6928int Item::save_decimal_in_field(Field *field, bool no_conversions)
6929{
6930 my_decimal decimal_value;
6931 my_decimal *value= val_decimal(&decimal_value);
6932 if (null_value)
6933 return set_field_to_null_with_conversions(field, no_conversions);
6934 field->set_notnull();
6935 return field->store_decimal(value);
6936}
6937
6938
6939int Item::save_int_in_field(Field *field, bool no_conversions)
6940{
6941 longlong nr= val_int();
6942 if (null_value)
6943 return set_field_to_null_with_conversions(field, no_conversions);
6944 field->set_notnull();
6945 return field->store(nr, unsigned_flag);
6946}
6947
6948
6949int Item::save_in_field(Field *field, bool no_conversions)
6950{
6951 int error= type_handler()->Item_save_in_field(this, field, no_conversions);
6952 return error ? error : (field->table->in_use->is_error() ? 1 : 0);
6953}
6954
6955
6956bool Item::save_in_param(THD *thd, Item_param *param)
6957{
6958 return param->set_from_item(thd, this);
6959}
6960
6961
6962int Item_string::save_in_field(Field *field, bool no_conversions)
6963{
6964 String *result;
6965 result=val_str(&str_value);
6966 return save_str_value_in_field(field, result);
6967}
6968
6969
6970Item *Item_string::clone_item(THD *thd)
6971{
6972 return new (thd->mem_root)
6973 Item_string(thd, name.str, str_value.ptr(),
6974 str_value.length(), collation.collation);
6975}
6976
6977
6978Item_basic_constant *
6979Item_string::make_string_literal_concat(THD *thd, const LEX_CSTRING *str)
6980{
6981 append(str->str, (uint32) str->length);
6982 if (!(collation.repertoire & MY_REPERTOIRE_EXTENDED))
6983 {
6984 // If the string has been pure ASCII so far, check the new part.
6985 CHARSET_INFO *cs= thd->variables.collation_connection;
6986 collation.repertoire|= my_string_repertoire(cs, str->str, str->length);
6987 }
6988 return this;
6989}
6990
6991
6992/*
6993 If "this" is a reasonably short pure ASCII string literal,
6994 try to parse known ODBC-style date, time or timestamp literals,
6995 e.g:
6996 SELECT {d'2001-01-01'};
6997 SELECT {t'10:20:30'};
6998 SELECT {ts'2001-01-01 10:20:30'};
6999*/
7000Item *Item_string::make_odbc_literal(THD *thd, const LEX_CSTRING *typestr)
7001{
7002 enum_field_types type= odbc_temporal_literal_type(typestr);
7003 Item *res= type == MYSQL_TYPE_STRING ? this :
7004 create_temporal_literal(thd, val_str(NULL), type, false);
7005 /*
7006 create_temporal_literal() returns NULL if failed to parse the string,
7007 or the string format did not match the type, e.g.: {d'2001-01-01 10:10:10'}
7008 */
7009 return res ? res : this;
7010}
7011
7012
7013static int save_int_value_in_field (Field *field, longlong nr,
7014 bool null_value, bool unsigned_flag)
7015{
7016 if (null_value)
7017 return set_field_to_null(field);
7018 field->set_notnull();
7019 return field->store(nr, unsigned_flag);
7020}
7021
7022
7023int Item_int::save_in_field(Field *field, bool no_conversions)
7024{
7025 return save_int_value_in_field (field, val_int(), null_value, unsigned_flag);
7026}
7027
7028
7029Item *Item_int::clone_item(THD *thd)
7030{
7031 return new (thd->mem_root) Item_int(thd, name.str, value, max_length, unsigned_flag);
7032}
7033
7034
7035void Item_datetime::set(longlong packed, enum_mysql_timestamp_type ts_type)
7036{
7037 unpack_time(packed, &ltime, ts_type);
7038}
7039
7040int Item_datetime::save_in_field(Field *field, bool no_conversions)
7041{
7042 field->set_notnull();
7043 return field->store_time_dec(&ltime, decimals);
7044}
7045
7046longlong Item_datetime::val_int()
7047{
7048 return TIME_to_ulonglong(&ltime);
7049}
7050
7051int Item_decimal::save_in_field(Field *field, bool no_conversions)
7052{
7053 field->set_notnull();
7054 return field->store_decimal(&decimal_value);
7055}
7056
7057
7058Item *Item_int_with_ref::clone_item(THD *thd)
7059{
7060 DBUG_ASSERT(ref->const_item());
7061 /*
7062 We need to evaluate the constant to make sure it works with
7063 parameter markers.
7064 */
7065 return (ref->unsigned_flag ?
7066 new (thd->mem_root)
7067 Item_uint(thd, ref->name.str, ref->val_int(), ref->max_length) :
7068 new (thd->mem_root)
7069 Item_int(thd, ref->name.str, ref->val_int(), ref->max_length));
7070}
7071
7072
7073Item *Item::neg(THD *thd)
7074{
7075 return new (thd->mem_root) Item_func_neg(thd, this);
7076}
7077
7078Item *Item_int::neg(THD *thd)
7079{
7080 /*
7081 The following if should never be true with code generated by
7082 our parser as LONGLONG_MIN values will be stored as decimal.
7083 The code is here in case someone generates an int from inside
7084 MariaDB
7085 */
7086 if (unlikely(value == LONGLONG_MIN))
7087 {
7088 /* Precision for int not big enough; Convert constant to decimal */
7089 Item_decimal *item= new (thd->mem_root) Item_decimal(thd, value, 0);
7090 return item ? item->neg(thd) : item;
7091 }
7092 if (value > 0)
7093 max_length++;
7094 else if (value < 0 && max_length)
7095 max_length--;
7096 value= -value;
7097 name= null_clex_str;
7098 return this;
7099}
7100
7101Item *Item_decimal::neg(THD *thd)
7102{
7103 my_decimal_neg(&decimal_value);
7104 unsigned_flag= 0;
7105 name= null_clex_str;
7106 max_length= my_decimal_precision_to_length_no_truncation(
7107 decimal_value.intg + decimals, decimals, unsigned_flag);
7108 return this;
7109}
7110
7111Item *Item_float::neg(THD *thd)
7112{
7113 if (value > 0)
7114 max_length++;
7115 else if (value < 0 && max_length)
7116 max_length--;
7117 value= -value;
7118 presentation= 0;
7119 name= null_clex_str;
7120 return this;
7121}
7122
7123Item *Item_uint::neg(THD *thd)
7124{
7125 Item_decimal *item;
7126 if (((ulonglong)value) <= LONGLONG_MAX)
7127 return new (thd->mem_root) Item_int(thd, -value, max_length+1);
7128 if (value == LONGLONG_MIN)
7129 return new (thd->mem_root) Item_int(thd, value, max_length+1);
7130 if (!(item= new (thd->mem_root) Item_decimal(thd, value, 1)))
7131 return 0;
7132 return item->neg(thd);
7133}
7134
7135
7136Item *Item_uint::clone_item(THD *thd)
7137{
7138 return new (thd->mem_root) Item_uint(thd, name.str, value, max_length);
7139}
7140
7141static uint nr_of_decimals(const char *str, const char *end)
7142{
7143 const char *decimal_point;
7144
7145 /* Find position for '.' */
7146 for (;;)
7147 {
7148 if (str == end)
7149 return 0;
7150 if (*str == 'e' || *str == 'E')
7151 return NOT_FIXED_DEC;
7152 if (*str++ == '.')
7153 break;
7154 }
7155 decimal_point= str;
7156 for ( ; str < end && my_isdigit(system_charset_info, *str) ; str++)
7157 ;
7158 if (str < end && (*str == 'e' || *str == 'E'))
7159 return NOT_FIXED_DEC;
7160 /*
7161 QQ:
7162 The number of decimal digist in fact should be (str - decimal_point - 1).
7163 But it seems the result of nr_of_decimals() is never used!
7164
7165 In case of 'e' and 'E' nr_of_decimals returns NOT_FIXED_DEC.
7166 In case if there is no 'e' or 'E' parser code in sql_yacc.yy
7167 never calls Item_float::Item_float() - it creates Item_decimal instead.
7168
7169 The only piece of code where we call Item_float::Item_float(str, len)
7170 without having 'e' or 'E' is item_xmlfunc.cc, but this Item_float
7171 never appears in metadata itself. Changing the code to return
7172 (str - decimal_point - 1) does not make any changes in the test results.
7173
7174 This should be addressed somehow.
7175 Looks like a reminder from before real DECIMAL times.
7176 */
7177 return (uint) (str - decimal_point);
7178}
7179
7180
7181/**
7182 This function is only called during parsing:
7183 - when parsing SQL query from sql_yacc.yy
7184 - when parsing XPath query from item_xmlfunc.cc
7185 We will signal an error if value is not a true double value (overflow):
7186 eng: Illegal %s '%-.192s' value found during parsing
7187
7188 Note: the string is NOT null terminated when called from item_xmlfunc.cc,
7189 so this->name will contain some SQL query tail behind the "length" bytes.
7190 This is Ok for now, as this Item is never seen in SHOW,
7191 or EXPLAIN, or anywhere else in metadata.
7192 Item->name should be fixed to use LEX_STRING eventually.
7193*/
7194
7195Item_float::Item_float(THD *thd, const char *str_arg, size_t length):
7196 Item_num(thd)
7197{
7198 int error;
7199 char *end_not_used;
7200 value= my_strntod(&my_charset_bin, (char*) str_arg, length, &end_not_used,
7201 &error);
7202 if (unlikely(error))
7203 {
7204 char tmp[NAME_LEN + 1];
7205 my_snprintf(tmp, sizeof(tmp), "%.*s", (int)length, str_arg);
7206 my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", tmp);
7207 }
7208 presentation= name.str= str_arg;
7209 name.length= strlen(str_arg);
7210 decimals=(uint8) nr_of_decimals(str_arg, str_arg+length);
7211 max_length=(uint32)length;
7212 fixed= 1;
7213}
7214
7215
7216int Item_float::save_in_field(Field *field, bool no_conversions)
7217{
7218 double nr= val_real();
7219 if (null_value)
7220 return set_field_to_null(field);
7221 field->set_notnull();
7222 return field->store(nr);
7223}
7224
7225
7226void Item_float::print(String *str, enum_query_type query_type)
7227{
7228 if (presentation)
7229 {
7230 str->append(presentation);
7231 return;
7232 }
7233 char buffer[20];
7234 String num(buffer, sizeof(buffer), &my_charset_bin);
7235 num.set_real(value, decimals, &my_charset_bin);
7236 str->append(num);
7237}
7238
7239
7240inline uint char_val(char X)
7241{
7242 return (uint) (X >= '0' && X <= '9' ? X-'0' :
7243 X >= 'A' && X <= 'Z' ? X-'A'+10 :
7244 X-'a'+10);
7245}
7246
7247
7248void Item_hex_constant::hex_string_init(THD *thd, const char *str, size_t str_length)
7249{
7250 max_length=(uint)((str_length+1)/2);
7251 char *ptr=(char*) thd->alloc(max_length+1);
7252 if (!ptr)
7253 {
7254 str_value.set("", 0, &my_charset_bin);
7255 return;
7256 }
7257 str_value.set(ptr,max_length,&my_charset_bin);
7258 char *end=ptr+max_length;
7259 if (max_length*2 != str_length)
7260 *ptr++=char_val(*str++); // Not even, assume 0 prefix
7261 while (ptr != end)
7262 {
7263 *ptr++= (char) (char_val(str[0])*16+char_val(str[1]));
7264 str+=2;
7265 }
7266 *ptr=0; // Keep purify happy
7267 collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
7268 fixed= 1;
7269 unsigned_flag= 1;
7270}
7271
7272
7273void Item_hex_hybrid::print(String *str, enum_query_type query_type)
7274{
7275 uint32 len= MY_MIN(str_value.length(), sizeof(longlong));
7276 const char *ptr= str_value.ptr() + str_value.length() - len;
7277 str->append("0x");
7278 str->append_hex(ptr, len);
7279}
7280
7281
7282uint Item_hex_hybrid::decimal_precision() const
7283{
7284 switch (max_length) {// HEX DEC
7285 case 0: // ---- ---
7286 case 1: return 3; // 0xFF 255
7287 case 2: return 5; // 0xFFFF 65535
7288 case 3: return 8; // 0xFFFFFF 16777215
7289 case 4: return 10; // 0xFFFFFFFF 4294967295
7290 case 5: return 13; // 0xFFFFFFFFFF 1099511627775
7291 case 6: return 15; // 0xFFFFFFFFFFFF 281474976710655
7292 case 7: return 17; // 0xFFFFFFFFFFFFFF 72057594037927935
7293 }
7294 return 20; // 0xFFFFFFFFFFFFFFFF 18446744073709551615
7295}
7296
7297
7298void Item_hex_string::print(String *str, enum_query_type query_type)
7299{
7300 str->append("X'");
7301 str->append_hex(str_value.ptr(), str_value.length());
7302 str->append("'");
7303}
7304
7305
7306/*
7307 bin item.
7308 In string context this is a binary string.
7309 In number context this is a longlong value.
7310*/
7311
7312Item_bin_string::Item_bin_string(THD *thd, const char *str, size_t str_length):
7313 Item_hex_hybrid(thd)
7314{
7315 const char *end= str + str_length - 1;
7316 char *ptr;
7317 uchar bits= 0;
7318 uint power= 1;
7319
7320 max_length= (uint)((str_length + 7) >> 3);
7321 if (!(ptr= (char*) thd->alloc(max_length + 1)))
7322 return;
7323 str_value.set(ptr, max_length, &my_charset_bin);
7324
7325 if (max_length > 0)
7326 {
7327 ptr+= max_length - 1;
7328 ptr[1]= 0; // Set end null for string
7329 for (; end >= str; end--)
7330 {
7331 if (power == 256)
7332 {
7333 power= 1;
7334 *ptr--= bits;
7335 bits= 0;
7336 }
7337 if (*end == '1')
7338 bits|= power;
7339 power<<= 1;
7340 }
7341 *ptr= (char) bits;
7342 }
7343 else
7344 ptr[0]= 0;
7345
7346 collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
7347 fixed= 1;
7348}
7349
7350
7351bool Item_temporal_literal::eq(const Item *item, bool binary_cmp) const
7352{
7353 return
7354 item->basic_const_item() && type() == item->type() &&
7355 field_type() == ((Item_temporal_literal *) item)->field_type() &&
7356 !my_time_compare(&cached_time,
7357 &((Item_temporal_literal *) item)->cached_time);
7358}
7359
7360void Item_date_literal::print(String *str, enum_query_type query_type)
7361{
7362 str->append("DATE'");
7363 char buf[MAX_DATE_STRING_REP_LENGTH];
7364 my_date_to_str(&cached_time, buf);
7365 str->append(buf);
7366 str->append('\'');
7367}
7368
7369
7370Item *Item_date_literal::clone_item(THD *thd)
7371{
7372 return new (thd->mem_root) Item_date_literal(thd, &cached_time);
7373}
7374
7375
7376bool Item_date_literal::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
7377{
7378 DBUG_ASSERT(fixed);
7379 fuzzy_date |= sql_mode_for_dates(current_thd);
7380 *ltime= cached_time;
7381 return (null_value= check_date_with_warn(ltime, fuzzy_date,
7382 MYSQL_TIMESTAMP_ERROR));
7383}
7384
7385
7386void Item_datetime_literal::print(String *str, enum_query_type query_type)
7387{
7388 str->append("TIMESTAMP'");
7389 char buf[MAX_DATE_STRING_REP_LENGTH];
7390 my_datetime_to_str(&cached_time, buf, decimals);
7391 str->append(buf);
7392 str->append('\'');
7393}
7394
7395
7396Item *Item_datetime_literal::clone_item(THD *thd)
7397{
7398 return new (thd->mem_root) Item_datetime_literal(thd, &cached_time, decimals);
7399}
7400
7401
7402bool Item_datetime_literal::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
7403{
7404 DBUG_ASSERT(fixed);
7405 fuzzy_date |= sql_mode_for_dates(current_thd);
7406 *ltime= cached_time;
7407 return (null_value= check_date_with_warn(ltime, fuzzy_date,
7408 MYSQL_TIMESTAMP_ERROR));
7409}
7410
7411
7412void Item_time_literal::print(String *str, enum_query_type query_type)
7413{
7414 str->append("TIME'");
7415 char buf[MAX_DATE_STRING_REP_LENGTH];
7416 my_time_to_str(&cached_time, buf, decimals);
7417 str->append(buf);
7418 str->append('\'');
7419}
7420
7421
7422Item *Item_time_literal::clone_item(THD *thd)
7423{
7424 return new (thd->mem_root) Item_time_literal(thd, &cached_time, decimals);
7425}
7426
7427
7428bool Item_time_literal::get_date(MYSQL_TIME *ltime, ulonglong fuzzy_date)
7429{
7430 DBUG_ASSERT(fixed);
7431 *ltime= cached_time;
7432 if (fuzzy_date & TIME_TIME_ONLY)
7433 return (null_value= false);
7434 return (null_value= check_date_with_warn(ltime, fuzzy_date,
7435 MYSQL_TIMESTAMP_ERROR));
7436}
7437
7438
7439
7440/**
7441 Pack data in buffer for sending.
7442*/
7443
7444bool Item_null::send(Protocol *protocol, st_value *buffer)
7445{
7446 return protocol->store_null();
7447}
7448
7449
7450/**
7451 Check if an item is a constant one and can be cached.
7452
7453 @param arg [out] TRUE <=> Cache this item.
7454
7455 @return TRUE Go deeper in item tree.
7456 @return FALSE Don't go deeper in item tree.
7457*/
7458
7459bool Item::cache_const_expr_analyzer(uchar **arg)
7460{
7461 bool *cache_flag= (bool*)*arg;
7462 if (!*cache_flag)
7463 {
7464 Item *item= real_item();
7465 /*
7466 Cache constant items unless it's a basic constant, constant field or
7467 a subselect (they use their own cache).
7468 */
7469 if (const_item() &&
7470 !(basic_const_item() || item->basic_const_item() ||
7471 item->type() == Item::NULL_ITEM || /* Item_name_const hack */
7472 item->type() == Item::FIELD_ITEM ||
7473 item->type() == SUBSELECT_ITEM ||
7474 item->type() == CACHE_ITEM ||
7475 /*
7476 Do not cache GET_USER_VAR() function as its const_item() may
7477 return TRUE for the current thread but it still may change
7478 during the execution.
7479 */
7480 (item->type() == Item::FUNC_ITEM &&
7481 ((Item_func*)item)->functype() == Item_func::GUSERVAR_FUNC)))
7482 *cache_flag= TRUE;
7483 return TRUE;
7484 }
7485 return FALSE;
7486}
7487
7488
7489/**
7490 Cache item if needed.
7491
7492 @param arg TRUE <=> Cache this item.
7493
7494 @return cache if cache needed.
7495 @return this otherwise.
7496*/
7497
7498Item* Item::cache_const_expr_transformer(THD *thd, uchar *arg)
7499{
7500 if (*(bool*)arg)
7501 {
7502 *((bool*)arg)= FALSE;
7503 Item_cache *cache= get_cache(thd);
7504 if (!cache)
7505 return NULL;
7506 cache->setup(thd, this);
7507 cache->store(this);
7508 return cache;
7509 }
7510 return this;
7511}
7512
7513/**
7514 Find Item by reference in the expression
7515*/
7516bool Item::find_item_processor(void *arg)
7517{
7518 return (this == ((Item *) arg));
7519}
7520
7521bool Item_field::send(Protocol *protocol, st_value *buffer)
7522{
7523 return protocol->store(result_field);
7524}
7525
7526
7527Item* Item::propagate_equal_fields_and_change_item_tree(THD *thd,
7528 const Context &ctx,
7529 COND_EQUAL *cond,
7530 Item **place)
7531{
7532 Item *item= propagate_equal_fields(thd, ctx, cond);
7533 if (item && item != this)
7534 thd->change_item_tree(place, item);
7535 return item;
7536}
7537
7538
7539void Item_field::update_null_value()
7540{
7541 /*
7542 need to set no_errors to prevent warnings about type conversion
7543 popping up.
7544 */
7545 THD *thd= field->table->in_use;
7546 int no_errors;
7547
7548 no_errors= thd->no_errors;
7549 thd->no_errors= 1;
7550 Item::update_null_value();
7551 thd->no_errors= no_errors;
7552}
7553
7554
7555/*
7556 Add the field to the select list and substitute it for the reference to
7557 the field.
7558
7559 SYNOPSIS
7560 Item_field::update_value_transformer()
7561 select_arg current select
7562
7563 DESCRIPTION
7564 If the field doesn't belong to the table being inserted into then it is
7565 added to the select list, pointer to it is stored in the ref_pointer_array
7566 of the select and the field itself is substituted for the Item_ref object.
7567 This is done in order to get correct values from update fields that
7568 belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY
7569 UPDATE statement.
7570
7571 RETURN
7572 0 if error occurred
7573 ref if all conditions are met
7574 this field otherwise
7575*/
7576
7577Item *Item_field::update_value_transformer(THD *thd, uchar *select_arg)
7578{
7579 SELECT_LEX *select= (SELECT_LEX*)select_arg;
7580 DBUG_ASSERT(fixed);
7581
7582 if (field->table != select->context.table_list->table &&
7583 type() != Item::TRIGGER_FIELD_ITEM)
7584 {
7585 List<Item> *all_fields= &select->join->all_fields;
7586 Ref_ptr_array &ref_pointer_array= select->ref_pointer_array;
7587 int el= all_fields->elements;
7588 Item_ref *ref;
7589
7590 ref_pointer_array[el]= (Item*)this;
7591 all_fields->push_front((Item*)this, thd->mem_root);
7592 ref= new (thd->mem_root)
7593 Item_ref(thd, &select->context, &ref_pointer_array[el],
7594 table_name, &field_name);
7595 return ref;
7596 }
7597 return this;
7598}
7599
7600
7601static
7602Item *get_field_item_for_having(THD *thd, Item *item, st_select_lex *sel)
7603{
7604 DBUG_ASSERT(item->type() == Item::FIELD_ITEM ||
7605 (item->type() == Item::REF_ITEM &&
7606 ((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF));
7607 Item_field *field_item= NULL;
7608 table_map map= sel->master_unit()->derived->table->map;
7609 Item_equal *item_equal= item->get_item_equal();
7610 if (!item_equal)
7611 field_item= (Item_field *)(item->real_item());
7612 else
7613 {
7614 Item_equal_fields_iterator li(*item_equal);
7615 Item *equal_item;
7616 while ((equal_item= li++))
7617 {
7618 if (equal_item->used_tables() == map)
7619 {
7620 field_item= (Item_field *)(equal_item->real_item());
7621 break;
7622 }
7623 }
7624 }
7625 if (field_item)
7626 {
7627 Item_ref *ref= new (thd->mem_root) Item_ref(thd, &sel->context,
7628 NullS, NullS,
7629 &field_item->field_name);
7630 return ref;
7631 }
7632 DBUG_ASSERT(0);
7633 return NULL;
7634}
7635
7636
7637Item *Item_field::derived_field_transformer_for_having(THD *thd, uchar *arg)
7638{
7639 st_select_lex *sel= (st_select_lex *)arg;
7640 table_map tab_map= sel->master_unit()->derived->table->map;
7641 if (item_equal && !(item_equal->used_tables() & tab_map))
7642 return this;
7643 if (!item_equal && used_tables() != tab_map)
7644 return this;
7645 return get_field_item_for_having(thd, this, sel);
7646}
7647
7648
7649Item *Item_direct_view_ref::derived_field_transformer_for_having(THD *thd,
7650 uchar *arg)
7651{
7652 st_select_lex *sel= (st_select_lex *)arg;
7653 table_map tab_map= sel->master_unit()->derived->table->map;
7654 if ((item_equal && !(item_equal->used_tables() & tab_map)) ||
7655 !item_equal)
7656 return this;
7657 return get_field_item_for_having(thd, this, sel);
7658}
7659
7660
7661static
7662Item *find_producing_item(Item *item, st_select_lex *sel)
7663{
7664 DBUG_ASSERT(item->type() == Item::FIELD_ITEM ||
7665 (item->type() == Item::REF_ITEM &&
7666 ((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF));
7667 Item *producing_item;
7668 Item_field *field_item= NULL;
7669 Item_equal *item_equal= item->get_item_equal();
7670 table_map tab_map= sel->master_unit()->derived->table->map;
7671 if (item->used_tables() == tab_map)
7672 field_item= (Item_field *) (item->real_item());
7673 if (!field_item && item_equal)
7674 {
7675 Item_equal_fields_iterator it(*item_equal);
7676 Item *equal_item;
7677 while ((equal_item= it++))
7678 {
7679 if (equal_item->used_tables() == tab_map)
7680 {
7681 field_item= (Item_field *) (equal_item->real_item());
7682 break;
7683 }
7684 }
7685 }
7686 List_iterator_fast<Item> li(sel->item_list);
7687 if (field_item)
7688 {
7689 uint field_no= field_item->field->field_index;
7690 for (uint i= 0; i <= field_no; i++)
7691 producing_item= li++;
7692 return producing_item;
7693 }
7694 return NULL;
7695}
7696
7697Item *Item_field::derived_field_transformer_for_where(THD *thd, uchar *arg)
7698{
7699 st_select_lex *sel= (st_select_lex *)arg;
7700 Item *producing_item= find_producing_item(this, sel);
7701 if (producing_item)
7702 return producing_item->build_clone(thd);
7703 return this;
7704}
7705
7706Item *Item_direct_view_ref::derived_field_transformer_for_where(THD *thd,
7707 uchar *arg)
7708{
7709 if (item_equal)
7710 {
7711 st_select_lex *sel= (st_select_lex *)arg;
7712 Item *producing_item= find_producing_item(this, sel);
7713 DBUG_ASSERT (producing_item != NULL);
7714 return producing_item->build_clone(thd);
7715 }
7716 return this;
7717}
7718
7719static
7720Grouping_tmp_field *find_matching_grouping_field(Item *item,
7721 st_select_lex *sel)
7722{
7723 DBUG_ASSERT(item->type() == Item::FIELD_ITEM ||
7724 (item->type() == Item::REF_ITEM &&
7725 ((Item_ref *) item)->ref_type() == Item_ref::VIEW_REF));
7726 List_iterator<Grouping_tmp_field> li(sel->grouping_tmp_fields);
7727 Grouping_tmp_field *gr_field;
7728 Item_field *field_item= (Item_field *) (item->real_item());
7729 while ((gr_field= li++))
7730 {
7731 if (field_item->field == gr_field->tmp_field)
7732 return gr_field;
7733 }
7734 Item_equal *item_equal= item->get_item_equal();
7735 if (item_equal)
7736 {
7737 Item_equal_fields_iterator it(*item_equal);
7738 Item *equal_item;
7739 while ((equal_item= it++))
7740 {
7741 field_item= (Item_field *) (equal_item->real_item());
7742 li.rewind();
7743 while ((gr_field= li++))
7744 {
7745 if (field_item->field == gr_field->tmp_field)
7746 return gr_field;
7747 }
7748 }
7749 }
7750 return NULL;
7751}
7752
7753
7754Item *Item_field::derived_grouping_field_transformer_for_where(THD *thd,
7755 uchar *arg)
7756{
7757 st_select_lex *sel= (st_select_lex *)arg;
7758 Grouping_tmp_field *gr_field= find_matching_grouping_field(this, sel);
7759 if (gr_field)
7760 return gr_field->producing_item->build_clone(thd);
7761 return this;
7762}
7763
7764
7765Item *
7766Item_direct_view_ref::derived_grouping_field_transformer_for_where(THD *thd,
7767 uchar *arg)
7768{
7769 if (!item_equal)
7770 return this;
7771 st_select_lex *sel= (st_select_lex *)arg;
7772 Grouping_tmp_field *gr_field= find_matching_grouping_field(this, sel);
7773 return gr_field->producing_item->build_clone(thd);
7774}
7775
7776void Item_field::print(String *str, enum_query_type query_type)
7777{
7778 if (field && field->table->const_table &&
7779 !(query_type & QT_NO_DATA_EXPANSION))
7780 {
7781 print_value(str);
7782 return;
7783 }
7784 Item_ident::print(str, query_type);
7785}
7786
7787
7788void Item_temptable_field::print(String *str, enum_query_type query_type)
7789{
7790 /*
7791 Item_ident doesn't have references to the underlying Field/TABLE objects,
7792 so it's ok to use the following:
7793 */
7794 Item_ident::print(str, query_type);
7795}
7796
7797
7798Item_ref::Item_ref(THD *thd, Name_resolution_context *context_arg,
7799 Item **item, const char *table_name_arg,
7800 const LEX_CSTRING *field_name_arg,
7801 bool alias_name_used_arg):
7802 Item_ident(thd, context_arg, NullS, table_name_arg, field_name_arg),
7803 ref(item), reference_trough_name(0)
7804{
7805 alias_name_used= alias_name_used_arg;
7806 /*
7807 This constructor used to create some internals references over fixed items
7808 */
7809 if ((set_properties_only= (ref && *ref && (*ref)->fixed)))
7810 set_properties();
7811}
7812
7813/*
7814 A Field_enumerator-compatible class that invokes mark_as_dependent() for
7815 each field that is a reference to some ancestor of current_select.
7816*/
7817class Dependency_marker: public Field_enumerator
7818{
7819public:
7820 THD *thd;
7821 st_select_lex *current_select;
7822 virtual void visit_field(Item_field *item)
7823 {
7824 // Find which select the field is in. This is achieved by walking up
7825 // the select tree and looking for the table of interest.
7826 st_select_lex *sel;
7827 for (sel= current_select;
7828 sel ;
7829 sel= (sel->context.outer_context ?
7830 sel->context.outer_context->select_lex:
7831 NULL))
7832 {
7833 List_iterator<TABLE_LIST> li(sel->leaf_tables);
7834 TABLE_LIST *tbl;
7835 while ((tbl= li++))
7836 {
7837 if (tbl->table == item->field->table)
7838 {
7839 if (sel != current_select)
7840 mark_as_dependent(thd, sel, current_select, item, item);
7841 return;
7842 }
7843 }
7844 }
7845 }
7846};
7847
7848Item_ref::Item_ref(THD *thd, TABLE_LIST *view_arg, Item **item,
7849 const LEX_CSTRING *field_name_arg,
7850 bool alias_name_used_arg):
7851 Item_ident(thd, view_arg, field_name_arg),
7852 ref(item), reference_trough_name(0)
7853{
7854 alias_name_used= alias_name_used_arg;
7855 /*
7856 This constructor is used to create some internal references over fixed items
7857 */
7858 if ((set_properties_only= (ref && *ref && (*ref)->fixed)))
7859 set_properties();
7860}
7861
7862
7863/**
7864 Resolve the name of a reference to a column reference.
7865
7866 The method resolves the column reference represented by 'this' as a column
7867 present in one of: GROUP BY clause, SELECT clause, outer queries. It is
7868 used typically for columns in the HAVING clause which are not under
7869 aggregate functions.
7870
7871 POSTCONDITION @n
7872 Item_ref::ref is 0 or points to a valid item.
7873
7874 @note
7875 The name resolution algorithm used is (where [T_j] is an optional table
7876 name that qualifies the column name):
7877
7878 @code
7879 resolve_extended([T_j].col_ref_i)
7880 {
7881 Search for a column or derived column named col_ref_i [in table T_j]
7882 in the SELECT and GROUP clauses of Q.
7883
7884 if such a column is NOT found AND // Lookup in outer queries.
7885 there are outer queries
7886 {
7887 for each outer query Q_k beginning from the inner-most one
7888 {
7889 Search for a column or derived column named col_ref_i
7890 [in table T_j] in the SELECT and GROUP clauses of Q_k.
7891
7892 if such a column is not found AND
7893 - Q_k is not a group query AND
7894 - Q_k is not inside an aggregate function
7895 OR
7896 - Q_(k-1) is not in a HAVING or SELECT clause of Q_k
7897 {
7898 search for a column or derived column named col_ref_i
7899 [in table T_j] in the FROM clause of Q_k;
7900 }
7901 }
7902 }
7903 }
7904 @endcode
7905 @n
7906 This procedure treats GROUP BY and SELECT clauses as one namespace for
7907 column references in HAVING. Notice that compared to
7908 Item_field::fix_fields, here we first search the SELECT and GROUP BY
7909 clauses, and then we search the FROM clause.
7910
7911 @param[in] thd current thread
7912 @param[in,out] reference view column if this item was resolved to a
7913 view column
7914
7915 @todo
7916 Here we could first find the field anyway, and then test this
7917 condition, so that we can give a better error message -
7918 ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
7919 ER_BAD_FIELD_ERROR which we produce now.
7920
7921 @retval
7922 TRUE if error
7923 @retval
7924 FALSE on success
7925*/
7926
7927bool Item_ref::fix_fields(THD *thd, Item **reference)
7928{
7929 enum_parsing_place place= NO_MATTER;
7930 DBUG_ASSERT(fixed == 0);
7931 SELECT_LEX *current_sel= thd->lex->current_select;
7932
7933 if (set_properties_only)
7934 {
7935 /* do nothing */
7936 }
7937 else if (!ref || ref == not_found_item)
7938 {
7939 DBUG_ASSERT(reference_trough_name != 0);
7940 if (!(ref= resolve_ref_in_select_and_group(thd, this,
7941 context->select_lex)))
7942 goto error; /* Some error occurred (e.g. ambiguous names). */
7943
7944 if (ref == not_found_item) /* This reference was not resolved. */
7945 {
7946 Name_resolution_context *last_checked_context= context;
7947 Name_resolution_context *outer_context= context->outer_context;
7948 Field *from_field;
7949 ref= 0;
7950
7951 if (unlikely(!outer_context))
7952 {
7953 /* The current reference cannot be resolved in this query. */
7954 my_error(ER_BAD_FIELD_ERROR,MYF(0),
7955 this->full_name(), thd->where);
7956 goto error;
7957 }
7958
7959 /*
7960 If there is an outer context (select), and it is not a derived table
7961 (which do not support the use of outer fields for now), try to
7962 resolve this reference in the outer select(s).
7963
7964 We treat each subselect as a separate namespace, so that different
7965 subselects may contain columns with the same names. The subselects are
7966 searched starting from the innermost.
7967 */
7968 from_field= (Field*) not_found_field;
7969
7970 do
7971 {
7972 SELECT_LEX *select= outer_context->select_lex;
7973 Item_subselect *prev_subselect_item=
7974 last_checked_context->select_lex->master_unit()->item;
7975 last_checked_context= outer_context;
7976
7977 /* Search in the SELECT and GROUP lists of the outer select. */
7978 if (outer_context->resolve_in_select_list)
7979 {
7980 if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
7981 goto error; /* Some error occurred (e.g. ambiguous names). */
7982 if (ref != not_found_item)
7983 {
7984 DBUG_ASSERT(*ref && (*ref)->fixed);
7985 prev_subselect_item->used_tables_and_const_cache_join(*ref);
7986 break;
7987 }
7988 /*
7989 Set ref to 0 to ensure that we get an error in case we replaced
7990 this item with another item and still use this item in some
7991 other place of the parse tree.
7992 */
7993 ref= 0;
7994 }
7995
7996 place= prev_subselect_item->parsing_place;
7997 /*
7998 Check table fields only if the subquery is used somewhere out of
7999 HAVING or the outer SELECT does not use grouping (i.e. tables are
8000 accessible).
8001 TODO:
8002 Here we could first find the field anyway, and then test this
8003 condition, so that we can give a better error message -
8004 ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
8005 ER_BAD_FIELD_ERROR which we produce now.
8006 */
8007 if ((place != IN_HAVING ||
8008 (!select->with_sum_func &&
8009 select->group_list.elements == 0)))
8010 {
8011 /*
8012 In case of view, find_field_in_tables() write pointer to view
8013 field expression to 'reference', i.e. it substitute that
8014 expression instead of this Item_ref
8015 */
8016 from_field= find_field_in_tables(thd, this,
8017 outer_context->
8018 first_name_resolution_table,
8019 outer_context->
8020 last_name_resolution_table,
8021 reference,
8022 IGNORE_EXCEPT_NON_UNIQUE,
8023 TRUE, TRUE);
8024 if (! from_field)
8025 goto error;
8026 if (from_field == view_ref_found)
8027 {
8028 Item::Type refer_type= (*reference)->type();
8029 prev_subselect_item->used_tables_and_const_cache_join(*reference);
8030 DBUG_ASSERT((*reference)->type() == REF_ITEM);
8031 mark_as_dependent(thd, last_checked_context->select_lex,
8032 context->select_lex, this,
8033 ((refer_type == REF_ITEM ||
8034 refer_type == FIELD_ITEM) ?
8035 (Item_ident*) (*reference) :
8036 0));
8037 /*
8038 view reference found, we substituted it instead of this
8039 Item, so can quit
8040 */
8041 return FALSE;
8042 }
8043 if (from_field != not_found_field)
8044 {
8045 if (cached_table && cached_table->select_lex &&
8046 outer_context->select_lex &&
8047 cached_table->select_lex != outer_context->select_lex)
8048 {
8049 /*
8050 Due to cache, find_field_in_tables() can return field which
8051 doesn't belong to provided outer_context. In this case we have
8052 to find proper field context in order to fix field correcly.
8053 */
8054 do
8055 {
8056 outer_context= outer_context->outer_context;
8057 select= outer_context->select_lex;
8058 prev_subselect_item=
8059 last_checked_context->select_lex->master_unit()->item;
8060 last_checked_context= outer_context;
8061 } while (outer_context && outer_context->select_lex &&
8062 cached_table->select_lex != outer_context->select_lex);
8063 }
8064 prev_subselect_item->used_tables_cache|= from_field->table->map;
8065 prev_subselect_item->const_item_cache= 0;
8066 break;
8067 }
8068 }
8069 DBUG_ASSERT(from_field == not_found_field);
8070
8071 /* Reference is not found => depend on outer (or just error). */
8072 prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
8073 prev_subselect_item->const_item_cache= 0;
8074
8075 outer_context= outer_context->outer_context;
8076 } while (outer_context);
8077
8078 DBUG_ASSERT(from_field != 0 && from_field != view_ref_found);
8079 if (from_field != not_found_field)
8080 {
8081 Item_field* fld;
8082 if (!(fld= new (thd->mem_root) Item_field(thd, from_field)))
8083 goto error;
8084 thd->change_item_tree(reference, fld);
8085 mark_as_dependent(thd, last_checked_context->select_lex,
8086 current_sel, fld, fld);
8087 /*
8088 A reference is resolved to a nest level that's outer or the same as
8089 the nest level of the enclosing set function : adjust the value of
8090 max_arg_level for the function if it's needed.
8091 */
8092 if (thd->lex->in_sum_func &&
8093 thd->lex->in_sum_func->nest_level >=
8094 last_checked_context->select_lex->nest_level)
8095 set_if_bigger(thd->lex->in_sum_func->max_arg_level,
8096 last_checked_context->select_lex->nest_level);
8097 return FALSE;
8098 }
8099 if (unlikely(ref == 0))
8100 {
8101 /* The item was not a table field and not a reference */
8102 my_error(ER_BAD_FIELD_ERROR, MYF(0),
8103 this->full_name(), thd->where);
8104 goto error;
8105 }
8106 /* Should be checked in resolve_ref_in_select_and_group(). */
8107 DBUG_ASSERT(*ref && (*ref)->fixed);
8108 mark_as_dependent(thd, last_checked_context->select_lex,
8109 context->select_lex, this, this);
8110 /*
8111 A reference is resolved to a nest level that's outer or the same as
8112 the nest level of the enclosing set function : adjust the value of
8113 max_arg_level for the function if it's needed.
8114 */
8115 if (thd->lex->in_sum_func &&
8116 thd->lex->in_sum_func->nest_level >=
8117 last_checked_context->select_lex->nest_level)
8118 set_if_bigger(thd->lex->in_sum_func->max_arg_level,
8119 last_checked_context->select_lex->nest_level);
8120 }
8121 }
8122
8123 DBUG_ASSERT(*ref);
8124 /*
8125 Check if this is an incorrect reference in a group function or forward
8126 reference. Do not issue an error if this is:
8127 1. outer reference (will be fixed later by the fix_inner_refs function);
8128 2. an unnamed reference inside an aggregate function.
8129 */
8130 if (!((*ref)->type() == REF_ITEM &&
8131 ((Item_ref *)(*ref))->ref_type() == OUTER_REF) &&
8132 (((*ref)->with_sum_func && name.str &&
8133 !(current_sel->linkage != GLOBAL_OPTIONS_TYPE &&
8134 current_sel->having_fix_field)) ||
8135 !(*ref)->fixed))
8136 {
8137 my_error(ER_ILLEGAL_REFERENCE, MYF(0),
8138 name.str, ((*ref)->with_sum_func?
8139 "reference to group function":
8140 "forward reference in item list"));
8141 goto error;
8142 }
8143
8144 set_properties();
8145
8146 if ((*ref)->check_cols(1))
8147 goto error;
8148 return FALSE;
8149
8150error:
8151 context->process_error(thd);
8152 return TRUE;
8153}
8154
8155
8156void Item_ref::set_properties()
8157{
8158 Type_std_attributes::set(*ref);
8159 maybe_null= (*ref)->maybe_null;
8160 /*
8161 We have to remember if we refer to a sum function, to ensure that
8162 split_sum_func() doesn't try to change the reference.
8163 */
8164 with_sum_func= (*ref)->with_sum_func;
8165 with_param= (*ref)->with_param;
8166 with_window_func= (*ref)->with_window_func;
8167 with_field= (*ref)->with_field;
8168 fixed= 1;
8169 if (alias_name_used)
8170 return;
8171 if ((*ref)->type() == FIELD_ITEM)
8172 alias_name_used= ((Item_ident *) (*ref))->alias_name_used;
8173 else
8174 alias_name_used= TRUE; // it is not field, so it is was resolved by alias
8175}
8176
8177
8178void Item_ref::cleanup()
8179{
8180 DBUG_ENTER("Item_ref::cleanup");
8181 Item_ident::cleanup();
8182 if (reference_trough_name)
8183 {
8184 /* We have to reset the reference as it may been freed */
8185 ref= 0;
8186 }
8187 DBUG_VOID_RETURN;
8188}
8189
8190
8191/**
8192 Transform an Item_ref object with a transformer callback function.
8193
8194 The function first applies the transform method to the item
8195 referenced by this Item_ref object. If this returns a new item the
8196 old item is substituted for a new one. After this the transformer
8197 is applied to the Item_ref object.
8198
8199 @param transformer the transformer callback function to be applied to
8200 the nodes of the tree of the object
8201 @param argument parameter to be passed to the transformer
8202
8203 @return Item returned as the result of transformation of the Item_ref object
8204 @retval !NULL The transformation was successful
8205 @retval NULL Out of memory error
8206*/
8207
8208Item* Item_ref::transform(THD *thd, Item_transformer transformer, uchar *arg)
8209{
8210 DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
8211 DBUG_ASSERT((*ref) != NULL);
8212
8213 /* Transform the object we are referencing. */
8214 Item *new_item= (*ref)->transform(thd, transformer, arg);
8215 if (!new_item)
8216 return NULL;
8217
8218 /*
8219 THD::change_item_tree() should be called only if the tree was
8220 really transformed, i.e. when a new item has been created.
8221 Otherwise we'll be allocating a lot of unnecessary memory for
8222 change records at each execution.
8223 */
8224 if (*ref != new_item)
8225 thd->change_item_tree(ref, new_item);
8226
8227 /* Transform the item ref object. */
8228 return (this->*transformer)(thd, arg);
8229}
8230
8231
8232/**
8233 Compile an Item_ref object with a processor and a transformer
8234 callback functions.
8235
8236 First the function applies the analyzer to the Item_ref object. Then
8237 if the analizer succeeeds we first applies the compile method to the
8238 object the Item_ref object is referencing. If this returns a new
8239 item the old item is substituted for a new one. After this the
8240 transformer is applied to the Item_ref object itself.
8241 The compile function is not called if the analyzer returns NULL
8242 in the parameter arg_p.
8243
8244 @param analyzer the analyzer callback function to be applied to the
8245 nodes of the tree of the object
8246 @param[in,out] arg_p parameter to be passed to the processor
8247 @param transformer the transformer callback function to be applied to the
8248 nodes of the tree of the object
8249 @param arg_t parameter to be passed to the transformer
8250
8251 @return Item returned as the result of transformation of the Item_ref object
8252*/
8253
8254Item* Item_ref::compile(THD *thd, Item_analyzer analyzer, uchar **arg_p,
8255 Item_transformer transformer, uchar *arg_t)
8256{
8257 /* Analyze this Item object. */
8258 if (!(this->*analyzer)(arg_p))
8259 return NULL;
8260
8261 /* Compile the Item we are referencing. */
8262 DBUG_ASSERT((*ref) != NULL);
8263 if (*arg_p)
8264 {
8265 uchar *arg_v= *arg_p;
8266 Item *new_item= (*ref)->compile(thd, analyzer, &arg_v, transformer, arg_t);
8267 if (new_item && *ref != new_item)
8268 thd->change_item_tree(ref, new_item);
8269 }
8270
8271 /* Transform this Item object. */
8272 return (this->*transformer)(thd, arg_t);
8273}
8274
8275
8276void Item_ref::print(String *str, enum_query_type query_type)
8277{
8278 if (ref)
8279 {
8280 if ((*ref)->type() != Item::CACHE_ITEM && ref_type() != VIEW_REF &&
8281 !table_name && name.str && alias_name_used)
8282 {
8283 THD *thd= current_thd;
8284 append_identifier(thd, str, &(*ref)->real_item()->name);
8285 }
8286 else
8287 (*ref)->print(str, query_type);
8288 }
8289 else
8290 Item_ident::print(str, query_type);
8291}
8292
8293
8294bool Item_ref::send(Protocol *prot, st_value *buffer)
8295{
8296 if (result_field)
8297 return prot->store(result_field);
8298 return (*ref)->send(prot, buffer);
8299}
8300
8301
8302double Item_ref::val_result()
8303{
8304 if (result_field)
8305 {
8306 if ((null_value= result_field->is_null()))
8307 return 0.0;
8308 return result_field->val_real();
8309 }
8310 return val_real();
8311}
8312
8313
8314bool Item_ref::is_null_result()
8315{
8316 if (result_field)
8317 return (null_value=result_field->is_null());
8318
8319 return is_null();
8320}
8321
8322
8323longlong Item_ref::val_int_result()
8324{
8325 if (result_field)
8326 {
8327 if ((null_value= result_field->is_null()))
8328 return 0;
8329 return result_field->val_int();
8330 }
8331 return val_int();
8332}
8333
8334
8335String *Item_ref::str_result(String* str)
8336{
8337 if (result_field)
8338 {
8339 if ((null_value= result_field->is_null()))
8340 return 0;
8341 str->set_charset(str_value.charset());
8342 return result_field->val_str(str, &str_value);
8343 }
8344 return val_str(str);
8345}
8346
8347
8348my_decimal *Item_ref::val_decimal_result(my_decimal *decimal_value)
8349{
8350 if (result_field)
8351 {
8352 if ((null_value= result_field->is_null()))
8353 return 0;
8354 return result_field->val_decimal(decimal_value);
8355 }
8356 return val_decimal(decimal_value);
8357}
8358
8359
8360bool Item_ref::val_bool_result()
8361{
8362 if (result_field)
8363 {
8364 if ((null_value= result_field->is_null()))
8365 return false;
8366 return result_field->val_bool();
8367 }
8368 return val_bool();
8369}
8370
8371
8372void Item_ref::save_result(Field *to)
8373{
8374 if (result_field)
8375 {
8376 save_field_in_field(result_field, &null_value, to, TRUE);
8377 return;
8378 }
8379 (*ref)->save_result(to);
8380 null_value= (*ref)->null_value;
8381}
8382
8383
8384void Item_ref::save_val(Field *to)
8385{
8386 (*ref)->save_result(to);
8387 null_value= (*ref)->null_value;
8388}
8389
8390
8391double Item_ref::val_real()
8392{
8393 DBUG_ASSERT(fixed);
8394 double tmp=(*ref)->val_result();
8395 null_value=(*ref)->null_value;
8396 return tmp;
8397}
8398
8399
8400longlong Item_ref::val_int()
8401{
8402 DBUG_ASSERT(fixed);
8403 longlong tmp=(*ref)->val_int_result();
8404 null_value=(*ref)->null_value;
8405 return tmp;
8406}
8407
8408
8409bool Item_ref::val_bool()
8410{
8411 DBUG_ASSERT(fixed);
8412 bool tmp= (*ref)->val_bool_result();
8413 null_value= (*ref)->null_value;
8414 return tmp;
8415}
8416
8417
8418String *Item_ref::val_str(String* tmp)
8419{
8420 DBUG_ASSERT(fixed);
8421 tmp=(*ref)->str_result(tmp);
8422 null_value=(*ref)->null_value;
8423 return tmp;
8424}
8425
8426
8427bool Item_ref::is_null()
8428{
8429 DBUG_ASSERT(fixed);
8430 bool tmp=(*ref)->is_null_result();
8431 null_value=(*ref)->null_value;
8432 return tmp;
8433}
8434
8435
8436bool Item_ref::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
8437{
8438 return (null_value=(*ref)->get_date_result(ltime,fuzzydate));
8439}
8440
8441
8442my_decimal *Item_ref::val_decimal(my_decimal *decimal_value)
8443{
8444 my_decimal *val= (*ref)->val_decimal_result(decimal_value);
8445 null_value= (*ref)->null_value;
8446 return val;
8447}
8448
8449int Item_ref::save_in_field(Field *to, bool no_conversions)
8450{
8451 int res;
8452 if (result_field)
8453 {
8454 if (result_field->is_null())
8455 {
8456 null_value= 1;
8457 res= set_field_to_null_with_conversions(to, no_conversions);
8458 return res;
8459 }
8460 to->set_notnull();
8461 res= field_conv(to, result_field);
8462 null_value= 0;
8463 return res;
8464 }
8465 res= (*ref)->save_in_field(to, no_conversions);
8466 null_value= (*ref)->null_value;
8467 return res;
8468}
8469
8470
8471void Item_ref::save_org_in_field(Field *field, fast_field_copier optimizer_data)
8472{
8473 (*ref)->save_org_in_field(field, optimizer_data);
8474}
8475
8476
8477void Item_ref::make_send_field(THD *thd, Send_field *field)
8478{
8479 (*ref)->make_send_field(thd, field);
8480 /* Non-zero in case of a view */
8481 if (name.str)
8482 field->col_name= name;
8483 if (table_name)
8484 field->table_name= table_name;
8485 if (db_name)
8486 field->db_name= db_name;
8487 if (orig_field_name.str)
8488 field->org_col_name= orig_field_name;
8489 if (orig_table_name)
8490 field->org_table_name= orig_table_name;
8491}
8492
8493
8494Item *Item_ref::get_tmp_table_item(THD *thd)
8495{
8496 if (!result_field)
8497 return (*ref)->get_tmp_table_item(thd);
8498
8499 Item_field *item= new (thd->mem_root) Item_field(thd, result_field);
8500 if (item)
8501 {
8502 item->table_name= table_name;
8503 item->db_name= db_name;
8504 }
8505 return item;
8506}
8507
8508
8509void Item_ref_null_helper::print(String *str, enum_query_type query_type)
8510{
8511 str->append(STRING_WITH_LEN("<ref_null_helper>("));
8512 if (ref)
8513 (*ref)->print(str, query_type);
8514 else
8515 str->append('?');
8516 str->append(')');
8517}
8518
8519
8520void Item_direct_ref::save_val(Field *to)
8521{
8522 (*ref)->save_val(to);
8523 null_value=(*ref)->null_value;
8524}
8525
8526
8527double Item_direct_ref::val_real()
8528{
8529 double tmp=(*ref)->val_real();
8530 null_value=(*ref)->null_value;
8531 return tmp;
8532}
8533
8534
8535longlong Item_direct_ref::val_int()
8536{
8537 longlong tmp=(*ref)->val_int();
8538 null_value=(*ref)->null_value;
8539 return tmp;
8540}
8541
8542
8543String *Item_direct_ref::val_str(String* tmp)
8544{
8545 tmp=(*ref)->val_str(tmp);
8546 null_value=(*ref)->null_value;
8547 return tmp;
8548}
8549
8550
8551my_decimal *Item_direct_ref::val_decimal(my_decimal *decimal_value)
8552{
8553 my_decimal *tmp= (*ref)->val_decimal(decimal_value);
8554 null_value=(*ref)->null_value;
8555 return tmp;
8556}
8557
8558
8559bool Item_direct_ref::val_bool()
8560{
8561 bool tmp= (*ref)->val_bool();
8562 null_value=(*ref)->null_value;
8563 return tmp;
8564}
8565
8566
8567bool Item_direct_ref::is_null()
8568{
8569 return (*ref)->is_null();
8570}
8571
8572
8573bool Item_direct_ref::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
8574{
8575 return (null_value=(*ref)->get_date(ltime,fuzzydate));
8576}
8577
8578
8579Item_cache_wrapper::~Item_cache_wrapper()
8580{
8581 DBUG_ASSERT(expr_cache == 0);
8582}
8583
8584Item_cache_wrapper::Item_cache_wrapper(THD *thd, Item *item_arg):
8585 Item_result_field(thd), orig_item(item_arg), expr_cache(NULL), expr_value(NULL)
8586{
8587 DBUG_ASSERT(orig_item->fixed);
8588 Type_std_attributes::set(orig_item);
8589 maybe_null= orig_item->maybe_null;
8590 with_sum_func= orig_item->with_sum_func;
8591 with_param= orig_item->with_param;
8592 with_field= orig_item->with_field;
8593 name= item_arg->name;
8594 m_with_subquery= orig_item->with_subquery();
8595
8596 if ((expr_value= orig_item->get_cache(thd)))
8597 expr_value->setup(thd, orig_item);
8598
8599 fixed= 1;
8600}
8601
8602
8603/**
8604 Initialize the cache if it is needed
8605*/
8606
8607void Item_cache_wrapper::init_on_demand()
8608{
8609 if (!expr_cache->is_inited())
8610 {
8611 orig_item->get_cache_parameters(parameters);
8612 expr_cache->init();
8613 }
8614}
8615
8616
8617void Item_cache_wrapper::print(String *str, enum_query_type query_type)
8618{
8619 if (query_type & QT_ITEM_CACHE_WRAPPER_SKIP_DETAILS)
8620 {
8621 /* Don't print the cache in EXPLAIN EXTENDED */
8622 orig_item->print(str, query_type);
8623 return;
8624 }
8625
8626 str->append("<expr_cache>");
8627 if (expr_cache)
8628 {
8629 init_on_demand();
8630 expr_cache->print(str, query_type);
8631 }
8632 else
8633 str->append(STRING_WITH_LEN("<<DISABLED>>"));
8634 str->append('(');
8635 orig_item->print(str, query_type);
8636 str->append(')');
8637}
8638
8639
8640/**
8641 Prepare the expression cache wrapper (do nothing)
8642
8643 @retval FALSE OK
8644*/
8645
8646bool Item_cache_wrapper::fix_fields(THD *thd __attribute__((unused)),
8647 Item **it __attribute__((unused)))
8648{
8649 DBUG_ASSERT(orig_item->fixed);
8650 DBUG_ASSERT(fixed);
8651 return FALSE;
8652}
8653
8654bool Item_cache_wrapper::send(Protocol *protocol, st_value *buffer)
8655{
8656 if (result_field)
8657 return protocol->store(result_field);
8658 return Item::send(protocol, buffer);
8659}
8660
8661/**
8662 Clean the expression cache wrapper up before reusing it.
8663*/
8664
8665void Item_cache_wrapper::cleanup()
8666{
8667 DBUG_ENTER("Item_cache_wrapper::cleanup");
8668 Item_result_field::cleanup();
8669 delete expr_cache;
8670 expr_cache= 0;
8671 /* expr_value is Item so it will be destroyed from list of Items */
8672 expr_value= 0;
8673 parameters.empty();
8674 DBUG_VOID_RETURN;
8675}
8676
8677
8678/**
8679 Create an expression cache that uses a temporary table
8680
8681 @param thd Thread handle
8682 @param depends_on Parameters of the expression to create cache for
8683
8684 @details
8685 The function takes 'depends_on' as the list of all parameters for
8686 the expression wrapped into this object and creates an expression
8687 cache in a temporary table containing the field for the parameters
8688 and the result of the expression.
8689
8690 @retval FALSE OK
8691 @retval TRUE Error
8692*/
8693
8694bool Item_cache_wrapper::set_cache(THD *thd)
8695{
8696 DBUG_ENTER("Item_cache_wrapper::set_cache");
8697 DBUG_ASSERT(expr_cache == 0);
8698 expr_cache= new Expression_cache_tmptable(thd, parameters, expr_value);
8699 DBUG_RETURN(expr_cache == NULL);
8700}
8701
8702Expression_cache_tracker* Item_cache_wrapper::init_tracker(MEM_ROOT *mem_root)
8703{
8704 if (expr_cache)
8705 {
8706 Expression_cache_tracker* tracker=
8707 new(mem_root) Expression_cache_tracker(expr_cache);
8708 if (tracker)
8709 ((Expression_cache_tmptable *)expr_cache)->set_tracker(tracker);
8710 return tracker;
8711 }
8712 return NULL;
8713}
8714
8715
8716/**
8717 Check if the current values of the parameters are in the expression cache
8718
8719 @details
8720 The function checks whether the current set of the parameters of the
8721 referenced item can be found in the expression cache. If so the function
8722 returns the item by which the result of the expression can be easily
8723 extracted from the cache with the corresponding val_* method.
8724
8725 @retval NULL - parameters are not in the cache
8726 @retval <item*> - item providing the result of the expression found in cache
8727*/
8728
8729Item *Item_cache_wrapper::check_cache()
8730{
8731 DBUG_ENTER("Item_cache_wrapper::check_cache");
8732 if (expr_cache)
8733 {
8734 Expression_cache_tmptable::result res;
8735 Item *cached_value;
8736 init_on_demand();
8737 res= expr_cache->check_value(&cached_value);
8738 if (res == Expression_cache_tmptable::HIT)
8739 DBUG_RETURN(cached_value);
8740 }
8741 DBUG_RETURN(NULL);
8742}
8743
8744
8745/**
8746 Get the value of the cached expression and put it in the cache
8747*/
8748
8749inline void Item_cache_wrapper::cache()
8750{
8751 expr_value->store(orig_item);
8752 expr_value->cache_value();
8753 expr_cache->put_value(expr_value); // put in expr_cache
8754}
8755
8756
8757/**
8758 Get the value of the possibly cached item into the field.
8759*/
8760
8761void Item_cache_wrapper::save_val(Field *to)
8762{
8763 Item *cached_value;
8764 DBUG_ENTER("Item_cache_wrapper::val_int");
8765 if (!expr_cache)
8766 {
8767 orig_item->save_val(to);
8768 null_value= orig_item->null_value;
8769 DBUG_VOID_RETURN;
8770 }
8771
8772 if ((cached_value= check_cache()))
8773 {
8774 cached_value->save_val(to);
8775 null_value= cached_value->null_value;
8776 DBUG_VOID_RETURN;
8777 }
8778 cache();
8779 null_value= expr_value->null_value;
8780 expr_value->save_val(to);
8781 DBUG_VOID_RETURN;
8782}
8783
8784
8785/**
8786 Get the integer value of the possibly cached item.
8787*/
8788
8789longlong Item_cache_wrapper::val_int()
8790{
8791 Item *cached_value;
8792 DBUG_ENTER("Item_cache_wrapper::val_int");
8793 if (!expr_cache)
8794 {
8795 longlong tmp= orig_item->val_int();
8796 null_value= orig_item->null_value;
8797 DBUG_RETURN(tmp);
8798 }
8799
8800 if ((cached_value= check_cache()))
8801 {
8802 longlong tmp= cached_value->val_int();
8803 null_value= cached_value->null_value;
8804 DBUG_RETURN(tmp);
8805 }
8806 cache();
8807 null_value= expr_value->null_value;
8808 DBUG_RETURN(expr_value->val_int());
8809}
8810
8811
8812/**
8813 Get the real value of the possibly cached item
8814*/
8815
8816double Item_cache_wrapper::val_real()
8817{
8818 Item *cached_value;
8819 DBUG_ENTER("Item_cache_wrapper::val_real");
8820 if (!expr_cache)
8821 {
8822 double tmp= orig_item->val_real();
8823 null_value= orig_item->null_value;
8824 DBUG_RETURN(tmp);
8825 }
8826
8827 if ((cached_value= check_cache()))
8828 {
8829 double tmp= cached_value->val_real();
8830 null_value= cached_value->null_value;
8831 DBUG_RETURN(tmp);
8832 }
8833 cache();
8834 null_value= expr_value->null_value;
8835 DBUG_RETURN(expr_value->val_real());
8836}
8837
8838
8839/**
8840 Get the string value of the possibly cached item
8841*/
8842
8843String *Item_cache_wrapper::val_str(String* str)
8844{
8845 Item *cached_value;
8846 DBUG_ENTER("Item_cache_wrapper::val_str");
8847 if (!expr_cache)
8848 {
8849 String *tmp= orig_item->val_str(str);
8850 null_value= orig_item->null_value;
8851 DBUG_RETURN(tmp);
8852 }
8853
8854 if ((cached_value= check_cache()))
8855 {
8856 String *tmp= cached_value->val_str(str);
8857 null_value= cached_value->null_value;
8858 DBUG_RETURN(tmp);
8859 }
8860 cache();
8861 if ((null_value= expr_value->null_value))
8862 DBUG_RETURN(NULL);
8863 DBUG_RETURN(expr_value->val_str(str));
8864}
8865
8866
8867/**
8868 Get the decimal value of the possibly cached item
8869*/
8870
8871my_decimal *Item_cache_wrapper::val_decimal(my_decimal* decimal_value)
8872{
8873 Item *cached_value;
8874 DBUG_ENTER("Item_cache_wrapper::val_decimal");
8875 if (!expr_cache)
8876 {
8877 my_decimal *tmp= orig_item->val_decimal(decimal_value);
8878 null_value= orig_item->null_value;
8879 DBUG_RETURN(tmp);
8880 }
8881
8882 if ((cached_value= check_cache()))
8883 {
8884 my_decimal *tmp= cached_value->val_decimal(decimal_value);
8885 null_value= cached_value->null_value;
8886 DBUG_RETURN(tmp);
8887 }
8888 cache();
8889 if ((null_value= expr_value->null_value))
8890 DBUG_RETURN(NULL);
8891 DBUG_RETURN(expr_value->val_decimal(decimal_value));
8892}
8893
8894
8895/**
8896 Get the boolean value of the possibly cached item
8897*/
8898
8899bool Item_cache_wrapper::val_bool()
8900{
8901 Item *cached_value;
8902 DBUG_ENTER("Item_cache_wrapper::val_bool");
8903 if (!expr_cache)
8904 {
8905 bool tmp= orig_item->val_bool();
8906 null_value= orig_item->null_value;
8907 DBUG_RETURN(tmp);
8908 }
8909
8910 if ((cached_value= check_cache()))
8911 {
8912 bool tmp= cached_value->val_bool();
8913 null_value= cached_value->null_value;
8914 DBUG_RETURN(tmp);
8915 }
8916 cache();
8917 null_value= expr_value->null_value;
8918 DBUG_RETURN(expr_value->val_bool());
8919}
8920
8921
8922/**
8923 Check for NULL the value of the possibly cached item
8924*/
8925
8926bool Item_cache_wrapper::is_null()
8927{
8928 Item *cached_value;
8929 DBUG_ENTER("Item_cache_wrapper::is_null");
8930 if (!expr_cache)
8931 {
8932 bool tmp= orig_item->is_null();
8933 null_value= orig_item->null_value;
8934 DBUG_RETURN(tmp);
8935 }
8936
8937 if ((cached_value= check_cache()))
8938 {
8939 bool tmp= cached_value->is_null();
8940 null_value= cached_value->null_value;
8941 DBUG_RETURN(tmp);
8942 }
8943 cache();
8944 DBUG_RETURN((null_value= expr_value->null_value));
8945}
8946
8947
8948/**
8949 Get the date value of the possibly cached item
8950*/
8951
8952bool Item_cache_wrapper::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
8953{
8954 Item *cached_value;
8955 DBUG_ENTER("Item_cache_wrapper::get_date");
8956 if (!expr_cache)
8957 DBUG_RETURN((null_value= orig_item->get_date(ltime, fuzzydate)));
8958
8959 if ((cached_value= check_cache()))
8960 DBUG_RETURN((null_value= cached_value->get_date(ltime, fuzzydate)));
8961
8962 cache();
8963 DBUG_RETURN((null_value= expr_value->get_date(ltime, fuzzydate)));
8964}
8965
8966
8967int Item_cache_wrapper::save_in_field(Field *to, bool no_conversions)
8968{
8969 int res;
8970 DBUG_ASSERT(!result_field);
8971 res= orig_item->save_in_field(to, no_conversions);
8972 null_value= orig_item->null_value;
8973 return res;
8974}
8975
8976
8977Item* Item_cache_wrapper::get_tmp_table_item(THD *thd)
8978{
8979 if (!orig_item->with_sum_func && !orig_item->const_item())
8980 return new (thd->mem_root) Item_temptable_field(thd, result_field);
8981 return copy_or_same(thd);
8982}
8983
8984
8985bool Item_direct_view_ref::send(Protocol *protocol, st_value *buffer)
8986{
8987 if (check_null_ref())
8988 return protocol->store_null();
8989 return Item_direct_ref::send(protocol, buffer);
8990}
8991
8992/**
8993 Prepare referenced field then call usual Item_direct_ref::fix_fields .
8994
8995 @param thd thread handler
8996 @param reference reference on reference where this item stored
8997
8998 @retval
8999 FALSE OK
9000 @retval
9001 TRUE Error
9002*/
9003
9004bool Item_direct_view_ref::fix_fields(THD *thd, Item **reference)
9005{
9006 /* view fild reference must be defined */
9007 DBUG_ASSERT(*ref);
9008 /* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */
9009 if ((*ref)->fixed)
9010 {
9011 Item *ref_item= (*ref)->real_item();
9012 if (ref_item->type() == Item::FIELD_ITEM)
9013 {
9014 /*
9015 In some cases we need to update table read set(see bug#47150).
9016 If ref item is FIELD_ITEM and fixed then field and table
9017 have proper values. So we can use them for update.
9018 */
9019 Field *fld= ((Item_field*) ref_item)->field;
9020 DBUG_ASSERT(fld && fld->table);
9021 if (thd->column_usage == MARK_COLUMNS_READ)
9022 bitmap_set_bit(fld->table->read_set, fld->field_index);
9023 }
9024 }
9025 else if (!(*ref)->fixed &&
9026 ((*ref)->fix_fields(thd, ref)))
9027 return TRUE;
9028
9029 if (Item_direct_ref::fix_fields(thd, reference))
9030 return TRUE;
9031 if (view->table && view->table->maybe_null)
9032 maybe_null= TRUE;
9033 set_null_ref_table();
9034 return FALSE;
9035}
9036
9037/*
9038 Prepare referenced outer field then call usual Item_direct_ref::fix_fields
9039
9040 SYNOPSIS
9041 Item_outer_ref::fix_fields()
9042 thd thread handler
9043 reference reference on reference where this item stored
9044
9045 RETURN
9046 FALSE OK
9047 TRUE Error
9048*/
9049
9050bool Item_outer_ref::fix_fields(THD *thd, Item **reference)
9051{
9052 bool err;
9053 /* outer_ref->check_cols() will be made in Item_direct_ref::fix_fields */
9054 if ((*ref) && !(*ref)->fixed && ((*ref)->fix_fields(thd, reference)))
9055 return TRUE;
9056 err= Item_direct_ref::fix_fields(thd, reference);
9057 if (!outer_ref)
9058 outer_ref= *ref;
9059 if ((*ref)->type() == Item::FIELD_ITEM)
9060 table_name= ((Item_field*)outer_ref)->table_name;
9061 return err;
9062}
9063
9064
9065void Item_outer_ref::fix_after_pullout(st_select_lex *new_parent,
9066 Item **ref_arg, bool merge)
9067{
9068 if (get_depended_from() == new_parent)
9069 {
9070 *ref_arg= outer_ref;
9071 (*ref_arg)->fix_after_pullout(new_parent, ref_arg, merge);
9072 }
9073}
9074
9075void Item_ref::fix_after_pullout(st_select_lex *new_parent, Item **refptr,
9076 bool merge)
9077{
9078 (*ref)->fix_after_pullout(new_parent, ref, merge);
9079 if (get_depended_from() == new_parent)
9080 depended_from= NULL;
9081}
9082
9083
9084/**
9085 Mark references from inner selects used in group by clause
9086
9087 The method is used by the walk method when called for the expressions
9088 from the group by clause. The callsare occurred in the function
9089 fix_inner_refs invoked by JOIN::prepare.
9090 The parameter passed to Item_outer_ref::check_inner_refs_processor
9091 is the iterator over the list of inner references from the subselects
9092 of the select to be prepared. The function marks those references
9093 from this list whose occurrences are encountered in the group by
9094 expressions passed to the walk method.
9095
9096 @param arg pointer to the iterator over a list of inner references
9097
9098 @return
9099 FALSE always
9100*/
9101
9102bool Item_outer_ref::check_inner_refs_processor(void *arg)
9103{
9104 List_iterator_fast<Item_outer_ref> *it=
9105 ((List_iterator_fast<Item_outer_ref> *) arg);
9106 Item_outer_ref *tmp_ref;
9107 while ((tmp_ref= (*it)++))
9108 {
9109 if (tmp_ref == this)
9110 {
9111 tmp_ref->found_in_group_by= 1;
9112 break;
9113 }
9114 }
9115 (*it).rewind();
9116 return FALSE;
9117}
9118
9119
9120/**
9121 Compare two view column references for equality.
9122
9123 A view column reference is considered equal to another column
9124 reference if the second one is a view column and if both column
9125 references resolve to the same item. It is assumed that both
9126 items are of the same type.
9127
9128 @param item item to compare with
9129 @param binary_cmp make binary comparison
9130
9131 @retval
9132 TRUE Referenced item is equal to given item
9133 @retval
9134 FALSE otherwise
9135*/
9136
9137bool Item_direct_view_ref::eq(const Item *item, bool binary_cmp) const
9138{
9139 if (item->type() == REF_ITEM)
9140 {
9141 Item_ref *item_ref= (Item_ref*) item;
9142 if (item_ref->ref_type() == VIEW_REF)
9143 {
9144 Item *item_ref_ref= *(item_ref->ref);
9145 return ((*ref)->real_item() == item_ref_ref->real_item());
9146 }
9147 }
9148 return FALSE;
9149}
9150
9151
9152Item_equal *Item_direct_view_ref::find_item_equal(COND_EQUAL *cond_equal)
9153{
9154 Item* field_item= real_item();
9155 if (field_item->type() != FIELD_ITEM)
9156 return NULL;
9157 return ((Item_field *) field_item)->find_item_equal(cond_equal);
9158}
9159
9160
9161/**
9162 Set a pointer to the multiple equality the view field reference belongs to
9163 (if any).
9164
9165 @details
9166 The function looks for a multiple equality containing this item of the type
9167 Item_direct_view_ref among those referenced by arg.
9168 In the case such equality exists the function does the following.
9169 If the found multiple equality contains a constant, then the item
9170 is substituted for this constant, otherwise the function sets a pointer
9171 to the multiple equality in the item.
9172
9173 @param arg reference to list of multiple equalities where
9174 the item (this object) is to be looked for
9175
9176 @note
9177 This function is supposed to be called as a callback parameter in calls
9178 of the compile method.
9179
9180 @note
9181 The function calls Item_field::propagate_equal_fields() for the field item
9182 this->real_item() to do the job. Then it takes the pointer to equal_item
9183 from this field item and assigns it to this->item_equal.
9184
9185 @return
9186 - pointer to the replacing constant item, if the field item was substituted
9187 - pointer to the field item, otherwise.
9188*/
9189
9190Item *Item_direct_view_ref::propagate_equal_fields(THD *thd,
9191 const Context &ctx,
9192 COND_EQUAL *cond)
9193{
9194 Item *field_item= real_item();
9195 if (field_item->type() != FIELD_ITEM)
9196 return this;
9197 Item *item= field_item->propagate_equal_fields(thd, ctx, cond);
9198 set_item_equal(field_item->get_item_equal());
9199 field_item->set_item_equal(NULL);
9200 if (item != field_item)
9201 return item;
9202 return this;
9203}
9204
9205
9206/**
9207 Replace an Item_direct_view_ref for an equal Item_field evaluated earlier
9208 (if any).
9209
9210 @details
9211 If this->item_equal points to some item and coincides with arg then
9212 the function returns a pointer to a field item that is referred to by the
9213 first element of the item_equal list which the Item_direct_view_ref
9214 object belongs to unless item_equal contains a constant item. In this
9215 case the function returns this constant item (if the substitution does
9216 not require conversion).
9217 If the Item_direct_view_ref object does not refer any Item_equal object
9218 'this' is returned .
9219
9220 @param arg NULL or points to so some item of the Item_equal type
9221
9222 @note
9223 This function is supposed to be called as a callback parameter in calls
9224 of the transformer method.
9225
9226 @note
9227 The function calls Item_field::replace_equal_field for the field item
9228 this->real_item() to do the job.
9229
9230 @return
9231 - pointer to a replacement Item_field if there is a better equal item or
9232 a pointer to a constant equal item;
9233 - this - otherwise.
9234*/
9235
9236Item *Item_direct_view_ref::replace_equal_field(THD *thd, uchar *arg)
9237{
9238 Item *field_item= real_item();
9239 if (field_item->type() != FIELD_ITEM)
9240 return this;
9241 field_item->set_item_equal(item_equal);
9242 Item *item= field_item->replace_equal_field(thd, arg);
9243 field_item->set_item_equal(0);
9244 return item != field_item ? item : this;
9245}
9246
9247
9248bool Item_direct_view_ref::excl_dep_on_table(table_map tab_map)
9249{
9250 table_map used= used_tables();
9251 if (used & OUTER_REF_TABLE_BIT)
9252 return false;
9253 if (!(used & ~tab_map))
9254 return true;
9255 if (item_equal)
9256 {
9257 DBUG_ASSERT(real_item()->type() == Item::FIELD_ITEM);
9258 return item_equal->used_tables() & tab_map;
9259 }
9260 return (*ref)->excl_dep_on_table(tab_map);
9261}
9262
9263bool Item_direct_view_ref::excl_dep_on_grouping_fields(st_select_lex *sel)
9264{
9265 if (item_equal)
9266 {
9267 DBUG_ASSERT(real_item()->type() == Item::FIELD_ITEM);
9268 return find_matching_grouping_field(this, sel) != NULL;
9269 }
9270 return (*ref)->excl_dep_on_grouping_fields(sel);
9271}
9272
9273
9274bool Item_default_value::eq(const Item *item, bool binary_cmp) const
9275{
9276 return item->type() == DEFAULT_VALUE_ITEM &&
9277 ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
9278}
9279
9280
9281bool Item_default_value::fix_fields(THD *thd, Item **items)
9282{
9283 Item *real_arg;
9284 Item_field *field_arg;
9285 Field *def_field;
9286 DBUG_ASSERT(fixed == 0);
9287
9288 if (!arg)
9289 {
9290 fixed= 1;
9291 return FALSE;
9292 }
9293 if (!arg->fixed && arg->fix_fields(thd, &arg))
9294 goto error;
9295
9296
9297 real_arg= arg->real_item();
9298 if (real_arg->type() != FIELD_ITEM)
9299 {
9300 my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->name.str);
9301 goto error;
9302 }
9303
9304 field_arg= (Item_field *)real_arg;
9305 if ((field_arg->field->flags & NO_DEFAULT_VALUE_FLAG))
9306 {
9307 my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0),
9308 field_arg->field->field_name.str);
9309 goto error;
9310 }
9311 if (!(def_field= (Field*) thd->alloc(field_arg->field->size_of())))
9312 goto error;
9313 memcpy((void *)def_field, (void *)field_arg->field,
9314 field_arg->field->size_of());
9315 IF_DBUG_ASSERT(def_field->is_stat_field=1,); // a hack to fool ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED
9316 if (def_field->default_value && def_field->default_value->flags)
9317 {
9318 uchar *newptr= (uchar*) thd->alloc(1+def_field->pack_length());
9319 if (!newptr)
9320 goto error;
9321 fix_session_vcol_expr_for_read(thd, def_field, def_field->default_value);
9322 if (should_mark_column(thd->column_usage))
9323 def_field->default_value->expr->walk(&Item::register_field_in_read_map, 1, 0);
9324 def_field->move_field(newptr+1, def_field->maybe_null() ? newptr : 0, 1);
9325 }
9326 else
9327 def_field->move_field_offset((my_ptrdiff_t)
9328 (def_field->table->s->default_values -
9329 def_field->table->record[0]));
9330 set_field(def_field);
9331 return FALSE;
9332
9333error:
9334 context->process_error(thd);
9335 return TRUE;
9336}
9337
9338
9339void Item_default_value::print(String *str, enum_query_type query_type)
9340{
9341 if (!arg)
9342 {
9343 str->append(STRING_WITH_LEN("default"));
9344 return;
9345 }
9346 str->append(STRING_WITH_LEN("default("));
9347 arg->print(str, query_type);
9348 str->append(')');
9349}
9350
9351void Item_default_value::calculate()
9352{
9353 if (field->default_value)
9354 field->set_default();
9355 DEBUG_SYNC(field->table->in_use, "after_Item_default_value_calculate");
9356}
9357
9358String *Item_default_value::val_str(String *str)
9359{
9360 calculate();
9361 return Item_field::val_str(str);
9362}
9363
9364double Item_default_value::val_real()
9365{
9366 calculate();
9367 return Item_field::val_real();
9368}
9369
9370longlong Item_default_value::val_int()
9371{
9372 calculate();
9373 return Item_field::val_int();
9374}
9375
9376my_decimal *Item_default_value::val_decimal(my_decimal *decimal_value)
9377{
9378 calculate();
9379 return Item_field::val_decimal(decimal_value);
9380}
9381
9382bool Item_default_value::get_date(MYSQL_TIME *ltime,ulonglong fuzzydate)
9383{
9384 calculate();
9385 return Item_field::get_date(ltime, fuzzydate);
9386}
9387
9388bool Item_default_value::send(Protocol *protocol, st_value *buffer)
9389{
9390 calculate();
9391 return Item_field::send(protocol, buffer);
9392}
9393
9394int Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
9395{
9396 if (arg)
9397 {
9398 calculate();
9399 return Item_field::save_in_field(field_arg, no_conversions);
9400 }
9401
9402 if (field_arg->default_value && field_arg->default_value->flags)
9403 return 0; // defaut fields will be set later, no need to do it twice
9404 return field_arg->save_in_field_default_value(context->error_processor ==
9405 &view_error_processor);
9406}
9407
9408table_map Item_default_value::used_tables() const
9409{
9410 if (!field || !field->default_value)
9411 return static_cast<table_map>(0);
9412 if (!field->default_value->expr) // not fully parsed field
9413 return static_cast<table_map>(RAND_TABLE_BIT);
9414 return field->default_value->expr->used_tables();
9415}
9416
9417/**
9418 This method like the walk method traverses the item tree, but at the
9419 same time it can replace some nodes in the tree.
9420*/
9421
9422Item *Item_default_value::transform(THD *thd, Item_transformer transformer,
9423 uchar *args)
9424{
9425 DBUG_ASSERT(!thd->stmt_arena->is_stmt_prepare());
9426
9427 /*
9428 If the value of arg is NULL, then this object represents a constant,
9429 so further transformation is unnecessary (and impossible).
9430 */
9431 if (!arg)
9432 return 0;
9433
9434 Item *new_item= arg->transform(thd, transformer, args);
9435 if (!new_item)
9436 return 0;
9437
9438 /*
9439 THD::change_item_tree() should be called only if the tree was
9440 really transformed, i.e. when a new item has been created.
9441 Otherwise we'll be allocating a lot of unnecessary memory for
9442 change records at each execution.
9443 */
9444 if (arg != new_item)
9445 thd->change_item_tree(&arg, new_item);
9446 return (this->*transformer)(thd, args);
9447}
9448
9449void Item_ignore_value::print(String *str, enum_query_type query_type)
9450{
9451 str->append(STRING_WITH_LEN("ignore"));
9452}
9453
9454int Item_ignore_value::save_in_field(Field *field_arg, bool no_conversions)
9455{
9456 return field_arg->save_in_field_ignore_value(context->error_processor ==
9457 &view_error_processor);
9458}
9459
9460String *Item_ignore_value::val_str(String *str)
9461{
9462 DBUG_ASSERT(0); // never should be called
9463 null_value= 1;
9464 return 0;
9465}
9466
9467double Item_ignore_value::val_real()
9468{
9469 DBUG_ASSERT(0); // never should be called
9470 null_value= 1;
9471 return 0.0;
9472}
9473
9474longlong Item_ignore_value::val_int()
9475{
9476 DBUG_ASSERT(0); // never should be called
9477 null_value= 1;
9478 return 0;
9479}
9480
9481my_decimal *Item_ignore_value::val_decimal(my_decimal *decimal_value)
9482{
9483 DBUG_ASSERT(0); // never should be called
9484 null_value= 1;
9485 return 0;
9486}
9487
9488bool Item_ignore_value::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
9489{
9490 DBUG_ASSERT(0); // never should be called
9491 null_value= 1;
9492 return TRUE;
9493}
9494
9495bool Item_ignore_value::send(Protocol *protocol, st_value *buffer)
9496{
9497 DBUG_ASSERT(0); // never should be called
9498 return TRUE;
9499}
9500
9501bool Item_insert_value::eq(const Item *item, bool binary_cmp) const
9502{
9503 return item->type() == INSERT_VALUE_ITEM &&
9504 ((Item_insert_value *)item)->arg->eq(arg, binary_cmp);
9505}
9506
9507
9508bool Item_insert_value::fix_fields(THD *thd, Item **items)
9509{
9510 DBUG_ASSERT(fixed == 0);
9511 /* We should only check that arg is in first table */
9512 if (!arg->fixed)
9513 {
9514 bool res;
9515 TABLE_LIST *orig_next_table= context->last_name_resolution_table;
9516 context->last_name_resolution_table= context->first_name_resolution_table;
9517 res= arg->fix_fields(thd, &arg);
9518 context->last_name_resolution_table= orig_next_table;
9519 if (res)
9520 return TRUE;
9521 }
9522
9523 if (arg->type() == REF_ITEM)
9524 arg= static_cast<Item_ref *>(arg)->ref[0];
9525 if (unlikely(arg->type() != FIELD_ITEM))
9526 {
9527 my_error(ER_BAD_FIELD_ERROR, MYF(0), "", "VALUES() function");
9528 return TRUE;
9529 }
9530
9531 Item_field *field_arg= (Item_field *)arg;
9532
9533 if (field_arg->field->table->insert_values)
9534 {
9535 Field *def_field= (Field*) thd->alloc(field_arg->field->size_of());
9536 if (!def_field)
9537 return TRUE;
9538 memcpy((void *)def_field, (void *)field_arg->field,
9539 field_arg->field->size_of());
9540 def_field->move_field_offset((my_ptrdiff_t)
9541 (def_field->table->insert_values -
9542 def_field->table->record[0]));
9543 set_field(def_field);
9544 }
9545 else
9546 {
9547 static uchar null_bit=1;
9548 /* charset doesn't matter here */
9549 Field *tmp_field= new Field_string(0, 0, &null_bit, 1, Field::NONE,
9550 &field_arg->field->field_name, &my_charset_bin);
9551 if (tmp_field)
9552 {
9553 tmp_field->init(field_arg->field->table);
9554 set_field(tmp_field);
9555 // the index is important when read bits set
9556 tmp_field->field_index= field_arg->field->field_index;
9557 }
9558 }
9559 return FALSE;
9560}
9561
9562void Item_insert_value::print(String *str, enum_query_type query_type)
9563{
9564 str->append(STRING_WITH_LEN("value("));
9565 arg->print(str, query_type);
9566 str->append(')');
9567}
9568
9569
9570/**
9571 Find index of Field object which will be appropriate for item
9572 representing field of row being changed in trigger.
9573
9574 @param thd current thread context
9575 @param table table of trigger (and where we looking for fields)
9576 @param table_grant_info GRANT_INFO of the subject table
9577
9578 @note
9579 This function does almost the same as fix_fields() for Item_field
9580 but is invoked right after trigger definition parsing. Since at
9581 this stage we can't say exactly what Field object (corresponding
9582 to TABLE::record[0] or TABLE::record[1]) should be bound to this
9583 Item, we only find out index of the Field and then select concrete
9584 Field object in fix_fields() (by that time Table_triggers_list::old_field/
9585 new_field should point to proper array of Fields).
9586 It also binds Item_trigger_field to Table_triggers_list object for
9587 table of trigger which uses this item.
9588*/
9589
9590void Item_trigger_field::setup_field(THD *thd, TABLE *table,
9591 GRANT_INFO *table_grant_info)
9592{
9593 /*
9594 It is too early to mark fields used here, because before execution
9595 of statement that will invoke trigger other statements may use same
9596 TABLE object, so all such mark-up will be wiped out.
9597 So instead we do it in Table_triggers_list::mark_fields_used()
9598 method which is called during execution of these statements.
9599 */
9600 enum_column_usage saved_column_usage= thd->column_usage;
9601 thd->column_usage= want_privilege == SELECT_ACL ? COLUMNS_READ
9602 : COLUMNS_WRITE;
9603 /*
9604 Try to find field by its name and if it will be found
9605 set field_idx properly.
9606 */
9607 (void)find_field_in_table(thd, table, field_name.str, field_name.length,
9608 0, &field_idx);
9609 thd->column_usage= saved_column_usage;
9610 triggers= table->triggers;
9611 table_grants= table_grant_info;
9612}
9613
9614
9615bool Item_trigger_field::eq(const Item *item, bool binary_cmp) const
9616{
9617 return item->type() == TRIGGER_FIELD_ITEM &&
9618 row_version == ((Item_trigger_field *)item)->row_version &&
9619 !lex_string_cmp(system_charset_info, &field_name,
9620 &((Item_trigger_field *)item)->field_name);
9621}
9622
9623
9624void Item_trigger_field::set_required_privilege(bool rw)
9625{
9626 /*
9627 Require SELECT and UPDATE privilege if this field will be read and
9628 set, and only UPDATE privilege for setting the field.
9629 */
9630 want_privilege= (rw ? SELECT_ACL | UPDATE_ACL : UPDATE_ACL);
9631}
9632
9633
9634bool Item_trigger_field::set_value(THD *thd, sp_rcontext * /*ctx*/, Item **it)
9635{
9636 Item *item= thd->sp_prepare_func_item(it);
9637
9638 if (!item)
9639 return true;
9640
9641 if (!fixed)
9642 {
9643 if (fix_fields(thd, NULL))
9644 return true;
9645 }
9646
9647 // NOTE: field->table->copy_blobs should be false here, but let's
9648 // remember the value at runtime to avoid subtle bugs.
9649 bool copy_blobs_saved= field->table->copy_blobs;
9650
9651 field->table->copy_blobs= true;
9652
9653 int err_code= item->save_in_field(field, 0);
9654
9655 field->table->copy_blobs= copy_blobs_saved;
9656 field->set_explicit_default(item);
9657
9658 return err_code < 0;
9659}
9660
9661
9662bool Item_trigger_field::fix_fields(THD *thd, Item **items)
9663{
9664 /*
9665 Since trigger is object tightly associated with TABLE object most
9666 of its set up can be performed during trigger loading i.e. trigger
9667 parsing! So we have little to do in fix_fields. :)
9668 */
9669
9670 DBUG_ASSERT(fixed == 0);
9671
9672 /* Set field. */
9673
9674 if (likely(field_idx != (uint)-1))
9675 {
9676#ifndef NO_EMBEDDED_ACCESS_CHECKS
9677 /*
9678 Check access privileges for the subject table. We check privileges only
9679 in runtime.
9680 */
9681
9682 if (table_grants)
9683 {
9684 table_grants->want_privilege= want_privilege;
9685
9686 if (check_grant_column(thd, table_grants,
9687 triggers->trigger_table->s->db.str,
9688 triggers->trigger_table->s->table_name.str,
9689 field_name.str, field_name.length,
9690 thd->security_ctx))
9691 return TRUE;
9692 }
9693#endif // NO_EMBEDDED_ACCESS_CHECKS
9694
9695 field= (row_version == OLD_ROW) ? triggers->old_field[field_idx] :
9696 triggers->new_field[field_idx];
9697 set_field(field);
9698 fixed= 1;
9699 return FALSE;
9700 }
9701
9702 my_error(ER_BAD_FIELD_ERROR, MYF(0), field_name.str,
9703 (row_version == NEW_ROW) ? "NEW" : "OLD");
9704 return TRUE;
9705}
9706
9707
9708void Item_trigger_field::print(String *str, enum_query_type query_type)
9709{
9710 str->append((row_version == NEW_ROW) ? "NEW" : "OLD", 3);
9711 str->append('.');
9712 str->append(&field_name);
9713}
9714
9715
9716bool Item_trigger_field::check_vcol_func_processor(void *arg)
9717{
9718 const char *ver= row_version == NEW_ROW ? "NEW." : "OLD.";
9719 return mark_unsupported_function(ver, field_name.str, arg, VCOL_IMPOSSIBLE);
9720}
9721
9722
9723void Item_trigger_field::cleanup()
9724{
9725 want_privilege= original_privilege;
9726 /*
9727 Since special nature of Item_trigger_field we should not do most of
9728 things from Item_field::cleanup() or Item_ident::cleanup() here.
9729 */
9730 Item::cleanup();
9731}
9732
9733
9734Item_result item_cmp_type(Item_result a,Item_result b)
9735{
9736 if (a == STRING_RESULT && b == STRING_RESULT)
9737 return STRING_RESULT;
9738 if (a == INT_RESULT && b == INT_RESULT)
9739 return INT_RESULT;
9740 else if (a == ROW_RESULT || b == ROW_RESULT)
9741 return ROW_RESULT;
9742 else if (a == TIME_RESULT || b == TIME_RESULT)
9743 return TIME_RESULT;
9744 if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
9745 (b == INT_RESULT || b == DECIMAL_RESULT))
9746 return DECIMAL_RESULT;
9747 return REAL_RESULT;
9748}
9749
9750
9751void resolve_const_item(THD *thd, Item **ref, Item *comp_item)
9752{
9753 Item *item= *ref;
9754 if (item->basic_const_item())
9755 return; // Can't be better
9756 Type_handler_hybrid_field_type cmp(comp_item->type_handler_for_comparison());
9757 if (!cmp.aggregate_for_comparison(item->type_handler_for_comparison()))
9758 {
9759 Item *new_item= cmp.type_handler()->
9760 make_const_item_for_comparison(thd, item, comp_item);
9761 if (new_item)
9762 thd->change_item_tree(ref, new_item);
9763 }
9764}
9765
9766/**
9767 Compare the value stored in field with the expression from the query.
9768
9769 @param field Field which the Item is stored in after conversion
9770 @param item Original expression from query
9771
9772 @return Returns an integer greater than, equal to, or less than 0 if
9773 the value stored in the field is greater than, equal to,
9774 or less than the original Item. A 0 may also be returned if
9775 out of memory.
9776
9777 @note We use this in the range optimizer/partition pruning,
9778 because in some cases we can't store the value in the field
9779 without some precision/character loss.
9780
9781 We similarly use it to verify that expressions like
9782 BIGINT_FIELD <cmp> <literal value>
9783 is done correctly (as int/decimal/float according to literal type).
9784
9785 @todo rewrite it to use Arg_comparator (currently it's a simplified and
9786 incomplete version of it)
9787*/
9788
9789int stored_field_cmp_to_item(THD *thd, Field *field, Item *item)
9790{
9791 Item_result res_type=item_cmp_type(field->result_type(),
9792 item->result_type());
9793 /*
9794 We have to check field->cmp_type() instead of res_type,
9795 as result_type() - and thus res_type - can never be TIME_RESULT (yet).
9796 */
9797 if (field->cmp_type() == TIME_RESULT)
9798 {
9799 MYSQL_TIME field_time, item_time, item_time2, *item_time_cmp= &item_time;
9800 if (field->type() == MYSQL_TYPE_TIME)
9801 {
9802 field->get_time(&field_time);
9803 item->get_time(&item_time);
9804 }
9805 else
9806 {
9807 field->get_date(&field_time, TIME_INVALID_DATES);
9808 item->get_date(&item_time, TIME_INVALID_DATES);
9809 if (item_time.time_type == MYSQL_TIMESTAMP_TIME)
9810 if (time_to_datetime(thd, &item_time, item_time_cmp= &item_time2))
9811 return 1;
9812 }
9813 return my_time_compare(&field_time, item_time_cmp);
9814 }
9815 if (res_type == STRING_RESULT)
9816 {
9817 char item_buff[MAX_FIELD_WIDTH];
9818 char field_buff[MAX_FIELD_WIDTH];
9819
9820 String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin);
9821 String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
9822 String *item_result= item->val_str(&item_tmp);
9823 /*
9824 Some implementations of Item::val_str(String*) actually modify
9825 the field Item::null_value, hence we can't check it earlier.
9826 */
9827 if (item->null_value)
9828 return 0;
9829 String *field_result= field->val_str(&field_tmp);
9830 return sortcmp(field_result, item_result, field->charset());
9831 }
9832 if (res_type == INT_RESULT)
9833 return 0; // Both are of type int
9834 if (res_type == DECIMAL_RESULT)
9835 {
9836 my_decimal item_buf, *item_val,
9837 field_buf, *field_val;
9838 item_val= item->val_decimal(&item_buf);
9839 if (item->null_value)
9840 return 0;
9841 field_val= field->val_decimal(&field_buf);
9842 return my_decimal_cmp(field_val, item_val);
9843 }
9844 /*
9845 The patch for Bug#13463415 started using this function for comparing
9846 BIGINTs. That uncovered a bug in Visual Studio 32bit optimized mode.
9847 Prefixing the auto variables with volatile fixes the problem....
9848 */
9849 volatile double result= item->val_real();
9850 if (item->null_value)
9851 return 0;
9852 volatile double field_result= field->val_real();
9853 if (field_result < result)
9854 return -1;
9855 else if (field_result > result)
9856 return 1;
9857 return 0;
9858}
9859
9860
9861void Item_cache::store(Item *item)
9862{
9863 example= item;
9864 if (!item)
9865 null_value= TRUE;
9866 value_cached= FALSE;
9867}
9868
9869void Item_cache::print(String *str, enum_query_type query_type)
9870{
9871 if (example && // There is a cached item
9872 (query_type & QT_NO_DATA_EXPANSION)) // Caller is show-create-table
9873 {
9874 // Instead of "cache" or the cached value, print the cached item name
9875 example->print(str, query_type);
9876 return;
9877 }
9878
9879 if (value_cached)
9880 {
9881 print_value(str);
9882 return;
9883 }
9884 str->append(STRING_WITH_LEN("<cache>("));
9885 if (example)
9886 example->print(str, query_type);
9887 else
9888 Item::print(str, query_type);
9889 str->append(')');
9890}
9891
9892/**
9893 Assign to this cache NULL value if it is possible
9894*/
9895
9896void Item_cache::set_null()
9897{
9898 if (maybe_null)
9899 {
9900 null_value= TRUE;
9901 value_cached= TRUE;
9902 }
9903}
9904
9905
9906bool Item_cache_int::cache_value()
9907{
9908 if (!example)
9909 return FALSE;
9910 value_cached= TRUE;
9911 value= example->val_int_result();
9912 null_value= example->null_value;
9913 unsigned_flag= example->unsigned_flag;
9914 return TRUE;
9915}
9916
9917
9918String *Item_cache_int::val_str(String *str)
9919{
9920 DBUG_ASSERT(fixed == 1);
9921 if (!has_value())
9922 return NULL;
9923 str->set_int(value, unsigned_flag, default_charset());
9924 return str;
9925}
9926
9927
9928my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val)
9929{
9930 DBUG_ASSERT(fixed == 1);
9931 if (!has_value())
9932 return NULL;
9933 int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val);
9934 return decimal_val;
9935}
9936
9937double Item_cache_int::val_real()
9938{
9939 DBUG_ASSERT(fixed == 1);
9940 if (!has_value())
9941 return 0.0;
9942 return (double) value;
9943}
9944
9945longlong Item_cache_int::val_int()
9946{
9947 DBUG_ASSERT(fixed == 1);
9948 if (!has_value())
9949 return 0;
9950 return value;
9951}
9952
9953int Item_cache_int::save_in_field(Field *field, bool no_conversions)
9954{
9955 int error;
9956 if (!has_value())
9957 return set_field_to_null_with_conversions(field, no_conversions);
9958
9959 field->set_notnull();
9960 error= field->store(value, unsigned_flag);
9961
9962 return error ? error : field->table->in_use->is_error() ? 1 : 0;
9963}
9964
9965
9966Item *Item_cache_int::convert_to_basic_const_item(THD *thd)
9967{
9968 Item *new_item;
9969 DBUG_ASSERT(value_cached || example != 0);
9970 if (!value_cached)
9971 cache_value();
9972 new_item= null_value ?
9973 (Item*) new (thd->mem_root) Item_null(thd) :
9974 (Item*) new (thd->mem_root) Item_int(thd, val_int(), max_length);
9975 return new_item;
9976}
9977
9978
9979Item_cache_temporal::Item_cache_temporal(THD *thd, const Type_handler *handler)
9980 :Item_cache_int(thd, handler)
9981{
9982 if (mysql_timestamp_type() == MYSQL_TIMESTAMP_ERROR)
9983 set_handler(&type_handler_datetime2);
9984}
9985
9986
9987longlong Item_cache_temporal::val_datetime_packed()
9988{
9989 DBUG_ASSERT(fixed == 1);
9990 if (Item_cache_temporal::field_type() == MYSQL_TYPE_TIME)
9991 return Item::val_datetime_packed(); // TIME-to-DATETIME conversion needed
9992 if ((!value_cached && !cache_value()) || null_value)
9993 {
9994 null_value= TRUE;
9995 return 0;
9996 }
9997 return value;
9998}
9999
10000
10001longlong Item_cache_temporal::val_time_packed()
10002{
10003 DBUG_ASSERT(fixed == 1);
10004 if (Item_cache_temporal::field_type() != MYSQL_TYPE_TIME)
10005 return Item::val_time_packed(); // DATETIME-to-TIME conversion needed
10006 if ((!value_cached && !cache_value()) || null_value)
10007 {
10008 null_value= TRUE;
10009 return 0;
10010 }
10011 return value;
10012}
10013
10014
10015String *Item_cache_temporal::val_str(String *str)
10016{
10017 DBUG_ASSERT(fixed == 1);
10018 if (!has_value())
10019 {
10020 null_value= true;
10021 return NULL;
10022 }
10023 return val_string_from_date(str);
10024}
10025
10026
10027my_decimal *Item_cache_temporal::val_decimal(my_decimal *decimal_value)
10028{
10029 DBUG_ASSERT(fixed == 1);
10030 if ((!value_cached && !cache_value()) || null_value)
10031 {
10032 null_value= true;
10033 return NULL;
10034 }
10035 return val_decimal_from_date(decimal_value);
10036}
10037
10038
10039longlong Item_cache_temporal::val_int()
10040{
10041 DBUG_ASSERT(fixed == 1);
10042 if ((!value_cached && !cache_value()) || null_value)
10043 {
10044 null_value= true;
10045 return 0;
10046 }
10047 return val_int_from_date();
10048}
10049
10050
10051double Item_cache_temporal::val_real()
10052{
10053 DBUG_ASSERT(fixed == 1);
10054 if ((!value_cached && !cache_value()) || null_value)
10055 {
10056 null_value= true;
10057 return 0;
10058 }
10059 return val_real_from_date();
10060}
10061
10062
10063bool Item_cache_temporal::cache_value()
10064{
10065 if (!example)
10066 return false;
10067 value_cached= true;
10068 value= example->val_datetime_packed_result();
10069 null_value= example->null_value;
10070 return true;
10071}
10072
10073
10074bool Item_cache_time::cache_value()
10075{
10076 if (!example)
10077 return false;
10078 value_cached= true;
10079 value= example->val_time_packed_result();
10080 null_value= example->null_value;
10081 return true;
10082}
10083
10084
10085bool Item_cache_temporal::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
10086{
10087 ErrConvInteger str(value);
10088
10089 if (!has_value())
10090 {
10091 bzero((char*) ltime,sizeof(*ltime));
10092 return (null_value= true);
10093 }
10094
10095 unpack_time(value, ltime, mysql_timestamp_type());
10096 return 0;
10097}
10098
10099
10100int Item_cache_temporal::save_in_field(Field *field, bool no_conversions)
10101{
10102 MYSQL_TIME ltime;
10103 if (get_date(&ltime, 0))
10104 return set_field_to_null_with_conversions(field, no_conversions);
10105 field->set_notnull();
10106 int error= field->store_time_dec(&ltime, decimals);
10107 return error ? error : field->table->in_use->is_error() ? 1 : 0;
10108}
10109
10110
10111void Item_cache_temporal::store_packed(longlong val_arg, Item *example_arg)
10112{
10113 /* An explicit value is given, save it. */
10114 store(example_arg);
10115 value_cached= true;
10116 value= val_arg;
10117 null_value= false;
10118}
10119
10120
10121Item *Item_cache_temporal::clone_item(THD *thd)
10122{
10123 Item_cache *tmp= type_handler()->Item_get_cache(thd, this);
10124 Item_cache_temporal *item= static_cast<Item_cache_temporal*>(tmp);
10125 item->store_packed(value, example);
10126 return item;
10127}
10128
10129
10130Item *Item_cache_temporal::convert_to_basic_const_item(THD *thd)
10131{
10132 Item *new_item;
10133 DBUG_ASSERT(value_cached || example != 0);
10134 if (!value_cached)
10135 cache_value();
10136 if (null_value)
10137 return new (thd->mem_root) Item_null(thd);
10138 else
10139 return make_literal(thd);
10140 return new_item;
10141}
10142
10143Item *Item_cache_datetime::make_literal(THD *thd)
10144{
10145 MYSQL_TIME ltime;
10146 unpack_time(val_datetime_packed(), &ltime, MYSQL_TIMESTAMP_DATETIME);
10147 return new (thd->mem_root) Item_datetime_literal(thd, &ltime, decimals);
10148}
10149
10150Item *Item_cache_date::make_literal(THD *thd)
10151{
10152 MYSQL_TIME ltime;
10153 unpack_time(val_datetime_packed(), &ltime, MYSQL_TIMESTAMP_DATE);
10154 return new (thd->mem_root) Item_date_literal(thd, &ltime);
10155}
10156
10157Item *Item_cache_time::make_literal(THD *thd)
10158{
10159 MYSQL_TIME ltime;
10160 unpack_time(val_time_packed(), &ltime, MYSQL_TIMESTAMP_TIME);
10161 return new (thd->mem_root) Item_time_literal(thd, &ltime, decimals);
10162}
10163
10164bool Item_cache_real::cache_value()
10165{
10166 if (!example)
10167 return FALSE;
10168 value_cached= TRUE;
10169 value= example->val_result();
10170 null_value= example->null_value;
10171 return TRUE;
10172}
10173
10174
10175double Item_cache_real::val_real()
10176{
10177 DBUG_ASSERT(fixed == 1);
10178 if (!has_value())
10179 return 0.0;
10180 return value;
10181}
10182
10183longlong Item_cache_real::val_int()
10184{
10185 DBUG_ASSERT(fixed == 1);
10186 if (!has_value())
10187 return 0;
10188 return (longlong) rint(value);
10189}
10190
10191
10192String* Item_cache_real::val_str(String *str)
10193{
10194 DBUG_ASSERT(fixed == 1);
10195 if (!has_value())
10196 return NULL;
10197 str->set_real(value, decimals, default_charset());
10198 return str;
10199}
10200
10201
10202my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val)
10203{
10204 DBUG_ASSERT(fixed == 1);
10205 if (!has_value())
10206 return NULL;
10207 double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
10208 return decimal_val;
10209}
10210
10211
10212Item *Item_cache_real::convert_to_basic_const_item(THD *thd)
10213{
10214 Item *new_item;
10215 DBUG_ASSERT(value_cached || example != 0);
10216 if (!value_cached)
10217 cache_value();
10218 new_item= null_value ?
10219 (Item*) new (thd->mem_root) Item_null(thd) :
10220 (Item*) new (thd->mem_root) Item_float(thd, val_real(),
10221 decimals);
10222 return new_item;
10223}
10224
10225
10226bool Item_cache_decimal::cache_value()
10227{
10228 if (!example)
10229 return FALSE;
10230 value_cached= TRUE;
10231 my_decimal *val= example->val_decimal_result(&decimal_value);
10232 if (!(null_value= example->null_value) && val != &decimal_value)
10233 my_decimal2decimal(val, &decimal_value);
10234 return TRUE;
10235}
10236
10237double Item_cache_decimal::val_real()
10238{
10239 DBUG_ASSERT(fixed);
10240 double res;
10241 if (!has_value())
10242 return 0.0;
10243 my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res);
10244 return res;
10245}
10246
10247longlong Item_cache_decimal::val_int()
10248{
10249 DBUG_ASSERT(fixed);
10250 longlong res;
10251 if (!has_value())
10252 return 0;
10253 my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res);
10254 return res;
10255}
10256
10257String* Item_cache_decimal::val_str(String *str)
10258{
10259 DBUG_ASSERT(fixed);
10260 if (!has_value())
10261 return NULL;
10262 my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, FALSE,
10263 &decimal_value);
10264 my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str);
10265 return str;
10266}
10267
10268my_decimal *Item_cache_decimal::val_decimal(my_decimal *val)
10269{
10270 DBUG_ASSERT(fixed);
10271 if (!has_value())
10272 return NULL;
10273 return &decimal_value;
10274}
10275
10276
10277Item *Item_cache_decimal::convert_to_basic_const_item(THD *thd)
10278{
10279 Item *new_item;
10280 DBUG_ASSERT(value_cached || example != 0);
10281 if (!value_cached)
10282 cache_value();
10283 if (null_value)
10284 new_item= (Item*) new (thd->mem_root) Item_null(thd);
10285 else
10286 {
10287 my_decimal decimal_value;
10288 my_decimal *result= val_decimal(&decimal_value);
10289 new_item= (Item*) new (thd->mem_root) Item_decimal(thd, result);
10290 }
10291 return new_item;
10292}
10293
10294
10295bool Item_cache_str::cache_value()
10296{
10297 if (!example)
10298 return FALSE;
10299 value_cached= TRUE;
10300 value_buff.set(buffer, sizeof(buffer), example->collation.collation);
10301 value= example->str_result(&value_buff);
10302 if ((null_value= example->null_value))
10303 value= 0;
10304 else if (value != &value_buff)
10305 {
10306 /*
10307 We copy string value to avoid changing value if 'item' is table field
10308 in queries like following (where t1.c is varchar):
10309 select a,
10310 (select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'),
10311 (select c from t1 where a=t2.a)
10312 from t2;
10313 */
10314 value_buff.copy(*value);
10315 value= &value_buff;
10316 }
10317 return TRUE;
10318}
10319
10320double Item_cache_str::val_real()
10321{
10322 DBUG_ASSERT(fixed == 1);
10323 if (!has_value())
10324 return 0.0;
10325 return value ? double_from_string_with_check(value) : 0.0;
10326}
10327
10328
10329longlong Item_cache_str::val_int()
10330{
10331 DBUG_ASSERT(fixed == 1);
10332 if (!has_value())
10333 return 0;
10334 return value ? longlong_from_string_with_check(value) : 0;
10335}
10336
10337
10338String* Item_cache_str::val_str(String *str)
10339{
10340 DBUG_ASSERT(fixed == 1);
10341 if (!has_value())
10342 return 0;
10343 return value;
10344}
10345
10346
10347my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val)
10348{
10349 DBUG_ASSERT(fixed == 1);
10350 if (!has_value())
10351 return NULL;
10352 return value ? decimal_from_string_with_check(decimal_val, value) : 0;
10353}
10354
10355
10356int Item_cache_str::save_in_field(Field *field, bool no_conversions)
10357{
10358 if (!has_value())
10359 return set_field_to_null_with_conversions(field, no_conversions);
10360 int res= Item_cache::save_in_field(field, no_conversions);
10361 return (is_varbinary && field->type() == MYSQL_TYPE_STRING &&
10362 value->length() < field->field_length) ? 1 : res;
10363}
10364
10365
10366bool Item_cache_row::allocate(THD *thd, uint num)
10367{
10368 item_count= num;
10369 return (!(values=
10370 (Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
10371}
10372
10373
10374Item *Item_cache_str::convert_to_basic_const_item(THD *thd)
10375{
10376 Item *new_item;
10377 DBUG_ASSERT(value_cached || example != 0);
10378 if (!value_cached)
10379 cache_value();
10380 if (null_value)
10381 new_item= (Item*) new (thd->mem_root) Item_null(thd);
10382 else
10383 {
10384 char buff[MAX_FIELD_WIDTH];
10385 String tmp(buff, sizeof(buff), value->charset());
10386 String *result= val_str(&tmp);
10387 uint length= result->length();
10388 char *tmp_str= thd->strmake(result->ptr(), length);
10389 new_item= new (thd->mem_root) Item_string(thd, tmp_str, length,
10390 result->charset());
10391 }
10392 return new_item;
10393}
10394
10395
10396bool Item_cache_row::setup(THD *thd, Item *item)
10397{
10398 example= item;
10399 if (!values && allocate(thd, item->cols()))
10400 return 1;
10401 for (uint i= 0; i < item_count; i++)
10402 {
10403 Item *el= item->element_index(i);
10404 Item_cache *tmp;
10405 if (!(tmp= values[i]= el->get_cache(thd)))
10406 return 1;
10407 tmp->setup(thd, el);
10408 }
10409 return 0;
10410}
10411
10412
10413void Item_cache_row::store(Item * item)
10414{
10415 example= item;
10416 if (!item)
10417 {
10418 null_value= TRUE;
10419 return;
10420 }
10421 for (uint i= 0; i < item_count; i++)
10422 values[i]->store(item->element_index(i));
10423}
10424
10425
10426bool Item_cache_row::cache_value()
10427{
10428 if (!example)
10429 return FALSE;
10430 value_cached= TRUE;
10431 null_value= 0;
10432 example->bring_value();
10433 for (uint i= 0; i < item_count; i++)
10434 {
10435 values[i]->cache_value();
10436 null_value|= values[i]->null_value;
10437 }
10438 return TRUE;
10439}
10440
10441
10442void Item_cache_row::illegal_method_call(const char *method)
10443{
10444 DBUG_ENTER("Item_cache_row::illegal_method_call");
10445 DBUG_PRINT("error", ("!!! %s method was called for row item", method));
10446 DBUG_ASSERT(0);
10447 my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
10448 DBUG_VOID_RETURN;
10449}
10450
10451
10452bool Item_cache_row::check_cols(uint c)
10453{
10454 if (c != item_count)
10455 {
10456 my_error(ER_OPERAND_COLUMNS, MYF(0), c);
10457 return 1;
10458 }
10459 return 0;
10460}
10461
10462
10463bool Item_cache_row::null_inside()
10464{
10465 for (uint i= 0; i < item_count; i++)
10466 {
10467 if (values[i]->cols() > 1)
10468 {
10469 if (values[i]->null_inside())
10470 return 1;
10471 }
10472 else
10473 {
10474 values[i]->update_null_value();
10475 if (values[i]->null_value)
10476 return 1;
10477 }
10478 }
10479 return 0;
10480}
10481
10482
10483void Item_cache_row::bring_value()
10484{
10485 if (!example)
10486 return;
10487 example->bring_value();
10488 null_value= example->null_value;
10489 for (uint i= 0; i < item_count; i++)
10490 values[i]->bring_value();
10491}
10492
10493
10494/**
10495 Assign to this cache NULL value if it is possible
10496*/
10497
10498void Item_cache_row::set_null()
10499{
10500 Item_cache::set_null();
10501 if (!values)
10502 return;
10503 for (uint i= 0; i < item_count; i++)
10504 values[i]->set_null();
10505};
10506
10507
10508double Item_type_holder::val_real()
10509{
10510 DBUG_ASSERT(0); // should never be called
10511 return 0.0;
10512}
10513
10514
10515longlong Item_type_holder::val_int()
10516{
10517 DBUG_ASSERT(0); // should never be called
10518 return 0;
10519}
10520
10521my_decimal *Item_type_holder::val_decimal(my_decimal *)
10522{
10523 DBUG_ASSERT(0); // should never be called
10524 return 0;
10525}
10526
10527String *Item_type_holder::val_str(String*)
10528{
10529 DBUG_ASSERT(0); // should never be called
10530 return 0;
10531}
10532
10533bool Item_type_holder::get_date(MYSQL_TIME *ltime, ulonglong fuzzydate)
10534{
10535 DBUG_ASSERT(0); // should never be called
10536 return true;
10537}
10538
10539void Item_result_field::cleanup()
10540{
10541 DBUG_ENTER("Item_result_field::cleanup()");
10542 Item::cleanup();
10543 result_field= 0;
10544 DBUG_VOID_RETURN;
10545}
10546
10547/**
10548 Dummy error processor used by default by Name_resolution_context.
10549
10550 @note
10551 do nothing
10552*/
10553
10554void dummy_error_processor(THD *thd, void *data)
10555{}
10556
10557/**
10558 Wrapper of hide_view_error call for Name_resolution_context error
10559 processor.
10560
10561 @note
10562 hide view underlying tables details in error messages
10563*/
10564
10565void view_error_processor(THD *thd, void *data)
10566{
10567 ((TABLE_LIST *)data)->hide_view_error(thd);
10568}
10569
10570
10571st_select_lex *Item_ident::get_depended_from() const
10572{
10573 st_select_lex *dep;
10574 if ((dep= depended_from))
10575 for ( ; dep->merged_into; dep= dep->merged_into) ;
10576 return dep;
10577}
10578
10579
10580table_map Item_ref::used_tables() const
10581{
10582 return get_depended_from() ? OUTER_REF_TABLE_BIT : (*ref)->used_tables();
10583}
10584
10585
10586void Item_ref::update_used_tables()
10587{
10588 if (!get_depended_from())
10589 (*ref)->update_used_tables();
10590}
10591
10592void Item_direct_view_ref::update_used_tables()
10593{
10594 set_null_ref_table();
10595 Item_direct_ref::update_used_tables();
10596}
10597
10598
10599table_map Item_direct_view_ref::used_tables() const
10600{
10601 DBUG_ASSERT(fixed);
10602
10603 if (get_depended_from())
10604 return OUTER_REF_TABLE_BIT;
10605
10606 if (view->is_merged_derived() || view->merged || !view->table)
10607 {
10608 table_map used= (*ref)->used_tables();
10609 return (used ?
10610 used :
10611 ((null_ref_table != NO_NULL_TABLE) ?
10612 null_ref_table->map :
10613 (table_map)0 ));
10614 }
10615 return view->table->map;
10616}
10617
10618table_map Item_direct_view_ref::not_null_tables() const
10619{
10620 return get_depended_from() ?
10621 0 :
10622 ((view->is_merged_derived() || view->merged || !view->table) ?
10623 (*ref)->not_null_tables() :
10624 view->table->map);
10625}
10626
10627/*
10628 we add RAND_TABLE_BIT to prevent moving this item from HAVING to WHERE
10629*/
10630table_map Item_ref_null_helper::used_tables() const
10631{
10632 return (get_depended_from() ?
10633 OUTER_REF_TABLE_BIT :
10634 (*ref)->used_tables() | RAND_TABLE_BIT);
10635}
10636
10637
10638#ifndef DBUG_OFF
10639
10640/* Debugger help function */
10641static char dbug_item_print_buf[2048];
10642
10643const char *dbug_print_item(Item *item)
10644{
10645 char *buf= dbug_item_print_buf;
10646 String str(buf, sizeof(dbug_item_print_buf), &my_charset_bin);
10647 str.length(0);
10648 if (!item)
10649 return "(Item*)NULL";
10650
10651 THD *thd= current_thd;
10652 ulonglong save_option_bits= thd->variables.option_bits;
10653 thd->variables.option_bits &= ~OPTION_QUOTE_SHOW_CREATE;
10654
10655 item->print(&str, QT_EXPLAIN);
10656
10657 thd->variables.option_bits= save_option_bits;
10658
10659 if (str.c_ptr_safe() == buf)
10660 return buf;
10661 else
10662 return "Couldn't fit into buffer";
10663}
10664
10665const char *dbug_print_select(SELECT_LEX *sl)
10666{
10667 char *buf= dbug_item_print_buf;
10668 String str(buf, sizeof(dbug_item_print_buf), &my_charset_bin);
10669 str.length(0);
10670 if (!sl)
10671 return "(SELECT_LEX*)NULL";
10672
10673 THD *thd= current_thd;
10674 ulonglong save_option_bits= thd->variables.option_bits;
10675 thd->variables.option_bits &= ~OPTION_QUOTE_SHOW_CREATE;
10676
10677 sl->print(thd, &str, QT_EXPLAIN);
10678
10679 thd->variables.option_bits= save_option_bits;
10680
10681 if (str.c_ptr() == buf)
10682 return buf;
10683 else
10684 return "Couldn't fit into buffer";
10685}
10686
10687const char *dbug_print_unit(SELECT_LEX_UNIT *un)
10688{
10689 char *buf= dbug_item_print_buf;
10690 String str(buf, sizeof(dbug_item_print_buf), &my_charset_bin);
10691 str.length(0);
10692 if (!un)
10693 return "(SELECT_LEX_UNIT*)NULL";
10694
10695 THD *thd= current_thd;
10696 ulonglong save_option_bits= thd->variables.option_bits;
10697 thd->variables.option_bits &= ~OPTION_QUOTE_SHOW_CREATE;
10698
10699 un->print(&str, QT_EXPLAIN);
10700
10701 thd->variables.option_bits= save_option_bits;
10702
10703 if (str.c_ptr() == buf)
10704 return buf;
10705 else
10706 return "Couldn't fit into buffer";
10707}
10708
10709
10710#endif /*DBUG_OFF*/
10711
10712bool Item_field::excl_dep_on_table(table_map tab_map)
10713{
10714 return used_tables() == tab_map ||
10715 (item_equal && (item_equal->used_tables() & tab_map));
10716}
10717
10718bool
10719Item_field::excl_dep_on_grouping_fields(st_select_lex *sel)
10720{
10721 return find_matching_grouping_field(this, sel) != NULL;
10722}
10723
10724
10725void Item::register_in(THD *thd)
10726{
10727 next= thd->free_list;
10728 thd->free_list= this;
10729}
10730