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