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