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