MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
item.cc
1 /*
2  Copyright (c) 2000, 2013, 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 as published by
6  the Free Software Foundation; version 2 of the License.
7 
8  This program is distributed in the hope that it will be useful,
9  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11  GNU General Public License for more details.
12 
13  You should have received a copy of the GNU General Public License
14  along with this program; if not, write to the Free Software
15  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
16 
17 
18 #include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */
19 #include "sql_priv.h"
20 #include "unireg.h" // REQUIRED: for other includes
21 #include <mysql.h>
22 #include <m_ctype.h>
23 #include "my_dir.h"
24 #include "sp_rcontext.h"
25 #include "sp_head.h" // sp_prepare_func_item
26 #include "sp.h" // sp_map_item_type
27 #include "sql_trigger.h"
28 #include "sql_select.h"
29 #include "sql_show.h" // append_identifier
30 #include "sql_view.h" // VIEW_ANY_SQL
31 #include "sql_time.h" // str_to_datetime_with_warn,
32  // make_truncated_value_warning
33 #include "sql_acl.h" // get_column_grant,
34  // SELECT_ACL, UPDATE_ACL,
35  // INSERT_ACL,
36  // check_grant_column
37 #include "sql_base.h" // enum_resolution_type,
38  // REPORT_EXCEPT_NOT_FOUND,
39  // find_item_in_list,
40  // RESOLVED_AGAINST_ALIAS, ...
41 #include "log_event.h" // append_query_string
42 #include "sql_test.h" // print_where
43 #include "sql_optimizer.h" // JOIN
44 
45 using std::min;
46 using std::max;
47 
48 const String my_null_string("NULL", 4, default_charset_info);
49 
50 /****************************************************************************/
51 
52 /* Hybrid_type_traits {_real} */
53 
54 void Hybrid_type_traits::fix_length_and_dec(Item *item, Item *arg) const
55 {
56  item->decimals= NOT_FIXED_DEC;
57  item->max_length= item->float_length(arg->decimals);
58 }
59 
60 static const Hybrid_type_traits real_traits_instance;
61 
62 const Hybrid_type_traits *Hybrid_type_traits::instance()
63 {
64  return &real_traits_instance;
65 }
66 
67 
68 my_decimal *
69 Hybrid_type_traits::val_decimal(Hybrid_type *val, my_decimal *to) const
70 {
71  double2my_decimal(E_DEC_FATAL_ERROR, val->real, val->dec_buf);
72  return val->dec_buf;
73 }
74 
75 
76 String *
77 Hybrid_type_traits::val_str(Hybrid_type *val, String *to, uint8 decimals) const
78 {
79  to->set_real(val->real, decimals, &my_charset_bin);
80  return to;
81 }
82 
83 /* Hybrid_type_traits_decimal */
84 static const Hybrid_type_traits_decimal decimal_traits_instance;
85 
86 const Hybrid_type_traits_decimal *Hybrid_type_traits_decimal::instance()
87 {
88  return &decimal_traits_instance;
89 }
90 
91 
92 void
93 Hybrid_type_traits_decimal::fix_length_and_dec(Item *item, Item *arg) const
94 {
95  item->decimals= arg->decimals;
96  item->max_length= min<uint32>(arg->max_length + DECIMAL_LONGLONG_DIGITS,
98 }
99 
100 
101 void Hybrid_type_traits_decimal::set_zero(Hybrid_type *val) const
102 {
103  my_decimal_set_zero(&val->dec_buf[0]);
104  val->used_dec_buf_no= 0;
105 }
106 
107 
108 void Hybrid_type_traits_decimal::add(Hybrid_type *val, Field *f) const
109 {
110  my_decimal_add(E_DEC_FATAL_ERROR,
111  &val->dec_buf[val->used_dec_buf_no ^ 1],
112  &val->dec_buf[val->used_dec_buf_no],
113  f->val_decimal(&val->dec_buf[2]));
114  val->used_dec_buf_no^= 1;
115 }
116 
117 
122 void Hybrid_type_traits_decimal::div(Hybrid_type *val, ulonglong u) const
123 {
124  int2my_decimal(E_DEC_FATAL_ERROR, u, TRUE, &val->dec_buf[2]);
125  /* XXX: what is '4' for scale? */
126  my_decimal_div(E_DEC_FATAL_ERROR,
127  &val->dec_buf[val->used_dec_buf_no ^ 1],
128  &val->dec_buf[val->used_dec_buf_no],
129  &val->dec_buf[2], 4);
130  val->used_dec_buf_no^= 1;
131 }
132 
133 
134 longlong
135 Hybrid_type_traits_decimal::val_int(Hybrid_type *val, bool unsigned_flag) const
136 {
137  longlong result;
138  my_decimal2int(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
139  unsigned_flag, &result);
140  return result;
141 }
142 
143 
144 double
145 Hybrid_type_traits_decimal::val_real(Hybrid_type *val) const
146 {
147  my_decimal2double(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
148  &val->real);
149  return val->real;
150 }
151 
152 
153 String *
154 Hybrid_type_traits_decimal::val_str(Hybrid_type *val, String *to,
155  uint8 decimals) const
156 {
157  my_decimal_round(E_DEC_FATAL_ERROR, &val->dec_buf[val->used_dec_buf_no],
158  decimals, FALSE, &val->dec_buf[2]);
159  my_decimal2string(E_DEC_FATAL_ERROR, &val->dec_buf[2], 0, 0, 0, to);
160  return to;
161 }
162 
163 /* Hybrid_type_traits_integer */
164 static const Hybrid_type_traits_integer integer_traits_instance;
165 
166 const Hybrid_type_traits_integer *Hybrid_type_traits_integer::instance()
167 {
168  return &integer_traits_instance;
169 }
170 
171 void
172 Hybrid_type_traits_integer::fix_length_and_dec(Item *item, Item *arg) const
173 {
174  item->decimals= 0;
175  item->max_length= MY_INT64_NUM_DECIMAL_DIGITS;
176  item->unsigned_flag= 0;
177 }
178 
179 /*****************************************************************************
180 ** Item functions
181 *****************************************************************************/
182 
187 void item_init(void)
188 {
189  item_user_lock_init();
190  uuid_short_init();
191 }
192 
193 
200 {
201  switch(result_type()) {
202  case INT_RESULT:
203  return val_int() != 0;
204  case DECIMAL_RESULT:
205  {
206  my_decimal decimal_value;
207  my_decimal *val= val_decimal(&decimal_value);
208  if (val)
209  return !my_decimal_is_zero(val);
210  return 0;
211  }
212  case REAL_RESULT:
213  case STRING_RESULT:
214  return val_real() != 0.0;
215  case ROW_RESULT:
216  default:
217  DBUG_ASSERT(0);
218  return 0; // Wrong (but safe)
219  }
220 }
221 
222 
223 /*
224  For the items which don't have its own fast val_str_ascii()
225  implementation we provide a generic slower version,
226  which converts from the Item character set to ASCII.
227  For better performance conversion happens only in
228  case of a "tricky" Item character set (e.g. UCS2).
229  Normally conversion does not happen.
230 */
231 String *Item::val_str_ascii(String *str)
232 {
233  if (!(collation.collation->state & MY_CS_NONASCII))
234  return val_str(str);
235 
236  DBUG_ASSERT(str != &str_value);
237 
238  uint errors;
239  String *res= val_str(&str_value);
240  if (!res)
241  return 0;
242 
243  if ((null_value= str->copy(res->ptr(), res->length(),
244  collation.collation, &my_charset_latin1,
245  &errors)))
246  return 0;
247 
248  return str;
249 }
250 
251 
252 String *Item::val_string_from_real(String *str)
253 {
254  double nr= val_real();
255  if (null_value)
256  return 0; /* purecov: inspected */
257  str->set_real(nr,decimals, &my_charset_bin);
258  return str;
259 }
260 
261 
262 String *Item::val_string_from_int(String *str)
263 {
264  longlong nr= val_int();
265  if (null_value)
266  return 0;
267  str->set_int(nr, unsigned_flag, &my_charset_bin);
268  return str;
269 }
270 
271 
272 String *Item::val_string_from_decimal(String *str)
273 {
274  my_decimal dec_buf, *dec= val_decimal(&dec_buf);
275  if (null_value)
276  return 0;
277  my_decimal_round(E_DEC_FATAL_ERROR, dec, decimals, FALSE, &dec_buf);
278  my_decimal2string(E_DEC_FATAL_ERROR, &dec_buf, 0, 0, 0, str);
279  return str;
280 }
281 
282 
283 String *Item::val_string_from_datetime(String *str)
284 {
285  DBUG_ASSERT(fixed == 1);
286  MYSQL_TIME ltime;
287  if (get_date(&ltime, TIME_FUZZY_DATE) ||
288  (null_value= str->alloc(MAX_DATE_STRING_REP_LENGTH)))
289  return (String *) 0;
290  make_datetime((DATE_TIME_FORMAT *) 0, &ltime, str, decimals);
291  return str;
292 }
293 
294 
295 String *Item::val_string_from_date(String *str)
296 {
297  DBUG_ASSERT(fixed == 1);
298  MYSQL_TIME ltime;
299  if (get_date(&ltime, TIME_FUZZY_DATE) ||
300  (null_value= str->alloc(MAX_DATE_STRING_REP_LENGTH)))
301  return (String *) 0;
302  make_date((DATE_TIME_FORMAT *) 0, &ltime, str);
303  return str;
304 }
305 
306 
307 String *Item::val_string_from_time(String *str)
308 {
309  DBUG_ASSERT(fixed == 1);
310  MYSQL_TIME ltime;
311  if (get_time(&ltime) || (null_value= str->alloc(MAX_DATE_STRING_REP_LENGTH)))
312  return (String *) 0;
313  make_time((DATE_TIME_FORMAT *) 0, &ltime, str, decimals);
314  return str;
315 }
316 
317 
318 my_decimal *Item::val_decimal_from_real(my_decimal *decimal_value)
319 {
320  double nr= val_real();
321  if (null_value)
322  return 0;
323  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
324  return (decimal_value);
325 }
326 
327 
328 my_decimal *Item::val_decimal_from_int(my_decimal *decimal_value)
329 {
330  longlong nr= val_int();
331  if (null_value)
332  return 0;
333  int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
334  return decimal_value;
335 }
336 
337 
338 my_decimal *Item::val_decimal_from_string(my_decimal *decimal_value)
339 {
340  String *res;
341 
342  if (!(res= val_str(&str_value)))
343  return NULL;
344 
345  if (str2my_decimal(E_DEC_FATAL_ERROR & ~E_DEC_BAD_NUM,
346  res->ptr(), res->length(), res->charset(),
347  decimal_value) & E_DEC_BAD_NUM)
348  {
349  ErrConvString err(res);
350  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
351  ER_TRUNCATED_WRONG_VALUE,
352  ER(ER_TRUNCATED_WRONG_VALUE), "DECIMAL",
353  err.ptr());
354  }
355  return decimal_value;
356 }
357 
358 
359 my_decimal *Item::val_decimal_from_date(my_decimal *decimal_value)
360 {
361  DBUG_ASSERT(fixed == 1);
362  MYSQL_TIME ltime;
363  if (get_date(&ltime, TIME_FUZZY_DATE))
364  {
365  my_decimal_set_zero(decimal_value);
366  null_value= 1; // set NULL, stop processing
367  return 0;
368  }
369  return date2my_decimal(&ltime, decimal_value);
370 }
371 
372 
373 my_decimal *Item::val_decimal_from_time(my_decimal *decimal_value)
374 {
375  DBUG_ASSERT(fixed == 1);
376  MYSQL_TIME ltime;
377  if (get_time(&ltime))
378  {
379  my_decimal_set_zero(decimal_value);
380  null_value= 1;
381  return 0;
382  }
383  return date2my_decimal(&ltime, decimal_value);
384 }
385 
386 
388 {
389  MYSQL_TIME ltime;
390  if ((null_value= get_time(&ltime)))
391  return 0;
392  return TIME_to_longlong_time_packed(&ltime);
393 }
394 
395 
397 {
398  MYSQL_TIME ltime;
399  longlong flags= (TIME_FUZZY_DATE | MODE_INVALID_DATES |
400  (current_thd->variables.sql_mode &
401  (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE)));
402  if ((null_value= get_date(&ltime, flags)))
403  return 0;
404  return TIME_to_longlong_datetime_packed(&ltime);
405 }
406 
407 
408 // TS-TODO: split into separate methods?
409 longlong Item::val_temporal_with_round(enum_field_types type, uint8 dec)
410 {
411  longlong nr= val_temporal_by_field_type();
412  longlong diff= my_time_fraction_remainder(MY_PACKED_TIME_GET_FRAC_PART(nr),
413  dec);
414  longlong abs_diff= diff > 0 ? diff : - diff;
415  if (abs_diff * 2 >= (int) log_10_int[DATETIME_MAX_DECIMALS - dec])
416  {
417  /* Needs rounding */
418  switch (type)
419  {
420  case MYSQL_TYPE_TIME:
421  {
422  MYSQL_TIME ltime;
423  TIME_from_longlong_time_packed(&ltime, nr);
424  return my_time_round(&ltime, dec) ?
425  0 : TIME_to_longlong_time_packed(&ltime);
426  }
427  case MYSQL_TYPE_TIMESTAMP:
428  case MYSQL_TYPE_DATETIME:
429  {
430  MYSQL_TIME ltime;
431  int warnings= 0;
432  TIME_from_longlong_datetime_packed(&ltime, nr);
433  return my_datetime_round(&ltime, dec, &warnings) ?
434  0 : TIME_to_longlong_datetime_packed(&ltime);
435  return nr;
436  }
437  default:
438  DBUG_ASSERT(0);
439  break;
440  }
441  }
442  /* Does not need rounding, do simple truncation. */
443  nr-= diff;
444  return nr;
445 }
446 
447 
448 double Item::val_real_from_decimal()
449 {
450  /* Note that fix_fields may not be called for Item_avg_field items */
451  double result;
452  my_decimal value_buff, *dec_val= val_decimal(&value_buff);
453  if (null_value)
454  return 0.0;
455  my_decimal2double(E_DEC_FATAL_ERROR, dec_val, &result);
456  return result;
457 }
458 
459 
460 longlong Item::val_int_from_decimal()
461 {
462  /* Note that fix_fields may not be called for Item_avg_field items */
463  longlong result;
464  my_decimal value, *dec_val= val_decimal(&value);
465  if (null_value)
466  return 0;
467  my_decimal2int(E_DEC_FATAL_ERROR, dec_val, unsigned_flag, &result);
468  return result;
469 }
470 
471 
472 longlong Item::val_int_from_time()
473 {
474  DBUG_ASSERT(fixed == 1);
475  MYSQL_TIME ltime;
476  return get_time(&ltime) ?
477  0LL : (ltime.neg ? -1 : 1) * TIME_to_ulonglong_time_round(&ltime);
478 }
479 
480 
481 longlong Item::val_int_from_date()
482 {
483  DBUG_ASSERT(fixed == 1);
484  MYSQL_TIME ltime;
485  return get_date(&ltime, TIME_FUZZY_DATE) ?
486  0LL : (longlong) TIME_to_ulonglong_date(&ltime);
487 }
488 
489 
490 longlong Item::val_int_from_datetime()
491 {
492  DBUG_ASSERT(fixed == 1);
493  MYSQL_TIME ltime;
494  return get_date(&ltime, TIME_FUZZY_DATE) ?
495  0LL: (longlong) TIME_to_ulonglong_datetime_round(&ltime);
496 }
497 
498 
499 type_conversion_status Item::save_time_in_field(Field *field)
500 {
501  MYSQL_TIME ltime;
502  if (get_time(&ltime))
503  return set_field_to_null_with_conversions(field, 0);
504  field->set_notnull();
505  return field->store_time(&ltime, decimals);
506 }
507 
508 
509 type_conversion_status Item::save_date_in_field(Field *field)
510 {
511  MYSQL_TIME ltime;
512  if (get_date(&ltime, TIME_FUZZY_DATE))
513  return set_field_to_null_with_conversions(field, 0);
514  field->set_notnull();
515  return field->store_time(&ltime, decimals);
516 }
517 
518 
519 /*
520  Store the string value in field directly
521 
522  SYNOPSIS
523  Item::save_str_value_in_field()
524  field a pointer to field where to store
525  result the pointer to the string value to be stored
526 
527  DESCRIPTION
528  The method is used by Item_*::save_in_field implementations
529  when we don't need to calculate the value to store
530  See Item_string::save_in_field() implementation for example
531 
532  IMPLEMENTATION
533  Check if the Item is null and stores the NULL or the
534  result value in the field accordingly.
535 
536  RETURN
537  Nonzero value if error
538 */
539 
540 type_conversion_status
541 Item::save_str_value_in_field(Field *field, String *result)
542 {
543  if (null_value)
544  return set_field_to_null(field);
545 
546  field->set_notnull();
547  return field->store(result->ptr(), result->length(), collation.collation);
548 }
549 
550 
551 Item::Item():
552  is_expensive_cache(-1), rsize(0),
553  marker(0), fixed(0),
554  collation(&my_charset_bin, DERIVATION_COERCIBLE), with_subselect(false),
555  with_stored_program(false), tables_locked_cache(false)
556 {
557  maybe_null=null_value=with_sum_func=unsigned_flag=0;
558  decimals= 0; max_length= 0;
559  cmp_context= (Item_result)-1;
560 
561  /* Put item in free list so that we can free all items at end */
562  THD *thd= current_thd;
563  next= thd->free_list;
564  thd->free_list= this;
565  /*
566  Item constructor can be called during execution other then SQL_COM
567  command => we should check thd->lex->current_select on zero (thd->lex
568  can be uninitialised)
569  */
570  if (thd->lex->current_select)
571  {
572  enum_parsing_place place=
573  thd->lex->current_select->parsing_place;
574  if (place == SELECT_LIST ||
575  place == IN_HAVING)
576  thd->lex->current_select->select_n_having_items++;
577  }
578 }
579 
587 Item::Item(THD *thd, Item *item):
588  is_expensive_cache(-1),
589  rsize(0),
590  str_value(item->str_value),
591  item_name(item->item_name),
592  orig_name(item->orig_name),
593  max_length(item->max_length),
594  marker(item->marker),
595  decimals(item->decimals),
596  maybe_null(item->maybe_null),
597  null_value(item->null_value),
598  unsigned_flag(item->unsigned_flag),
599  with_sum_func(item->with_sum_func),
600  fixed(item->fixed),
601  collation(item->collation),
602  cmp_context(item->cmp_context),
603  with_subselect(item->has_subquery()),
604  with_stored_program(item->with_stored_program),
605  tables_locked_cache(item->tables_locked_cache)
606 {
607  next= thd->free_list; // Put in free list
608  thd->free_list= this;
609 }
610 
611 
612 uint Item::decimal_precision() const
613 {
614  Item_result restype= result_type();
615 
616  if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
617  {
618  uint prec=
619  my_decimal_length_to_precision(max_char_length(), decimals,
620  unsigned_flag);
621  return min<uint>(prec, DECIMAL_MAX_PRECISION);
622  }
623  switch (field_type())
624  {
625  case MYSQL_TYPE_TIME:
626  return decimals + TIME_INT_DIGITS;
627  case MYSQL_TYPE_DATETIME:
628  case MYSQL_TYPE_TIMESTAMP:
629  return decimals + DATETIME_INT_DIGITS;
630  case MYSQL_TYPE_DATE:
631  return decimals + DATE_INT_DIGITS;
632  default:
633  break;
634  }
635  return min<uint>(max_char_length(), DECIMAL_MAX_PRECISION);
636 }
637 
638 
640 {
641  if (const_item() && result_type() == STRING_RESULT && !is_temporal())
642  {
643  MYSQL_TIME ltime;
644  String buf, *tmp;
645  MYSQL_TIME_STATUS status;
646  DBUG_ASSERT(fixed);
647  // Nanosecond rounding is not needed, for performance purposes
648  if ((tmp= val_str(&buf)) &&
649  str_to_time(tmp, &ltime, TIME_NO_NSEC_ROUNDING, &status) == 0)
650  return MY_MIN(status.fractional_digits, DATETIME_MAX_DECIMALS);
651  }
652  return MY_MIN(decimals, DATETIME_MAX_DECIMALS);
653 }
654 
655 
657 {
658  if (const_item() && result_type() == STRING_RESULT && !is_temporal())
659  {
660  MYSQL_TIME ltime;
661  String buf, *tmp;
662  MYSQL_TIME_STATUS status;
663  DBUG_ASSERT(fixed);
664  // Nanosecond rounding is not needed, for performance purposes
665  if ((tmp= val_str(&buf)) &&
666  !str_to_datetime(tmp, &ltime, TIME_NO_NSEC_ROUNDING | TIME_FUZZY_DATE,
667  &status))
668  return MY_MIN(status.fractional_digits, DATETIME_MAX_DECIMALS);
669  }
670  return MY_MIN(decimals, DATETIME_MAX_DECIMALS);
671 }
672 
673 
674 void Item::print_item_w_name(String *str, enum_query_type query_type)
675 {
676  print(str, query_type);
677 
678  if (item_name.is_set())
679  {
680  THD *thd= current_thd;
681  str->append(STRING_WITH_LEN(" AS "));
682  append_identifier(thd, str, item_name);
683  }
684 }
685 
686 
699  enum_query_type query_type,
700  bool used_alias)
701 {
702  if (used_alias)
703  {
704  DBUG_ASSERT(item_name.is_set());
705  // In the clause, user has referenced expression using an alias; we use it
706  append_identifier(current_thd, str, item_name);
707  }
708  else
709  print(str,query_type);
710 }
711 
712 
713 void Item::cleanup()
714 {
715  DBUG_ENTER("Item::cleanup");
716  fixed=0;
717  marker= 0;
718  tables_locked_cache= false;
719  if (orig_name.is_set())
720  item_name= orig_name;
721  DBUG_VOID_RETURN;
722 }
723 
724 
731 bool Item::cleanup_processor(uchar *arg)
732 {
733  if (fixed)
734  cleanup();
735  return FALSE;
736 }
737 
738 
745 void Item::rename(char *new_name)
746 {
747  /*
748  we can compare pointers to names here, because if name was not changed,
749  pointer will be same
750  */
751  if (!orig_name.is_set() && new_name != item_name.ptr())
752  orig_name= item_name;
753  item_name.set(new_name);
754 }
755 
756 
786 Item* Item::transform(Item_transformer transformer, uchar *arg)
787 {
788  DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
789 
790  return (this->*transformer)(arg);
791 }
792 
793 
794 Item_ident::Item_ident(Name_resolution_context *context_arg,
795  const char *db_name_arg,const char *table_name_arg,
796  const char *field_name_arg)
797  :orig_db_name(db_name_arg), orig_table_name(table_name_arg),
798  orig_field_name(field_name_arg), context(context_arg),
799  db_name(db_name_arg), table_name(table_name_arg),
800  field_name(field_name_arg),
801  alias_name_used(FALSE), cached_field_index(NO_CACHED_FIELD_INDEX),
802  cached_table(0), depended_from(0)
803 {
804  item_name.set(field_name_arg);
805 }
806 
807 
812 Item_ident::Item_ident(THD *thd, Item_ident *item)
813  :Item(thd, item),
814  orig_db_name(item->orig_db_name),
815  orig_table_name(item->orig_table_name),
816  orig_field_name(item->orig_field_name),
817  context(item->context),
818  db_name(item->db_name),
819  table_name(item->table_name),
820  field_name(item->field_name),
821  alias_name_used(item->alias_name_used),
822  cached_field_index(item->cached_field_index),
823  cached_table(item->cached_table),
824  depended_from(item->depended_from)
825 {}
826 
827 void Item_ident::cleanup()
828 {
829  DBUG_ENTER("Item_ident::cleanup");
830 #ifdef CANT_BE_USED_AS_MEMORY_IS_FREED
831  db_name ? db_name : "(null)",
832  orig_db_name ? orig_db_name : "(null)",
833  table_name ? table_name : "(null)",
834  orig_table_name ? orig_table_name : "(null)",
835  field_name ? field_name : "(null)",
836  orig_field_name ? orig_field_name : "(null)"));
837 #endif
838  Item::cleanup();
839  db_name= orig_db_name;
840  table_name= orig_table_name;
841  field_name= orig_field_name;
842  DBUG_VOID_RETURN;
843 }
844 
845 bool Item_ident::remove_dependence_processor(uchar * arg)
846 {
847  DBUG_ENTER("Item_ident::remove_dependence_processor");
848  if (depended_from == (st_select_lex *) arg)
849  depended_from= 0;
850  context= &((st_select_lex *) arg)->context;
851  DBUG_RETURN(0);
852 }
853 
854 
874 {
875  DBUG_ENTER("Item_field::collect_item_field_processor");
876  DBUG_PRINT("info", ("%s", field->field_name ? field->field_name : "noname"));
877  List<Item_field> *item_list= (List<Item_field>*) arg;
878  List_iterator<Item_field> item_list_it(*item_list);
879  Item_field *curr_item;
880  while ((curr_item= item_list_it++))
881  {
882  if (curr_item->eq(this, 1))
883  DBUG_RETURN(FALSE); /* Already in the set. */
884  }
885  item_list->push_back(this);
886  DBUG_RETURN(FALSE);
887 }
888 
889 
890 bool Item_field::add_field_to_set_processor(uchar *arg)
891 {
892  DBUG_ENTER("Item_field::add_field_to_set_processor");
893  DBUG_PRINT("info", ("%s", field->field_name ? field->field_name : "noname"));
894  TABLE *table= (TABLE *) arg;
895  if (field->table == table)
896  bitmap_set_bit(&table->tmp_set, field->field_index);
897  DBUG_RETURN(FALSE);
898 }
899 
900 
902 {
903  MY_BITMAP *bitmap= reinterpret_cast<MY_BITMAP*>(argument);
904  bitmap_clear_bit(bitmap, field->field_index);
905  return false;
906 }
907 
925 {
926  KEY_PART_INFO *first_non_group_part= *((KEY_PART_INFO **) arg);
927  KEY_PART_INFO *last_part= *(((KEY_PART_INFO **) arg) + 1);
928  KEY_PART_INFO *cur_part;
929 
930  for (cur_part= first_non_group_part; cur_part != last_part; cur_part++)
931  {
932  if (field->eq(cur_part->field))
933  return TRUE;
934  }
935  return FALSE;
936 }
937 
938 
939 /*
940  Mark field in read_map
941 
942  NOTES
943  This is used by filesort to register used fields in a a temporary
944  column read set or to register used fields in a view
945 */
946 
947 bool Item_field::register_field_in_read_map(uchar *arg)
948 {
949  TABLE *table= (TABLE *) arg;
950  if (field->table == table || !table)
951  bitmap_set_bit(field->table->read_set, field->field_index);
952  return 0;
953 }
954 
955 
956 bool Item::check_cols(uint c)
957 {
958  if (c != 1)
959  {
960  my_error(ER_OPERAND_COLUMNS, MYF(0), c);
961  return 1;
962  }
963  return 0;
964 }
965 
966 
967 const Name_string null_name_string(NULL, 0);
968 
969 
970 void Name_string::copy(const char *str, size_t length, const CHARSET_INFO *cs)
971 {
972  if (!length)
973  {
974  /* Empty string, used by AS or internal function like last_insert_id() */
975  set(str ? "" : NULL, 0);
976  return;
977  }
978  if (cs->ctype)
979  {
980  /*
981  This will probably need a better implementation in the future:
982  a function in CHARSET_INFO structure.
983  */
984  while (length && !my_isgraph(cs, *str))
985  { // Fix problem with yacc
986  length--;
987  str++;
988  }
989  }
990  if (!my_charset_same(cs, system_charset_info))
991  {
992  size_t res_length;
993  char *tmp= sql_strmake_with_convert(str, length, cs, MAX_ALIAS_NAME,
994  system_charset_info, &res_length);
995  set(tmp, tmp ? res_length : 0);
996  }
997  else
998  {
999  size_t len= min<size_t>(length, MAX_ALIAS_NAME);
1000  char *tmp= sql_strmake(str, len);
1001  set(tmp, tmp ? len : 0);
1002  }
1003 }
1004 
1005 
1006 void Item_name_string::copy(const char *str_arg, size_t length_arg,
1007  const CHARSET_INFO *cs_arg,
1008  bool is_autogenerated_arg)
1009 {
1010  m_is_autogenerated= is_autogenerated_arg;
1011  copy(str_arg, length_arg, cs_arg);
1012  if (length_arg > length() && !is_autogenerated())
1013  {
1014  ErrConvString tmp(str_arg, static_cast<uint>(length_arg), cs_arg);
1015  if (length() == 0)
1016  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1017  ER_NAME_BECOMES_EMPTY, ER(ER_NAME_BECOMES_EMPTY),
1018  tmp.ptr());
1019  else
1020  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
1021  ER_REMOVED_SPACES, ER(ER_REMOVED_SPACES),
1022  tmp.ptr());
1023  }
1024 }
1025 
1026 
1035 bool Item::eq(const Item *item, bool binary_cmp) const
1036 {
1037  /*
1038  Note, that this is never TRUE if item is a Item_param:
1039  for all basic constants we have special checks, and Item_param's
1040  type() can be only among basic constant types.
1041  */
1042  return type() == item->type() && item_name.eq_safe(item->item_name);
1043 }
1044 
1045 
1046 Item *Item::safe_charset_converter(const CHARSET_INFO *tocs)
1047 {
1048  Item_func_conv_charset *conv= new Item_func_conv_charset(this, tocs, 1);
1049  return conv->safe ? conv : NULL;
1050 }
1051 
1052 
1065 {
1066  /*
1067  Item_num returns pure ASCII result,
1068  so conversion is needed only in case of "tricky" character
1069  sets like UCS2. If tocs is not "tricky", return the item itself.
1070  */
1071  if (!(tocs->state & MY_CS_NONASCII))
1072  return this;
1073 
1074  Item_string *conv;
1075  uint conv_errors;
1076  char buf[64], buf2[64];
1077  String tmp(buf, sizeof(buf), &my_charset_bin);
1078  String cstr(buf2, sizeof(buf2), &my_charset_bin);
1079  String *ostr= val_str(&tmp);
1080  char *ptr;
1081  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
1082  if (conv_errors || !(conv= new Item_string(cstr.ptr(), cstr.length(),
1083  cstr.charset(),
1084  collation.derivation)))
1085  {
1086  /*
1087  Safe conversion is not possible (or EOM).
1088  We could not convert a string into the requested character set
1089  without data loss. The target charset does not cover all the
1090  characters from the string. Operation cannot be done correctly.
1091  */
1092  return NULL;
1093  }
1094  if (!(ptr= current_thd->strmake(cstr.ptr(), cstr.length())))
1095  return NULL;
1096  conv->str_value.set(ptr, cstr.length(), cstr.charset());
1097  /* Ensure that no one is going to change the result string */
1098  conv->str_value.mark_as_const();
1099  conv->fix_char_length(max_char_length());
1100  return conv;
1101 }
1102 
1103 
1105 {
1106  Item_string *conv;
1107  char buf[64];
1108  String *s, tmp(buf, sizeof(buf), &my_charset_bin);
1109  s= val_str(&tmp);
1110  if ((conv= new Item_static_string_func(func_name, s->ptr(), s->length(),
1111  s->charset())))
1112  {
1113  conv->str_value.copy();
1114  conv->str_value.mark_as_const();
1115  }
1116  return conv;
1117 }
1118 
1119 
1120 Item *Item_string::safe_charset_converter(const CHARSET_INFO *tocs)
1121 {
1122  return charset_converter(tocs, true);
1123 }
1124 
1125 
1135 {
1136  Item_string *conv;
1137  uint conv_errors;
1138  char *ptr;
1139  String tmp, cstr, *ostr= val_str(&tmp);
1140  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
1141  conv_errors= lossless && conv_errors;
1142  if (conv_errors || !(conv= new Item_string(cstr.ptr(), cstr.length(),
1143  cstr.charset(),
1144  collation.derivation)))
1145  {
1146  /*
1147  Safe conversion is not possible (or EOM).
1148  We could not convert a string into the requested character set
1149  without data loss. The target charset does not cover all the
1150  characters from the string. Operation cannot be done correctly.
1151  */
1152  return NULL;
1153  }
1154  if (!(ptr= current_thd->strmake(cstr.ptr(), cstr.length())))
1155  return NULL;
1156  conv->str_value.set(ptr, cstr.length(), cstr.charset());
1157  /* Ensure that no one is going to change the result string */
1158  conv->str_value.mark_as_const();
1159  return conv;
1160 }
1161 
1162 
1163 Item *Item_param::safe_charset_converter(const CHARSET_INFO *tocs)
1164 {
1165  if (const_item())
1166  {
1167  uint cnv_errors;
1168  String *ostr= val_str(&cnvstr);
1169  cnvitem->str_value.copy(ostr->ptr(), ostr->length(),
1170  ostr->charset(), tocs, &cnv_errors);
1171  if (cnv_errors)
1172  return NULL;
1173  cnvitem->str_value.mark_as_const();
1174  cnvitem->max_length= cnvitem->str_value.numchars() * tocs->mbmaxlen;
1175  return cnvitem;
1176  }
1177  return Item::safe_charset_converter(tocs);
1178 }
1179 
1180 
1181 Item *Item_static_string_func::
1182 safe_charset_converter(const CHARSET_INFO *tocs)
1183 {
1184  Item_string *conv;
1185  uint conv_errors;
1186  String tmp, cstr, *ostr= val_str(&tmp);
1187  cstr.copy(ostr->ptr(), ostr->length(), ostr->charset(), tocs, &conv_errors);
1188  if (conv_errors ||
1189  !(conv= new Item_static_string_func(func_name,
1190  cstr.ptr(), cstr.length(),
1191  cstr.charset(),
1192  collation.derivation)))
1193  {
1194  /*
1195  Safe conversion is not possible (or EOM).
1196  We could not convert a string into the requested character set
1197  without data loss. The target charset does not cover all the
1198  characters from the string. Operation cannot be done correctly.
1199  */
1200  return NULL;
1201  }
1202  conv->str_value.copy();
1203  /* Ensure that no one is going to change the result string */
1204  conv->str_value.mark_as_const();
1205  return conv;
1206 }
1207 
1208 
1209 bool Item_string::eq(const Item *item, bool binary_cmp) const
1210 {
1211  if (type() == item->type() && item->basic_const_item())
1212  {
1213  if (binary_cmp)
1214  return !stringcmp(&str_value, &item->str_value);
1215  return (collation.collation == item->collation.collation &&
1216  !sortcmp(&str_value, &item->str_value, collation.collation));
1217  }
1218  return 0;
1219 }
1220 
1221 
1223 {
1224  char buff[MAX_DATE_STRING_REP_LENGTH];
1225  String tmp(buff, sizeof(buff), &my_charset_bin), *res;
1226  if (!(res= val_str(&tmp)))
1227  {
1228  set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
1229  return true;
1230  }
1231  return str_to_datetime_with_warn(res, ltime, flags);
1232 }
1233 
1234 
1236 {
1237  double value= val_real();
1238  if (null_value)
1239  {
1240  set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
1241  return true;
1242  }
1243  return my_double_to_datetime_with_warn(value, ltime, flags);
1244 
1245 }
1246 
1247 
1249 {
1250  my_decimal buf, *decimal= val_decimal(&buf);
1251  if (null_value)
1252  {
1253  set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
1254  return true;
1255  }
1256  return my_decimal_to_datetime_with_warn(decimal, ltime, flags);
1257 }
1258 
1259 
1261 {
1262  longlong value= val_int();
1263  if (null_value)
1264  {
1265  set_zero_time(ltime, MYSQL_TIMESTAMP_DATETIME);
1266  return true;
1267  }
1268  return my_longlong_to_datetime_with_warn(value, ltime, flags);
1269 }
1270 
1271 
1273 {
1274  MYSQL_TIME tm;
1275  if (get_time(&tm))
1276  {
1277  DBUG_ASSERT(null_value);
1278  return true;
1279  }
1280  time_to_datetime(current_thd, &tm, ltime);
1281  return false;
1282 }
1283 
1284 
1285 bool Item::get_date_from_numeric(MYSQL_TIME *ltime, uint fuzzydate)
1286 {
1287  switch (result_type())
1288  {
1289  case REAL_RESULT:
1290  return get_date_from_real(ltime, fuzzydate);
1291  case DECIMAL_RESULT:
1292  return get_date_from_decimal(ltime, fuzzydate);
1293  case INT_RESULT:
1294  return get_date_from_int(ltime, fuzzydate);
1295  case STRING_RESULT:
1296  case ROW_RESULT:
1297  DBUG_ASSERT(0);
1298  }
1299  return (null_value= true); // Impossible result_type
1300 }
1301 
1302 
1308 bool Item::get_date_from_non_temporal(MYSQL_TIME *ltime, uint fuzzydate)
1309 {
1310  DBUG_ASSERT(!is_temporal());
1311  switch (result_type())
1312  {
1313  case STRING_RESULT:
1314  return get_date_from_string(ltime, fuzzydate);
1315  case REAL_RESULT:
1316  return get_date_from_real(ltime, fuzzydate);
1317  case DECIMAL_RESULT:
1318  return get_date_from_decimal(ltime, fuzzydate);
1319  case INT_RESULT:
1320  return get_date_from_int(ltime, fuzzydate);
1321  case ROW_RESULT:
1322  DBUG_ASSERT(0);
1323  }
1324  return (null_value= true); // Impossible result_type
1325 }
1326 
1327 
1329 {
1330  char buff[MAX_DATE_STRING_REP_LENGTH];
1331  String tmp(buff, sizeof(buff), &my_charset_bin), *res;
1332  if (!(res= val_str(&tmp)))
1333  {
1334  set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
1335  return true;
1336  }
1337  return str_to_time_with_warn(res, ltime);
1338 }
1339 
1340 
1342 {
1343  double value= val_real();
1344  if (null_value)
1345  {
1346  set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
1347  return true;
1348  }
1349  return my_double_to_time_with_warn(value, ltime);
1350 }
1351 
1352 
1354 {
1355  my_decimal buf, *decimal= val_decimal(&buf);
1356  if (null_value)
1357  {
1358  set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
1359  return true;
1360  }
1361  return my_decimal_to_time_with_warn(decimal, ltime);
1362 }
1363 
1364 
1366 {
1367  DBUG_ASSERT(!is_temporal());
1368  longlong value= val_int();
1369  if (null_value)
1370  {
1371  set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
1372  return true;
1373  }
1374  return my_longlong_to_time_with_warn(value, ltime);
1375 }
1376 
1377 
1379 {
1380  DBUG_ASSERT(fixed == 1);
1381  if (get_date(ltime, TIME_FUZZY_DATE)) // Need this check if NULL value
1382  return true;
1383  set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
1384  return false;
1385 }
1386 
1387 
1389 {
1390  DBUG_ASSERT(fixed == 1);
1391  if (get_date(ltime, TIME_FUZZY_DATE))
1392  return true;
1393  datetime_to_time(ltime);
1394  return false;
1395 }
1396 
1397 
1399 {
1400  DBUG_ASSERT(!is_temporal());
1401  switch (result_type())
1402  {
1403  case REAL_RESULT:
1404  return get_time_from_real(ltime);
1405  case DECIMAL_RESULT:
1406  return get_time_from_decimal(ltime);
1407  case INT_RESULT:
1408  return get_time_from_int(ltime);
1409  case STRING_RESULT:
1410  case ROW_RESULT:
1411  DBUG_ASSERT(0);
1412  }
1413  return (null_value= true); // Impossible result type
1414 }
1415 
1416 
1417 
1418 
1426 {
1427  DBUG_ASSERT(!is_temporal());
1428  switch (result_type())
1429  {
1430  case STRING_RESULT:
1431  return get_time_from_string(ltime);
1432  case REAL_RESULT:
1433  return get_time_from_real(ltime);
1434  case DECIMAL_RESULT:
1435  return get_time_from_decimal(ltime);
1436  case INT_RESULT:
1437  return get_time_from_int(ltime);
1438  case ROW_RESULT:
1439  DBUG_ASSERT(0);
1440  }
1441  return (null_value= true); // Impossible result type
1442 }
1443 
1444 
1445 /*
1446 - Return NULL if argument is NULL.
1447 - Return zero if argument is not NULL, but we could not convert it to DATETIME.
1448 - Return zero if argument is not NULL and represents a valid DATETIME value,
1449  but the value is out of the supported Unix timestamp range.
1450 */
1451 bool Item::get_timeval(struct timeval *tm, int *warnings)
1452 {
1453  MYSQL_TIME ltime;
1454  if (get_date(&ltime, TIME_FUZZY_DATE))
1455  {
1456  if (null_value)
1457  return true; /* Value is NULL */
1458  goto zero; /* Could not extract date from the value */
1459  }
1460  if (datetime_to_timeval(current_thd, &ltime, tm, warnings))
1461  goto zero; /* Value is out of the supported range */
1462  return false; /* Value is a good Unix timestamp */
1463 zero:
1464  tm->tv_sec= tm->tv_usec= 0;
1465  return false;
1466 }
1467 
1468 
1469 const CHARSET_INFO *Item::default_charset()
1470 {
1471  return current_thd->variables.collation_connection;
1472 }
1473 
1474 
1475 /*
1476  Save value in field, but don't give any warnings
1477 
1478  NOTES
1479  This is used to temporary store and retrieve a value in a column,
1480  for example in opt_range to adjust the key value to fit the column.
1481 */
1482 
1483 type_conversion_status
1484 Item::save_in_field_no_warnings(Field *field, bool no_conversions)
1485 {
1486  DBUG_ENTER("Item::save_in_field_no_warnings");
1487  TABLE *table= field->table;
1488  THD *thd= table->in_use;
1489  enum_check_fields tmp= thd->count_cuted_fields;
1490  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
1491  sql_mode_t sql_mode= thd->variables.sql_mode;
1492  thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
1493  thd->count_cuted_fields= CHECK_FIELD_IGNORE;
1494 
1495  const type_conversion_status res= save_in_field(field, no_conversions);
1496 
1497  thd->count_cuted_fields= tmp;
1498  dbug_tmp_restore_column_map(table->write_set, old_map);
1499  thd->variables.sql_mode= sql_mode;
1500  DBUG_RETURN(res);
1501 }
1502 
1503 
1505 {
1506  DBUG_ASSERT(fixed);
1507 
1508  enum_field_types type= field_type();
1509  return (type == MYSQL_TYPE_BLOB || type == MYSQL_TYPE_GEOMETRY ||
1510  max_length > CONVERT_IF_BIGGER_TO_BLOB);
1511 }
1512 
1513 
1514 /*****************************************************************************
1515  Item_sp_variable methods
1516 *****************************************************************************/
1517 
1518 Item_sp_variable::Item_sp_variable(const Name_string sp_var_name)
1519  :m_thd(0), m_name(sp_var_name)
1520 #ifndef DBUG_OFF
1521  , m_sp(0)
1522 #endif
1523 {
1524 }
1525 
1526 
1527 bool Item_sp_variable::fix_fields(THD *thd, Item **)
1528 {
1529  Item *it;
1530 
1531  m_thd= thd; /* NOTE: this must be set before any this_xxx() */
1532  it= this_item();
1533 
1534  DBUG_ASSERT(it->fixed);
1535 
1536  max_length= it->max_length;
1537  decimals= it->decimals;
1538  unsigned_flag= it->unsigned_flag;
1539  fixed= 1;
1540  collation.set(it->collation);
1541 
1542  return FALSE;
1543 }
1544 
1545 
1546 double Item_sp_variable::val_real()
1547 {
1548  DBUG_ASSERT(fixed);
1549  Item *it= this_item();
1550  double ret= it->val_real();
1551  null_value= it->null_value;
1552  return ret;
1553 }
1554 
1555 
1556 longlong Item_sp_variable::val_int()
1557 {
1558  DBUG_ASSERT(fixed);
1559  Item *it= this_item();
1560  longlong ret= it->val_int();
1561  null_value= it->null_value;
1562  return ret;
1563 }
1564 
1565 
1566 String *Item_sp_variable::val_str(String *sp)
1567 {
1568  DBUG_ASSERT(fixed);
1569  Item *it= this_item();
1570  String *res= it->val_str(sp);
1571 
1572  null_value= it->null_value;
1573 
1574  if (!res)
1575  return NULL;
1576 
1577  /*
1578  This way we mark returned value of val_str as const,
1579  so that various functions (e.g. CONCAT) won't try to
1580  modify the value of the Item. Analogous mechanism is
1581  implemented for Item_param.
1582  Without this trick Item_splocal could be changed as a
1583  side-effect of expression computation. Here is an example
1584  of what happens without it: suppose x is varchar local
1585  variable in a SP with initial value 'ab' Then
1586  select concat(x,'c');
1587  would change x's value to 'abc', as Item_func_concat::val_str()
1588  would use x's internal buffer to compute the result.
1589  This is intended behaviour of Item_func_concat. Comments to
1590  Item_param class contain some more details on the topic.
1591  */
1592 
1593  if (res != &str_value)
1594  str_value.set(res->ptr(), res->length(), res->charset());
1595  else
1596  res->mark_as_const();
1597 
1598  return &str_value;
1599 }
1600 
1601 
1602 my_decimal *Item_sp_variable::val_decimal(my_decimal *decimal_value)
1603 {
1604  DBUG_ASSERT(fixed);
1605  Item *it= this_item();
1606  my_decimal *val= it->val_decimal(decimal_value);
1607  null_value= it->null_value;
1608  return val;
1609 }
1610 
1611 
1612 bool Item_sp_variable::get_date(MYSQL_TIME *ltime, uint fuzzydate)
1613 {
1614  DBUG_ASSERT(fixed);
1615  Item *it= this_item();
1616  return (null_value= it->get_date(ltime, fuzzydate));
1617 }
1618 
1619 
1620 bool Item_sp_variable::get_time(MYSQL_TIME *ltime)
1621 {
1622  DBUG_ASSERT(fixed);
1623  Item *it= this_item();
1624  return (null_value= it->get_time(ltime));
1625 }
1626 
1627 
1628 bool Item_sp_variable::is_null()
1629 {
1630  return this_item()->is_null();
1631 }
1632 
1633 
1634 /*****************************************************************************
1635  Item_splocal methods
1636 *****************************************************************************/
1637 
1638 Item_splocal::Item_splocal(const Name_string sp_var_name,
1639  uint sp_var_idx,
1640  enum_field_types sp_var_type,
1641  uint pos_in_q, uint len_in_q)
1642  :Item_sp_variable(sp_var_name),
1643  m_var_idx(sp_var_idx),
1644  limit_clause_param(FALSE),
1645  pos_in_query(pos_in_q), len_in_query(len_in_q)
1646 {
1647  maybe_null= TRUE;
1648 
1649  sp_var_type= real_type_to_type(sp_var_type);
1650  m_type= sp_map_item_type(sp_var_type);
1651  m_field_type= sp_var_type;
1652  m_result_type= sp_map_result_type(sp_var_type);
1653 }
1654 
1655 
1656 Item *
1657 Item_splocal::this_item()
1658 {
1659  DBUG_ASSERT(m_sp == m_thd->sp_runtime_ctx->sp);
1660 
1661  return m_thd->sp_runtime_ctx->get_item(m_var_idx);
1662 }
1663 
1664 const Item *
1665 Item_splocal::this_item() const
1666 {
1667  DBUG_ASSERT(m_sp == m_thd->sp_runtime_ctx->sp);
1668 
1669  return m_thd->sp_runtime_ctx->get_item(m_var_idx);
1670 }
1671 
1672 
1673 Item **
1674 Item_splocal::this_item_addr(THD *thd, Item **)
1675 {
1676  DBUG_ASSERT(m_sp == thd->sp_runtime_ctx->sp);
1677 
1678  return thd->sp_runtime_ctx->get_item_addr(m_var_idx);
1679 }
1680 
1681 
1682 void Item_splocal::print(String *str, enum_query_type)
1683 {
1684  str->reserve(m_name.length() + 8);
1685  str->append(m_name);
1686  str->append('@');
1687  str->qs_append(m_var_idx);
1688 }
1689 
1690 
1691 bool Item_splocal::set_value(THD *thd, sp_rcontext *ctx, Item **it)
1692 {
1693  return ctx->set_variable(thd, get_var_idx(), it);
1694 }
1695 
1696 
1697 /*****************************************************************************
1698  Item_case_expr methods
1699 *****************************************************************************/
1700 
1701 Item_case_expr::Item_case_expr(uint case_expr_id)
1702  :Item_sp_variable(Name_string(C_STRING_WITH_LEN("case_expr"))),
1703  m_case_expr_id(case_expr_id)
1704 {
1705 }
1706 
1707 
1708 Item *
1709 Item_case_expr::this_item()
1710 {
1711  DBUG_ASSERT(m_sp == m_thd->sp_runtime_ctx->sp);
1712 
1713  return m_thd->sp_runtime_ctx->get_case_expr(m_case_expr_id);
1714 }
1715 
1716 
1717 
1718 const Item *
1719 Item_case_expr::this_item() const
1720 {
1721  DBUG_ASSERT(m_sp == m_thd->sp_runtime_ctx->sp);
1722 
1723  return m_thd->sp_runtime_ctx->get_case_expr(m_case_expr_id);
1724 }
1725 
1726 
1727 Item **
1728 Item_case_expr::this_item_addr(THD *thd, Item **)
1729 {
1730  DBUG_ASSERT(m_sp == thd->sp_runtime_ctx->sp);
1731 
1732  return thd->sp_runtime_ctx->get_case_expr_addr(m_case_expr_id);
1733 }
1734 
1735 
1736 void Item_case_expr::print(String *str, enum_query_type)
1737 {
1738  if (str->reserve(MAX_INT_WIDTH + sizeof("case_expr@")))
1739  return; /* purecov: inspected */
1740  (void) str->append(STRING_WITH_LEN("case_expr@"));
1741  str->qs_append(m_case_expr_id);
1742 }
1743 
1744 
1745 /*****************************************************************************
1746  Item_name_const methods
1747 *****************************************************************************/
1748 
1749 double Item_name_const::val_real()
1750 {
1751  DBUG_ASSERT(fixed);
1752  double ret= value_item->val_real();
1753  null_value= value_item->null_value;
1754  return ret;
1755 }
1756 
1757 
1758 longlong Item_name_const::val_int()
1759 {
1760  DBUG_ASSERT(fixed);
1761  longlong ret= value_item->val_int();
1762  null_value= value_item->null_value;
1763  return ret;
1764 }
1765 
1766 
1767 String *Item_name_const::val_str(String *sp)
1768 {
1769  DBUG_ASSERT(fixed);
1770  String *ret= value_item->val_str(sp);
1771  null_value= value_item->null_value;
1772  return ret;
1773 }
1774 
1775 
1776 my_decimal *Item_name_const::val_decimal(my_decimal *decimal_value)
1777 {
1778  DBUG_ASSERT(fixed);
1779  my_decimal *val= value_item->val_decimal(decimal_value);
1780  null_value= value_item->null_value;
1781  return val;
1782 }
1783 
1784 
1785 bool Item_name_const::get_date(MYSQL_TIME *ltime, uint fuzzydate)
1786 {
1787  DBUG_ASSERT(fixed);
1788  return (null_value= value_item->get_date(ltime, fuzzydate));
1789 }
1790 
1791 
1792 bool Item_name_const::get_time(MYSQL_TIME *ltime)
1793 {
1794  DBUG_ASSERT(fixed);
1795  return (null_value= value_item->get_time(ltime));
1796 }
1797 
1798 
1799 bool Item_name_const::is_null()
1800 {
1801  return value_item->is_null();
1802 }
1803 
1804 
1805 Item_name_const::Item_name_const(Item *name_arg, Item *val):
1806  value_item(val), name_item(name_arg)
1807 {
1808  /*
1809  The value argument to NAME_CONST can only be a literal
1810  constant. Some extra tests are needed to support
1811  a collation specificer and to handle negative values
1812  */
1813 
1814  if (!(valid_args= name_item->basic_const_item() &&
1815  (value_item->basic_const_item() ||
1816  ((value_item->type() == FUNC_ITEM) &&
1817  ((((Item_func *) value_item)->functype() ==
1818  Item_func::COLLATE_FUNC) ||
1819  ((((Item_func *) value_item)->functype() ==
1820  Item_func::NEG_FUNC) &&
1821  (((Item_func *) value_item)->key_item()->basic_const_item())))))))
1822  my_error(ER_WRONG_ARGUMENTS, MYF(0), "NAME_CONST");
1823  Item::maybe_null= TRUE;
1824 }
1825 
1826 
1827 Item::Type Item_name_const::type() const
1828 {
1829  /*
1830  As
1831  1. one can try to create the Item_name_const passing non-constant
1832  arguments, although it's incorrect and
1833  2. the type() method can be called before the fix_fields() to get
1834  type information for a further type cast, e.g.
1835  if (item->type() == FIELD_ITEM)
1836  ((Item_field *) item)->...
1837  we return NULL_ITEM in the case to avoid wrong casting.
1838 
1839  valid_args guarantees value_item->basic_const_item(); if type is
1840  FUNC_ITEM, then we have a fudged item_func_neg() on our hands
1841  and return the underlying type.
1842  For Item_func_set_collation()
1843  e.g. NAME_CONST('name', 'value' COLLATE collation) we return its
1844  'value' argument type.
1845  */
1846  if (!valid_args)
1847  return NULL_ITEM;
1848  Item::Type value_type= value_item->type();
1849  if (value_type == FUNC_ITEM)
1850  {
1851  /*
1852  The second argument of NAME_CONST('name', 'value') must be
1853  a simple constant item or a NEG_FUNC/COLLATE_FUNC.
1854  */
1855  DBUG_ASSERT(((Item_func *) value_item)->functype() ==
1856  Item_func::NEG_FUNC ||
1857  ((Item_func *) value_item)->functype() ==
1858  Item_func::COLLATE_FUNC);
1859  return ((Item_func *) value_item)->key_item()->type();
1860  }
1861  return value_type;
1862 }
1863 
1864 
1865 bool Item_name_const::fix_fields(THD *thd, Item **ref)
1866 {
1867  char buf[128];
1868  String *tmp;
1869  String s(buf, sizeof(buf), &my_charset_bin);
1870  s.length(0);
1871 
1872  if (value_item->fix_fields(thd, &value_item) ||
1873  name_item->fix_fields(thd, &name_item) ||
1874  !value_item->const_item() ||
1875  !name_item->const_item() ||
1876  !(tmp= name_item->val_str(&s))) // Can't have a NULL name
1877  {
1878  my_error(ER_RESERVED_SYNTAX, MYF(0), "NAME_CONST");
1879  return TRUE;
1880  }
1881  if (item_name.is_autogenerated())
1882  {
1883  item_name.copy(tmp->ptr(), (uint) tmp->length(), system_charset_info);
1884  }
1885  collation.set(value_item->collation.collation, DERIVATION_IMPLICIT,
1886  value_item->collation.repertoire);
1887  max_length= value_item->max_length;
1888  decimals= value_item->decimals;
1889  fixed= 1;
1890  return FALSE;
1891 }
1892 
1893 
1894 void Item_name_const::print(String *str, enum_query_type query_type)
1895 {
1896  str->append(STRING_WITH_LEN("NAME_CONST("));
1897  name_item->print(str, query_type);
1898  str->append(',');
1899  value_item->print(str, query_type);
1900  str->append(')');
1901 }
1902 
1903 
1904 /*
1905  need a special class to adjust printing : references to aggregate functions
1906  must not be printed as refs because the aggregate functions that are added to
1907  the front of select list are not printed as well.
1908 */
1910 {
1911 public:
1912  Item_aggregate_ref(Name_resolution_context *context_arg, Item **item,
1913  const char *table_name_arg, const char *field_name_arg)
1914  :Item_ref(context_arg, item, table_name_arg, field_name_arg) {}
1915 
1916  virtual inline void print (String *str, enum_query_type query_type)
1917  {
1918  if (ref)
1919  (*ref)->print(str, query_type);
1920  else
1921  Item_ident::print(str, query_type);
1922  }
1923  virtual Ref_Type ref_type() { return AGGREGATE_REF; }
1924 };
1925 
1926 
1946 void Item::split_sum_func2(THD *thd, Ref_ptr_array ref_pointer_array,
1947  List<Item> &fields, Item **ref,
1948  bool skip_registered)
1949 {
1950  /* An item of type Item_sum is registered <=> ref_by != 0 */
1951  if (type() == SUM_FUNC_ITEM && skip_registered &&
1952  ((Item_sum *) this)->ref_by)
1953  return;
1954  if ((type() != SUM_FUNC_ITEM && with_sum_func) ||
1955  (type() == FUNC_ITEM &&
1956  (((Item_func *) this)->functype() == Item_func::ISNOTNULLTEST_FUNC ||
1957  ((Item_func *) this)->functype() == Item_func::TRIG_COND_FUNC)))
1958  {
1959  /* Will split complicated items and ignore simple ones */
1960  split_sum_func(thd, ref_pointer_array, fields);
1961  }
1962  else if ((type() == SUM_FUNC_ITEM || (used_tables() & ~PARAM_TABLE_BIT)) &&
1963  type() != SUBSELECT_ITEM &&
1964  (type() != REF_ITEM ||
1965  ((Item_ref*)this)->ref_type() == Item_ref::VIEW_REF))
1966  {
1967  /*
1968  Replace item with a reference so that we can easily calculate
1969  it (in case of sum functions) or copy it (in case of fields)
1970 
1971  The test above is to ensure we don't do a reference for things
1972  that are constants (PARAM_TABLE_BIT is in effect a constant)
1973  or already referenced (for example an item in HAVING)
1974  Exception is Item_direct_view_ref which we need to convert to
1975  Item_ref to allow fields from view being stored in tmp table.
1976  */
1977  Item_aggregate_ref *item_ref;
1978  uint el= fields.elements;
1979  Item *real_itm= real_item();
1980 
1981  ref_pointer_array[el]= real_itm;
1982  if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context,
1983  &ref_pointer_array[el], 0,
1984  item_name.ptr())))
1985  return; // fatal_error is set
1986  if (type() == SUM_FUNC_ITEM)
1987  item_ref->depended_from= ((Item_sum *) this)->depended_from();
1988  fields.push_front(real_itm);
1989  thd->change_item_tree(ref, item_ref);
1990  }
1991 }
1992 
1993 
1994 static bool
1995 left_is_superset(DTCollation *left, DTCollation *right)
1996 {
1997  /* Allow convert to Unicode */
1998  if (left->collation->state & MY_CS_UNICODE &&
1999  (left->derivation < right->derivation ||
2000  (left->derivation == right->derivation &&
2001  (!(right->collation->state & MY_CS_UNICODE) ||
2002  /* The code below makes 4-byte utf8 a superset over 3-byte utf8 */
2003  (left->collation->state & MY_CS_UNICODE_SUPPLEMENT &&
2004  !(right->collation->state & MY_CS_UNICODE_SUPPLEMENT) &&
2005  left->collation->mbmaxlen > right->collation->mbmaxlen &&
2006  left->collation->mbminlen == right->collation->mbminlen)))))
2007  return TRUE;
2008  /* Allow convert from ASCII */
2009  if (right->repertoire == MY_REPERTOIRE_ASCII &&
2010  (left->derivation < right->derivation ||
2011  (left->derivation == right->derivation &&
2012  !(left->repertoire == MY_REPERTOIRE_ASCII))))
2013  return TRUE;
2014  /* Disallow conversion otherwise */
2015  return FALSE;
2016 }
2017 
2055 {
2056  if (!my_charset_same(collation, dt.collation))
2057  {
2058  /*
2059  We do allow to use binary strings (like BLOBS)
2060  together with character strings.
2061  Binaries have more precedence than a character
2062  string of the same derivation.
2063  */
2064  if (collation == &my_charset_bin)
2065  {
2066  if (derivation <= dt.derivation)
2067  ; // Do nothing
2068  else
2069  {
2070  set(dt);
2071  }
2072  }
2073  else if (dt.collation == &my_charset_bin)
2074  {
2075  if (dt.derivation <= derivation)
2076  {
2077  set(dt);
2078  }
2079  }
2080  else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
2081  left_is_superset(this, &dt))
2082  {
2083  // Do nothing
2084  }
2085  else if ((flags & MY_COLL_ALLOW_SUPERSET_CONV) &&
2086  left_is_superset(&dt, this))
2087  {
2088  set(dt);
2089  }
2090  else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
2091  derivation < dt.derivation &&
2092  dt.derivation >= DERIVATION_SYSCONST)
2093  {
2094  // Do nothing;
2095  }
2096  else if ((flags & MY_COLL_ALLOW_COERCIBLE_CONV) &&
2097  dt.derivation < derivation &&
2098  derivation >= DERIVATION_SYSCONST)
2099  {
2100  set(dt);
2101  }
2102  else
2103  {
2104  // Cannot apply conversion
2105  set(&my_charset_bin, DERIVATION_NONE,
2106  (dt.repertoire|repertoire));
2107  return 1;
2108  }
2109  }
2110  else if (derivation < dt.derivation)
2111  {
2112  // Do nothing
2113  }
2114  else if (dt.derivation < derivation)
2115  {
2116  set(dt);
2117  }
2118  else
2119  {
2120  if (collation == dt.collation)
2121  {
2122  // Do nothing
2123  }
2124  else
2125  {
2126  if (derivation == DERIVATION_EXPLICIT)
2127  {
2128  set(0, DERIVATION_NONE, 0);
2129  return 1;
2130  }
2131  if (collation->state & MY_CS_BINSORT)
2132  return 0;
2133  if (dt.collation->state & MY_CS_BINSORT)
2134  {
2135  set(dt);
2136  return 0;
2137  }
2138  const CHARSET_INFO *bin= get_charset_by_csname(collation->csname,
2139  MY_CS_BINSORT,MYF(0));
2140  set(bin, DERIVATION_NONE);
2141  }
2142  }
2143  repertoire|= dt.repertoire;
2144  return 0;
2145 }
2146 
2147 /******************************/
2148 static
2149 void my_coll_agg_error(DTCollation &c1, DTCollation &c2, const char *fname)
2150 {
2151  my_error(ER_CANT_AGGREGATE_2COLLATIONS,MYF(0),
2152  c1.collation->name,c1.derivation_name(),
2153  c2.collation->name,c2.derivation_name(),
2154  fname);
2155 }
2156 
2157 
2158 static
2159 void my_coll_agg_error(DTCollation &c1, DTCollation &c2, DTCollation &c3,
2160  const char *fname)
2161 {
2162  my_error(ER_CANT_AGGREGATE_3COLLATIONS,MYF(0),
2163  c1.collation->name,c1.derivation_name(),
2164  c2.collation->name,c2.derivation_name(),
2165  c3.collation->name,c3.derivation_name(),
2166  fname);
2167 }
2168 
2169 
2170 static
2171 void my_coll_agg_error(Item** args, uint count, const char *fname,
2172  int item_sep)
2173 {
2174  if (count == 2)
2175  my_coll_agg_error(args[0]->collation, args[item_sep]->collation, fname);
2176  else if (count == 3)
2177  my_coll_agg_error(args[0]->collation, args[item_sep]->collation,
2178  args[2*item_sep]->collation, fname);
2179  else
2180  my_error(ER_CANT_AGGREGATE_NCOLLATIONS,MYF(0),fname);
2181 }
2182 
2183 
2184 bool agg_item_collations(DTCollation &c, const char *fname,
2185  Item **av, uint count, uint flags, int item_sep)
2186 {
2187  uint i;
2188  Item **arg;
2189  bool unknown_cs= 0;
2190 
2191  c.set(av[0]->collation);
2192  for (i= 1, arg= &av[item_sep]; i < count; i++, arg++)
2193  {
2194  if (c.aggregate((*arg)->collation, flags))
2195  {
2196  if (c.derivation == DERIVATION_NONE &&
2197  c.collation == &my_charset_bin)
2198  {
2199  unknown_cs= 1;
2200  continue;
2201  }
2202  my_coll_agg_error(av, count, fname, item_sep);
2203  return TRUE;
2204  }
2205  }
2206 
2207  if (unknown_cs &&
2208  c.derivation != DERIVATION_EXPLICIT)
2209  {
2210  my_coll_agg_error(av, count, fname, item_sep);
2211  return TRUE;
2212  }
2213 
2214  if ((flags & MY_COLL_DISALLOW_NONE) &&
2215  c.derivation == DERIVATION_NONE)
2216  {
2217  my_coll_agg_error(av, count, fname, item_sep);
2218  return TRUE;
2219  }
2220 
2221  /* If all arguments where numbers, reset to @@collation_connection */
2222  if (flags & MY_COLL_ALLOW_NUMERIC_CONV &&
2223  c.derivation == DERIVATION_NUMERIC)
2224  c.set(Item::default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_NUMERIC);
2225 
2226  return FALSE;
2227 }
2228 
2229 
2230 bool agg_item_collations_for_comparison(DTCollation &c, const char *fname,
2231  Item **av, uint count, uint flags)
2232 {
2233  return (agg_item_collations(c, fname, av, count,
2234  flags | MY_COLL_DISALLOW_NONE, 1));
2235 }
2236 
2237 
2238 bool agg_item_set_converter(DTCollation &coll, const char *fname,
2239  Item **args, uint nargs, uint flags, int item_sep)
2240 {
2241  Item **arg, *safe_args[2]= {NULL, NULL};
2242 
2243  /*
2244  For better error reporting: save the first and the second argument.
2245  We need this only if the the number of args is 3 or 2:
2246  - for a longer argument list, "Illegal mix of collations"
2247  doesn't display each argument's characteristics.
2248  - if nargs is 1, then this error cannot happen.
2249  */
2250  if (nargs >=2 && nargs <= 3)
2251  {
2252  safe_args[0]= args[0];
2253  safe_args[1]= args[item_sep];
2254  }
2255 
2256  THD *thd= current_thd;
2257  bool res= FALSE;
2258  uint i;
2259 
2260  /*
2261  In case we're in statement prepare, create conversion item
2262  in its memory: it will be reused on each execute.
2263  */
2264  Prepared_stmt_arena_holder ps_arena_holder(
2265  thd, thd->stmt_arena->is_stmt_prepare());
2266 
2267  for (i= 0, arg= args; i < nargs; i++, arg+= item_sep)
2268  {
2269  Item* conv;
2270  uint32 dummy_offset;
2271  if (!String::needs_conversion(1, (*arg)->collation.collation,
2272  coll.collation,
2273  &dummy_offset))
2274  continue;
2275 
2276  /*
2277  No needs to add converter if an "arg" is NUMERIC or DATETIME
2278  value (which is pure ASCII) and at the same time target DTCollation
2279  is ASCII-compatible. For example, no needs to rewrite:
2280  SELECT * FROM t1 WHERE datetime_field = '2010-01-01';
2281  to
2282  SELECT * FROM t1 WHERE CONVERT(datetime_field USING cs) = '2010-01-01';
2283 
2284  TODO: avoid conversion of any values with
2285  repertoire ASCII and 7bit-ASCII-compatible,
2286  not only numeric/datetime origin.
2287  */
2288  if ((*arg)->collation.derivation == DERIVATION_NUMERIC &&
2289  (*arg)->collation.repertoire == MY_REPERTOIRE_ASCII &&
2290  !((*arg)->collation.collation->state & MY_CS_NONASCII) &&
2291  !(coll.collation->state & MY_CS_NONASCII))
2292  continue;
2293 
2294  if (!(conv= (*arg)->safe_charset_converter(coll.collation)) &&
2295  ((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII))
2296  conv= new Item_func_conv_charset(*arg, coll.collation, 1);
2297 
2298  if (!conv)
2299  {
2300  if (nargs >=2 && nargs <= 3)
2301  {
2302  /* restore the original arguments for better error message */
2303  args[0]= safe_args[0];
2304  args[item_sep]= safe_args[1];
2305  }
2306  my_coll_agg_error(args, nargs, fname, item_sep);
2307  res= TRUE;
2308  break; // we cannot return here, we need to restore "arena".
2309  }
2310  if ((*arg)->type() == Item::FIELD_ITEM)
2311  ((Item_field *)(*arg))->no_const_subst= 1;
2312  /*
2313  If in statement prepare, then we create a converter for two
2314  constant items, do it once and then reuse it.
2315  If we're in execution of a prepared statement, arena is NULL,
2316  and the conv was created in runtime memory. This can be
2317  the case only if the argument is a parameter marker ('?'),
2318  because for all true constants the charset converter has already
2319  been created in prepare. In this case register the change for
2320  rollback.
2321  */
2322  if (thd->stmt_arena->is_stmt_prepare())
2323  *arg= conv;
2324  else
2325  thd->change_item_tree(arg, conv);
2326 
2327  if (conv->fix_fields(thd, arg))
2328  {
2329  res= TRUE;
2330  break; // we cannot return here, we need to restore "arena".
2331  }
2332  }
2333 
2334  return res;
2335 }
2336 
2337 
2338 /*
2339  Collect arguments' character sets together.
2340  We allow to apply automatic character set conversion in some cases.
2341  The conditions when conversion is possible are:
2342  - arguments A and B have different charsets
2343  - A wins according to coercibility rules
2344  (i.e. a column is stronger than a string constant,
2345  an explicit COLLATE clause is stronger than a column)
2346  - character set of A is either superset for character set of B,
2347  or B is a string constant which can be converted into the
2348  character set of A without data loss.
2349 
2350  If all of the above is true, then it's possible to convert
2351  B into the character set of A, and then compare according
2352  to the collation of A.
2353 
2354  For functions with more than two arguments:
2355 
2356  collect(A,B,C) ::= collect(collect(A,B),C)
2357 
2358  Since this function calls THD::change_item_tree() on the passed Item **
2359  pointers, it is necessary to pass the original Item **'s, not copies.
2360  Otherwise their values will not be properly restored (see BUG#20769).
2361  If the items are not consecutive (eg. args[2] and args[5]), use the
2362  item_sep argument, ie.
2363 
2364  agg_item_charsets(coll, fname, &args[2], 2, flags, 3)
2365 
2366 */
2367 
2368 bool agg_item_charsets(DTCollation &coll, const char *fname,
2369  Item **args, uint nargs, uint flags, int item_sep)
2370 {
2371  if (agg_item_collations(coll, fname, args, nargs, flags, item_sep))
2372  return TRUE;
2373 
2374  return agg_item_set_converter(coll, fname, args, nargs, flags, item_sep);
2375 }
2376 
2377 
2378 void Item_ident_for_show::make_field(Send_field *tmp_field)
2379 {
2380  tmp_field->table_name= tmp_field->org_table_name= table_name;
2381  tmp_field->db_name= db_name;
2382  tmp_field->col_name= tmp_field->org_col_name= field->field_name;
2383  tmp_field->charsetnr= field->charset()->number;
2384  tmp_field->length=field->field_length;
2385  tmp_field->type=field->type();
2386  tmp_field->flags= field->table->maybe_null ?
2387  (field->flags & ~NOT_NULL_FLAG) : field->flags;
2388  tmp_field->decimals= field->decimals();
2389 }
2390 
2391 /**********************************************/
2392 
2393 Item_field::Item_field(Field *f)
2394  :Item_ident(0, NullS, *f->table_name, f->field_name),
2395  item_equal(0), no_const_subst(0),
2396  have_privileges(0), any_privileges(0)
2397 {
2398  set_field(f);
2399  /*
2400  field_name and table_name should not point to garbage
2401  if this item is to be reused
2402  */
2403  orig_table_name= orig_field_name= "";
2404 }
2405 
2406 
2414 Item_field::Item_field(THD *thd, Name_resolution_context *context_arg,
2415  Field *f)
2416  :Item_ident(context_arg, f->table->s->db.str, *f->table_name, f->field_name),
2417  item_equal(0), no_const_subst(0),
2418  have_privileges(0), any_privileges(0)
2419 {
2420  /*
2421  We always need to provide Item_field with a fully qualified field
2422  name to avoid ambiguity when executing prepared statements like
2423  SELECT * from d1.t1, d2.t1; (assuming d1.t1 and d2.t1 have columns
2424  with same names).
2425  This is because prepared statements never deal with wildcards in
2426  select list ('*') and always fix fields using fully specified path
2427  (i.e. db.table.column).
2428  No check for OOM: if db_name is NULL, we'll just get
2429  "Field not found" error.
2430  We need to copy db_name, table_name and field_name because they must
2431  be allocated in the statement memory, not in table memory (the table
2432  structure can go away and pop up again between subsequent executions
2433  of a prepared statement or after the close_tables_for_reopen() call
2434  in mysql_multi_update_prepare() or due to wildcard expansion in stored
2435  procedures).
2436  */
2437  {
2438  if (db_name)
2439  orig_db_name= thd->strdup(db_name);
2440  if (table_name)
2441  orig_table_name= thd->strdup(table_name);
2442  if (field_name)
2443  orig_field_name= thd->strdup(field_name);
2444  /*
2445  We don't restore 'name' in cleanup because it's not changed
2446  during execution. Still we need it to point to persistent
2447  memory if this item is to be reused.
2448  */
2449  item_name.set(orig_field_name);
2450  }
2451  set_field(f);
2452 }
2453 
2454 
2455 Item_field::Item_field(Name_resolution_context *context_arg,
2456  const char *db_arg,const char *table_name_arg,
2457  const char *field_name_arg)
2458  :Item_ident(context_arg, db_arg,table_name_arg,field_name_arg),
2459  field(0), result_field(0), item_equal(0), no_const_subst(0),
2460  have_privileges(0), any_privileges(0)
2461 {
2462  SELECT_LEX *select= current_thd->lex->current_select;
2463  collation.set(DERIVATION_IMPLICIT);
2464  if (select && select->parsing_place != IN_HAVING)
2465  select->select_n_where_fields++;
2466 }
2467 
2472 Item_field::Item_field(THD *thd, Item_field *item)
2473  :Item_ident(thd, item),
2474  field(item->field),
2475  result_field(item->result_field),
2476  item_equal(item->item_equal),
2477  no_const_subst(item->no_const_subst),
2478  have_privileges(item->have_privileges),
2479  any_privileges(item->any_privileges)
2480 {
2481  collation.set(DERIVATION_IMPLICIT);
2482 }
2483 
2484 
2503 inline static uint32
2504 adjust_max_effective_column_length(Field *field_par, uint32 max_length)
2505 {
2506  uint32 new_max_length= field_par->max_display_length();
2507  uint32 sign_length= (field_par->flags & UNSIGNED_FLAG) ? 0 : 1;
2508 
2509  switch (field_par->type())
2510  {
2511  case MYSQL_TYPE_INT24:
2512  /*
2513  Compensate for MAX_MEDIUMINT_WIDTH being 1 too long (8)
2514  compared to the actual number of digits that can fit into
2515  the column.
2516  */
2517  new_max_length+= 1;
2518  /* fall through */
2519  case MYSQL_TYPE_LONG:
2520  case MYSQL_TYPE_TINY:
2521  case MYSQL_TYPE_SHORT:
2522 
2523  /* Take out the sign and add a conditional sign */
2524  new_max_length= new_max_length - 1 + sign_length;
2525  break;
2526 
2527  /* BINGINT is always 20 no matter the sign */
2528  case MYSQL_TYPE_LONGLONG:
2529  /* make gcc happy */
2530  default:
2531  break;
2532  }
2533 
2534  /* Adjust only if the actual precision based one is bigger than specified */
2535  return new_max_length > max_length ? new_max_length : max_length;
2536 }
2537 
2538 
2539 void Item_field::set_field(Field *field_par)
2540 {
2541  field=result_field=field_par; // for easy coding with fields
2542  maybe_null=field->maybe_null();
2543  decimals= field->decimals();
2544  table_name= *field_par->table_name;
2545  field_name= field_par->field_name;
2546  db_name= field_par->table->s->db.str;
2547  alias_name_used= field_par->table->alias_name_used;
2548  unsigned_flag=test(field_par->flags & UNSIGNED_FLAG);
2549  collation.set(field_par->charset(), field_par->derivation(),
2550  field_par->repertoire());
2551  fix_char_length(field_par->char_length());
2552 
2553  max_length= adjust_max_effective_column_length(field_par, max_length);
2554 
2555  fixed= 1;
2556  if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
2557  any_privileges= 0;
2558 }
2559 
2560 
2568 {
2569  set_field(f);
2570  /* 'name' is pointing at field->field_name of old field */
2571  item_name.set(f->field_name);
2572 }
2573 
2574 const char *Item_ident::full_name() const
2575 {
2576  char *tmp;
2577  if (!table_name || !field_name)
2578  return field_name ? field_name : item_name.is_set() ? item_name.ptr() : "tmp_field";
2579  if (db_name && db_name[0])
2580  {
2581  tmp=(char*) sql_alloc((uint) strlen(db_name)+(uint) strlen(table_name)+
2582  (uint) strlen(field_name)+3);
2583  strxmov(tmp,db_name,".",table_name,".",field_name,NullS);
2584  }
2585  else
2586  {
2587  if (table_name[0])
2588  {
2589  tmp= (char*) sql_alloc((uint) strlen(table_name) +
2590  (uint) strlen(field_name) + 2);
2591  strxmov(tmp, table_name, ".", field_name, NullS);
2592  }
2593  else
2594  tmp= (char*) field_name;
2595  }
2596  return tmp;
2597 }
2598 
2599 void Item_ident::print(String *str, enum_query_type query_type)
2600 {
2601  THD *thd= current_thd;
2602  char d_name_buff[MAX_ALIAS_NAME], t_name_buff[MAX_ALIAS_NAME];
2603  const char *d_name= db_name, *t_name= table_name;
2604  if (lower_case_table_names== 1 ||
2605  (lower_case_table_names == 2 && !alias_name_used))
2606  {
2607  if (table_name && table_name[0])
2608  {
2609  strmov(t_name_buff, table_name);
2610  my_casedn_str(files_charset_info, t_name_buff);
2611  t_name= t_name_buff;
2612  }
2613  if (db_name && db_name[0])
2614  {
2615  strmov(d_name_buff, db_name);
2616  my_casedn_str(files_charset_info, d_name_buff);
2617  d_name= d_name_buff;
2618  }
2619  }
2620 
2621  if (!table_name || !field_name || !field_name[0])
2622  {
2623  const char *nm= (field_name && field_name[0]) ?
2624  field_name : item_name.is_set() ? item_name.ptr() : "tmp_field";
2625  append_identifier(thd, str, nm, (uint) strlen(nm));
2626  return;
2627  }
2628  if (db_name && db_name[0] && !alias_name_used)
2629  {
2630  if (!(cached_table && cached_table->belong_to_view &&
2631  cached_table->belong_to_view->compact_view_format))
2632  {
2633  const size_t d_name_len= strlen(d_name);
2634  if (!((query_type & QT_NO_DEFAULT_DB) &&
2635  db_is_default_db(d_name, d_name_len, thd)))
2636  {
2637  append_identifier(thd, str, d_name, (uint)d_name_len);
2638  str->append('.');
2639  }
2640  }
2641  append_identifier(thd, str, t_name, (uint)strlen(t_name));
2642  str->append('.');
2643  append_identifier(thd, str, field_name, (uint)strlen(field_name));
2644  }
2645  else
2646  {
2647  if (table_name[0])
2648  {
2649  append_identifier(thd, str, t_name, (uint) strlen(t_name));
2650  str->append('.');
2651  append_identifier(thd, str, field_name, (uint) strlen(field_name));
2652  }
2653  else
2654  append_identifier(thd, str, field_name, (uint) strlen(field_name));
2655  }
2656 }
2657 
2658 /* ARGSUSED */
2659 String *Item_field::val_str(String *str)
2660 {
2661  DBUG_ASSERT(fixed == 1);
2662  if ((null_value=field->is_null()))
2663  return 0;
2664  str->set_charset(str_value.charset());
2665  return field->val_str(str,&str_value);
2666 }
2667 
2668 
2669 double Item_field::val_real()
2670 {
2671  DBUG_ASSERT(fixed == 1);
2672  if ((null_value=field->is_null()))
2673  return 0.0;
2674  return field->val_real();
2675 }
2676 
2677 
2678 longlong Item_field::val_int()
2679 {
2680  DBUG_ASSERT(fixed == 1);
2681  if ((null_value=field->is_null()))
2682  return 0;
2683  return field->val_int();
2684 }
2685 
2686 
2688 {
2689  DBUG_ASSERT(fixed == 1);
2690  if ((null_value= field->is_null()))
2691  return 0;
2692  return field->val_time_temporal();
2693 }
2694 
2695 
2697 {
2698  DBUG_ASSERT(fixed == 1);
2699  if ((null_value= field->is_null()))
2700  return 0;
2701  return field->val_date_temporal();
2702 }
2703 
2704 
2705 my_decimal *Item_field::val_decimal(my_decimal *decimal_value)
2706 {
2707  if ((null_value= field->is_null()))
2708  return 0;
2709  return field->val_decimal(decimal_value);
2710 }
2711 
2712 
2713 String *Item_field::str_result(String *str)
2714 {
2715  if ((null_value=result_field->is_null()))
2716  return 0;
2717  str->set_charset(str_value.charset());
2718  return result_field->val_str(str,&str_value);
2719 }
2720 
2721 bool Item_field::get_date(MYSQL_TIME *ltime,uint fuzzydate)
2722 {
2723  if ((null_value=field->is_null()) || field->get_date(ltime,fuzzydate))
2724  {
2725  memset(ltime, 0, sizeof(*ltime));
2726  return 1;
2727  }
2728  return 0;
2729 }
2730 
2731 bool Item_field::get_date_result(MYSQL_TIME *ltime,uint fuzzydate)
2732 {
2733  if ((null_value=result_field->is_null()) ||
2734  result_field->get_date(ltime,fuzzydate))
2735  {
2736  memset(ltime, 0, sizeof(*ltime));
2737  return 1;
2738  }
2739  return 0;
2740 }
2741 
2742 bool Item_field::get_time(MYSQL_TIME *ltime)
2743 {
2744  if ((null_value= field->is_null()) || field->get_time(ltime))
2745  {
2746  memset(ltime, 0, sizeof(*ltime));
2747  return 1;
2748  }
2749  return 0;
2750 }
2751 
2752 bool Item_field::get_timeval(struct timeval *tm, int *warnings)
2753 {
2754  if ((null_value= field->is_null()))
2755  return true;
2756  if (field->get_timestamp(tm, warnings))
2757  tm->tv_sec= tm->tv_usec= 0;
2758  return false;
2759 }
2760 
2761 double Item_field::val_result()
2762 {
2763  if ((null_value=result_field->is_null()))
2764  return 0.0;
2765  return result_field->val_real();
2766 }
2767 
2768 longlong Item_field::val_int_result()
2769 {
2770  if ((null_value=result_field->is_null()))
2771  return 0;
2772  return result_field->val_int();
2773 }
2774 
2776 {
2777  if ((null_value= result_field->is_null()))
2778  return 0;
2779  return result_field->val_time_temporal();
2780 }
2781 
2783 {
2784  if ((null_value= result_field->is_null()))
2785  return 0;
2786  return result_field->val_date_temporal();
2787 }
2788 
2789 my_decimal *Item_field::val_decimal_result(my_decimal *decimal_value)
2790 {
2791  if ((null_value= result_field->is_null()))
2792  return 0;
2793  return result_field->val_decimal(decimal_value);
2794 }
2795 
2796 
2797 bool Item_field::val_bool_result()
2798 {
2799  if ((null_value= result_field->is_null()))
2800  return FALSE;
2801  switch (result_field->result_type()) {
2802  case INT_RESULT:
2803  return result_field->val_int() != 0;
2804  case DECIMAL_RESULT:
2805  {
2806  my_decimal decimal_value;
2807  my_decimal *val= result_field->val_decimal(&decimal_value);
2808  if (val)
2809  return !my_decimal_is_zero(val);
2810  return 0;
2811  }
2812  case REAL_RESULT:
2813  case STRING_RESULT:
2814  return result_field->val_real() != 0.0;
2815  case ROW_RESULT:
2816  default:
2817  DBUG_ASSERT(0);
2818  return 0; // Shut up compiler
2819  }
2820 }
2821 
2822 
2823 bool Item_field::is_null_result()
2824 {
2825  return (null_value=result_field->is_null());
2826 }
2827 
2828 
2829 bool Item_field::eq(const Item *item, bool binary_cmp) const
2830 {
2831  Item *real_item= ((Item *) item)->real_item();
2832  if (real_item->type() != FIELD_ITEM)
2833  return 0;
2834 
2835  Item_field *item_field= (Item_field*) real_item;
2836  if (item_field->field && field)
2837  return item_field->field == field;
2838  /*
2839  We may come here when we are trying to find a function in a GROUP BY
2840  clause from the select list.
2841  In this case the '100 % correct' way to do this would be to first
2842  run fix_fields() on the GROUP BY item and then retry this function, but
2843  I think it's better to relax the checking a bit as we will in
2844  most cases do the correct thing by just checking the field name.
2845  (In cases where we would choose wrong we would have to generate a
2846  ER_NON_UNIQ_ERROR).
2847  */
2848  return (item_field->item_name.eq_safe(field_name) &&
2849  (!item_field->table_name || !table_name ||
2850  (!my_strcasecmp(table_alias_charset, item_field->table_name,
2851  table_name) &&
2852  (!item_field->db_name || !db_name ||
2853  (item_field->db_name && !strcmp(item_field->db_name,
2854  db_name))))));
2855 }
2856 
2857 
2858 table_map Item_field::used_tables() const
2859 {
2860  if (field->table->const_table)
2861  return 0; // const item
2862  return (depended_from ? OUTER_REF_TABLE_BIT : field->table->map);
2863 }
2864 
2865 
2867 {
2868  if (field->table->const_table)
2869  return 0; // const item
2870  return field->table->map;
2871 }
2872 
2873 void Item_ident::fix_after_pullout(st_select_lex *parent_select,
2874  st_select_lex *removed_select)
2875 {
2876  /*
2877  Some field items may be created for use in execution only, without
2878  a name resolution context. They have already been used in execution,
2879  so no transformation is necessary here.
2880 
2881  @todo: Provide strict phase-division in optimizer, to make sure that
2882  execution-only objects do not exist during transformation stage.
2883  Then, this test would be deemed unnecessary.
2884  */
2885  if (context == NULL)
2886  {
2887  DBUG_ASSERT(type() == FIELD_ITEM);
2888  return;
2889  }
2890 
2891  if (context->select_lex == removed_select ||
2892  context->select_lex == parent_select)
2893  {
2894  if (parent_select == depended_from)
2895  depended_from= NULL;
2897  ctx->outer_context= NULL; // We don't build a complete name resolver
2898  ctx->table_list= NULL; // We rely on first_name_resolution_table instead
2899  ctx->select_lex= parent_select;
2900  ctx->first_name_resolution_table= context->first_name_resolution_table;
2901  ctx->last_name_resolution_table= context->last_name_resolution_table;
2902  ctx->error_processor= context->error_processor;
2903  ctx->error_processor_data= context->error_processor_data;
2905  ctx->security_ctx= context->security_ctx;
2906  this->context=ctx;
2907  }
2908  else
2909  {
2910  /*
2911  The definition scope of this field item reference is inner to the removed
2912  select_lex object.
2913  No new resolution is needed, but we may need to update the dependency.
2914  */
2915  if (removed_select == depended_from)
2916  depended_from= parent_select;
2917  }
2918 
2919  if (depended_from)
2920  {
2921  /*
2922  Refresh used_tables information for subqueries between the definition
2923  scope and resolution scope of the field item reference.
2924  */
2925  st_select_lex *child_select= context->select_lex;
2926 
2927  while (child_select->outer_select() != depended_from)
2928  {
2929  /*
2930  The subquery on this level is outer-correlated with respect to the field
2931  */
2932  Item_subselect *subq_predicate= child_select->master_unit()->item;
2933 
2934  subq_predicate->used_tables_cache|= OUTER_REF_TABLE_BIT;
2935  child_select= child_select->outer_select();
2936  }
2937 
2938  /*
2939  child_select is select_lex immediately inner to the depended_from level.
2940  Now, locate the subquery predicate that contains this select_lex and
2941  update used tables information.
2942  */
2943  Item_subselect *subq_predicate= child_select->master_unit()->item;
2944 
2945  subq_predicate->used_tables_cache|= this->resolved_used_tables();
2946  subq_predicate->const_item_cache&= this->const_item();
2947  }
2948 }
2949 
2950 
2951 Item *Item_field::get_tmp_table_item(THD *thd)
2952 {
2953  Item_field *new_item= new Item_field(thd, this);
2954  if (new_item)
2955  new_item->field= new_item->result_field;
2956  return new_item;
2957 }
2958 
2959 longlong Item_field::val_int_endpoint(bool left_endp, bool *incl_endp)
2960 {
2961  longlong res= val_int();
2962  return null_value? LONGLONG_MIN : res;
2963 }
2964 
2970 Item_int::Item_int(const char *str_arg, uint length)
2971 {
2972  char *end_ptr= (char*) str_arg + length;
2973  int error;
2974  value= my_strtoll10(str_arg, &end_ptr, &error);
2975  max_length= (uint) (end_ptr - str_arg);
2976  item_name.copy(str_arg, max_length);
2977  fixed= 1;
2978 }
2979 
2980 
2981 my_decimal *Item_int::val_decimal(my_decimal *decimal_value)
2982 {
2983  int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_value);
2984  return decimal_value;
2985 }
2986 
2987 String *Item_int::val_str(String *str)
2988 {
2989  // following assert is redundant, because fixed=1 assigned in constructor
2990  DBUG_ASSERT(fixed == 1);
2991  str->set_int(value, unsigned_flag, collation.collation);
2992  return str;
2993 }
2994 
2995 void Item_int::print(String *str, enum_query_type query_type)
2996 {
2997  // my_charset_bin is good enough for numbers
2998  str_value.set_int(value, unsigned_flag, &my_charset_bin);
2999  str->append(str_value);
3000 }
3001 
3002 
3003 String *Item_uint::val_str(String *str)
3004 {
3005  // following assert is redundant, because fixed=1 assigned in constructor
3006  DBUG_ASSERT(fixed == 1);
3007  str->set((ulonglong) value, collation.collation);
3008  return str;
3009 }
3010 
3011 
3012 void Item_uint::print(String *str, enum_query_type query_type)
3013 {
3014  // latin1 is good enough for numbers
3015  str_value.set((ulonglong) value, default_charset());
3016  str->append(str_value);
3017 }
3018 
3019 
3020 Item_decimal::Item_decimal(const char *str_arg, uint length,
3021  const CHARSET_INFO *charset)
3022 {
3023  str2my_decimal(E_DEC_FATAL_ERROR, str_arg, length, charset, &decimal_value);
3024  item_name.set(str_arg);
3025  decimals= (uint8) decimal_value.frac;
3026  fixed= 1;
3027  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3028  decimals,
3029  decimals,
3030  unsigned_flag);
3031 }
3032 
3033 Item_decimal::Item_decimal(longlong val, bool unsig)
3034 {
3035  int2my_decimal(E_DEC_FATAL_ERROR, val, unsig, &decimal_value);
3036  decimals= (uint8) decimal_value.frac;
3037  fixed= 1;
3038  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3039  decimals,
3040  decimals,
3041  unsigned_flag);
3042 }
3043 
3044 
3045 Item_decimal::Item_decimal(double val, int precision, int scale)
3046 {
3047  double2my_decimal(E_DEC_FATAL_ERROR, val, &decimal_value);
3048  decimals= (uint8) decimal_value.frac;
3049  fixed= 1;
3050  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3051  decimals,
3052  decimals,
3053  unsigned_flag);
3054 }
3055 
3056 
3057 Item_decimal::Item_decimal(const Name_string &name_arg,
3058  const my_decimal *val_arg,
3059  uint decimal_par, uint length)
3060 {
3061  my_decimal2decimal(val_arg, &decimal_value);
3062  item_name= name_arg;
3063  decimals= (uint8) decimal_par;
3064  max_length= length;
3065  fixed= 1;
3066 }
3067 
3068 
3069 Item_decimal::Item_decimal(my_decimal *value_par)
3070 {
3071  my_decimal2decimal(value_par, &decimal_value);
3072  decimals= (uint8) decimal_value.frac;
3073  fixed= 1;
3074  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3075  decimals,
3076  decimals,
3077  unsigned_flag);
3078 }
3079 
3080 
3081 Item_decimal::Item_decimal(const uchar *bin, int precision, int scale)
3082 {
3083  binary2my_decimal(E_DEC_FATAL_ERROR, bin,
3084  &decimal_value, precision, scale);
3085  decimals= (uint8) decimal_value.frac;
3086  fixed= 1;
3087  max_length= my_decimal_precision_to_length_no_truncation(precision, decimals,
3088  unsigned_flag);
3089 }
3090 
3091 
3092 longlong Item_decimal::val_int()
3093 {
3094  longlong result;
3095  my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &result);
3096  return result;
3097 }
3098 
3099 double Item_decimal::val_real()
3100 {
3101  double result;
3102  my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
3103  return result;
3104 }
3105 
3106 String *Item_decimal::val_str(String *result)
3107 {
3108  result->set_charset(&my_charset_numeric);
3109  my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, result);
3110  return result;
3111 }
3112 
3113 void Item_decimal::print(String *str, enum_query_type query_type)
3114 {
3115  my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, &str_value);
3116  str->append(str_value);
3117 }
3118 
3119 
3120 bool Item_decimal::eq(const Item *item, bool binary_cmp) const
3121 {
3122  if (type() == item->type() && item->basic_const_item())
3123  {
3124  /*
3125  We need to cast off const to call val_decimal(). This should
3126  be OK for a basic constant. Additionally, we can pass 0 as
3127  a true decimal constant will return its internal decimal
3128  storage and ignore the argument.
3129  */
3130  Item *arg= (Item*) item;
3131  my_decimal *value= arg->val_decimal(0);
3132  return !my_decimal_cmp(&decimal_value, value);
3133  }
3134  return 0;
3135 }
3136 
3137 
3138 void Item_decimal::set_decimal_value(my_decimal *value_par)
3139 {
3140  my_decimal2decimal(value_par, &decimal_value);
3141  decimals= (uint8) decimal_value.frac;
3142  unsigned_flag= !decimal_value.sign();
3143  max_length= my_decimal_precision_to_length_no_truncation(decimal_value.intg +
3144  decimals,
3145  decimals,
3146  unsigned_flag);
3147 }
3148 
3149 
3150 String *Item_float::val_str(String *str)
3151 {
3152  // following assert is redundant, because fixed=1 assigned in constructor
3153  DBUG_ASSERT(fixed == 1);
3154  str->set_real(value,decimals,&my_charset_bin);
3155  return str;
3156 }
3157 
3158 
3159 my_decimal *Item_float::val_decimal(my_decimal *decimal_value)
3160 {
3161  // following assert is redundant, because fixed=1 assigned in constructor
3162  DBUG_ASSERT(fixed == 1);
3163  double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_value);
3164  return (decimal_value);
3165 }
3166 
3167 
3177 void Item_string::print(String *str, enum_query_type query_type)
3178 {
3179  const bool print_introducer=
3180  !(query_type & QT_WITHOUT_INTRODUCERS) && is_cs_specified();
3181  if (print_introducer)
3182  {
3183  str->append('_');
3184  str->append(collation.collation->csname);
3185  }
3186 
3187  str->append('\'');
3188 
3189  if (query_type & QT_TO_SYSTEM_CHARSET)
3190  {
3191  if (print_introducer)
3192  {
3193  /*
3194  Because we wrote an introducer, we must print str_value in its
3195  charset, and the resulting bytes must not be changed until they
3196  reach the end client.
3197  But the caller is asking for system_charset_info, and may later
3198  convert into character_set_results. That means two conversions: we
3199  must ensure that they don't change our printed bytes.
3200  So we print str_value in the least common denominator of the three
3201  charsets involved: ASCII. Non-ASCII characters are printed as \xFF
3202  sequences (which is ASCII too). This way, our bytes will not be
3203  changed.
3204  */
3205  ErrConvString tmp(str_value.ptr(), str_value.length(), &my_charset_bin);
3206  str->append(tmp.ptr());
3207  }
3208  else
3209  {
3210  if (my_charset_same(str_value.charset(), system_charset_info))
3211  str_value.print(str); // already in system_charset_info
3212  else // need to convert
3213  {
3214  THD *thd= current_thd;
3215  LEX_STRING utf8_lex_str;
3216 
3217  thd->convert_string(&utf8_lex_str,
3218  system_charset_info,
3219  str_value.ptr(),
3220  str_value.length(),
3221  str_value.charset());
3222 
3223  String utf8_str(utf8_lex_str.str,
3224  utf8_lex_str.length,
3225  system_charset_info);
3226 
3227  utf8_str.print(str);
3228  }
3229  }
3230  }
3231  else
3232  {
3233  // Caller wants a result in the charset of str_value.
3234  str_value.print(str);
3235  }
3236 
3237  str->append('\'');
3238 }
3239 
3240 
3241 double
3242 double_from_string_with_check (const CHARSET_INFO *cs,
3243  const char *cptr, char *end)
3244 {
3245  int error;
3246  char *org_end;
3247  double tmp;
3248 
3249  org_end= end;
3250  tmp= my_strntod(cs, (char*) cptr, end - cptr, &end, &error);
3251  if (error || (end != org_end && !check_if_only_end_space(cs, end, org_end)))
3252  {
3253  ErrConvString err(cptr, org_end - cptr, cs);
3254  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3255  ER_TRUNCATED_WRONG_VALUE,
3256  ER(ER_TRUNCATED_WRONG_VALUE), "DOUBLE",
3257  err.ptr());
3258  }
3259  return tmp;
3260 }
3261 
3262 
3263 double Item_string::val_real()
3264 {
3265  DBUG_ASSERT(fixed == 1);
3266  return double_from_string_with_check (str_value.charset(), str_value.ptr(),
3267  (char *) str_value.ptr() + str_value.length());
3268 }
3269 
3270 
3271 longlong
3272 longlong_from_string_with_check (const CHARSET_INFO *cs,
3273  const char *cptr, char *end)
3274 {
3275  int err;
3276  longlong tmp;
3277  char *org_end= end;
3278 
3279  tmp= (*(cs->cset->strtoll10))(cs, cptr, &end, &err);
3280  /*
3281  TODO: Give error if we wanted a signed integer and we got an unsigned
3282  one
3283  */
3284  if (!current_thd->no_errors &&
3285  (err > 0 ||
3286  (end != org_end && !check_if_only_end_space(cs, end, org_end))))
3287  {
3288  ErrConvString err(cptr, cs);
3289  push_warning_printf(current_thd, Sql_condition::WARN_LEVEL_WARN,
3290  ER_TRUNCATED_WRONG_VALUE,
3291  ER(ER_TRUNCATED_WRONG_VALUE), "INTEGER",
3292  err.ptr());
3293  }
3294  return tmp;
3295 }
3296 
3297 
3303 {
3304  DBUG_ASSERT(fixed == 1);
3305  return longlong_from_string_with_check(str_value.charset(), str_value.ptr(),
3306  (char *) str_value.ptr()+ str_value.length());
3307 }
3308 
3309 
3310 my_decimal *Item_string::val_decimal(my_decimal *decimal_value)
3311 {
3312  return val_decimal_from_string(decimal_value);
3313 }
3314 
3315 
3316 bool Item_null::eq(const Item *item, bool binary_cmp) const
3317 { return item->type() == type(); }
3318 
3319 
3320 double Item_null::val_real()
3321 {
3322  // following assert is redundant, because fixed=1 assigned in constructor
3323  DBUG_ASSERT(fixed == 1);
3324  null_value=1;
3325  return 0.0;
3326 }
3327 longlong Item_null::val_int()
3328 {
3329  // following assert is redundant, because fixed=1 assigned in constructor
3330  DBUG_ASSERT(fixed == 1);
3331  null_value=1;
3332  return 0;
3333 }
3334 /* ARGSUSED */
3335 String *Item_null::val_str(String *str)
3336 {
3337  // following assert is redundant, because fixed=1 assigned in constructor
3338  DBUG_ASSERT(fixed == 1);
3339  null_value=1;
3340  return 0;
3341 }
3342 
3343 my_decimal *Item_null::val_decimal(my_decimal *decimal_value)
3344 {
3345  return 0;
3346 }
3347 
3348 
3349 Item *Item_null::safe_charset_converter(const CHARSET_INFO *tocs)
3350 {
3351  collation.set(tocs);
3352  return this;
3353 }
3354 
3355 /*********************** Item_param related ******************************/
3356 
3362 static void
3363 default_set_param_func(Item_param *param,
3364  uchar **pos __attribute__((unused)),
3365  ulong len __attribute__((unused)))
3366 {
3367  param->set_null();
3368 }
3369 
3370 
3371 Item_param::Item_param(uint pos_in_query_arg) :
3372  state(NO_VALUE),
3373  item_result_type(STRING_RESULT),
3374  /* Don't pretend to be a literal unless value for this item is set. */
3375  item_type(PARAM_ITEM),
3376  param_type(MYSQL_TYPE_VARCHAR),
3377  pos_in_query(pos_in_query_arg),
3378  set_param_func(default_set_param_func),
3379  limit_clause_param(FALSE),
3380  m_out_param_info(NULL)
3381 {
3382  item_name.set("?");
3383  /*
3384  Since we can't say whenever this item can be NULL or cannot be NULL
3385  before mysql_stmt_execute(), so we assuming that it can be NULL until
3386  value is set.
3387  */
3388  maybe_null= 1;
3389  cnvitem= new Item_string("", 0, &my_charset_bin, DERIVATION_COERCIBLE);
3390  cnvstr.set(cnvbuf, sizeof(cnvbuf), &my_charset_bin);
3391 }
3392 
3393 
3394 void Item_param::set_null()
3395 {
3396  DBUG_ENTER("Item_param::set_null");
3397  /* These are cleared after each execution by reset() method */
3398  null_value= 1;
3399  /*
3400  Because of NULL and string values we need to set max_length for each new
3401  placeholder value: user can submit NULL for any placeholder type, and
3402  string length can be different in each execution.
3403  */
3404  max_length= 0;
3405  decimals= 0;
3406  state= NULL_VALUE;
3407  item_type= Item::NULL_ITEM;
3408  DBUG_VOID_RETURN;
3409 }
3410 
3411 void Item_param::set_int(longlong i, uint32 max_length_arg)
3412 {
3413  DBUG_ENTER("Item_param::set_int");
3414  value.integer= (longlong) i;
3415  state= INT_VALUE;
3416  max_length= max_length_arg;
3417  decimals= 0;
3418  maybe_null= 0;
3419  DBUG_VOID_RETURN;
3420 }
3421 
3422 void Item_param::set_double(double d)
3423 {
3424  DBUG_ENTER("Item_param::set_double");
3425  value.real= d;
3426  state= REAL_VALUE;
3427  max_length= DBL_DIG + 8;
3428  decimals= NOT_FIXED_DEC;
3429  maybe_null= 0;
3430  DBUG_VOID_RETURN;
3431 }
3432 
3433 
3446 void Item_param::set_decimal(const char *str, ulong length)
3447 {
3448  char *end;
3449  DBUG_ENTER("Item_param::set_decimal");
3450 
3451  end= (char*) str+length;
3452  str2my_decimal(E_DEC_FATAL_ERROR, str, &decimal_value, &end);
3453  state= DECIMAL_VALUE;
3454  decimals= decimal_value.frac;
3455  max_length=
3456  my_decimal_precision_to_length_no_truncation(decimal_value.precision(),
3457  decimals, unsigned_flag);
3458  maybe_null= 0;
3459  DBUG_VOID_RETURN;
3460 }
3461 
3462 void Item_param::set_decimal(const my_decimal *dv)
3463 {
3464  state= DECIMAL_VALUE;
3465 
3466  my_decimal2decimal(dv, &decimal_value);
3467 
3468  decimals= (uint8) decimal_value.frac;
3469  unsigned_flag= !decimal_value.sign();
3470  max_length= my_decimal_precision_to_length(decimal_value.intg + decimals,
3471  decimals, unsigned_flag);
3472 }
3473 
3487 void Item_param::set_time(MYSQL_TIME *tm, timestamp_type time_type,
3488  uint32 max_length_arg)
3489 {
3490  DBUG_ENTER("Item_param::set_time");
3491 
3492  value.time= *tm;
3493  value.time.time_type= time_type;
3494 
3495  if (check_datetime_range(&value.time))
3496  {
3497  make_truncated_value_warning(ErrConvString(&value.time,
3498  MY_MIN(decimals,
3499  DATETIME_MAX_DECIMALS)),
3500  time_type);
3501  set_zero_time(&value.time, MYSQL_TIMESTAMP_ERROR);
3502  }
3503 
3504  state= TIME_VALUE;
3505  maybe_null= 0;
3506  max_length= max_length_arg;
3507  decimals= 0;
3508  DBUG_VOID_RETURN;
3509 }
3510 
3511 
3512 bool Item_param::set_str(const char *str, ulong length)
3513 {
3514  DBUG_ENTER("Item_param::set_str");
3515  /*
3516  Assign string with no conversion: data is converted only after it's
3517  been written to the binary log.
3518  */
3519  uint dummy_errors;
3520  if (str_value.copy(str, length, &my_charset_bin, &my_charset_bin,
3521  &dummy_errors))
3522  DBUG_RETURN(TRUE);
3523  state= STRING_VALUE;
3524  max_length= length;
3525  maybe_null= 0;
3526  /* max_length and decimals are set after charset conversion */
3527  /* sic: str may be not null-terminated, don't add DBUG_PRINT here */
3528  DBUG_RETURN(FALSE);
3529 }
3530 
3531 
3532 bool Item_param::set_longdata(const char *str, ulong length)
3533 {
3534  DBUG_ENTER("Item_param::set_longdata");
3535 
3536  /*
3537  If client character set is multibyte, end of long data packet
3538  may hit at the middle of a multibyte character. Additionally,
3539  if binary log is open we must write long data value to the
3540  binary log in character set of client. This is why we can't
3541  convert long data to connection character set as it comes
3542  (here), and first have to concatenate all pieces together,
3543  write query to the binary log and only then perform conversion.
3544  */
3545  if (str_value.length() + length > current_thd->variables.max_allowed_packet)
3546  {
3547  my_message(ER_UNKNOWN_ERROR,
3548  "Parameter of prepared statement which is set through "
3549  "mysql_send_long_data() is longer than "
3550  "'max_allowed_packet' bytes",
3551  MYF(0));
3552  DBUG_RETURN(true);
3553  }
3554 
3555  if (str_value.append(str, length, &my_charset_bin))
3556  DBUG_RETURN(TRUE);
3557  state= LONG_DATA_VALUE;
3558  maybe_null= 0;
3559 
3560  DBUG_RETURN(FALSE);
3561 }
3562 
3563 
3576 bool Item_param::set_from_user_var(THD *thd, const user_var_entry *entry)
3577 {
3578  DBUG_ENTER("Item_param::set_from_user_var");
3579  if (entry && entry->ptr())
3580  {
3581  item_result_type= entry->type();
3582  unsigned_flag= entry->unsigned_flag;
3583  if (limit_clause_param)
3584  {
3585  my_bool unused;
3586  set_int(entry->val_int(&unused), MY_INT64_NUM_DECIMAL_DIGITS);
3587  item_type= Item::INT_ITEM;
3588  DBUG_RETURN(!unsigned_flag && value.integer < 0 ? 1 : 0);
3589  }
3590  switch (item_result_type) {
3591  case REAL_RESULT:
3592  set_double(*(double*) entry->ptr());
3593  item_type= Item::REAL_ITEM;
3594  break;
3595  case INT_RESULT:
3596  set_int(*(longlong*) entry->ptr(), MY_INT64_NUM_DECIMAL_DIGITS);
3597  item_type= Item::INT_ITEM;
3598  break;
3599  case STRING_RESULT:
3600  {
3601  const CHARSET_INFO *fromcs= entry->collation.collation;
3602  const CHARSET_INFO *tocs= thd->variables.collation_connection;
3603  uint32 dummy_offset;
3604 
3605  value.cs_info.character_set_of_placeholder= fromcs;
3606  value.cs_info.character_set_client= thd->variables.character_set_client;
3607  /*
3608  Setup source and destination character sets so that they
3609  are different only if conversion is necessary: this will
3610  make later checks easier.
3611  */
3612  value.cs_info.final_character_set_of_str_value=
3613  String::needs_conversion(0, fromcs, tocs, &dummy_offset) ?
3614  tocs : fromcs;
3615  /*
3616  Exact value of max_length is not known unless data is converted to
3617  charset of connection, so we have to set it later.
3618  */
3619  item_type= Item::STRING_ITEM;
3620 
3621  if (set_str((const char *) entry->ptr(), entry->length()))
3622  DBUG_RETURN(1);
3623  break;
3624  }
3625  case DECIMAL_RESULT:
3626  {
3627  const my_decimal *ent_value= (const my_decimal *) entry->ptr();
3628  my_decimal2decimal(ent_value, &decimal_value);
3629  state= DECIMAL_VALUE;
3630  decimals= ent_value->frac;
3631  max_length=
3632  my_decimal_precision_to_length_no_truncation(ent_value->precision(),
3633  decimals, unsigned_flag);
3634  item_type= Item::DECIMAL_ITEM;
3635  break;
3636  }
3637  default:
3638  DBUG_ASSERT(0);
3639  set_null();
3640  }
3641  }
3642  else
3643  set_null();
3644 
3645  DBUG_RETURN(0);
3646 }
3647 
3657 {
3658  DBUG_ENTER("Item_param::reset");
3659  /* Shrink string buffer if it's bigger than max possible CHAR column */
3660  if (str_value.alloced_length() > MAX_CHAR_WIDTH)
3661  str_value.free();
3662  else
3663  str_value.length(0);
3664  str_value_ptr.length(0);
3665  /*
3666  We must prevent all charset conversions until data has been written
3667  to the binary log.
3668  */
3669  str_value.set_charset(&my_charset_bin);
3670  collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
3671  state= NO_VALUE;
3672  maybe_null= 1;
3673  null_value= 0;
3674  /*
3675  Don't reset item_type to PARAM_ITEM: it's only needed to guard
3676  us from item optimizations at prepare stage, when item doesn't yet
3677  contain a literal of some kind.
3678  In all other cases when this object is accessed its value is
3679  set (this assumption is guarded by 'state' and
3680  DBUG_ASSERTS(state != NO_VALUE) in all Item_param::get_*
3681  methods).
3682  */
3683  DBUG_VOID_RETURN;
3684 }
3685 
3686 
3687 type_conversion_status
3688 Item_param::save_in_field(Field *field, bool no_conversions)
3689 {
3690  field->set_notnull();
3691 
3692  switch (state) {
3693  case INT_VALUE:
3694  return field->store(value.integer, unsigned_flag);
3695  case REAL_VALUE:
3696  return field->store(value.real);
3697  case DECIMAL_VALUE:
3698  return field->store_decimal(&decimal_value);
3699  case TIME_VALUE:
3700  field->store_time(&value.time);
3701  return TYPE_OK;
3702  case STRING_VALUE:
3703  case LONG_DATA_VALUE:
3704  return field->store(str_value.ptr(), str_value.length(),
3705  str_value.charset());
3706  case NULL_VALUE:
3707  return set_field_to_null_with_conversions(field, no_conversions);
3708  case NO_VALUE:
3709  default:
3710  DBUG_ASSERT(0);
3711  }
3712  return TYPE_ERR_BAD_VALUE;
3713 }
3714 
3715 
3716 bool Item_param::get_time(MYSQL_TIME *res)
3717 {
3718  if (state == TIME_VALUE)
3719  {
3720  *res= value.time;
3721  return 0;
3722  }
3723  /*
3724  If parameter value isn't supplied assertion will fire in val_str()
3725  which is called from Item::get_time_from_string().
3726  */
3727  return is_temporal() ? get_time_from_string(res) :
3729 }
3730 
3731 
3732 bool Item_param::get_date(MYSQL_TIME *res, uint fuzzydate)
3733 {
3734  if (state == TIME_VALUE)
3735  {
3736  *res= value.time;
3737  return 0;
3738  }
3739  return is_temporal() ? get_date_from_string(res, fuzzydate) :
3740  get_date_from_non_temporal(res, fuzzydate);
3741 }
3742 
3743 
3744 double Item_param::val_real()
3745 {
3746  switch (state) {
3747  case REAL_VALUE:
3748  return value.real;
3749  case INT_VALUE:
3750  return (double) value.integer;
3751  case DECIMAL_VALUE:
3752  {
3753  double result;
3754  my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &result);
3755  return result;
3756  }
3757  case STRING_VALUE:
3758  case LONG_DATA_VALUE:
3759  {
3760  int dummy_err;
3761  char *end_not_used;
3762  return my_strntod(str_value.charset(), (char*) str_value.ptr(),
3763  str_value.length(), &end_not_used, &dummy_err);
3764  }
3765  case TIME_VALUE:
3766  /*
3767  This works for example when user says SELECT ?+0.0 and supplies
3768  time value for the placeholder.
3769  */
3770  return TIME_to_double(&value.time);
3771  case NULL_VALUE:
3772  return 0.0;
3773  default:
3774  DBUG_ASSERT(0);
3775  }
3776  return 0.0;
3777 }
3778 
3779 
3780 longlong Item_param::val_int()
3781 {
3782  switch (state) {
3783  case REAL_VALUE:
3784  return (longlong) rint(value.real);
3785  case INT_VALUE:
3786  return value.integer;
3787  case DECIMAL_VALUE:
3788  {
3789  longlong i;
3790  my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &i);
3791  return i;
3792  }
3793  case STRING_VALUE:
3794  case LONG_DATA_VALUE:
3795  {
3796  int dummy_err;
3797  return my_strntoll(str_value.charset(), str_value.ptr(),
3798  str_value.length(), 10, (char**) 0, &dummy_err);
3799  }
3800  case TIME_VALUE:
3801  return (longlong) TIME_to_ulonglong_round(&value.time);
3802  case NULL_VALUE:
3803  return 0;
3804  default:
3805  DBUG_ASSERT(0);
3806  }
3807  return 0;
3808 }
3809 
3810 
3811 my_decimal *Item_param::val_decimal(my_decimal *dec)
3812 {
3813  switch (state) {
3814  case DECIMAL_VALUE:
3815  return &decimal_value;
3816  case REAL_VALUE:
3817  double2my_decimal(E_DEC_FATAL_ERROR, value.real, dec);
3818  return dec;
3819  case INT_VALUE:
3820  int2my_decimal(E_DEC_FATAL_ERROR, value.integer, unsigned_flag, dec);
3821  return dec;
3822  case STRING_VALUE:
3823  case LONG_DATA_VALUE:
3824  string2my_decimal(E_DEC_FATAL_ERROR, &str_value, dec);
3825  return dec;
3826  case TIME_VALUE:
3827  return date2my_decimal(&value.time, dec);
3828  case NULL_VALUE:
3829  return 0;
3830  default:
3831  DBUG_ASSERT(0);
3832  }
3833  return 0;
3834 }
3835 
3836 
3837 String *Item_param::val_str(String* str)
3838 {
3839  switch (state) {
3840  case STRING_VALUE:
3841  case LONG_DATA_VALUE:
3842  return &str_value_ptr;
3843  case REAL_VALUE:
3844  str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
3845  return str;
3846  case INT_VALUE:
3847  str->set(value.integer, &my_charset_bin);
3848  return str;
3849  case DECIMAL_VALUE:
3850  if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
3851  0, 0, 0, str) <= 1)
3852  return str;
3853  return NULL;
3854  case TIME_VALUE:
3855  {
3856  if (str->reserve(MAX_DATE_STRING_REP_LENGTH))
3857  break;
3858  str->length((uint) my_TIME_to_str(&value.time, (char *) str->ptr(),
3859  MY_MIN(decimals, DATETIME_MAX_DECIMALS)));
3860  str->set_charset(&my_charset_bin);
3861  return str;
3862  }
3863  case NULL_VALUE:
3864  return NULL;
3865  default:
3866  DBUG_ASSERT(0);
3867  }
3868  return str;
3869 }
3870 
3882 const String *Item_param::query_val_str(THD *thd, String* str) const
3883 {
3884  switch (state) {
3885  case INT_VALUE:
3886  str->set_int(value.integer, unsigned_flag, &my_charset_bin);
3887  break;
3888  case REAL_VALUE:
3889  str->set_real(value.real, NOT_FIXED_DEC, &my_charset_bin);
3890  break;
3891  case DECIMAL_VALUE:
3892  if (my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value,
3893  0, 0, 0, str) > 1)
3894  return &my_null_string;
3895  break;
3896  case TIME_VALUE:
3897  {
3898  char *buf, *ptr;
3899  str->length(0);
3900  /*
3901  TODO: in case of error we need to notify replication
3902  that binary log contains wrong statement
3903  */
3904  if (str->reserve(MAX_DATE_STRING_REP_LENGTH+3))
3905  break;
3906 
3907  /* Create date string inplace */
3908  buf= str->c_ptr_quick();
3909  ptr= buf;
3910  *ptr++= '\'';
3911  ptr+= (uint) my_TIME_to_str(&value.time, ptr,
3912  MY_MIN(decimals, DATETIME_MAX_DECIMALS));
3913  *ptr++= '\'';
3914  str->length((uint32) (ptr - buf));
3915  break;
3916  }
3917  case STRING_VALUE:
3918  case LONG_DATA_VALUE:
3919  {
3920  str->length(0);
3921  append_query_string(thd, value.cs_info.character_set_client, &str_value,
3922  str);
3923  break;
3924  }
3925  case NULL_VALUE:
3926  return &my_null_string;
3927  default:
3928  DBUG_ASSERT(0);
3929  }
3930  return str;
3931 }
3932 
3933 
3940 {
3941  bool rc= FALSE;
3942  if (state == STRING_VALUE || state == LONG_DATA_VALUE)
3943  {
3944  /*
3945  Check is so simple because all charsets were set up properly
3946  in setup_one_conversion_function, where typecode of
3947  placeholder was also taken into account: the variables are different
3948  here only if conversion is really necessary.
3949  */
3950  if (value.cs_info.final_character_set_of_str_value !=
3951  value.cs_info.character_set_of_placeholder)
3952  {
3953  rc= thd->convert_string(&str_value,
3954  value.cs_info.character_set_of_placeholder,
3955  value.cs_info.final_character_set_of_str_value);
3956  }
3957  else
3958  str_value.set_charset(value.cs_info.final_character_set_of_str_value);
3959  /* Here str_value is guaranteed to be in final_character_set_of_str_value */
3960 
3961  max_length= str_value.numchars() * str_value.charset()->mbmaxlen;
3962 
3963  /* For the strings converted to numeric form within some functions */
3964  decimals= NOT_FIXED_DEC;
3965  /*
3966  str_value_ptr is returned from val_str(). It must be not alloced
3967  to prevent it's modification by val_str() invoker.
3968  */
3969  str_value_ptr.set(str_value.ptr(), str_value.length(),
3970  str_value.charset());
3971  /* Synchronize item charset with value charset */
3972  collation.set(str_value.charset(), DERIVATION_COERCIBLE);
3973  }
3974  return rc;
3975 }
3976 
3977 
3978 bool Item_param::basic_const_item() const
3979 {
3980  if (state == NO_VALUE || state == TIME_VALUE)
3981  return FALSE;
3982  return TRUE;
3983 }
3984 
3985 
3986 Item *
3987 Item_param::clone_item()
3988 {
3989  /* see comments in the header file */
3990  switch (state) {
3991  case NULL_VALUE:
3992  return new Item_null(item_name);
3993  case INT_VALUE:
3994  return (unsigned_flag ?
3995  new Item_uint(item_name, value.integer, max_length) :
3996  new Item_int(item_name, value.integer, max_length));
3997  case REAL_VALUE:
3998  return new Item_float(item_name, value.real, decimals, max_length);
3999  case STRING_VALUE:
4000  case LONG_DATA_VALUE:
4001  return new Item_string(item_name, str_value.c_ptr_quick(), str_value.length(),
4002  str_value.charset());
4003  case TIME_VALUE:
4004  break;
4005  case NO_VALUE:
4006  default:
4007  DBUG_ASSERT(0);
4008  };
4009  return 0;
4010 }
4011 
4012 
4013 bool
4014 Item_param::eq(const Item *arg, bool binary_cmp) const
4015 {
4016  Item *item;
4017  if (!basic_const_item() || !arg->basic_const_item() || arg->type() != type())
4018  return FALSE;
4019  /*
4020  We need to cast off const to call val_int(). This should be OK for
4021  a basic constant.
4022  */
4023  item= (Item*) arg;
4024 
4025  switch (state) {
4026  case NULL_VALUE:
4027  return TRUE;
4028  case INT_VALUE:
4029  return value.integer == item->val_int() &&
4030  unsigned_flag == item->unsigned_flag;
4031  case REAL_VALUE:
4032  return value.real == item->val_real();
4033  case STRING_VALUE:
4034  case LONG_DATA_VALUE:
4035  if (binary_cmp)
4036  return !stringcmp(&str_value, &item->str_value);
4037  return !sortcmp(&str_value, &item->str_value, collation.collation);
4038  default:
4039  break;
4040  }
4041  return FALSE;
4042 }
4043 
4044 /* End of Item_param related */
4045 
4046 void Item_param::print(String *str, enum_query_type query_type)
4047 {
4048  if (state == NO_VALUE)
4049  {
4050  str->append('?');
4051  }
4052  else
4053  {
4054  char buffer[STRING_BUFFER_USUAL_SIZE];
4055  String tmp(buffer, sizeof(buffer), &my_charset_bin);
4056  const String *res;
4057  res= query_val_str(current_thd, &tmp);
4058  str->append(*res);
4059  }
4060 }
4061 
4062 
4084 void
4086 {
4087  unsigned_flag= src->unsigned_flag;
4088  param_type= src->param_type;
4089  set_param_func= src->set_param_func;
4090  item_type= src->item_type;
4091  item_result_type= src->item_result_type;
4092 
4093  collation.set(src->collation);
4094  maybe_null= src->maybe_null;
4095  null_value= src->null_value;
4096  max_length= src->max_length;
4097  decimals= src->decimals;
4098  state= src->state;
4099  value= src->value;
4100 
4101  decimal_value.swap(src->decimal_value);
4102  str_value.swap(src->str_value);
4103  str_value_ptr.swap(src->str_value_ptr);
4104 }
4105 
4106 
4120 bool
4121 Item_param::set_value(THD *thd, sp_rcontext *ctx, Item **it)
4122 {
4123  Item *arg= *it;
4124 
4125  if (arg->is_null())
4126  {
4127  set_null();
4128  return FALSE;
4129  }
4130 
4131  null_value= FALSE;
4132 
4133  switch (arg->result_type()) {
4134  case STRING_RESULT:
4135  {
4136  char str_buffer[STRING_BUFFER_USUAL_SIZE];
4137  String sv_buffer(str_buffer, sizeof(str_buffer), &my_charset_bin);
4138  String *sv= arg->val_str(&sv_buffer);
4139 
4140  if (!sv)
4141  return TRUE;
4142 
4143  set_str(sv->c_ptr_safe(), sv->length());
4144  str_value_ptr.set(str_value.ptr(),
4145  str_value.length(),
4146  str_value.charset());
4147  collation.set(str_value.charset(), DERIVATION_COERCIBLE);
4148  decimals= 0;
4149  item_type= Item::STRING_ITEM;
4150  break;
4151  }
4152 
4153  case REAL_RESULT:
4154  set_double(arg->val_real());
4155  item_type= Item::REAL_ITEM;
4156  break;
4157 
4158  case INT_RESULT:
4159  set_int(arg->val_int(), arg->max_length);
4160  item_type= Item::INT_ITEM;
4161  break;
4162 
4163  case DECIMAL_RESULT:
4164  {
4165  my_decimal dv_buf;
4166  my_decimal *dv= arg->val_decimal(&dv_buf);
4167 
4168  if (!dv)
4169  return TRUE;
4170 
4171  set_decimal(dv);
4172  item_type= Item::DECIMAL_ITEM;
4173  break;
4174  }
4175 
4176  default:
4177  /* That can not happen. */
4178 
4179  DBUG_ASSERT(TRUE); // Abort in debug mode.
4180 
4181  set_null(); // Set to NULL in release mode.
4182  item_type= Item::NULL_ITEM;
4183  return FALSE;
4184  }
4185 
4186  item_result_type= arg->result_type();
4187  return FALSE;
4188 }
4189 
4190 
4200 void
4201 Item_param::set_out_param_info(Send_field *info)
4202 {
4203  m_out_param_info= info;
4204  param_type= m_out_param_info->type;
4205 }
4206 
4207 
4218 const Send_field *
4220 {
4221  return m_out_param_info;
4222 }
4223 
4224 
4234 {
4235  Item::make_field(field);
4236 
4237  if (!m_out_param_info)
4238  return;
4239 
4240  /*
4241  This is an OUT-parameter of stored procedure. We should use
4242  OUT-parameter info to fill out the names.
4243  */
4244 
4245  field->db_name= m_out_param_info->db_name;
4246  field->table_name= m_out_param_info->table_name;
4247  field->org_table_name= m_out_param_info->org_table_name;
4248  field->col_name= m_out_param_info->col_name;
4249  field->org_col_name= m_out_param_info->org_col_name;
4250 
4251  field->length= m_out_param_info->length;
4252  field->charsetnr= m_out_param_info->charsetnr;
4253  field->flags= m_out_param_info->flags;
4254  field->decimals= m_out_param_info->decimals;
4255  field->type= m_out_param_info->type;
4256 }
4257 
4258 /****************************************************************************
4259  Item_copy
4260 ****************************************************************************/
4262 {
4263  switch (item->result_type())
4264  {
4265  case STRING_RESULT:
4266  return new Item_copy_string (item);
4267  case REAL_RESULT:
4268  return new Item_copy_float (item);
4269  case INT_RESULT:
4270  return item->unsigned_flag ?
4271  new Item_copy_uint (item) : new Item_copy_int (item);
4272  case DECIMAL_RESULT:
4273  return new Item_copy_decimal (item);
4274  default:
4275  DBUG_ASSERT (0);
4276  }
4277  /* should not happen */
4278  return NULL;
4279 }
4280 
4281 /****************************************************************************
4282  Item_copy_string
4283 ****************************************************************************/
4284 
4285 double Item_copy_string::val_real()
4286 {
4287  int err_not_used;
4288  char *end_not_used;
4289  return (null_value ? 0.0 :
4290  my_strntod(str_value.charset(), (char*) str_value.ptr(),
4291  str_value.length(), &end_not_used, &err_not_used));
4292 }
4293 
4294 longlong Item_copy_string::val_int()
4295 {
4296  int err;
4297  return null_value ? LL(0) : my_strntoll(str_value.charset(),str_value.ptr(),
4298  str_value.length(),10, (char**) 0,
4299  &err);
4300 }
4301 
4302 
4303 type_conversion_status
4304 Item_copy_string::save_in_field(Field *field, bool no_conversions)
4305 {
4306  return save_str_value_in_field(field, &str_value);
4307 }
4308 
4309 
4311 {
4312  String *res=item->val_str(&str_value);
4313  if (res && res != &str_value)
4314  str_value.copy(*res);
4315  null_value=item->null_value;
4316 }
4317 
4318 /* ARGSUSED */
4319 String *Item_copy_string::val_str(String *str)
4320 {
4321  // Item_copy_string is used without fix_fields call
4322  if (null_value)
4323  return (String*) 0;
4324  return &str_value;
4325 }
4326 
4327 
4328 my_decimal *Item_copy_string::val_decimal(my_decimal *decimal_value)
4329 {
4330  // Item_copy_string is used without fix_fields call
4331  if (null_value)
4332  return (my_decimal *) 0;
4333  string2my_decimal(E_DEC_FATAL_ERROR, &str_value, decimal_value);
4334  return (decimal_value);
4335 }
4336 
4337 
4338 bool Item_copy_string::get_date(MYSQL_TIME *ltime, uint fuzzydate)
4339 {
4340  return get_date_from_string(ltime, fuzzydate);
4341 }
4342 
4343 bool Item_copy_string::get_time(MYSQL_TIME *ltime)
4344 {
4345  return get_time_from_string(ltime);
4346 }
4347 
4348 /****************************************************************************
4349  Item_copy_int
4350 ****************************************************************************/
4351 
4353 {
4354  cached_value= item->val_int();
4355  null_value=item->null_value;
4356 }
4357 
4358 static type_conversion_status
4359 save_int_value_in_field (Field *field, longlong nr,
4360  bool null_value, bool unsigned_flag);
4361 
4362 type_conversion_status
4363 Item_copy_int::save_in_field(Field *field, bool no_conversions)
4364 {
4365  return save_int_value_in_field(field, cached_value,
4366  null_value, unsigned_flag);
4367 }
4368 
4369 
4370 String *Item_copy_int::val_str(String *str)
4371 {
4372  if (null_value)
4373  return (String *) 0;
4374 
4375  str->set(cached_value, &my_charset_bin);
4376  return str;
4377 }
4378 
4379 
4380 my_decimal *Item_copy_int::val_decimal(my_decimal *decimal_value)
4381 {
4382  if (null_value)
4383  return (my_decimal *) 0;
4384 
4385  int2my_decimal(E_DEC_FATAL_ERROR, cached_value, unsigned_flag, decimal_value);
4386  return decimal_value;
4387 }
4388 
4389 
4390 /****************************************************************************
4391  Item_copy_uint
4392 ****************************************************************************/
4393 
4394 String *Item_copy_uint::val_str(String *str)
4395 {
4396  if (null_value)
4397  return (String *) 0;
4398 
4399  str->set((ulonglong) cached_value, &my_charset_bin);
4400  return str;
4401 }
4402 
4403 
4404 /****************************************************************************
4405  Item_copy_float
4406 ****************************************************************************/
4407 
4408 String *Item_copy_float::val_str(String *str)
4409 {
4410  if (null_value)
4411  return (String *) 0;
4412  else
4413  {
4414  double nr= val_real();
4415  str->set_real(nr,decimals, &my_charset_bin);
4416  return str;
4417  }
4418 }
4419 
4420 
4421 my_decimal *Item_copy_float::val_decimal(my_decimal *decimal_value)
4422 {
4423  if (null_value)
4424  return (my_decimal *) 0;
4425  else
4426  {
4427  double nr= val_real();
4428  double2my_decimal(E_DEC_FATAL_ERROR, nr, decimal_value);
4429  return decimal_value;
4430  }
4431 }
4432 
4433 
4434 type_conversion_status
4435 Item_copy_float::save_in_field(Field *field, bool no_conversions)
4436 {
4437  // TODO: call set_field_to_null_with_conversions below
4438  if (null_value)
4439  return set_field_to_null(field);
4440 
4441  field->set_notnull();
4442  return field->store(cached_value);
4443 }
4444 
4445 
4446 /****************************************************************************
4447  Item_copy_decimal
4448 ****************************************************************************/
4449 
4450 type_conversion_status
4451 Item_copy_decimal::save_in_field(Field *field, bool no_conversions)
4452 {
4453  // TODO: call set_field_to_null_with_conversions below
4454  if (null_value)
4455  return set_field_to_null(field);
4456  field->set_notnull();
4457  return field->store_decimal(&cached_value);
4458 }
4459 
4460 
4461 String *Item_copy_decimal::val_str(String *result)
4462 {
4463  if (null_value)
4464  return (String *) 0;
4465  result->set_charset(&my_charset_bin);
4466  my_decimal2string(E_DEC_FATAL_ERROR, &cached_value, 0, 0, 0, result);
4467  return result;
4468 }
4469 
4470 
4471 double Item_copy_decimal::val_real()
4472 {
4473  if (null_value)
4474  return 0.0;
4475  else
4476  {
4477  double result;
4478  my_decimal2double(E_DEC_FATAL_ERROR, &cached_value, &result);
4479  return result;
4480  }
4481 }
4482 
4483 
4484 longlong Item_copy_decimal::val_int()
4485 {
4486  if (null_value)
4487  return LL(0);
4488  else
4489  {
4490  longlong result;
4491  my_decimal2int(E_DEC_FATAL_ERROR, &cached_value, unsigned_flag, &result);
4492  return result;
4493  }
4494 }
4495 
4496 
4498 {
4499  my_decimal *nr= item->val_decimal(&cached_value);
4500  if (nr && nr != &cached_value)
4501  my_decimal2decimal (nr, &cached_value);
4502  null_value= item->null_value;
4503 }
4504 
4505 
4506 /*
4507  Functions to convert item to field (for send_result_set_metadata)
4508 */
4509 
4510 /* ARGSUSED */
4511 bool Item::fix_fields(THD *thd, Item **ref)
4512 {
4513 
4514  // We do not check fields which are fixed during construction
4515  DBUG_ASSERT(fixed == 0 || basic_const_item());
4516  fixed= 1;
4517  return FALSE;
4518 }
4519 
4520 double Item_ref_null_helper::val_real()
4521 {
4522  DBUG_ASSERT(fixed == 1);
4523  double tmp= (*ref)->val_result();
4524  owner->was_null|= null_value= (*ref)->null_value;
4525  return tmp;
4526 }
4527 
4528 
4529 longlong Item_ref_null_helper::val_int()
4530 {
4531  DBUG_ASSERT(fixed == 1);
4532  longlong tmp= (*ref)->val_int_result();
4533  owner->was_null|= null_value= (*ref)->null_value;
4534  return tmp;
4535 }
4536 
4537 
4539 {
4540  DBUG_ASSERT(fixed == 1);
4541  DBUG_ASSERT((*ref)->is_temporal());
4542  longlong tmp= (*ref)->val_time_temporal_result();
4543  owner->was_null|= null_value= (*ref)->null_value;
4544  return tmp;
4545 }
4546 
4547 
4549 {
4550  DBUG_ASSERT(fixed == 1);
4551  DBUG_ASSERT((*ref)->is_temporal());
4552  longlong tmp= (*ref)->val_date_temporal_result();
4553  owner->was_null|= null_value= (*ref)->null_value;
4554  return tmp;
4555 }
4556 
4557 
4558 my_decimal *Item_ref_null_helper::val_decimal(my_decimal *decimal_value)
4559 {
4560  DBUG_ASSERT(fixed == 1);
4561  my_decimal *val= (*ref)->val_decimal_result(decimal_value);
4562  owner->was_null|= null_value= (*ref)->null_value;
4563  return val;
4564 }
4565 
4566 
4568 {
4569  DBUG_ASSERT(fixed == 1);
4570  bool val= (*ref)->val_bool_result();
4571  owner->was_null|= null_value= (*ref)->null_value;
4572  return val;
4573 }
4574 
4575 
4576 String* Item_ref_null_helper::val_str(String* s)
4577 {
4578  DBUG_ASSERT(fixed == 1);
4579  String* tmp= (*ref)->str_result(s);
4580  owner->was_null|= null_value= (*ref)->null_value;
4581  return tmp;
4582 }
4583 
4584 
4585 bool Item_ref_null_helper::get_date(MYSQL_TIME *ltime, uint fuzzydate)
4586 {
4587  return (owner->was_null|= null_value= (*ref)->get_date(ltime, fuzzydate));
4588 }
4589 
4590 
4603 static void mark_as_dependent(THD *thd, SELECT_LEX *last, SELECT_LEX *current,
4604  Item_ident *resolved_item,
4605  Item_ident *mark_item)
4606 {
4607  const char *db_name= (resolved_item->db_name ?
4608  resolved_item->db_name : "");
4609  const char *table_name= (resolved_item->table_name ?
4610  resolved_item->table_name : "");
4611  /* store pointer on SELECT_LEX from which item is dependent */
4612  if (mark_item)
4613  mark_item->depended_from= last;
4614  current->mark_as_dependent(last);
4615  if (thd->lex->describe & DESCRIBE_EXTENDED)
4616  {
4617  push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
4618  ER_WARN_FIELD_RESOLVED, ER(ER_WARN_FIELD_RESOLVED),
4619  db_name, (db_name[0] ? "." : ""),
4620  table_name, (table_name [0] ? "." : ""),
4621  resolved_item->field_name,
4622  current->select_number, last->select_number);
4623  }
4624 }
4625 
4626 
4647 void mark_select_range_as_dependent(THD *thd,
4648  SELECT_LEX *last_select,
4649  SELECT_LEX *current_sel,
4650  Field *found_field, Item *found_item,
4651  Item_ident *resolved_item)
4652 {
4653  /*
4654  Go from current SELECT to SELECT where field was resolved (it
4655  have to be reachable from current SELECT, because it was already
4656  done once when we resolved this field and cached result of
4657  resolving)
4658  */
4659  SELECT_LEX *previous_select= current_sel;
4660  for (; previous_select->outer_select() != last_select;
4661  previous_select= previous_select->outer_select())
4662  {
4663  Item_subselect *prev_subselect_item=
4664  previous_select->master_unit()->item;
4665  prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
4666  prev_subselect_item->const_item_cache= 0;
4667  }
4668  {
4669  Item_subselect *prev_subselect_item=
4670  previous_select->master_unit()->item;
4671  Item_ident *dependent= resolved_item;
4672  if (found_field == view_ref_found)
4673  {
4674  Item::Type type= found_item->type();
4675  prev_subselect_item->used_tables_cache|=
4676  found_item->used_tables();
4677  dependent= ((type == Item::REF_ITEM || type == Item::FIELD_ITEM) ?
4678  (Item_ident*) found_item :
4679  0);
4680  }
4681  else
4682  prev_subselect_item->used_tables_cache|=
4683  found_field->table->map;
4684  prev_subselect_item->const_item_cache= 0;
4685  mark_as_dependent(thd, last_select, current_sel, resolved_item,
4686  dependent);
4687  }
4688 }
4689 
4690 
4701 static bool find_item_in_item_list (Item *item, List<Item> *list)
4702 {
4703  List_iterator<Item> li(*list);
4704  Item *it= NULL;
4705  while ((it= li++))
4706  {
4707  if (it->walk(&Item::find_item_processor, true,
4708  (uchar*)item))
4709  return true;
4710  }
4711  return false;
4712 }
4713 
4714 
4730 static Item** find_field_in_group_list(Item *find_item, ORDER *group_list)
4731 {
4732  const char *db_name;
4733  const char *table_name;
4734  const char *field_name;
4735  ORDER *found_group= NULL;
4736  int found_match_degree= 0;
4737  Item_ident *cur_field;
4738  int cur_match_degree= 0;
4739  char name_buff[NAME_LEN+1];
4740 
4741  if (find_item->type() == Item::FIELD_ITEM ||
4742  find_item->type() == Item::REF_ITEM)
4743  {
4744  db_name= ((Item_ident*) find_item)->db_name;
4745  table_name= ((Item_ident*) find_item)->table_name;
4746  field_name= ((Item_ident*) find_item)->field_name;
4747  }
4748  else
4749  return NULL;
4750 
4751  if (db_name && lower_case_table_names)
4752  {
4753  /* Convert database to lower case for comparison */
4754  strmake(name_buff, db_name, sizeof(name_buff)-1);
4755  my_casedn_str(files_charset_info, name_buff);
4756  db_name= name_buff;
4757  }
4758 
4759  DBUG_ASSERT(field_name != 0);
4760 
4761  for (ORDER *cur_group= group_list ; cur_group ; cur_group= cur_group->next)
4762  {
4763  if ((*(cur_group->item))->real_item()->type() == Item::FIELD_ITEM)
4764  {
4765  cur_field= (Item_ident*) *cur_group->item;
4766  cur_match_degree= 0;
4767 
4768  DBUG_ASSERT(cur_field->field_name != 0);
4769 
4770  if (!my_strcasecmp(system_charset_info,
4771  cur_field->field_name, field_name))
4772  ++cur_match_degree;
4773  else
4774  continue;
4775 
4776  if (cur_field->table_name && table_name)
4777  {
4778  /* If field_name is qualified by a table name. */
4779  if (my_strcasecmp(table_alias_charset, cur_field->table_name, table_name))
4780  /* Same field names, different tables. */
4781  return NULL;
4782 
4783  ++cur_match_degree;
4784  if (cur_field->db_name && db_name)
4785  {
4786  /* If field_name is also qualified by a database name. */
4787  if (strcmp(cur_field->db_name, db_name))
4788  /* Same field names, different databases. */
4789  return NULL;
4790  ++cur_match_degree;
4791  }
4792  }
4793 
4794  if (cur_match_degree > found_match_degree)
4795  {
4796  found_match_degree= cur_match_degree;
4797  found_group= cur_group;
4798  }
4799  else if (found_group && (cur_match_degree == found_match_degree) &&
4800  ! (*(found_group->item))->eq(cur_field, 0))
4801  {
4802  /*
4803  If the current resolve candidate matches equally well as the current
4804  best match, they must reference the same column, otherwise the field
4805  is ambiguous.
4806  */
4807  my_error(ER_NON_UNIQ_ERROR, MYF(0),
4808  find_item->full_name(), current_thd->where);
4809  return NULL;
4810  }
4811  }
4812  }
4813 
4814  if (found_group)
4815  return found_group->item;
4816  else
4817  return NULL;
4818 }
4819 
4820 
4831 #ifndef DBUG_OFF
4832 static bool is_fixed_or_outer_ref(Item *ref)
4833 {
4834  /*
4835  The requirements are that the Item pointer
4836  1) is not NULL, and
4837  2a) points to a fixed Item, or
4838  2b) points to an Item_outer_ref.
4839  */
4840  return (ref != NULL && // 1
4841  (ref->fixed || // 2a
4842  (ref->type() == Item::REF_ITEM && // 2b
4843  static_cast<Item_ref *>(ref)->ref_type() == Item_ref::OUTER_REF)));
4844 }
4845 #endif
4846 
4847 
4884 static Item**
4885 resolve_ref_in_select_and_group(THD *thd, Item_ident *ref, SELECT_LEX *select)
4886 {
4887  Item **group_by_ref= NULL;
4888  Item **select_ref= NULL;
4889  ORDER *group_list= select->group_list.first;
4890  bool ambiguous_fields= FALSE;
4891  uint counter;
4892  enum_resolution_type resolution;
4893 
4894  /*
4895  Search for a column or derived column named as 'ref' in the SELECT
4896  clause of the current select.
4897  */
4898  if (!(select_ref= find_item_in_list(ref, *(select->get_item_list()),
4899  &counter, REPORT_EXCEPT_NOT_FOUND,
4900  &resolution)))
4901  return NULL; /* Some error occurred. */
4902  if (resolution == RESOLVED_AGAINST_ALIAS)
4903  ref->alias_name_used= TRUE;
4904 
4905  /* If this is a non-aggregated field inside HAVING, search in GROUP BY. */
4906  if (select->having_fix_field && !ref->with_sum_func && group_list)
4907  {
4908  group_by_ref= find_field_in_group_list(ref, group_list);
4909 
4910  /* Check if the fields found in SELECT and GROUP BY are the same field. */
4911  if (group_by_ref && (select_ref != not_found_item) &&
4912  !((*group_by_ref)->eq(*select_ref, 0)))
4913  {
4914  ambiguous_fields= TRUE;
4915  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_NON_UNIQ_ERROR,
4916  ER(ER_NON_UNIQ_ERROR), ref->full_name(),
4917  current_thd->where);
4918 
4919  }
4920  }
4921 
4922  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
4923  select->having_fix_field &&
4924  select_ref != not_found_item && !group_by_ref)
4925  {
4926  /*
4927  Report the error if fields was found only in the SELECT item list and
4928  the strict mode is enabled.
4929  */
4930  my_error(ER_NON_GROUPING_FIELD_USED, MYF(0),
4931  ref->item_name.ptr(), "HAVING");
4932  return NULL;
4933  }
4934  if (select_ref != not_found_item || group_by_ref)
4935  {
4936  if (select_ref != not_found_item && !ambiguous_fields)
4937  {
4938  DBUG_ASSERT(*select_ref != 0);
4939  if (!select->ref_pointer_array[counter])
4940  {
4941  my_error(ER_ILLEGAL_REFERENCE, MYF(0),
4942  ref->item_name.ptr(), "forward reference in item list");
4943  return NULL;
4944  }
4945  /*
4946  Assert if its an incorrect reference . We do not assert if its a outer
4947  reference, as they get fixed later in fix_innner_refs function.
4948  */
4949  DBUG_ASSERT(is_fixed_or_outer_ref(*select_ref));
4950 
4951  return &select->ref_pointer_array[counter];
4952  }
4953  if (group_by_ref)
4954  return group_by_ref;
4955  DBUG_ASSERT(FALSE);
4956  return NULL; /* So there is no compiler warning. */
4957  }
4958 
4959  return (Item**) not_found_item;
4960 }
4961 
4962 
5002 int
5003 Item_field::fix_outer_field(THD *thd, Field **from_field, Item **reference)
5004 {
5005  enum_parsing_place place= NO_MATTER;
5006  bool field_found= (*from_field != not_found_field);
5007  bool upward_lookup= FALSE;
5008 
5009  /*
5010  If there are outer contexts (outer selects, but current select is
5011  not derived table or view) try to resolve this reference in the
5012  outer contexts.
5013 
5014  We treat each subselect as a separate namespace, so that different
5015  subselects may contain columns with the same names. The subselects
5016  are searched starting from the innermost.
5017  */
5018  Name_resolution_context *last_checked_context= context;
5019  Item **ref= (Item **) not_found_item;
5020  SELECT_LEX *current_sel= (SELECT_LEX *) thd->lex->current_select;
5021  Name_resolution_context *outer_context= 0;
5022  SELECT_LEX *select= 0;
5023  /* Currently derived tables cannot be correlated */
5024  if (current_sel->master_unit()->first_select()->linkage !=
5025  DERIVED_TABLE_TYPE)
5026  outer_context= context->outer_context;
5027  for (;
5028  outer_context;
5029  outer_context= outer_context->outer_context)
5030  {
5031  select= outer_context->select_lex;
5032  Item_subselect *prev_subselect_item=
5033  last_checked_context->select_lex->master_unit()->item;
5034  last_checked_context= outer_context;
5035  upward_lookup= TRUE;
5036 
5037  place= prev_subselect_item->parsing_place;
5038  /*
5039  If outer_field is set, field was already found by first call
5040  to find_field_in_tables(). Only need to find appropriate context.
5041  */
5042  if (field_found && outer_context->select_lex !=
5043  cached_table->select_lex)
5044  continue;
5045  /*
5046  In case of a view, find_field_in_tables() writes the pointer to
5047  the found view field into '*reference', in other words, it
5048  substitutes this Item_field with the found expression.
5049  */
5050  if (field_found || (*from_field= find_field_in_tables(thd, this,
5051  outer_context->
5052  first_name_resolution_table,
5053  outer_context->
5054  last_name_resolution_table,
5055  reference,
5056  IGNORE_EXCEPT_NON_UNIQUE,
5057  TRUE, TRUE)) !=
5058  not_found_field)
5059  {
5060  if (*from_field)
5061  {
5062  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY &&
5063  select->cur_pos_in_all_fields != SELECT_LEX::ALL_FIELDS_UNDEF_POS)
5064  {
5065  /*
5066  As this is an outer field it should be added to the list of
5067  non aggregated fields of the outer select.
5068  */
5069  push_to_non_agg_fields(select);
5070  }
5071  if (*from_field != view_ref_found)
5072  {
5073  prev_subselect_item->used_tables_cache|= (*from_field)->table->map;
5074  prev_subselect_item->const_item_cache= 0;
5075  set_field(*from_field);
5076  if (!last_checked_context->select_lex->having_fix_field &&
5077  select->group_list.elements &&
5078  (place == SELECT_LIST || place == IN_HAVING))
5079  {
5080  Item_outer_ref *rf;
5081  /*
5082  If an outer field is resolved in a grouping select then it
5083  is replaced for an Item_outer_ref object. Otherwise an
5084  Item_field object is used.
5085  The new Item_outer_ref object is saved in the inner_refs_list of
5086  the outer select. Here it is only created. It can be fixed only
5087  after the original field has been fixed and this is done in the
5088  fix_inner_refs() function.
5089  */
5090  ;
5091  if (!(rf= new Item_outer_ref(context, this)))
5092  return -1;
5093  thd->change_item_tree(reference, rf);
5094  select->inner_refs_list.push_back(rf);
5095  rf->in_sum_func= thd->lex->in_sum_func;
5096  }
5097  /*
5098  A reference is resolved to a nest level that's outer or the same as
5099  the nest level of the enclosing set function : adjust the value of
5100  max_arg_level for the function if it's needed.
5101  */
5102  if (thd->lex->in_sum_func &&
5103  thd->lex->in_sum_func->nest_level >= select->nest_level)
5104  {
5105  Item::Type ref_type= (*reference)->type();
5106  set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5107  select->nest_level);
5108  set_field(*from_field);
5109  fixed= 1;
5110  mark_as_dependent(thd, last_checked_context->select_lex,
5111  context->select_lex, this,
5112  ((ref_type == REF_ITEM ||
5113  ref_type == FIELD_ITEM) ?
5114  (Item_ident*) (*reference) : 0));
5115  return 0;
5116  }
5117  }
5118  else
5119  {
5120  Item::Type ref_type= (*reference)->type();
5121  prev_subselect_item->used_tables_cache|=
5122  (*reference)->used_tables();
5123  prev_subselect_item->const_item_cache&=
5124  (*reference)->const_item();
5125  mark_as_dependent(thd, last_checked_context->select_lex,
5126  context->select_lex, this,
5127  ((ref_type == REF_ITEM || ref_type == FIELD_ITEM) ?
5128  (Item_ident*) (*reference) :
5129  0));
5130  /*
5131  A reference to a view field had been found and we
5132  substituted it instead of this Item (find_field_in_tables
5133  does it by assigning the new value to *reference), so now
5134  we can return from this function.
5135  */
5136  return 0;
5137  }
5138  }
5139  break;
5140  }
5141 
5142  /* Search in SELECT and GROUP lists of the outer select. */
5143  if (place != IN_WHERE && place != IN_ON &&
5144  outer_context->resolve_in_select_list)
5145  {
5146  if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
5147  return -1; /* Some error occurred (e.g. ambiguous names). */
5148  if (ref != not_found_item)
5149  {
5150  /*
5151  Either the item we found is already fixed, or it is an outer
5152  reference that will be fixed later in fix_inner_refs().
5153  */
5154  DBUG_ASSERT(is_fixed_or_outer_ref(*ref));
5155  prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
5156  prev_subselect_item->const_item_cache&= (*ref)->const_item();
5157  break;
5158  }
5159  }
5160 
5161  /*
5162  Reference is not found in this select => this subquery depend on
5163  outer select (or we just trying to find wrong identifier, in this
5164  case it does not matter which used tables bits we set)
5165  */
5166  prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
5167  prev_subselect_item->const_item_cache= 0;
5168  }
5169 
5170  DBUG_ASSERT(ref != 0);
5171  if (!*from_field)
5172  return -1;
5173  if (ref == not_found_item && *from_field == not_found_field)
5174  {
5175  if (upward_lookup)
5176  {
5177  // We can't say exactly what absent table or field
5178  my_error(ER_BAD_FIELD_ERROR, MYF(0), full_name(), thd->where);
5179  }
5180  else
5181  {
5182  /* Call find_field_in_tables only to report the error */
5183  find_field_in_tables(thd, this,
5184  context->first_name_resolution_table,
5185  context->last_name_resolution_table,
5186  reference, REPORT_ALL_ERRORS,
5187  !any_privileges, TRUE);
5188  }
5189  return -1;
5190  }
5191  else if (ref != not_found_item)
5192  {
5193  Item *save;
5194  Item_ref *rf;
5195 
5196  /* Should have been checked in resolve_ref_in_select_and_group(). */
5197  DBUG_ASSERT(is_fixed_or_outer_ref(*ref));
5198  /*
5199  Here, a subset of actions performed by Item_ref::set_properties
5200  is not enough. So we pass ptr to NULL into Item_[direct]_ref
5201  constructor, so no initialization is performed, and call
5202  fix_fields() below.
5203  */
5204  save= *ref;
5205  *ref= NULL; // Don't call set_properties()
5206  rf= (place == IN_HAVING ?
5207  new Item_ref(context, ref, (char*) table_name,
5208  (char*) field_name, alias_name_used) :
5209  (!select->group_list.elements ?
5210  new Item_direct_ref(context, ref, (char*) table_name,
5211  (char*) field_name, alias_name_used) :
5212  new Item_outer_ref(context, ref, (char*) table_name,
5213  (char*) field_name, alias_name_used)));
5214  *ref= save;
5215  if (!rf)
5216  return -1;
5217 
5218  if (place != IN_HAVING && select->group_list.elements)
5219  {
5220  outer_context->select_lex->inner_refs_list.push_back((Item_outer_ref*)rf);
5221  ((Item_outer_ref*)rf)->in_sum_func= thd->lex->in_sum_func;
5222  }
5223  thd->change_item_tree(reference, rf);
5224  /*
5225  rf is Item_ref => never substitute other items (in this case)
5226  during fix_fields() => we can use rf after fix_fields()
5227  */
5228  DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
5229  if (rf->fix_fields(thd, reference) || rf->check_cols(1))
5230  return -1;
5231 
5232  mark_as_dependent(thd, last_checked_context->select_lex,
5233  context->select_lex, this,
5234  rf);
5235  return 0;
5236  }
5237  else
5238  {
5239  mark_as_dependent(thd, last_checked_context->select_lex,
5240  context->select_lex,
5241  this, (Item_ident*)*reference);
5242  if (last_checked_context->select_lex->having_fix_field)
5243  {
5244  Item_ref *rf;
5245  rf= new Item_ref(context,
5246  (cached_table->db[0] ? cached_table->db : 0),
5247  (char*) cached_table->alias, (char*) field_name);
5248  if (!rf)
5249  return -1;
5250  thd->change_item_tree(reference, rf);
5251  /*
5252  rf is Item_ref => never substitute other items (in this case)
5253  during fix_fields() => we can use rf after fix_fields()
5254  */
5255  DBUG_ASSERT(!rf->fixed); // Assured by Item_ref()
5256  if (rf->fix_fields(thd, reference) || rf->check_cols(1))
5257  return -1;
5258  return 0;
5259  }
5260  }
5261  return 1;
5262 }
5263 
5264 
5265 bool Item_field::push_to_non_agg_fields(SELECT_LEX *select_lex)
5266 {
5267  marker= select_lex->cur_pos_in_all_fields;
5268  /*
5269  Push expressions from the SELECT list to the back of the list, and
5270  expressions from GROUP BY/ORDER BY to the front of the list
5271  (non_agg_fields must have the same ordering as all_fields, see
5272  match_exprs_for_only_full_group_by()).
5273  */
5274  return (marker < 0) ?
5275  select_lex->non_agg_fields.push_front(this) :
5276  select_lex->non_agg_fields.push_back(this);
5277 }
5278 
5279 
5325 bool Item_field::fix_fields(THD *thd, Item **reference)
5326 {
5327  DBUG_ASSERT(fixed == 0);
5328  Field *from_field= (Field *)not_found_field;
5329  bool outer_fixed= false;
5330 
5331  if (!field) // If field is not checked
5332  {
5333  /*
5334  In case of view, find_field_in_tables() write pointer to view field
5335  expression to 'reference', i.e. it substitute that expression instead
5336  of this Item_field
5337  */
5338  from_field= find_field_in_tables(thd, this,
5339  context->first_name_resolution_table,
5340  context->last_name_resolution_table,
5341  reference,
5342  thd->lex->use_only_table_context ?
5343  REPORT_ALL_ERRORS :
5344  IGNORE_EXCEPT_NON_UNIQUE,
5345  !any_privileges, TRUE);
5346  if (thd->is_error())
5347  goto error;
5348  if (from_field == not_found_field)
5349  {
5350  int ret;
5351  /* Look up in current select's item_list to find aliased fields */
5352  if (thd->lex->current_select->is_item_list_lookup)
5353  {
5354  uint counter;
5355  enum_resolution_type resolution;
5356  Item** res= find_item_in_list(this, thd->lex->current_select->item_list,
5357  &counter, REPORT_EXCEPT_NOT_FOUND,
5358  &resolution);
5359  if (!res)
5360  return 1;
5361  if (resolution == RESOLVED_AGAINST_ALIAS)
5362  alias_name_used= TRUE;
5363  if (res != (Item **)not_found_item)
5364  {
5365  if ((*res)->type() == Item::FIELD_ITEM)
5366  {
5367  /*
5368  It's an Item_field referencing another Item_field in the select
5369  list.
5370  Use the field from the Item_field in the select list and leave
5371  the Item_field instance in place.
5372  */
5373 
5374  Field *new_field= (*((Item_field**)res))->field;
5375 
5376  if (new_field == NULL)
5377  {
5378  /* The column to which we link isn't valid. */
5379  my_error(ER_BAD_FIELD_ERROR, MYF(0), (*res)->item_name.ptr(),
5380  current_thd->where);
5381  return(1);
5382  }
5383 
5384  set_field(new_field);
5385  return 0;
5386  }
5387  else
5388  {
5389  /*
5390  It's not an Item_field in the select list so we must make a new
5391  Item_ref to point to the Item in the select list and replace the
5392  Item_field created by the parser with the new Item_ref.
5393  Ex: SELECT func1(col) as c ... ORDER BY func2(c);
5394  NOTE: If we are fixing an alias reference inside ORDER/GROUP BY
5395  item tree, then we use new Item_ref as an intermediate value
5396  to resolve referenced item only.
5397  In this case the new Item_ref item is unused.
5398  */
5399  Item_ref *rf= new Item_ref(context, db_name,table_name,field_name);
5400  if (!rf)
5401  return 1;
5402 
5403  bool save_group_fix_field= thd->lex->current_select->group_fix_field;
5404  /*
5405  No need for recursive resolving of aliases.
5406  */
5407  thd->lex->current_select->group_fix_field= 0;
5408 
5409  bool ret= rf->fix_fields(thd, (Item **) &rf) || rf->check_cols(1);
5410  thd->lex->current_select->group_fix_field= save_group_fix_field;
5411  if (ret)
5412  return TRUE;
5413 
5414  if (save_group_fix_field && alias_name_used)
5415  thd->change_item_tree(reference, *rf->ref);
5416  else
5417  thd->change_item_tree(reference, rf);
5418 
5419  return FALSE;
5420  }
5421  }
5422  }
5423  if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
5424  goto error;
5425  outer_fixed= TRUE;
5426  if (!ret)
5427  goto mark_non_agg_field;
5428  }
5429  else if (!from_field)
5430  goto error;
5431 
5432  /*
5433  We should resolve this as an outer field reference if
5434  1. we haven't done it before, and
5435  2. the select_lex of the table that contains this field is
5436  different from the select_lex of the current name resolution
5437  context.
5438  */
5439  if (!outer_fixed && // 1
5440  cached_table && cached_table->select_lex && context->select_lex && // 2
5441  cached_table->select_lex != context->select_lex)
5442  {
5443  int ret;
5444  if ((ret= fix_outer_field(thd, &from_field, reference)) < 0)
5445  goto error;
5446  outer_fixed= 1;
5447  if (!ret)
5448  goto mark_non_agg_field;
5449  }
5450 
5451  /*
5452  if it is not expression from merged VIEW we will set this field.
5453 
5454  We can leave expression substituted from view for next PS/SP rexecution
5455  (i.e. do not register this substitution for reverting on cleanup()
5456  (register_item_tree_changing())), because this subtree will be
5457  fix_field'ed during setup_tables()->setup_underlying() (i.e. before
5458  all other expressions of query, and references on tables which do
5459  not present in query will not make problems.
5460 
5461  Also we suppose that view can't be changed during PS/SP life.
5462  */
5463  if (from_field == view_ref_found)
5464  return FALSE;
5465 
5466  set_field(from_field);
5467  if (thd->lex->in_sum_func &&
5468  thd->lex->in_sum_func->nest_level ==
5469  thd->lex->current_select->nest_level)
5470  set_if_bigger(thd->lex->in_sum_func->max_arg_level,
5471  thd->lex->current_select->nest_level);
5472  }
5473  else if (thd->mark_used_columns != MARK_COLUMNS_NONE)
5474  {
5475  TABLE *table= field->table;
5476  MY_BITMAP *current_bitmap, *other_bitmap;
5477  if (thd->mark_used_columns == MARK_COLUMNS_READ)
5478  {
5479  current_bitmap= table->read_set;
5480  other_bitmap= table->write_set;
5481  }
5482  else
5483  {
5484  current_bitmap= table->write_set;
5485  other_bitmap= table->read_set;
5486  }
5487  if (!bitmap_fast_test_and_set(current_bitmap, field->field_index))
5488  {
5489  if (!bitmap_is_set(other_bitmap, field->field_index))
5490  {
5491  /* First usage of column */
5492  table->used_fields++; // Used to optimize loops
5493  /* purecov: begin inspected */
5494  table->covering_keys.intersect(field->part_of_key);
5495  /* purecov: end */
5496  }
5497  }
5498  }
5499 #ifndef NO_EMBEDDED_ACCESS_CHECKS
5500  if (any_privileges)
5501  {
5502  char *db, *tab;
5503  db= cached_table->get_db_name();
5504  tab= cached_table->get_table_name();
5505  if (!(have_privileges= (get_column_grant(thd, &field->table->grant,
5506  db, tab, field_name) &
5507  VIEW_ANY_ACL)))
5508  {
5509  my_error(ER_COLUMNACCESS_DENIED_ERROR, MYF(0),
5510  "ANY", thd->security_ctx->priv_user,
5511  thd->security_ctx->host_or_ip, field_name, tab);
5512  goto error;
5513  }
5514  }
5515 #endif
5516  fixed= 1;
5517  if (!outer_fixed && !thd->lex->in_sum_func &&
5518  thd->lex->current_select->cur_pos_in_all_fields !=
5519  SELECT_LEX::ALL_FIELDS_UNDEF_POS)
5520  {
5521  // See same code in Field_iterator_table::create_item()
5522  if (thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
5523  push_to_non_agg_fields(thd->lex->current_select);
5524  /*
5525  If (1) aggregation (2) without grouping, we may have to return a result
5526  row even if the nested loop finds nothing; in this result row,
5527  non-aggregated table columns present in the SELECT list will show a NULL
5528  value even if the table column itself is not nullable.
5529  */
5530  if (thd->lex->current_select->with_sum_func && // (1)
5531  !thd->lex->current_select->group_list.elements) // (2)
5532  maybe_null= true;
5533  }
5534 
5535 mark_non_agg_field:
5536  if (fixed && thd->variables.sql_mode & MODE_ONLY_FULL_GROUP_BY)
5537  {
5538  /*
5539  Mark selects according to presence of non aggregated columns.
5540  Columns from outer selects added to the aggregate function
5541  outer_fields list as its unknown at the moment whether it's
5542  aggregated or not.
5543  We're using either the select lex of the cached table (if present)
5544  or the field's resolution context. context->select_lex is
5545  safe for use because it's either the SELECT we want to use
5546  (the current level) or a stub added by non-SELECT queries.
5547  */
5548  SELECT_LEX *select_lex= cached_table ?
5549  cached_table->select_lex : context->select_lex;
5550  if (!thd->lex->in_sum_func)
5551  select_lex->set_non_agg_field_used(true);
5552  else
5553  {
5554  if (outer_fixed)
5555  thd->lex->in_sum_func->outer_fields.push_back(this);
5556  else if (thd->lex->in_sum_func->nest_level !=
5557  thd->lex->current_select->nest_level)
5558  select_lex->set_non_agg_field_used(true);
5559  }
5560  }
5561  return FALSE;
5562 
5563 error:
5564  context->process_error(thd);
5565  return TRUE;
5566 }
5567 
5568 Item *Item_field::safe_charset_converter(const CHARSET_INFO *tocs)
5569 {
5570  no_const_subst= 1;
5571  return Item::safe_charset_converter(tocs);
5572 }
5573 
5574 
5575 void Item_field::cleanup()
5576 {
5577  DBUG_ENTER("Item_field::cleanup");
5578  Item_ident::cleanup();
5579  /*
5580  Even if this object was created by direct link to field in setup_wild()
5581  it will be linked correctly next time by name of field and table alias.
5582  I.e. we can drop 'field'.
5583  */
5584  field= result_field= 0;
5585  item_equal= NULL;
5586  null_value= FALSE;
5587  DBUG_VOID_RETURN;
5588 }
5589 
5609 {
5610  Item_equal *item= 0;
5611  while (cond_equal)
5612  {
5613  List_iterator_fast<Item_equal> li(cond_equal->current_level);
5614  while ((item= li++))
5615  {
5616  if (item->contains(field))
5617  return item;
5618  }
5619  /*
5620  The field is not found in any of the multiple equalities
5621  of the current level. Look for it in upper levels
5622  */
5623  cond_equal= cond_equal->upper_levels;
5624  }
5625  return 0;
5626 }
5627 
5628 
5660 {
5661  return (result_type() != STRING_RESULT) || (*arg);
5662 }
5663 
5664 
5677 static void convert_zerofill_number_to_string(Item **item, Field_num *field)
5678 {
5679  char buff[MAX_FIELD_WIDTH],*pos;
5680  String tmp(buff,sizeof(buff), field->charset()), *res;
5681 
5682  res= (*item)->val_str(&tmp);
5683  if ((*item)->is_null())
5684  *item= new Item_null();
5685  else
5686  {
5687  field->prepend_zeros(res);
5688  pos= (char *) sql_strmake (res->ptr(), res->length());
5689  *item= new Item_string(pos, res->length(), field->charset());
5690  }
5691 }
5692 
5693 
5719 {
5720  if (no_const_subst)
5721  return this;
5722  item_equal= find_item_equal((COND_EQUAL *) arg);
5723  Item *item= 0;
5724  if (item_equal)
5725  item= item_equal->get_const();
5726  /*
5727  Disable const propagation for items used in different comparison contexts.
5728  This must be done because, for example, Item_hex_string->val_int() is not
5729  the same as (Item_hex_string->val_str() in BINARY column)->val_int().
5730  We cannot simply disable the replacement in a particular context (
5731  e.g. <bin_col> = <int_col> AND <bin_col> = <hex_string>) since
5732  Items don't know the context they are in and there are functions like
5733  IF (<hex_string>, 'yes', 'no').
5734  */
5735  if (!item || !has_compatible_context(item))
5736  item= this;
5737  else if (field && (field->flags & ZEROFILL_FLAG) && IS_NUM(field->type()))
5738  {
5739  /*
5740  We don't need to zero-fill timestamp columns here because they will be
5741  first converted to a string (in date/time format) and compared as such if
5742  compared with another string.
5743  */
5744  if (item && field->type() != FIELD_TYPE_TIMESTAMP && cmp_context != INT_RESULT)
5745  convert_zerofill_number_to_string(&item, (Field_num *)field);
5746  else
5747  item= this;
5748  }
5749  return item;
5750 }
5751 
5752 
5760 {
5761  if (field->charset() != &my_charset_bin)
5762  no_const_subst=1;
5763  return FALSE;
5764 }
5765 
5766 
5793 {
5794  if (item_equal)
5795  {
5796  Item *const_item= item_equal->get_const();
5797  if (const_item)
5798  {
5799  if (!has_compatible_context(const_item))
5800  return this;
5801  return const_item;
5802  }
5803  Item_field *subst= item_equal->get_subst_item(this);
5804  DBUG_ASSERT(subst);
5805  if (field->table != subst->field->table && !field->eq(subst->field))
5806  return subst;
5807  }
5808  return this;
5809 }
5810 
5811 
5812 void Item::init_make_field(Send_field *tmp_field,
5813  enum enum_field_types field_type_arg)
5814 {
5815  char *empty_name= (char*) "";
5816  tmp_field->db_name= empty_name;
5817  tmp_field->org_table_name= empty_name;
5818  tmp_field->org_col_name= empty_name;
5819  tmp_field->table_name= empty_name;
5820  tmp_field->col_name= item_name.ptr();
5821  tmp_field->charsetnr= collation.collation->number;
5822  tmp_field->flags= (maybe_null ? 0 : NOT_NULL_FLAG) |
5823  (my_binary_compare(charset_for_protocol()) ?
5824  BINARY_FLAG : 0);
5825  tmp_field->type= field_type_arg;
5826  tmp_field->length=max_length;
5827  tmp_field->decimals=decimals;
5828  if (unsigned_flag)
5829  tmp_field->flags |= UNSIGNED_FLAG;
5830 }
5831 
5832 void Item::make_field(Send_field *tmp_field)
5833 {
5834  init_make_field(tmp_field, field_type());
5835 }
5836 
5837 
5838 enum_field_types Item::string_field_type() const
5839 {
5840  enum_field_types f_type= MYSQL_TYPE_VAR_STRING;
5841  if (max_length >= 16777216)
5842  f_type= MYSQL_TYPE_LONG_BLOB;
5843  else if (max_length >= 65536)
5844  f_type= MYSQL_TYPE_MEDIUM_BLOB;
5845  return f_type;
5846 }
5847 
5848 
5849 void Item_empty_string::make_field(Send_field *tmp_field)
5850 {
5851  init_make_field(tmp_field, string_field_type());
5852 }
5853 
5854 
5855 enum_field_types Item::field_type() const
5856 {
5857  switch (result_type()) {
5858  case STRING_RESULT: return string_field_type();
5859  case INT_RESULT: return MYSQL_TYPE_LONGLONG;
5860  case DECIMAL_RESULT: return MYSQL_TYPE_NEWDECIMAL;
5861  case REAL_RESULT: return MYSQL_TYPE_DOUBLE;
5862  case ROW_RESULT:
5863  default:
5864  DBUG_ASSERT(0);
5865  return MYSQL_TYPE_VARCHAR;
5866  }
5867 }
5868 
5869 
5870 String *Item::check_well_formed_result(String *str, bool send_error)
5871 {
5872  /* Check whether we got a well-formed string */
5873  const CHARSET_INFO *cs= str->charset();
5874  int well_formed_error;
5875  uint wlen= cs->cset->well_formed_len(cs,
5876  str->ptr(), str->ptr() + str->length(),
5877  str->length(), &well_formed_error);
5878  if (wlen < str->length())
5879  {
5880  THD *thd= current_thd;
5881  char hexbuf[7];
5882  uint diff= str->length() - wlen;
5883  set_if_smaller(diff, 3);
5884  octet2hex(hexbuf, str->ptr() + wlen, diff);
5885  if (send_error)
5886  {
5887  my_error(ER_INVALID_CHARACTER_STRING, MYF(0),
5888  cs->csname, hexbuf);
5889  return 0;
5890  }
5891  if (thd->is_strict_mode())
5892  {
5893  null_value= 1;
5894  str= 0;
5895  }
5896  else
5897  {
5898  str->length(wlen);
5899  }
5900  push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_INVALID_CHARACTER_STRING,
5901  ER(ER_INVALID_CHARACTER_STRING), cs->csname, hexbuf);
5902  }
5903  return str;
5904 }
5905 
5906 /*
5907  Compare two items using a given collation
5908 
5909  SYNOPSIS
5910  eq_by_collation()
5911  item item to compare with
5912  binary_cmp TRUE <-> compare as binaries
5913  cs collation to use when comparing strings
5914 
5915  DESCRIPTION
5916  This method works exactly as Item::eq if the collation cs coincides with
5917  the collation of the compared objects. Otherwise, first the collations that
5918  differ from cs are replaced for cs and then the items are compared by
5919  Item::eq. After the comparison the original collations of items are
5920  restored.
5921 
5922  RETURN
5923  1 compared items has been detected as equal
5924  0 otherwise
5925 */
5926 
5927 bool Item::eq_by_collation(Item *item, bool binary_cmp,
5928  const CHARSET_INFO *cs)
5929 {
5930  const CHARSET_INFO *save_cs= 0;
5931  const CHARSET_INFO *save_item_cs= 0;
5932  if (collation.collation != cs)
5933  {
5934  save_cs= collation.collation;
5935  collation.collation= cs;
5936  }
5937  if (item->collation.collation != cs)
5938  {
5939  save_item_cs= item->collation.collation;
5940  item->collation.collation= cs;
5941  }
5942  bool res= eq(item, binary_cmp);
5943  if (save_cs)
5944  collation.collation= save_cs;
5945  if (save_item_cs)
5946  item->collation.collation= save_item_cs;
5947  return res;
5948 }
5949 
5950 
5963 {
5964  DBUG_ENTER("Item::can_be_evaluated_now");
5965 
5966  if (tables_locked_cache)
5967  DBUG_RETURN(true);
5968 
5969  if (has_subquery() || has_stored_program())
5970  const_cast<Item*>(this)->tables_locked_cache=
5971  current_thd->lex->is_query_tables_locked();
5972  else
5973  const_cast<Item*>(this)->tables_locked_cache= true;
5974 
5975  DBUG_RETURN(tables_locked_cache);
5976 }
5977 
5978 
5990 {
5991  Field *field;
5992  DBUG_ASSERT(collation.collation);
5993  if (max_length/collation.collation->mbmaxlen > CONVERT_IF_BIGGER_TO_BLOB)
5994  field= new Field_blob(max_length, maybe_null, item_name.ptr(),
5995  collation.collation, TRUE);
5996  /* Item_type_holder holds the exact type, do not change it */
5997  else if (max_length > 0 &&
5998  (type() != Item::TYPE_HOLDER || field_type() != MYSQL_TYPE_STRING))
5999  field= new Field_varstring(max_length, maybe_null, item_name.ptr(),
6000  table->s, collation.collation);
6001  else
6002  field= new Field_string(max_length, maybe_null, item_name.ptr(),
6003  collation.collation);
6004  if (field)
6005  field->init(table);
6006  return field;
6007 }
6008 
6009 
6023 {
6024  /*
6025  The field functions defines a field to be not null if null_ptr is not 0
6026  */
6027  uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
6028  Field *field;
6029 
6030  switch (field_type()) {
6031  case MYSQL_TYPE_DECIMAL:
6032  case MYSQL_TYPE_NEWDECIMAL:
6033  field= Field_new_decimal::create_from_item(this);
6034  break;
6035  case MYSQL_TYPE_TINY:
6036  field= new Field_tiny((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6037  item_name.ptr(), 0, unsigned_flag);
6038  break;
6039  case MYSQL_TYPE_SHORT:
6040  field= new Field_short((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6041  item_name.ptr(), 0, unsigned_flag);
6042  break;
6043  case MYSQL_TYPE_LONG:
6044  field= new Field_long((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6045  item_name.ptr(), 0, unsigned_flag);
6046  break;
6047 #ifdef HAVE_LONG_LONG
6048  case MYSQL_TYPE_LONGLONG:
6049  field= new Field_longlong((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6050  item_name.ptr(), 0, unsigned_flag);
6051  break;
6052 #endif
6053  case MYSQL_TYPE_FLOAT:
6054  field= new Field_float((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6055  item_name.ptr(), decimals, 0, unsigned_flag);
6056  break;
6057  case MYSQL_TYPE_DOUBLE:
6058  field= new Field_double((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6059  item_name.ptr(), decimals, 0, unsigned_flag);
6060  break;
6061  case MYSQL_TYPE_INT24:
6062  field= new Field_medium((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6063  item_name.ptr(), 0, unsigned_flag);
6064  break;
6065  case MYSQL_TYPE_DATE:
6066  case MYSQL_TYPE_NEWDATE:
6067  field= new Field_newdate(maybe_null, item_name.ptr());
6068  break;
6069  case MYSQL_TYPE_TIME:
6070  field= new Field_timef(maybe_null, item_name.ptr(), decimals);
6071  break;
6072  case MYSQL_TYPE_TIMESTAMP:
6073  field= new Field_timestampf(maybe_null, item_name.ptr(), decimals);
6074  break;
6075  case MYSQL_TYPE_DATETIME:
6076  field= new Field_datetimef(maybe_null, item_name.ptr(), decimals);
6077  break;
6078  case MYSQL_TYPE_YEAR:
6079  field= new Field_year((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
6080  item_name.ptr());
6081  break;
6082  case MYSQL_TYPE_BIT:
6083  field= new Field_bit_as_char(NULL, max_length, null_ptr, 0,
6084  Field::NONE, item_name.ptr());
6085  break;
6086  default:
6087  /* This case should never be chosen */
6088  DBUG_ASSERT(0);
6089  /* If something goes awfully wrong, it's better to get a string than die */
6090  case MYSQL_TYPE_STRING:
6091  case MYSQL_TYPE_NULL:
6092  if (fixed_length && max_length < CONVERT_IF_BIGGER_TO_BLOB)
6093  {
6094  field= new Field_string(max_length, maybe_null, item_name.ptr(),
6095  collation.collation);
6096  break;
6097  }
6098  /* Fall through to make_string_field() */
6099  case MYSQL_TYPE_ENUM:
6100  case MYSQL_TYPE_SET:
6101  case MYSQL_TYPE_VAR_STRING:
6102  case MYSQL_TYPE_VARCHAR:
6103  return make_string_field(table);
6104  case MYSQL_TYPE_TINY_BLOB:
6105  case MYSQL_TYPE_MEDIUM_BLOB:
6106  case MYSQL_TYPE_LONG_BLOB:
6107  case MYSQL_TYPE_BLOB:
6108  if (this->type() == Item::TYPE_HOLDER)
6109  field= new Field_blob(max_length, maybe_null, item_name.ptr(), collation.collation,
6110  1);
6111  else
6112  field= new Field_blob(max_length, maybe_null, item_name.ptr(), collation.collation);
6113  break; // Blob handled outside of case
6114 #ifdef HAVE_SPATIAL
6115  case MYSQL_TYPE_GEOMETRY:
6116  field= new Field_geom(max_length, maybe_null,
6117  item_name.ptr(), table->s, get_geometry_type());
6118 #endif /* HAVE_SPATIAL */
6119  }
6120  if (field)
6121  field->init(table);
6122  return field;
6123 }
6124 
6125 
6126 /* ARGSUSED */
6127 void Item_field::make_field(Send_field *tmp_field)
6128 {
6129  field->make_field(tmp_field);
6130  DBUG_ASSERT(tmp_field->table_name != 0);
6131  if (item_name.is_set())
6132  tmp_field->col_name= item_name.ptr(); // Use user supplied name
6133  if (table_name)
6134  tmp_field->table_name= table_name;
6135  if (db_name)
6136  tmp_field->db_name= db_name;
6137 }
6138 
6139 
6145 {
6146  if (field->is_null())
6147  {
6148  null_value=1;
6150  }
6151  else
6152  {
6153  to->set_notnull();
6154  field_conv(to,field);
6155  null_value=0;
6156  }
6157 }
6158 
6159 type_conversion_status
6160 Item_field::save_in_field(Field *to, bool no_conversions)
6161 {
6162  type_conversion_status res;
6163  DBUG_ENTER("Item_field::save_in_field");
6164  if (result_field->is_null())
6165  {
6166  null_value=1;
6167  DBUG_RETURN(set_field_to_null_with_conversions(to, no_conversions));
6168  }
6169  to->set_notnull();
6170 
6171  /*
6172  If we're setting the same field as the one we're reading from there's
6173  nothing to do. This can happen in 'SET x = x' type of scenarios.
6174  */
6175  if (to == result_field)
6176  {
6177  null_value=0;
6178  DBUG_RETURN(TYPE_OK);
6179  }
6180 
6181  res= field_conv(to,result_field);
6182  null_value=0;
6183  DBUG_RETURN(res);
6184 }
6185 
6186 
6201 type_conversion_status
6202 Item_null::save_in_field(Field *field, bool no_conversions)
6203 {
6204  return set_field_to_null_with_conversions(field, no_conversions);
6205 }
6206 
6207 
6219 type_conversion_status Item_null::save_safe_in_field(Field *field)
6220 {
6221  return set_field_to_null(field);
6222 }
6223 
6224 
6225 /*
6226  This implementation can lose str_value content, so if the
6227  Item uses str_value to store something, it should
6228  reimplement it's ::save_in_field() as Item_string, for example, does.
6229 
6230  Note: all Item_XXX::val_str(str) methods must NOT rely on the fact that
6231  str != str_value. For example, see fix for bug #44743.
6232 */
6233 
6234 type_conversion_status
6235 Item::save_in_field(Field *field, bool no_conversions)
6236 {
6237  type_conversion_status error;
6238  if (result_type() == STRING_RESULT)
6239  {
6240  String *result;
6241  const CHARSET_INFO *cs= collation.collation;
6242  char buff[MAX_FIELD_WIDTH]; // Alloc buffer for small columns
6243  str_value.set_quick(buff, sizeof(buff), cs);
6244  result=val_str(&str_value);
6245  if (null_value)
6246  {
6247  str_value.set_quick(0, 0, cs);
6248  return set_field_to_null_with_conversions(field, no_conversions);
6249  }
6250 
6251  /* NOTE: If null_value == FALSE, "result" must be not NULL. */
6252 
6253  field->set_notnull();
6254  error=field->store(result->ptr(),result->length(),cs);
6255  str_value.set_quick(0, 0, cs);
6256  }
6257  else if (result_type() == REAL_RESULT &&
6258  field->result_type() == STRING_RESULT)
6259  {
6260  double nr= val_real();
6261  if (null_value)
6262  return set_field_to_null_with_conversions(field, no_conversions);
6263  field->set_notnull();
6264  error= field->store(nr);
6265  }
6266  else if (result_type() == REAL_RESULT)
6267  {
6268  double nr= val_real();
6269  if (null_value)
6270  return set_field_to_null_with_conversions(field, no_conversions);
6271  field->set_notnull();
6272  error=field->store(nr);
6273  }
6274  else if (result_type() == DECIMAL_RESULT)
6275  {
6276  my_decimal decimal_value;
6277  my_decimal *value= val_decimal(&decimal_value);
6278  if (null_value)
6279  return set_field_to_null_with_conversions(field, no_conversions);
6280  field->set_notnull();
6281  error=field->store_decimal(value);
6282  }
6283  else
6284  {
6285  longlong nr=val_int();
6286  if (null_value)
6287  return set_field_to_null_with_conversions(field, no_conversions);
6288  field->set_notnull();
6289  error=field->store(nr, unsigned_flag);
6290  }
6291  return error ? error : (field->table->in_use->is_error() ?
6292  TYPE_ERR_BAD_VALUE : TYPE_OK);
6293 }
6294 
6295 
6296 type_conversion_status
6297 Item_string::save_in_field(Field *field, bool no_conversions)
6298 {
6299  String *result;
6300  result=val_str(&str_value);
6301  return save_str_value_in_field(field, result);
6302 }
6303 
6304 
6305 type_conversion_status
6306 Item_uint::save_in_field(Field *field, bool no_conversions)
6307 {
6308  /* Item_int::save_in_field handles both signed and unsigned. */
6309  return Item_int::save_in_field(field, no_conversions);
6310 }
6311 
6324 static type_conversion_status
6325 save_int_value_in_field (Field *field, longlong nr,
6326  bool null_value, bool unsigned_flag)
6327 {
6328  // TODO: call set_field_to_null_with_conversions below
6329  if (null_value)
6330  return set_field_to_null(field);
6331  field->set_notnull();
6332  return field->store(nr, unsigned_flag);
6333 }
6334 
6335 
6353 type_conversion_status
6354 Item_int::save_in_field(Field *field, bool no_conversions)
6355 {
6356  return save_int_value_in_field (field, val_int(), null_value,
6357  unsigned_flag);
6358 }
6359 
6360 
6361 type_conversion_status
6362 Item_temporal::save_in_field(Field *field, bool no_conversions)
6363 {
6364  longlong nr= field->is_temporal_with_time() ?
6365  val_temporal_with_round(field->type(), field->decimals()) :
6367  // TODO: call set_field_to_null_with_conversions below
6368  if (null_value)
6369  return set_field_to_null(field);
6370  field->set_notnull();
6371  return field->store_packed(nr);
6372 }
6373 
6374 
6375 type_conversion_status
6376 Item_decimal::save_in_field(Field *field, bool no_conversions)
6377 {
6378  field->set_notnull();
6379  return field->store_decimal(&decimal_value);
6380 }
6381 
6382 
6383 bool Item_int::eq(const Item *arg, bool binary_cmp) const
6384 {
6385  /* No need to check for null value as basic constant can't be NULL */
6386  if (arg->basic_const_item() && arg->type() == type())
6387  {
6388  /*
6389  We need to cast off const to call val_int(). This should be OK for
6390  a basic constant.
6391  */
6392  Item *item= (Item*) arg;
6393  return item->val_int() == value && item->unsigned_flag == unsigned_flag;
6394  }
6395  return FALSE;
6396 }
6397 
6398 
6399 Item *Item_int_with_ref::clone_item()
6400 {
6401  DBUG_ASSERT(ref->const_item());
6402  /*
6403  We need to evaluate the constant to make sure it works with
6404  parameter markers.
6405  */
6406  return (ref->unsigned_flag ?
6407  new Item_uint(ref->item_name, ref->val_int(), ref->max_length) :
6408  new Item_int(ref->item_name, ref->val_int(), ref->max_length));
6409 }
6410 
6411 
6412 Item *Item_time_with_ref::clone_item()
6413 {
6414  DBUG_ASSERT(ref->const_item());
6415  /*
6416  We need to evaluate the constant to make sure it works with
6417  parameter markers.
6418  */
6419  return new Item_temporal(MYSQL_TYPE_TIME, ref->item_name,
6420  ref->val_time_temporal(), ref->max_length);
6421 }
6422 
6423 
6424 Item *Item_datetime_with_ref::clone_item()
6425 {
6426  DBUG_ASSERT(ref->const_item());
6427  /*
6428  We need to evaluate the constant to make sure it works with
6429  parameter markers.
6430  */
6431  return new Item_temporal(MYSQL_TYPE_DATETIME, ref->item_name,
6432  ref->val_date_temporal(), ref->max_length);
6433 }
6434 
6435 
6436 void Item_temporal_with_ref::print(String *str, enum_query_type query_type)
6437 {
6438  char buff[MAX_DATE_STRING_REP_LENGTH];
6439  MYSQL_TIME ltime;
6440  TIME_from_longlong_packed(&ltime, field_type(), value);
6441  str->append("'");
6442  my_TIME_to_str(&ltime, buff, decimals);
6443  str->append(buff);
6444  str->append('\'');
6445 }
6446 
6447 
6448 Item_num *Item_uint::neg()
6449 {
6450  Item_decimal *item= new Item_decimal(value, 1);
6451  return item->neg();
6452 }
6453 
6454 
6455 static uint nr_of_decimals(const char *str, const char *end)
6456 {
6457  const char *decimal_point;
6458 
6459  /* Find position for '.' */
6460  for (;;)
6461  {
6462  if (str == end)
6463  return 0;
6464  if (*str == 'e' || *str == 'E')
6465  return NOT_FIXED_DEC;
6466  if (*str++ == '.')
6467  break;
6468  }
6469  decimal_point= str;
6470  for ( ; str < end && my_isdigit(system_charset_info, *str) ; str++)
6471  ;
6472  if (str < end && (*str == 'e' || *str == 'E'))
6473  return NOT_FIXED_DEC;
6474  /*
6475  QQ:
6476  The number of decimal digist in fact should be (str - decimal_point - 1).
6477  But it seems the result of nr_of_decimals() is never used!
6478 
6479  In case of 'e' and 'E' nr_of_decimals returns NOT_FIXED_DEC.
6480  In case if there is no 'e' or 'E' parser code in sql_yacc.yy
6481  never calls Item_float::Item_float() - it creates Item_decimal instead.
6482 
6483  The only piece of code where we call Item_float::Item_float(str, len)
6484  without having 'e' or 'E' is item_xmlfunc.cc, but this Item_float
6485  never appears in metadata itself. Changing the code to return
6486  (str - decimal_point - 1) does not make any changes in the test results.
6487 
6488  This should be addressed somehow.
6489  Looks like a reminder from before real DECIMAL times.
6490  */
6491  return (uint) (str - decimal_point);
6492 }
6493 
6494 
6506 Item_float::Item_float(const char *str_arg, uint length)
6507 {
6508  int error;
6509  char *end_not_used;
6510  value= my_strntod(&my_charset_bin, (char*) str_arg, length, &end_not_used,
6511  &error);
6512  if (error)
6513  {
6514  char tmp[NAME_LEN + 1];
6515  my_snprintf(tmp, sizeof(tmp), "%.*s", length, str_arg);
6516  my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", tmp);
6517  }
6518  presentation.copy(str_arg, length);
6519  item_name.copy(str_arg, length);
6520  decimals=(uint8) nr_of_decimals(str_arg, str_arg+length);
6521  max_length=length;
6522  fixed= 1;
6523 }
6524 
6525 
6526 type_conversion_status
6527 Item_float::save_in_field(Field *field, bool no_conversions)
6528 {
6529  double nr= val_real();
6530  // TODO: call set_field_to_null_with_conversions below
6531  if (null_value)
6532  return set_field_to_null(field);
6533  field->set_notnull();
6534  return field->store(nr);
6535 }
6536 
6537 
6538 void Item_float::print(String *str, enum_query_type query_type)
6539 {
6540  if (presentation.ptr())
6541  {
6542  str->append(presentation.ptr());
6543  return;
6544  }
6545  char buffer[20];
6546  String num(buffer, sizeof(buffer), &my_charset_bin);
6547  num.set_real(value, decimals, &my_charset_bin);
6548  str->append(num);
6549 }
6550 
6551 
6552 /*
6553  hex item
6554  In string context this is a binary string.
6555  In number context this is a longlong value.
6556 */
6557 
6558 bool Item_float::eq(const Item *arg, bool binary_cmp) const
6559 {
6560  if (arg->basic_const_item() && arg->type() == type())
6561  {
6562  /*
6563  We need to cast off const to call val_int(). This should be OK for
6564  a basic constant.
6565  */
6566  Item *item= (Item*) arg;
6567  return item->val_real() == value;
6568  }
6569  return FALSE;
6570 }
6571 
6572 
6573 inline uint char_val(char X)
6574 {
6575  return (uint) (X >= '0' && X <= '9' ? X-'0' :
6576  X >= 'A' && X <= 'Z' ? X-'A'+10 :
6577  X-'a'+10);
6578 }
6579 
6580 Item_hex_string::Item_hex_string()
6581 {
6582  hex_string_init("", 0);
6583 }
6584 
6585 Item_hex_string::Item_hex_string(const char *str, uint str_length)
6586 {
6587  hex_string_init(str, str_length);
6588 }
6589 
6590 void Item_hex_string::hex_string_init(const char *str, uint str_length)
6591 {
6592  max_length=(str_length+1)/2;
6593  char *ptr=(char*) sql_alloc(max_length+1);
6594  if (!ptr)
6595  {
6596  str_value.set("", 0, &my_charset_bin);
6597  return;
6598  }
6599  str_value.set(ptr,max_length,&my_charset_bin);
6600  char *end=ptr+max_length;
6601  if (max_length*2 != str_length)
6602  *ptr++=char_val(*str++); // Not even, assume 0 prefix
6603  while (ptr != end)
6604  {
6605  *ptr++= (char) (char_val(str[0])*16+char_val(str[1]));
6606  str+=2;
6607  }
6608  *ptr=0; // Keep purify happy
6609  collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
6610  fixed= 1;
6611  unsigned_flag= 1;
6612 }
6613 
6614 longlong Item_hex_string::val_int()
6615 {
6616  // following assert is redundant, because fixed=1 assigned in constructor
6617  DBUG_ASSERT(fixed == 1);
6618  char *end=(char*) str_value.ptr()+str_value.length(),
6619  *ptr= end - min<size_t>(str_value.length(), sizeof(longlong));
6620 
6621  ulonglong value=0;
6622  for (; ptr != end ; ptr++)
6623  value=(value << 8)+ (ulonglong) (uchar) *ptr;
6624  return (longlong) value;
6625 }
6626 
6627 
6628 my_decimal *Item_hex_string::val_decimal(my_decimal *decimal_value)
6629 {
6630  // following assert is redundant, because fixed=1 assigned in constructor
6631  DBUG_ASSERT(fixed == 1);
6632  ulonglong value= (ulonglong)val_int();
6633  int2my_decimal(E_DEC_FATAL_ERROR, value, TRUE, decimal_value);
6634  return (decimal_value);
6635 }
6636 
6637 
6638 type_conversion_status
6639 Item_hex_string::save_in_field(Field *field, bool no_conversions)
6640 {
6641  field->set_notnull();
6642  if (field->result_type() == STRING_RESULT)
6643  return field->store(str_value.ptr(), str_value.length(),
6644  collation.collation);
6645 
6646  ulonglong nr;
6647  uint32 length= str_value.length();
6648  if (!length)
6649  {
6650  field->reset();
6651  return TYPE_WARN_OUT_OF_RANGE;
6652  }
6653  if (length > 8)
6654  {
6655  nr= field->flags & UNSIGNED_FLAG ? ULONGLONG_MAX : LONGLONG_MAX;
6656  goto warn;
6657  }
6658  nr= (ulonglong) val_int();
6659  if ((length == 8) && !(field->flags & UNSIGNED_FLAG) && (nr > LONGLONG_MAX))
6660  {
6661  nr= LONGLONG_MAX;
6662  goto warn;
6663  }
6664  return field->store((longlong) nr, TRUE); // Assume hex numbers are unsigned
6665 
6666 warn:
6667  const type_conversion_status res= field->store((longlong) nr, TRUE);
6668  if (res == TYPE_OK)
6669  field->set_warning(Sql_condition::WARN_LEVEL_WARN,
6670  ER_WARN_DATA_OUT_OF_RANGE, 1);
6671  return res;
6672 }
6673 
6674 
6675 void Item_hex_string::print(String *str, enum_query_type query_type)
6676 {
6677  char *end= (char*) str_value.ptr() + str_value.length(),
6678  *ptr= end - min<size_t>(str_value.length(), sizeof(longlong));
6679  str->append("0x");
6680  for (; ptr != end ; ptr++)
6681  {
6682  str->append(_dig_vec_lower[((uchar) *ptr) >> 4]);
6683  str->append(_dig_vec_lower[((uchar) *ptr) & 0x0F]);
6684  }
6685 }
6686 
6687 
6688 bool Item_hex_string::eq(const Item *arg, bool binary_cmp) const
6689 {
6690  if (arg->basic_const_item() && arg->type() == type())
6691  {
6692  if (binary_cmp)
6693  return !stringcmp(&str_value, &arg->str_value);
6694  return !sortcmp(&str_value, &arg->str_value, collation.collation);
6695  }
6696  return FALSE;
6697 }
6698 
6699 
6700 Item *Item_hex_string::safe_charset_converter(const CHARSET_INFO *tocs)
6701 {
6702  Item_string *conv;
6703  String tmp, *str= val_str(&tmp);
6704 
6705  if (!(conv= new Item_string(str->ptr(), str->length(), tocs)))
6706  return NULL;
6707  conv->str_value.copy();
6708  conv->str_value.mark_as_const();
6709  return conv;
6710 }
6711 
6712 
6713 /*
6714  bin item.
6715  In string context this is a binary string.
6716  In number context this is a longlong value.
6717 */
6718 
6719 Item_bin_string::Item_bin_string(const char *str, uint str_length)
6720 {
6721  const char *end= str + str_length - 1;
6722  uchar bits= 0;
6723  uint power= 1;
6724 
6725  max_length= (str_length + 7) >> 3;
6726  char *ptr= (char*) sql_alloc(max_length + 1);
6727  if (!ptr)
6728  return;
6729  str_value.set(ptr, max_length, &my_charset_bin);
6730 
6731  if (max_length > 0)
6732  {
6733  ptr+= max_length - 1;
6734  ptr[1]= 0; // Set end null for string
6735  for (; end >= str; end--)
6736  {
6737  if (power == 256)
6738  {
6739  power= 1;
6740  *ptr--= bits;
6741  bits= 0;
6742  }
6743  if (*end == '1')
6744  bits|= power;
6745  power<<= 1;
6746  }
6747  *ptr= (char) bits;
6748  }
6749  else
6750  ptr[0]= 0;
6751 
6752  collation.set(&my_charset_bin, DERIVATION_COERCIBLE);
6753  fixed= 1;
6754 }
6755 
6756 
6761 bool Item_null::send(Protocol *protocol, String *packet)
6762 {
6763  return protocol->store_null();
6764 }
6765 
6770 bool Item::send(Protocol *protocol, String *buffer)
6771 {
6772  bool UNINIT_VAR(result); // Will be set if null_value == 0
6773  enum_field_types f_type;
6774 
6775  switch ((f_type=field_type())) {
6776  default:
6777  case MYSQL_TYPE_NULL:
6778  case MYSQL_TYPE_DECIMAL:
6779  case MYSQL_TYPE_ENUM:
6780  case MYSQL_TYPE_SET:
6781  case MYSQL_TYPE_TINY_BLOB:
6782  case MYSQL_TYPE_MEDIUM_BLOB:
6783  case MYSQL_TYPE_LONG_BLOB:
6784  case MYSQL_TYPE_BLOB:
6785  case MYSQL_TYPE_GEOMETRY:
6786  case MYSQL_TYPE_STRING:
6787  case MYSQL_TYPE_VAR_STRING:
6788  case MYSQL_TYPE_VARCHAR:
6789  case MYSQL_TYPE_BIT:
6790  case MYSQL_TYPE_NEWDECIMAL:
6791  {
6792  String *res;
6793  if ((res=val_str(buffer)))
6794  result= protocol->store(res->ptr(),res->length(),res->charset());
6795  else
6796  {
6797  DBUG_ASSERT(null_value);
6798  }
6799  break;
6800  }
6801  case MYSQL_TYPE_TINY:
6802  {
6803  longlong nr;
6804  nr= val_int();
6805  if (!null_value)
6806  result= protocol->store_tiny(nr);
6807  break;
6808  }
6809  case MYSQL_TYPE_SHORT:
6810  case MYSQL_TYPE_YEAR:
6811  {
6812  longlong nr;
6813  nr= val_int();
6814  if (!null_value)
6815  result= protocol->store_short(nr);
6816  break;
6817  }
6818  case MYSQL_TYPE_INT24:
6819  case MYSQL_TYPE_LONG:
6820  {
6821  longlong nr;
6822  nr= val_int();
6823  if (!null_value)
6824  result= protocol->store_long(nr);
6825  break;
6826  }
6827  case MYSQL_TYPE_LONGLONG:
6828  {
6829  longlong nr;
6830  nr= val_int();
6831  if (!null_value)
6832  result= protocol->store_longlong(nr, unsigned_flag);
6833  break;
6834  }
6835  case MYSQL_TYPE_FLOAT:
6836  {
6837  float nr;
6838  nr= (float) val_real();
6839  if (!null_value)
6840  result= protocol->store(nr, decimals, buffer);
6841  break;
6842  }
6843  case MYSQL_TYPE_DOUBLE:
6844  {
6845  double nr= val_real();
6846  if (!null_value)
6847  result= protocol->store(nr, decimals, buffer);
6848  break;
6849  }
6850  case MYSQL_TYPE_DATETIME:
6851  case MYSQL_TYPE_DATE:
6852  case MYSQL_TYPE_TIMESTAMP:
6853  {
6854  MYSQL_TIME tm;
6855  get_date(&tm, TIME_FUZZY_DATE);
6856  if (!null_value)
6857  result= (f_type == MYSQL_TYPE_DATE) ? protocol->store_date(&tm) :
6858  protocol->store(&tm, decimals);
6859  break;
6860  }
6861  case MYSQL_TYPE_TIME:
6862  {
6863  MYSQL_TIME tm;
6864  get_time(&tm);
6865  if (!null_value)
6866  result= protocol->store_time(&tm, decimals);
6867  break;
6868  }
6869  }
6870  if (null_value)
6871  result= protocol->store_null();
6872  return result;
6873 }
6874 
6875 
6886 {
6887  Item **cache_item= (Item **)*arg;
6888  if (!*cache_item)
6889  {
6890  Item *item= real_item();
6891  /*
6892  Cache constant items unless it's a basic constant, constant field or
6893  a subquery (they use their own cache), or it is already cached.
6894  */
6895  if (const_item() &&
6896  !(basic_const_item() || item->basic_const_item() ||
6897  item->type() == Item::FIELD_ITEM ||
6898  item->type() == SUBSELECT_ITEM ||
6899  item->type() == CACHE_ITEM ||
6900  /*
6901  Do not cache GET_USER_VAR() function as its const_item() may
6902  return TRUE for the current thread but it still may change
6903  during the execution.
6904  */
6905  (item->type() == Item::FUNC_ITEM &&
6906  ((Item_func*)item)->functype() == Item_func::GUSERVAR_FUNC)))
6907  /*
6908  Note that we use cache_item as a flag (NULL vs non-NULL), but we
6909  are storing the pointer so that we can assert that we cache the
6910  correct item in Item::cache_const_expr_transformer().
6911  */
6912  *cache_item= this;
6913  /*
6914  If this item will be cached, no need to explore items further down
6915  in the tree, but the transformer must be called, so return 'true'.
6916  If this item will not be cached, items further doen in the tree
6917  must be explored, so return 'true'.
6918  */
6919  return true;
6920  }
6921  /*
6922  An item above in the tree is to be cached, so need to cache the present
6923  item, and no need to go down the tree.
6924  */
6925  return false;
6926 }
6927 
6928 
6939 {
6940  Item **item= (Item **)arg;
6941  if (*item) // Item is to be cached, note that it is used as a flag
6942  {
6943  DBUG_ASSERT(*item == this);
6944  /*
6945  Flag applies to present item, must reset it so it does not affect
6946  the parent item.
6947  */
6948  *((Item **)arg)= NULL;
6949  Item_cache *cache= Item_cache::get_cache(this);
6950  if (!cache)
6951  return NULL;
6952  cache->setup(this);
6953  cache->store(this);
6954  return cache;
6955  }
6956  return this;
6957 }
6958 
6959 
6961 {
6962  const char *name= reinterpret_cast<char*>(*arg);
6963 
6964  if (strcmp(field_name, name) == 0)
6965  return true;
6966  else
6967  return false;
6968 }
6969 
6970 
6972 {
6973  Item *item= reinterpret_cast<Item*>(arg);
6974  item->item_name= item_name;
6975  return item;
6976 }
6977 
6978 
6979 bool Item_field::send(Protocol *protocol, String *buffer)
6980 {
6981  return protocol->store(result_field);
6982 }
6983 
6984 
6985 void Item_field::update_null_value()
6986 {
6987  /*
6988  need to set no_errors to prevent warnings about type conversion
6989  popping up.
6990  */
6991  THD *thd= field->table->in_use;
6992  int no_errors;
6993 
6994  no_errors= thd->no_errors;
6995  thd->no_errors= 1;
6996  Item::update_null_value();
6997  thd->no_errors= no_errors;
6998 }
6999 
7000 
7001 /*
7002  Add the field to the select list and substitute it for the reference to
7003  the field.
7004 
7005  SYNOPSIS
7006  Item_field::update_value_transformer()
7007  select_arg current select
7008 
7009  DESCRIPTION
7010  If the field doesn't belong to the table being inserted into then it is
7011  added to the select list, pointer to it is stored in the ref_pointer_array
7012  of the select and the field itself is substituted for the Item_ref object.
7013  This is done in order to get correct values from update fields that
7014  belongs to the SELECT part in the INSERT .. SELECT .. ON DUPLICATE KEY
7015  UPDATE statement.
7016 
7017  RETURN
7018  0 if error occured
7019  ref if all conditions are met
7020  this field otherwise
7021 */
7022 
7023 Item *Item_field::update_value_transformer(uchar *select_arg)
7024 {
7025  SELECT_LEX *select= (SELECT_LEX*)select_arg;
7026  DBUG_ASSERT(fixed);
7027 
7028  if (field->table != select->context.table_list->table &&
7029  type() != Item::TRIGGER_FIELD_ITEM)
7030  {
7031  List<Item> *all_fields= &select->join->all_fields;
7032  Ref_ptr_array &ref_pointer_array= select->ref_pointer_array;
7033  int el= all_fields->elements;
7034  Item_ref *ref;
7035 
7036  ref_pointer_array[el]= (Item*)this;
7037  all_fields->push_front((Item*)this);
7038  ref= new Item_ref(&select->context, &ref_pointer_array[el],
7039  table_name, field_name);
7040  return ref;
7041  }
7042  return this;
7043 }
7044 
7045 
7046 void Item_field::print(String *str, enum_query_type query_type)
7047 {
7048  if (field && field->table->const_table)
7049  {
7050  char buff[MAX_FIELD_WIDTH];
7051  String tmp(buff,sizeof(buff),str->charset());
7052  field->val_str(&tmp);
7053  if (field->is_null())
7054  str->append("NULL");
7055  else
7056  {
7057  str->append('\'');
7058  str->append(tmp);
7059  str->append('\'');
7060  }
7061  return;
7062  }
7063  Item_ident::print(str, query_type);
7064 }
7065 
7066 
7067 Item_ref::Item_ref(Name_resolution_context *context_arg,
7068  Item **item, const char *table_name_arg,
7069  const char *field_name_arg,
7070  bool alias_name_used_arg)
7071  :Item_ident(context_arg, NullS, table_name_arg, field_name_arg),
7072  result_field(0), ref(item)
7073 {
7074  alias_name_used= alias_name_used_arg;
7075  /*
7076  This constructor used to create some internals references over fixed items
7077  */
7078  if (ref && *ref && (*ref)->fixed)
7079  set_properties();
7080 }
7081 
7082 
7147 bool Item_ref::fix_fields(THD *thd, Item **reference)
7148 {
7149  enum_parsing_place place= NO_MATTER;
7150  DBUG_ASSERT(fixed == 0);
7151  SELECT_LEX *current_sel= thd->lex->current_select;
7152 
7153  if (!ref || ref == not_found_item)
7154  {
7155  if (!(ref= resolve_ref_in_select_and_group(thd, this,
7156  context->select_lex)))
7157  goto error; /* Some error occurred (e.g. ambiguous names). */
7158 
7159  if (ref == not_found_item) /* This reference was not resolved. */
7160  {
7161  Name_resolution_context *last_checked_context= context;
7162  Name_resolution_context *outer_context= context->outer_context;
7163  Field *from_field;
7164  ref= 0;
7165 
7166  if (!outer_context)
7167  {
7168  /* The current reference cannot be resolved in this query. */
7169  my_error(ER_BAD_FIELD_ERROR,MYF(0),
7170  this->full_name(), current_thd->where);
7171  goto error;
7172  }
7173 
7174  /*
7175  If there is an outer context (select), and it is not a derived table
7176  (which do not support the use of outer fields for now), try to
7177  resolve this reference in the outer select(s).
7178 
7179  We treat each subselect as a separate namespace, so that different
7180  subselects may contain columns with the same names. The subselects are
7181  searched starting from the innermost.
7182  */
7183  from_field= (Field*) not_found_field;
7184 
7185  do
7186  {
7187  SELECT_LEX *select= outer_context->select_lex;
7188  Item_subselect *prev_subselect_item=
7189  last_checked_context->select_lex->master_unit()->item;
7190  last_checked_context= outer_context;
7191 
7192  /* Search in the SELECT and GROUP lists of the outer select. */
7193  if (outer_context->resolve_in_select_list)
7194  {
7195  if (!(ref= resolve_ref_in_select_and_group(thd, this, select)))
7196  goto error; /* Some error occurred (e.g. ambiguous names). */
7197  if (ref != not_found_item)
7198  {
7199  DBUG_ASSERT(is_fixed_or_outer_ref(*ref));
7200  prev_subselect_item->used_tables_cache|= (*ref)->used_tables();
7201  prev_subselect_item->const_item_cache&= (*ref)->const_item();
7202  break;
7203  }
7204  /*
7205  Set ref to 0 to ensure that we get an error in case we replaced
7206  this item with another item and still use this item in some
7207  other place of the parse tree.
7208  */
7209  ref= 0;
7210  }
7211 
7212  place= prev_subselect_item->parsing_place;
7213  /*
7214  Check table fields only if the subquery is used somewhere out of
7215  HAVING or the outer SELECT does not use grouping (i.e. tables are
7216  accessible).
7217  TODO:
7218  Here we could first find the field anyway, and then test this
7219  condition, so that we can give a better error message -
7220  ER_WRONG_FIELD_WITH_GROUP, instead of the less informative
7221  ER_BAD_FIELD_ERROR which we produce now.
7222  */
7223  if ((place != IN_HAVING ||
7224  (!select->with_sum_func &&
7225  select->group_list.elements == 0)))
7226  {
7227  /*
7228  In case of view, find_field_in_tables() write pointer to view
7229  field expression to 'reference', i.e. it substitute that
7230  expression instead of this Item_ref
7231  */
7232  from_field= find_field_in_tables(thd, this,
7233  outer_context->
7234  first_name_resolution_table,
7235  outer_context->
7236  last_name_resolution_table,
7237  reference,
7238  IGNORE_EXCEPT_NON_UNIQUE,
7239  TRUE, TRUE);
7240  if (! from_field)
7241  goto error;
7242  if (from_field == view_ref_found)
7243  {
7244  Item::Type refer_type= (*reference)->type();
7245  prev_subselect_item->used_tables_cache|=
7246  (*reference)->used_tables();
7247  prev_subselect_item->const_item_cache&=
7248  (*reference)->const_item();
7249  DBUG_ASSERT((*reference)->type() == REF_ITEM);
7250  mark_as_dependent(thd, last_checked_context->select_lex,
7251  context->select_lex, this,
7252  ((refer_type == REF_ITEM ||
7253  refer_type == FIELD_ITEM) ?
7254  (Item_ident*) (*reference) :
7255  0));
7256  /*
7257  view reference found, we substituted it instead of this
7258  Item, so can quit
7259  */
7260  return FALSE;
7261  }
7262  if (from_field != not_found_field)
7263  {
7264  if (cached_table && cached_table->select_lex &&
7265  outer_context->select_lex &&
7266  cached_table->select_lex != outer_context->select_lex)
7267  {
7268  /*
7269  Due to cache, find_field_in_tables() can return field which
7270  doesn't belong to provided outer_context. In this case we have
7271  to find proper field context in order to fix field correcly.
7272  */
7273  do
7274  {
7275  outer_context= outer_context->outer_context;
7276  select= outer_context->select_lex;
7277  prev_subselect_item=
7278  last_checked_context->select_lex->master_unit()->item;
7279  last_checked_context= outer_context;
7280  } while (outer_context && outer_context->select_lex &&
7281  cached_table->select_lex != outer_context->select_lex);
7282  }
7283  prev_subselect_item->used_tables_cache|= from_field->table->map;
7284  prev_subselect_item->const_item_cache= 0;
7285  break;
7286  }
7287  }
7288  DBUG_ASSERT(from_field == not_found_field);
7289 
7290  /* Reference is not found => depend on outer (or just error). */
7291  prev_subselect_item->used_tables_cache|= OUTER_REF_TABLE_BIT;
7292  prev_subselect_item->const_item_cache= 0;
7293 
7294  outer_context= outer_context->outer_context;
7295  } while (outer_context);
7296 
7297  DBUG_ASSERT(from_field != 0 && from_field != view_ref_found);
7298  if (from_field != not_found_field)
7299  {
7300  Item_field* fld;
7301 
7302  {
7303  Prepared_stmt_arena_holder ps_arena_holder(thd);
7304  fld= new Item_field(thd, last_checked_context, from_field);
7305 
7306  if (!fld)
7307  goto error;
7308  }
7309 
7310  thd->change_item_tree(reference, fld);
7311  mark_as_dependent(thd, last_checked_context->select_lex,
7312  thd->lex->current_select, this, fld);
7313  /*
7314  A reference is resolved to a nest level that's outer or the same as
7315  the nest level of the enclosing set function : adjust the value of
7316  max_arg_level for the function if it's needed.
7317  */
7318  if (thd->lex->in_sum_func &&
7319  thd->lex->in_sum_func->nest_level >=
7320  last_checked_context->select_lex->nest_level)
7321  set_if_bigger(thd->lex->in_sum_func->max_arg_level,
7322  last_checked_context->select_lex->nest_level);
7323  return FALSE;
7324  }
7325  if (ref == 0)
7326  {
7327  /* The item was not a table field and not a reference */
7328  my_error(ER_BAD_FIELD_ERROR, MYF(0),
7329  this->full_name(), current_thd->where);
7330  goto error;
7331  }
7332  /* Should be checked in resolve_ref_in_select_and_group(). */
7333  DBUG_ASSERT(is_fixed_or_outer_ref(*ref));
7334  mark_as_dependent(thd, last_checked_context->select_lex,
7335  context->select_lex, this, this);
7336  /*
7337  A reference is resolved to a nest level that's outer or the same as
7338  the nest level of the enclosing set function : adjust the value of
7339  max_arg_level for the function if it's needed.
7340  */
7341  if (thd->lex->in_sum_func &&
7342  thd->lex->in_sum_func->nest_level >=
7343  last_checked_context->select_lex->nest_level)
7344  set_if_bigger(thd->lex->in_sum_func->max_arg_level,
7345  last_checked_context->select_lex->nest_level);
7346  }
7347  }
7348 
7349  DBUG_ASSERT(*ref);
7350  /*
7351  Check if this is an incorrect reference in a group function or forward
7352  reference. Do not issue an error if this is:
7353  1. outer reference (will be fixed later by the fix_inner_refs function);
7354  2. an unnamed reference inside an aggregate function.
7355  */
7356  if (!((*ref)->type() == REF_ITEM &&
7357  ((Item_ref *)(*ref))->ref_type() == OUTER_REF) &&
7358  (((*ref)->with_sum_func && item_name.ptr() &&
7359  !(current_sel->linkage != GLOBAL_OPTIONS_TYPE &&
7360  current_sel->having_fix_field)) ||
7361  !(*ref)->fixed))
7362  {
7363  my_error(ER_ILLEGAL_REFERENCE, MYF(0),
7364  item_name.ptr(), ((*ref)->with_sum_func?
7365  "reference to group function":
7366  "forward reference in item list"));
7367  goto error;
7368  }
7369 
7370  set_properties();
7371 
7372  if ((*ref)->check_cols(1))
7373  goto error;
7374  return FALSE;
7375 
7376 error:
7377  context->process_error(thd);
7378  return TRUE;
7379 }
7380 
7381 
7382 void Item_ref::set_properties()
7383 {
7384  max_length= (*ref)->max_length;
7385  maybe_null= (*ref)->maybe_null;
7386  decimals= (*ref)->decimals;
7387  collation.set((*ref)->collation);
7388  /*
7389  We have to remember if we refer to a sum function, to ensure that
7390  split_sum_func() doesn't try to change the reference.
7391  */
7392  with_sum_func= (*ref)->with_sum_func;
7393  unsigned_flag= (*ref)->unsigned_flag;
7394  fixed= 1;
7395  if (alias_name_used)
7396  return;
7397  if ((*ref)->type() == FIELD_ITEM)
7398  alias_name_used= ((Item_ident *) (*ref))->alias_name_used;
7399  else
7400  alias_name_used= TRUE; // it is not field, so it is was resolved by alias
7401 }
7402 
7403 
7404 void Item_ref::cleanup()
7405 {
7406  DBUG_ENTER("Item_ref::cleanup");
7407  Item_ident::cleanup();
7408  result_field= 0;
7409  DBUG_VOID_RETURN;
7410 }
7411 
7412 
7431 Item* Item_ref::transform(Item_transformer transformer, uchar *arg)
7432 {
7433  DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
7434  DBUG_ASSERT((*ref) != NULL);
7435 
7436  /* Transform the object we are referencing. */
7437  Item *new_item= (*ref)->transform(transformer, arg);
7438  if (!new_item)
7439  return NULL;
7440 
7441  /*
7442  If the object is transformed into a new object, discard the Item_ref
7443  object and return the new object as result.
7444  */
7445  if (new_item != *ref)
7446  return new_item;
7447 
7448  /* Transform the item ref object. */
7449  Item *transformed_item= (this->*transformer)(arg);
7450  DBUG_ASSERT(transformed_item == this);
7451  return transformed_item;
7452 }
7453 
7454 
7476 Item* Item_ref::compile(Item_analyzer analyzer, uchar **arg_p,
7477  Item_transformer transformer, uchar *arg_t)
7478 {
7479  if (!(this->*analyzer)(arg_p))
7480  return this;
7481 
7482  DBUG_ASSERT((*ref) != NULL);
7483  Item *new_item= (*ref)->compile(analyzer, arg_p, transformer, arg_t);
7484  if (new_item == NULL)
7485  return NULL;
7486 
7487  /*
7488  If the object is compiled into a new object, discard the Item_ref
7489  object and return the new object as result.
7490  */
7491  if (new_item != *ref)
7492  return new_item;
7493 
7494  return (this->*transformer)(arg_t);
7495 }
7496 
7497 
7498 void Item_ref::print(String *str, enum_query_type query_type)
7499 {
7500  if (ref)
7501  {
7502  if ((*ref)->type() != Item::CACHE_ITEM && ref_type() != VIEW_REF &&
7503  !table_name && item_name.ptr() && alias_name_used)
7504  {
7505  THD *thd= current_thd;
7506  append_identifier(thd, str, (*ref)->real_item()->item_name);
7507  }
7508  else
7509  (*ref)->print(str, query_type);
7510  }
7511  else
7512  Item_ident::print(str, query_type);
7513 }
7514 
7515 
7516 bool Item_ref::send(Protocol *prot, String *tmp)
7517 {
7518  if (result_field)
7519  return prot->store(result_field);
7520  return (*ref)->send(prot, tmp);
7521 }
7522 
7523 
7524 double Item_ref::val_result()
7525 {
7526  if (result_field)
7527  {
7528  if ((null_value= result_field->is_null()))
7529  return 0.0;
7530  return result_field->val_real();
7531  }
7532  return val_real();
7533 }
7534 
7535 
7536 bool Item_ref::is_null_result()
7537 {
7538  if (result_field)
7539  return (null_value=result_field->is_null());
7540 
7541  return is_null();
7542 }
7543 
7544 
7545 longlong Item_ref::val_int_result()
7546 {
7547  if (result_field)
7548  {
7549  if ((null_value= result_field->is_null()))
7550  return 0;
7551  return result_field->val_int();
7552  }
7553  return val_int();
7554 }
7555 
7556 
7557 String *Item_ref::str_result(String* str)
7558 {
7559  if (result_field)
7560  {
7561  if ((null_value= result_field->is_null()))
7562  return 0;
7563  str->set_charset(str_value.charset());
7564  return result_field->val_str(str, &str_value);
7565  }
7566  return val_str(str);
7567 }
7568 
7569 
7570 my_decimal *Item_ref::val_decimal_result(my_decimal *decimal_value)
7571 {
7572  if (result_field)
7573  {
7574  if ((null_value= result_field->is_null()))
7575  return 0;
7576  return result_field->val_decimal(decimal_value);
7577  }
7578  return val_decimal(decimal_value);
7579 }
7580 
7581 
7582 bool Item_ref::val_bool_result()
7583 {
7584  if (result_field)
7585  {
7586  if ((null_value= result_field->is_null()))
7587  return 0;
7588  switch (result_field->result_type()) {
7589  case INT_RESULT:
7590  return result_field->val_int() != 0;
7591  case DECIMAL_RESULT:
7592  {
7593  my_decimal decimal_value;
7594  my_decimal *val= result_field->val_decimal(&decimal_value);
7595  if (val)
7596  return !my_decimal_is_zero(val);
7597  return 0;
7598  }
7599  case REAL_RESULT:
7600  case STRING_RESULT:
7601  return result_field->val_real() != 0.0;
7602  case ROW_RESULT:
7603  default:
7604  DBUG_ASSERT(0);
7605  }
7606  }
7607  return val_bool();
7608 }
7609 
7610 
7611 double Item_ref::val_real()
7612 {
7613  DBUG_ASSERT(fixed);
7614  double tmp=(*ref)->val_result();
7615  null_value=(*ref)->null_value;
7616  return tmp;
7617 }
7618 
7619 
7620 longlong Item_ref::val_int()
7621 {
7622  DBUG_ASSERT(fixed);
7623  longlong tmp=(*ref)->val_int_result();
7624  null_value=(*ref)->null_value;
7625  return tmp;
7626 }
7627 
7628 
7630 {
7631  DBUG_ASSERT(fixed);
7632  DBUG_ASSERT((*ref)->is_temporal());
7633  longlong tmp= (*ref)->val_time_temporal_result();
7634  null_value= (*ref)->null_value;
7635  return tmp;
7636 }
7637 
7638 
7640 {
7641  DBUG_ASSERT(fixed);
7642  DBUG_ASSERT((*ref)->is_temporal());
7643  longlong tmp= (*ref)->val_date_temporal_result();
7644  null_value= (*ref)->null_value;
7645  return tmp;
7646 }
7647 
7648 
7650 {
7651  DBUG_ASSERT(fixed);
7652  bool tmp= (*ref)->val_bool_result();
7653  null_value= (*ref)->null_value;
7654  return tmp;
7655 }
7656 
7657 
7658 String *Item_ref::val_str(String* tmp)
7659 {
7660  DBUG_ASSERT(fixed);
7661  tmp=(*ref)->str_result(tmp);
7662  null_value=(*ref)->null_value;
7663  return tmp;
7664 }
7665 
7666 
7667 bool Item_ref::is_null()
7668 {
7669  DBUG_ASSERT(fixed);
7670  bool tmp=(*ref)->is_null_result();
7671  null_value=(*ref)->null_value;
7672  return tmp;
7673 }
7674 
7675 
7676 bool Item_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
7677 {
7678  return (null_value=(*ref)->get_date_result(ltime,fuzzydate));
7679 }
7680 
7681 
7682 my_decimal *Item_ref::val_decimal(my_decimal *decimal_value)
7683 {
7684  my_decimal *val= (*ref)->val_decimal_result(decimal_value);
7685  null_value= (*ref)->null_value;
7686  return val;
7687 }
7688 
7689 type_conversion_status
7690 Item_ref::save_in_field(Field *to, bool no_conversions)
7691 {
7692  type_conversion_status res;
7693  if (result_field)
7694  {
7695  if (result_field->is_null())
7696  {
7697  null_value= 1;
7698  res= set_field_to_null_with_conversions(to, no_conversions);
7699  return res;
7700  }
7701  to->set_notnull();
7702  res= field_conv(to, result_field);
7703  null_value= 0;
7704  return res;
7705  }
7706  res= (*ref)->save_in_field(to, no_conversions);
7707  null_value= (*ref)->null_value;
7708  return res;
7709 }
7710 
7711 
7712 void Item_ref::save_org_in_field(Field *field)
7713 {
7714  (*ref)->save_org_in_field(field);
7715 }
7716 
7717 
7718 void Item_ref::make_field(Send_field *field)
7719 {
7720  (*ref)->make_field(field);
7721  /* Non-zero in case of a view */
7722  if (item_name.is_set())
7723  field->col_name= item_name.ptr();
7724  if (table_name)
7725  field->table_name= table_name;
7726  if (db_name)
7727  field->db_name= db_name;
7728  if (orig_field_name)
7729  field->org_col_name= orig_field_name;
7730  if (orig_table_name)
7731  field->org_table_name= orig_table_name;
7732 }
7733 
7734 
7735 Item *Item_ref::get_tmp_table_item(THD *thd)
7736 {
7737  if (!result_field)
7738  return (*ref)->get_tmp_table_item(thd);
7739 
7740  Item_field *item= new Item_field(result_field);
7741  if (item)
7742  {
7743  item->table_name= table_name;
7744  item->db_name= db_name;
7745  }
7746  return item;
7747 }
7748 
7749 
7750 void Item_ref_null_helper::print(String *str, enum_query_type query_type)
7751 {
7752  str->append(STRING_WITH_LEN("<ref_null_helper>("));
7753  if (ref)
7754  (*ref)->print(str, query_type);
7755  else
7756  str->append('?');
7757  str->append(')');
7758 }
7759 
7760 
7761 double Item_direct_ref::val_real()
7762 {
7763  double tmp=(*ref)->val_real();
7764  null_value=(*ref)->null_value;
7765  return tmp;
7766 }
7767 
7768 
7769 longlong Item_direct_ref::val_int()
7770 {
7771  longlong tmp=(*ref)->val_int();
7772  null_value=(*ref)->null_value;
7773  return tmp;
7774 }
7775 
7776 
7778 {
7779  DBUG_ASSERT((*ref)->is_temporal());
7780  longlong tmp= (*ref)->val_time_temporal();
7781  null_value= (*ref)->null_value;
7782  return tmp;
7783 }
7784 
7785 
7787 {
7788  DBUG_ASSERT((*ref)->is_temporal());
7789  longlong tmp= (*ref)->val_date_temporal();
7790  null_value= (*ref)->null_value;
7791  return tmp;
7792 }
7793 
7794 
7795 String *Item_direct_ref::val_str(String* tmp)
7796 {
7797  tmp=(*ref)->val_str(tmp);
7798  null_value=(*ref)->null_value;
7799  return tmp;
7800 }
7801 
7802 
7803 my_decimal *Item_direct_ref::val_decimal(my_decimal *decimal_value)
7804 {
7805  my_decimal *tmp= (*ref)->val_decimal(decimal_value);
7806  null_value=(*ref)->null_value;
7807  return tmp;
7808 }
7809 
7810 
7812 {
7813  bool tmp= (*ref)->val_bool();
7814  null_value=(*ref)->null_value;
7815  return tmp;
7816 }
7817 
7818 
7819 bool Item_direct_ref::is_null()
7820 {
7821  return (*ref)->is_null();
7822 }
7823 
7824 
7825 bool Item_direct_ref::get_date(MYSQL_TIME *ltime,uint fuzzydate)
7826 {
7827  bool tmp= (*ref)->get_date(ltime, fuzzydate);
7828  null_value= (*ref)->null_value;
7829  return tmp;
7830 }
7831 
7832 
7845 bool Item_direct_view_ref::fix_fields(THD *thd, Item **reference)
7846 {
7847  /* view fild reference must be defined */
7848  DBUG_ASSERT(*ref);
7849  /* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */
7850  if ((*ref)->fixed)
7851  {
7852  Item *ref_item= (*ref)->real_item();
7853  if (ref_item->type() == Item::FIELD_ITEM)
7854  {
7855  /*
7856  In some cases we need to update table read set(see bug#47150).
7857  If ref item is FIELD_ITEM and fixed then field and table
7858  have proper values. So we can use them for update.
7859  */
7860  Field *fld= ((Item_field*) ref_item)->field;
7861  DBUG_ASSERT(fld && fld->table);
7862  if (thd->mark_used_columns == MARK_COLUMNS_READ)
7863  bitmap_set_bit(fld->table->read_set, fld->field_index);
7864  }
7865  }
7866  else if (!(*ref)->fixed &&
7867  ((*ref)->fix_fields(thd, ref)))
7868  return TRUE;
7869 
7870  return Item_direct_ref::fix_fields(thd, reference);
7871 }
7872 
7873 /*
7874  Prepare referenced outer field then call usual Item_direct_ref::fix_fields
7875 
7876  SYNOPSIS
7877  Item_outer_ref::fix_fields()
7878  thd thread handler
7879  reference reference on reference where this item stored
7880 
7881  RETURN
7882  FALSE OK
7883  TRUE Error
7884 */
7885 
7886 bool Item_outer_ref::fix_fields(THD *thd, Item **reference)
7887 {
7888  bool err;
7889  /* outer_ref->check_cols() will be made in Item_direct_ref::fix_fields */
7890  if ((*ref) && !(*ref)->fixed && ((*ref)->fix_fields(thd, reference)))
7891  return TRUE;
7892  err= Item_direct_ref::fix_fields(thd, reference);
7893  if (!outer_ref)
7894  outer_ref= *ref;
7895  if ((*ref)->type() == Item::FIELD_ITEM)
7896  table_name= ((Item_field*)outer_ref)->table_name;
7897  return err;
7898 }
7899 
7900 void Item_outer_ref::fix_after_pullout(st_select_lex *parent_select,
7901  st_select_lex *removed_select)
7902 {
7903  /*
7904  If this assertion holds, we need not call fix_after_pullout() on both
7905  *ref and outer_ref, and Item_ref::fix_after_pullout() is sufficient.
7906  */
7907  DBUG_ASSERT(*ref == outer_ref);
7908 
7909  Item_ref::fix_after_pullout(parent_select, removed_select);
7910 }
7911 
7912 void Item_ref::fix_after_pullout(st_select_lex *parent_select,
7913  st_select_lex *removed_select)
7914 {
7915  (*ref)->fix_after_pullout(parent_select, removed_select);
7916 
7917  Item_ident::fix_after_pullout(parent_select, removed_select);
7918 }
7919 
7920 
7938 bool Item_direct_view_ref::eq(const Item *item, bool binary_cmp) const
7939 {
7940  if (item->type() == REF_ITEM)
7941  {
7942  Item_ref *item_ref= (Item_ref*) item;
7943  if (item_ref->ref_type() == VIEW_REF)
7944  {
7945  Item *item_ref_ref= *(item_ref->ref);
7946  return ((*ref)->real_item() == item_ref_ref->real_item());
7947  }
7948  }
7949  return FALSE;
7950 }
7951 
7952 bool Item_default_value::eq(const Item *item, bool binary_cmp) const
7953 {
7954  return item->type() == DEFAULT_VALUE_ITEM &&
7955  ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
7956 }
7957 
7958 
7960 {
7961  Item *real_arg;
7962  Item_field *field_arg;
7963  Field *def_field;
7964  DBUG_ASSERT(fixed == 0);
7965 
7966  if (!arg)
7967  {
7968  fixed= 1;
7969  return FALSE;
7970  }
7971  if (!arg->fixed && arg->fix_fields(thd, &arg))
7972  goto error;
7973 
7974 
7975  real_arg= arg->real_item();
7976  if (real_arg->type() != FIELD_ITEM)
7977  {
7978  my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), arg->item_name.ptr());
7979  goto error;
7980  }
7981 
7982  field_arg= (Item_field *)real_arg;
7983  if (field_arg->field->flags & NO_DEFAULT_VALUE_FLAG)
7984  {
7985  my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), field_arg->field->field_name);
7986  goto error;
7987  }
7988 
7989  def_field= field_arg->field->clone();
7990  if (def_field == NULL)
7991  goto error;
7992 
7993  def_field->move_field_offset((my_ptrdiff_t)
7994  (def_field->table->s->default_values -
7995  def_field->table->record[0]));
7996  set_field(def_field);
7997  return FALSE;
7998 
7999 error:
8000  context->process_error(thd);
8001  return TRUE;
8002 }
8003 
8004 
8005 void Item_default_value::print(String *str, enum_query_type query_type)
8006 {
8007  if (!arg)
8008  {
8009  str->append(STRING_WITH_LEN("default"));
8010  return;
8011  }
8012  str->append(STRING_WITH_LEN("default("));
8013  arg->print(str, query_type);
8014  str->append(')');
8015 }
8016 
8017 
8018 type_conversion_status
8019 Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
8020 {
8021  if (!arg)
8022  {
8023  if (field_arg->flags & NO_DEFAULT_VALUE_FLAG &&
8024  field_arg->real_type() != MYSQL_TYPE_ENUM)
8025  {
8026  if (field_arg->reset())
8027  {
8028  my_message(ER_CANT_CREATE_GEOMETRY_OBJECT,
8029  ER(ER_CANT_CREATE_GEOMETRY_OBJECT), MYF(0));
8030  return TYPE_ERR_BAD_VALUE;
8031  }
8032 
8033  if (context->error_processor == &view_error_processor)
8034  {
8035  TABLE_LIST *view= cached_table->top_table();
8036  push_warning_printf(field_arg->table->in_use,
8037  Sql_condition::WARN_LEVEL_WARN,
8038  ER_NO_DEFAULT_FOR_VIEW_FIELD,
8039  ER(ER_NO_DEFAULT_FOR_VIEW_FIELD),
8040  view->view_db.str,
8041  view->view_name.str);
8042  }
8043  else
8044  {
8045  push_warning_printf(field_arg->table->in_use,
8046  Sql_condition::WARN_LEVEL_WARN,
8047  ER_NO_DEFAULT_FOR_FIELD,
8048  ER(ER_NO_DEFAULT_FOR_FIELD),
8049  field_arg->field_name);
8050  }
8051  return TYPE_ERR_BAD_VALUE;
8052  }
8053  field_arg->set_default();
8054  return field_arg->validate_stored_val(current_thd);
8055  }
8056  return Item_field::save_in_field(field_arg, no_conversions);
8057 }
8058 
8059 
8065 Item *Item_default_value::transform(Item_transformer transformer, uchar *args)
8066 {
8067  DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
8068 
8069  /*
8070  If the value of arg is NULL, then this object represents a constant,
8071  so further transformation is unnecessary (and impossible).
8072  */
8073  if (!arg)
8074  return 0;
8075 
8076  Item *new_item= arg->transform(transformer, args);
8077  if (!new_item)
8078  return 0;
8079 
8080  /*
8081  THD::change_item_tree() should be called only if the tree was
8082  really transformed, i.e. when a new item has been created.
8083  Otherwise we'll be allocating a lot of unnecessary memory for
8084  change records at each execution.
8085  */
8086  if (arg != new_item)
8087  current_thd->change_item_tree(&arg, new_item);
8088  return (this->*transformer)(args);
8089 }
8090 
8091 
8092 bool Item_insert_value::eq(const Item *item, bool binary_cmp) const
8093 {
8094  return item->type() == INSERT_VALUE_ITEM &&
8095  ((Item_default_value *)item)->arg->eq(arg, binary_cmp);
8096 }
8097 
8098 
8099 bool Item_insert_value::fix_fields(THD *thd, Item **reference)
8100 {
8101  DBUG_ASSERT(fixed == 0);
8102  /* We should only check that arg is in first table */
8103  if (!arg->fixed)
8104  {
8105  bool res;
8106  TABLE_LIST *orig_next_table= context->last_name_resolution_table;
8107  context->last_name_resolution_table= context->first_name_resolution_table;
8108  res= arg->fix_fields(thd, &arg);
8109  context->last_name_resolution_table= orig_next_table;
8110  if (res)
8111  return TRUE;
8112  }
8113 
8114  if (arg->type() == REF_ITEM)
8115  arg= static_cast<Item_ref *>(arg)->ref[0];
8116  if (arg->type() != FIELD_ITEM)
8117  {
8118  my_error(ER_BAD_FIELD_ERROR, MYF(0), "", "VALUES() function");
8119  return TRUE;
8120  }
8121 
8122  Item_field *field_arg= (Item_field *)arg;
8123 
8124  if (field_arg->field->table->insert_values &&
8125  find_item_in_item_list(this, &thd->lex->value_list))
8126  {
8127  Field *def_field= field_arg->field->clone();
8128  if (!def_field)
8129  return TRUE;
8130 
8131  def_field->move_field_offset((my_ptrdiff_t)
8132  (def_field->table->insert_values -
8133  def_field->table->record[0]));
8134  set_field(def_field);
8135  }
8136  else
8137  {
8138  // VALUES() is used out-of-scope - its value is always NULL
8139  Prepared_stmt_arena_holder ps_arena_holder(thd);
8140  Item *const item= new Item_null(this->item_name);
8141  if (!item)
8142  return true;
8143  *reference= item;
8144  }
8145  return false;
8146 }
8147 
8148 void Item_insert_value::print(String *str, enum_query_type query_type)
8149 {
8150  str->append(STRING_WITH_LEN("values("));
8151  arg->print(str, query_type);
8152  str->append(')');
8153 }
8154 
8155 
8177  GRANT_INFO *table_grant_info)
8178 {
8179  /*
8180  It is too early to mark fields used here, because before execution
8181  of statement that will invoke trigger other statements may use same
8182  TABLE object, so all such mark-up will be wiped out.
8183  So instead we do it in Table_triggers_list::mark_fields_used()
8184  method which is called during execution of these statements.
8185  */
8186  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
8187  thd->mark_used_columns= MARK_COLUMNS_NONE;
8188  /*
8189  Try to find field by its name and if it will be found
8190  set field_idx properly.
8191  */
8192  (void)find_field_in_table(thd, table, field_name, (uint) strlen(field_name),
8193  0, &field_idx);
8194  thd->mark_used_columns= save_mark_used_columns;
8195  triggers= table->triggers;
8196  table_grants= table_grant_info;
8197 }
8198 
8199 
8200 bool Item_trigger_field::eq(const Item *item, bool binary_cmp) const
8201 {
8202  return item->type() == TRIGGER_FIELD_ITEM &&
8203  row_version == ((Item_trigger_field *)item)->row_version &&
8204  !my_strcasecmp(system_charset_info, field_name,
8205  ((Item_trigger_field *)item)->field_name);
8206 }
8207 
8208 
8209 void Item_trigger_field::set_required_privilege(bool rw)
8210 {
8211  /*
8212  Require SELECT and UPDATE privilege if this field will be read and
8213  set, and only UPDATE privilege for setting the field.
8214  */
8215  want_privilege= (rw ? SELECT_ACL | UPDATE_ACL : UPDATE_ACL);
8216 }
8217 
8218 
8219 bool Item_trigger_field::set_value(THD *thd, sp_rcontext * /*ctx*/, Item **it)
8220 {
8221  Item *item= sp_prepare_func_item(thd, it);
8222 
8223  if (!item)
8224  return true;
8225 
8226  if (!fixed)
8227  {
8228  if (fix_fields(thd, NULL))
8229  return true;
8230  }
8231 
8232  // NOTE: field->table->copy_blobs should be false here, but let's
8233  // remember the value at runtime to avoid subtle bugs.
8234  bool copy_blobs_saved= field->table->copy_blobs;
8235 
8236  field->table->copy_blobs= true;
8237 
8238  int err_code= item->save_in_field(field, 0);
8239 
8240  field->table->copy_blobs= copy_blobs_saved;
8241 
8242  return err_code < 0;
8243 }
8244 
8245 
8246 bool Item_trigger_field::fix_fields(THD *thd, Item **items)
8247 {
8248  /*
8249  Since trigger is object tightly associated with TABLE object most
8250  of its set up can be performed during trigger loading i.e. trigger
8251  parsing! So we have little to do in fix_fields. :)
8252  */
8253 
8254  DBUG_ASSERT(fixed == 0);
8255 
8256  /* Set field. */
8257 
8258  if (field_idx != (uint)-1)
8259  {
8260 #ifndef NO_EMBEDDED_ACCESS_CHECKS
8261  /*
8262  Check access privileges for the subject table. We check privileges only
8263  in runtime.
8264  */
8265 
8266  if (table_grants)
8267  {
8268  table_grants->want_privilege= want_privilege;
8269 
8270  if (check_grant_column(thd, table_grants, triggers->trigger_table->s->db.str,
8271  triggers->trigger_table->s->table_name.str, field_name,
8272  strlen(field_name), thd->security_ctx))
8273  return TRUE;
8274  }
8275 #endif // NO_EMBEDDED_ACCESS_CHECKS
8276 
8277  field= (row_version == OLD_ROW) ? triggers->old_field[field_idx] :
8278  triggers->new_field[field_idx];
8279  set_field(field);
8280  fixed= 1;
8281  return FALSE;
8282  }
8283 
8284  my_error(ER_BAD_FIELD_ERROR, MYF(0), field_name,
8285  (row_version == NEW_ROW) ? "NEW" : "OLD");
8286  return TRUE;
8287 }
8288 
8289 
8290 void Item_trigger_field::print(String *str, enum_query_type query_type)
8291 {
8292  str->append((row_version == NEW_ROW) ? "NEW" : "OLD", 3);
8293  str->append('.');
8294  str->append(field_name);
8295 }
8296 
8297 
8298 void Item_trigger_field::cleanup()
8299 {
8300  want_privilege= original_privilege;
8301  /*
8302  Since special nature of Item_trigger_field we should not do most of
8303  things from Item_field::cleanup() or Item_ident::cleanup() here.
8304  */
8305  Item::cleanup();
8306 }
8307 
8308 
8309 Item_result item_cmp_type(Item_result a,Item_result b)
8310 {
8311  if (a == STRING_RESULT && b == STRING_RESULT)
8312  return STRING_RESULT;
8313  if (a == INT_RESULT && b == INT_RESULT)
8314  return INT_RESULT;
8315  else if (a == ROW_RESULT || b == ROW_RESULT)
8316  return ROW_RESULT;
8317  if ((a == INT_RESULT || a == DECIMAL_RESULT) &&
8318  (b == INT_RESULT || b == DECIMAL_RESULT))
8319  return DECIMAL_RESULT;
8320  return REAL_RESULT;
8321 }
8322 
8323 
8324 void resolve_const_item(THD *thd, Item **ref, Item *comp_item)
8325 {
8326  Item *item= *ref;
8327  Item *new_item= NULL;
8328  if (item->basic_const_item())
8329  return; // Can't be better
8330  Item_result res_type=item_cmp_type(comp_item->result_type(),
8331  item->result_type());
8332  switch (res_type) {
8333  case STRING_RESULT:
8334  {
8335  char buff[MAX_FIELD_WIDTH];
8336  String tmp(buff,sizeof(buff),&my_charset_bin),*result;
8337  result=item->val_str(&tmp);
8338  if (item->null_value)
8339  new_item= new Item_null(item->item_name);
8340  else if (item->is_temporal())
8341  {
8342  enum_field_types type= item->field_type() == MYSQL_TYPE_TIMESTAMP ?
8343  MYSQL_TYPE_DATETIME : item->field_type();
8344  new_item= create_temporal_literal(thd, result->ptr(), result->length(),
8345  result->charset(), type, true);
8346  }
8347  else
8348  {
8349  uint length= result->length();
8350  char *tmp_str= sql_strmake(result->ptr(), length);
8351  new_item= new Item_string(item->item_name, tmp_str, length, result->charset());
8352  }
8353  break;
8354  }
8355  case INT_RESULT:
8356  {
8357  longlong result=item->val_int();
8358  uint length=item->max_length;
8359  bool null_value=item->null_value;
8360  new_item= (null_value ? (Item*) new Item_null(item->item_name) :
8361  (Item*) new Item_int(item->item_name, result, length));
8362  break;
8363  }
8364  case ROW_RESULT:
8365  if (item->type() == Item::ROW_ITEM && comp_item->type() == Item::ROW_ITEM)
8366  {
8367  /*
8368  Substitute constants only in Item_rows. Don't affect other Items
8369  with ROW_RESULT (eg Item_singlerow_subselect).
8370 
8371  For such Items more optimal is to detect if it is constant and replace
8372  it with Item_row. This would optimize queries like this:
8373  SELECT * FROM t1 WHERE (a,b) = (SELECT a,b FROM t2 LIMIT 1);
8374  */
8375  Item_row *item_row= (Item_row*) item;
8376  Item_row *comp_item_row= (Item_row*) comp_item;
8377  uint col;
8378  new_item= 0;
8379  /*
8380  If item and comp_item are both Item_rows and have same number of cols
8381  then process items in Item_row one by one.
8382  We can't ignore NULL values here as this item may be used with <=>, in
8383  which case NULL's are significant.
8384  */
8385  DBUG_ASSERT(item->result_type() == comp_item->result_type());
8386  DBUG_ASSERT(item_row->cols() == comp_item_row->cols());
8387  col= item_row->cols();
8388  while (col-- > 0)
8389  resolve_const_item(thd, item_row->addr(col),
8390  comp_item_row->element_index(col));
8391  break;
8392  }
8393  /* Fallthrough */
8394  case REAL_RESULT:
8395  { // It must REAL_RESULT
8396  double result= item->val_real();
8397  uint length=item->max_length,decimals=item->decimals;
8398  bool null_value=item->null_value;
8399  new_item= (null_value ? (Item*) new Item_null(item->item_name) : (Item*)
8400  new Item_float(item->item_name, result, decimals, length));
8401  break;
8402  }
8403  case DECIMAL_RESULT:
8404  {
8405  my_decimal decimal_value;
8406  my_decimal *result= item->val_decimal(&decimal_value);
8407  bool null_value= item->null_value;
8408  new_item= (null_value ?
8409  (Item*) new Item_null(item->item_name) :
8410  (Item*) new Item_decimal(item->item_name, result,
8411  item->max_length, item->decimals));
8412  break;
8413  }
8414  default:
8415  DBUG_ASSERT(0);
8416  }
8417  if (new_item)
8418  thd->change_item_tree(ref, new_item);
8419 }
8420 
8441 int stored_field_cmp_to_item(THD *thd, Field *field, Item *item)
8442 {
8443  Item_result res_type=item_cmp_type(field->result_type(),
8444  item->result_type());
8445  if (field->type() == MYSQL_TYPE_TIME &&
8446  item->field_type() == MYSQL_TYPE_TIME)
8447  {
8448  longlong field_value= field->val_time_temporal();
8449  longlong item_value= item->val_time_temporal();
8450  return field_value < item_value ? -1 : field_value > item_value ? 1 : 0;
8451  }
8452  if (field->is_temporal_with_date() && item->is_temporal())
8453  {
8454  /*
8455  Note, in case of TIME data type we also go here
8456  and call item->val_date_temporal(), because we want
8457  TIME to be converted to DATE/DATETIME properly.
8458  Only non-temporal data types go though get_mysql_time_from_str()
8459  in the below code branch.
8460  */
8461  longlong field_value= field->val_date_temporal();
8462  longlong item_value= item->val_date_temporal();
8463  return field_value < item_value ? -1 : field_value > item_value ? 1 : 0;
8464  }
8465  if (res_type == STRING_RESULT)
8466  {
8467  char item_buff[MAX_FIELD_WIDTH];
8468  char field_buff[MAX_FIELD_WIDTH];
8469 
8470  String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin);
8471  String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
8472  String *item_result= item->val_str(&item_tmp);
8473  /*
8474  Some implementations of Item::val_str(String*) actually modify
8475  the field Item::null_value, hence we can't check it earlier.
8476  */
8477  if (item->null_value)
8478  return 0;
8479  String *field_result= field->val_str(&field_tmp);
8480 
8481  if (field->is_temporal_with_date())
8482  {
8483  enum_mysql_timestamp_type type=
8484  field_type_to_timestamp_type(field->type());
8485  const char *field_name= field->field_name;
8486  MYSQL_TIME field_time, item_time;
8487  get_mysql_time_from_str(thd, field_result, type, field_name, &field_time);
8488  get_mysql_time_from_str(thd, item_result, type, field_name, &item_time);
8489 
8490  return my_time_compare(&field_time, &item_time);
8491  }
8492  return sortcmp(field_result, item_result, field->charset());
8493  }
8494  if (res_type == INT_RESULT)
8495  return 0; // Both are of type int
8496  if (res_type == DECIMAL_RESULT)
8497  {
8498  my_decimal item_buf, *item_val,
8499  field_buf, *field_val;
8500  item_val= item->val_decimal(&item_buf);
8501  if (item->null_value)
8502  return 0;
8503  field_val= field->val_decimal(&field_buf);
8504  return my_decimal_cmp(field_val, item_val);
8505  }
8506  /*
8507  The patch for Bug#13463415 started using this function for comparing
8508  BIGINTs. That uncovered a bug in Visual Studio 32bit optimized mode.
8509  Prefixing the auto variables with volatile fixes the problem....
8510  */
8511  volatile double result= item->val_real();
8512  if (item->null_value)
8513  return 0;
8514  volatile double field_result= field->val_real();
8515  if (field_result < result)
8516  return -1;
8517  else if (field_result > result)
8518  return 1;
8519  return 0;
8520 }
8521 
8522 Item_cache* Item_cache::get_cache(const Item *item)
8523 {
8524  return get_cache(item, item->result_type());
8525 }
8526 
8527 
8537 Item_cache* Item_cache::get_cache(const Item *item, const Item_result type)
8538 {
8539  switch (type) {
8540  case INT_RESULT:
8541  return new Item_cache_int(item->field_type());
8542  case REAL_RESULT:
8543  return new Item_cache_real();
8544  case DECIMAL_RESULT:
8545  return new Item_cache_decimal();
8546  case STRING_RESULT:
8547  /* Not all functions that return DATE/TIME are actually DATE/TIME funcs. */
8548  if (item->is_temporal())
8549  return new Item_cache_datetime(item->field_type());
8550  return new Item_cache_str(item);
8551  case ROW_RESULT:
8552  return new Item_cache_row();
8553  default:
8554  // should never be in real life
8555  DBUG_ASSERT(0);
8556  return 0;
8557  }
8558 }
8559 
8560 void Item_cache::store(Item *item)
8561 {
8562  example= item;
8563  if (!item)
8564  null_value= TRUE;
8565  value_cached= FALSE;
8566 }
8567 
8568 void Item_cache::print(String *str, enum_query_type query_type)
8569 {
8570  str->append(STRING_WITH_LEN("<cache>("));
8571  if (example)
8572  example->print(str, query_type);
8573  else
8574  Item::print(str, query_type);
8575  str->append(')');
8576 }
8577 
8578 bool Item_cache::walk (Item_processor processor, bool walk_subquery,
8579  uchar *argument)
8580 {
8581  if (example && example->walk(processor, walk_subquery, argument))
8582  return 1;
8583  return (this->*processor)(argument);
8584 }
8585 
8586 bool Item_cache_int::cache_value()
8587 {
8588  if (!example)
8589  return FALSE;
8590  value_cached= TRUE;
8591  value= example->val_int_result();
8592  null_value= example->null_value;
8593  unsigned_flag= example->unsigned_flag;
8594  return TRUE;
8595 }
8596 
8597 
8598 void Item_cache_int::store(Item *item, longlong val_arg)
8599 {
8600  /* An explicit values is given, save it. */
8601  value_cached= TRUE;
8602  value= val_arg;
8603  null_value= item->null_value;
8604  unsigned_flag= item->unsigned_flag;
8605 }
8606 
8607 
8608 String *Item_cache_int::val_str(String *str)
8609 {
8610  DBUG_ASSERT(fixed == 1);
8611  if (!has_value())
8612  return NULL;
8613  str->set_int(value, unsigned_flag, default_charset());
8614  return str;
8615 }
8616 
8617 
8618 my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val)
8619 {
8620  DBUG_ASSERT(fixed == 1);
8621  if (!has_value())
8622  return NULL;
8623  int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val);
8624  return decimal_val;
8625 }
8626 
8627 double Item_cache_int::val_real()
8628 {
8629  DBUG_ASSERT(fixed == 1);
8630  if (!has_value())
8631  return 0.0;
8632  return (double) value;
8633 }
8634 
8635 longlong Item_cache_int::val_int()
8636 {
8637  DBUG_ASSERT(fixed == 1);
8638  if (!has_value())
8639  return 0;
8640  return value;
8641 }
8642 
8643 bool Item_cache_datetime::cache_value_int()
8644 {
8645  if (!example)
8646  return false;
8647 
8648  value_cached= true;
8649  // Mark cached string value obsolete
8650  str_value_cached= false;
8651 
8652  DBUG_ASSERT(field_type() == example->field_type());
8653  int_value= example->val_temporal_by_field_type();
8654  null_value= example->null_value;
8655  unsigned_flag= example->unsigned_flag;
8656 
8657  return true;
8658 }
8659 
8660 
8661 bool Item_cache_datetime::cache_value()
8662 {
8663  if (!example)
8664  return FALSE;
8665 
8666  if (cmp_context == INT_RESULT)
8667  return cache_value_int();
8668 
8669  str_value_cached= TRUE;
8670  // Mark cached int value obsolete
8671  value_cached= FALSE;
8672  /* Assume here that the underlying item will do correct conversion.*/
8673  String *res= example->str_result(&str_value);
8674  if (res && res != &str_value)
8675  str_value.copy(*res);
8676  null_value= example->null_value;
8677  unsigned_flag= example->unsigned_flag;
8678  return TRUE;
8679 }
8680 
8681 
8682 void Item_cache_datetime::store(Item *item, longlong val_arg)
8683 {
8684  /* An explicit values is given, save it. */
8685  value_cached= TRUE;
8686  int_value= val_arg;
8687  null_value= item->null_value;
8688  unsigned_flag= item->unsigned_flag;
8689 }
8690 
8691 
8692 void Item_cache_datetime::store(Item *item)
8693 {
8694  Item_cache::store(item);
8695  str_value_cached= FALSE;
8696 }
8697 
8698 String *Item_cache_datetime::val_str(String *str)
8699 {
8700  DBUG_ASSERT(fixed == 1);
8701 
8702  if ((value_cached || str_value_cached) && null_value)
8703  return NULL;
8704 
8705  if (!str_value_cached)
8706  {
8707  /*
8708  When it's possible the Item_cache_datetime uses INT datetime
8709  representation due to speed reasons. But still, it always has the STRING
8710  result type and thus it can be asked to return a string value.
8711  It is possible that at this time cached item doesn't contain correct
8712  string value, thus we have to convert cached int value to string and
8713  return it.
8714  */
8715  if (value_cached)
8716  {
8717  MYSQL_TIME ltime;
8718  TIME_from_longlong_packed(&ltime, cached_field_type, int_value);
8719  if ((null_value= my_TIME_to_str(&ltime, &str_value,
8720  MY_MIN(decimals, DATETIME_MAX_DECIMALS))))
8721  return NULL;
8722  str_value_cached= TRUE;
8723  }
8724  else if (!cache_value())
8725  return NULL;
8726  }
8727  return &str_value;
8728 }
8729 
8730 
8731 my_decimal *Item_cache_datetime::val_decimal(my_decimal *decimal_val)
8732 {
8733  DBUG_ASSERT(fixed == 1);
8734 
8735  if (str_value_cached)
8736  {
8737  switch (cached_field_type)
8738  {
8739  case MYSQL_TYPE_TIME:
8740  return val_decimal_from_time(decimal_val);
8741  case MYSQL_TYPE_DATETIME:
8742  case MYSQL_TYPE_TIMESTAMP:
8743  case MYSQL_TYPE_DATE:
8744  return val_decimal_from_date(decimal_val);
8745  default:
8746  DBUG_ASSERT(0);
8747  return NULL;
8748  }
8749  }
8750 
8751  if ((!value_cached && !cache_value_int()) || null_value)
8752  return 0;
8753  return my_decimal_from_datetime_packed(decimal_val, field_type(), int_value);
8754 }
8755 
8756 
8757 bool Item_cache_datetime::get_date(MYSQL_TIME *ltime, uint fuzzydate)
8758 {
8759  if ((value_cached || str_value_cached) && null_value)
8760  return true;
8761 
8762  if (str_value_cached) // TS-TODO: reuse MYSQL_TIME_cache eventually.
8763  return get_date_from_string(ltime, fuzzydate);
8764 
8765  if ((!value_cached && !cache_value_int()) || null_value)
8766  return (null_value= true);
8767 
8768 
8769  switch (cached_field_type)
8770  {
8771  case MYSQL_TYPE_TIME:
8772  {
8773  MYSQL_TIME tm;
8774  TIME_from_longlong_time_packed(&tm, int_value);
8775  time_to_datetime(current_thd, &tm, ltime);
8776  return false;
8777  }
8778  case MYSQL_TYPE_DATE:
8779  {
8780  int warnings= 0;
8781  TIME_from_longlong_date_packed(ltime, int_value);
8782  return check_date(ltime, non_zero_date(ltime), fuzzydate, &warnings);
8783  }
8784  case MYSQL_TYPE_DATETIME:
8785  case MYSQL_TYPE_TIMESTAMP:
8786  {
8787  int warnings= 0;
8788  TIME_from_longlong_datetime_packed(ltime, int_value);
8789  return check_date(ltime, non_zero_date(ltime), fuzzydate, &warnings);
8790  }
8791  default:
8792  DBUG_ASSERT(0);
8793  }
8794  return true;
8795 }
8796 
8797 
8798 bool Item_cache_datetime::get_time(MYSQL_TIME *ltime)
8799 {
8800  if ((value_cached || str_value_cached) && null_value)
8801  return true;
8802 
8803  if (str_value_cached) // TS-TODO: reuse MYSQL_TIME_cache eventually.
8804  return get_time_from_string(ltime);
8805 
8806  if ((!value_cached && !cache_value_int()) || null_value)
8807  return true;
8808 
8809  switch (cached_field_type)
8810  {
8811  case MYSQL_TYPE_TIME:
8812  TIME_from_longlong_time_packed(ltime, int_value);
8813  return false;
8814  case MYSQL_TYPE_DATE:
8815  set_zero_time(ltime, MYSQL_TIMESTAMP_TIME);
8816  return false;
8817  case MYSQL_TYPE_DATETIME:
8818  case MYSQL_TYPE_TIMESTAMP:
8819  TIME_from_longlong_datetime_packed(ltime, int_value);
8820  datetime_to_time(ltime);
8821  return false;
8822  default:
8823  DBUG_ASSERT(0);
8824  }
8825  return true;
8826 }
8827 
8828 
8829 double Item_cache_datetime::val_real()
8830 {
8831  return val_real_from_decimal();
8832 }
8833 
8835 {
8836  DBUG_ASSERT(fixed == 1);
8837  if ((!value_cached && !cache_value_int()) || null_value)
8838  return 0;
8839  if (is_temporal_with_date())
8840  {
8841  /* Convert packed date to packed time */
8842  MYSQL_TIME ltime;
8843  return get_time_from_date(&ltime) ? 0 :
8844  TIME_to_longlong_packed(&ltime, field_type());
8845  }
8846  return int_value;
8847 }
8848 
8850 {
8851  DBUG_ASSERT(fixed == 1);
8852  if ((!value_cached && !cache_value_int()) || null_value)
8853  return 0;
8854  if (cached_field_type == MYSQL_TYPE_TIME)
8855  {
8856  /* Convert packed time to packed date */
8857  MYSQL_TIME ltime;
8858  return get_date_from_time(&ltime) ? 0 :
8859  TIME_to_longlong_datetime_packed(&ltime);
8860 
8861  }
8862  return int_value;
8863 }
8864 
8865 longlong Item_cache_datetime::val_int()
8866 {
8867  return val_int_from_decimal();
8868 }
8869 
8870 bool Item_cache_real::cache_value()
8871 {
8872  if (!example)
8873  return FALSE;
8874  value_cached= TRUE;
8875  value= example->val_result();
8876  null_value= example->null_value;
8877  return TRUE;
8878 }
8879 
8880 
8881 double Item_cache_real::val_real()
8882 {
8883  DBUG_ASSERT(fixed == 1);
8884  if (!has_value())
8885  return 0.0;
8886  return value;
8887 }
8888 
8889 longlong Item_cache_real::val_int()
8890 {
8891  DBUG_ASSERT(fixed == 1);
8892  if (!has_value())
8893  return 0;
8894  return (longlong) rint(value);
8895 }
8896 
8897 
8898 String* Item_cache_real::val_str(String *str)
8899 {
8900  DBUG_ASSERT(fixed == 1);
8901  if (!has_value())
8902  return NULL;
8903  str->set_real(value, decimals, default_charset());
8904  return str;
8905 }
8906 
8907 
8908 my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val)
8909 {
8910  DBUG_ASSERT(fixed == 1);
8911  if (!has_value())
8912  return NULL;
8913  double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
8914  return decimal_val;
8915 }
8916 
8917 
8918 bool Item_cache_decimal::cache_value()
8919 {
8920  if (!example)
8921  return FALSE;
8922  value_cached= TRUE;
8923  my_decimal *val= example->val_decimal_result(&decimal_value);
8924  if (!(null_value= example->null_value) && val != &decimal_value)
8925  my_decimal2decimal(val, &decimal_value);
8926  return TRUE;
8927 }
8928 
8929 double Item_cache_decimal::val_real()
8930 {
8931  DBUG_ASSERT(fixed);
8932  double res;
8933  if (!has_value())
8934  return 0.0;
8935  my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res);
8936  return res;
8937 }
8938 
8939 longlong Item_cache_decimal::val_int()
8940 {
8941  DBUG_ASSERT(fixed);
8942  longlong res;
8943  if (!has_value())
8944  return 0;
8945  my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res);
8946  return res;
8947 }
8948 
8949 String* Item_cache_decimal::val_str(String *str)
8950 {
8951  DBUG_ASSERT(fixed);
8952  if (!has_value())
8953  return NULL;
8954  my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, FALSE,
8955  &decimal_value);
8956  my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str);
8957  return str;
8958 }
8959 
8960 my_decimal *Item_cache_decimal::val_decimal(my_decimal *val)
8961 {
8962  DBUG_ASSERT(fixed);
8963  if (!has_value())
8964  return NULL;
8965  return &decimal_value;
8966 }
8967 
8968 
8969 bool Item_cache_str::cache_value()
8970 {
8971  if (!example)
8972  return FALSE;
8973  value_cached= TRUE;
8974  value_buff.set(buffer, sizeof(buffer), example->collation.collation);
8975  value= example->str_result(&value_buff);
8976  if ((null_value= example->null_value))
8977  value= 0;
8978  else if (value != &value_buff)
8979  {
8980  /*
8981  We copy string value to avoid changing value if 'item' is table field
8982  in queries like following (where t1.c is varchar):
8983  select a,
8984  (select a,b,c from t1 where t1.a=t2.a) = ROW(a,2,'a'),
8985  (select c from t1 where a=t2.a)
8986  from t2;
8987  */
8988  value_buff.copy(*value);
8989  value= &value_buff;
8990  }
8991  return TRUE;
8992 }
8993 
8994 double Item_cache_str::val_real()
8995 {
8996  DBUG_ASSERT(fixed == 1);
8997  int err_not_used;
8998  char *end_not_used;
8999  if (!has_value())
9000  return 0.0;
9001  if (value)
9002  return my_strntod(value->charset(), (char*) value->ptr(),
9003  value->length(), &end_not_used, &err_not_used);
9004  return (double) 0;
9005 }
9006 
9007 
9008 longlong Item_cache_str::val_int()
9009 {
9010  DBUG_ASSERT(fixed == 1);
9011  int err;
9012  if (!has_value())
9013  return 0;
9014  if (value)
9015  return my_strntoll(value->charset(), value->ptr(),
9016  value->length(), 10, (char**) 0, &err);
9017  else
9018  return (longlong)0;
9019 }
9020 
9021 
9022 String* Item_cache_str::val_str(String *str)
9023 {
9024  DBUG_ASSERT(fixed == 1);
9025  if (!has_value())
9026  return 0;
9027  return value;
9028 }
9029 
9030 
9031 my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val)
9032 {
9033  DBUG_ASSERT(fixed == 1);
9034  if (!has_value())
9035  return NULL;
9036  if (value)
9037  string2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
9038  else
9039  decimal_val= 0;
9040  return decimal_val;
9041 }
9042 
9043 
9044 type_conversion_status
9045 Item_cache_str::save_in_field(Field *field, bool no_conversions)
9046 {
9047  if (!value_cached && !cache_value())
9048  return TYPE_ERR_BAD_VALUE; // Fatal: couldn't cache the value
9049  if (null_value)
9050  return set_field_to_null_with_conversions(field, no_conversions);
9051  const type_conversion_status res= Item_cache::save_in_field(field,
9052  no_conversions);
9053  if (is_varbinary && field->type() == MYSQL_TYPE_STRING && value != NULL &&
9054  value->length() < field->field_length)
9055  return TYPE_WARN_OUT_OF_RANGE;
9056  return res;
9057 
9058 }
9059 
9060 
9061 bool Item_cache_row::allocate(uint num)
9062 {
9063  item_count= num;
9064  THD *thd= current_thd;
9065  return (!(values=
9066  (Item_cache **) thd->calloc(sizeof(Item_cache *)*item_count)));
9067 }
9068 
9069 
9070 bool Item_cache_row::setup(Item * item)
9071 {
9072  example= item;
9073  if (!values && allocate(item->cols()))
9074  return 1;
9075  for (uint i= 0; i < item_count; i++)
9076  {
9077  Item *el= item->element_index(i);
9078  Item_cache *tmp;
9079  if (!(tmp= values[i]= Item_cache::get_cache(el)))
9080  return 1;
9081  tmp->setup(el);
9082  }
9083  return 0;
9084 }
9085 
9086 
9087 void Item_cache_row::store(Item * item)
9088 {
9089  example= item;
9090  if (!item)
9091  {
9092  null_value= TRUE;
9093  return;
9094  }
9095  for (uint i= 0; i < item_count; i++)
9096  values[i]->store(item->element_index(i));
9097 }
9098 
9099 
9100 bool Item_cache_row::cache_value()
9101 {
9102  if (!example)
9103  return FALSE;
9104  value_cached= TRUE;
9105  null_value= 0;
9106  example->bring_value();
9107  for (uint i= 0; i < item_count; i++)
9108  {
9109  values[i]->cache_value();
9110  null_value|= values[i]->null_value;
9111  }
9112  return TRUE;
9113 }
9114 
9115 
9116 void Item_cache_row::illegal_method_call(const char *method)
9117 {
9118  DBUG_ENTER("Item_cache_row::illegal_method_call");
9119  DBUG_PRINT("error", ("!!! %s method was called for row item", method));
9120  DBUG_ASSERT(0);
9121  my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
9122  DBUG_VOID_RETURN;
9123 }
9124 
9125 
9126 bool Item_cache_row::check_cols(uint c)
9127 {
9128  if (c != item_count)
9129  {
9130  my_error(ER_OPERAND_COLUMNS, MYF(0), c);
9131  return 1;
9132  }
9133  return 0;
9134 }
9135 
9136 
9137 bool Item_cache_row::null_inside()
9138 {
9139  for (uint i= 0; i < item_count; i++)
9140  {
9141  if (values[i]->cols() > 1)
9142  {
9143  if (values[i]->null_inside())
9144  return 1;
9145  }
9146  else
9147  {
9148  values[i]->update_null_value();
9149  if (values[i]->null_value)
9150  return 1;
9151  }
9152  }
9153  return 0;
9154 }
9155 
9156 
9157 void Item_cache_row::bring_value()
9158 {
9159  if (!example)
9160  return;
9161  example->bring_value();
9162  null_value= example->null_value;
9163  for (uint i= 0; i < item_count; i++)
9164  values[i]->bring_value();
9165 }
9166 
9167 
9168 Item_type_holder::Item_type_holder(THD *thd, Item *item)
9169  :Item(thd, item), enum_set_typelib(0), fld_type(get_real_type(item))
9170 {
9171  DBUG_ASSERT(item->fixed);
9172  maybe_null= item->maybe_null;
9173  collation.set(item->collation);
9174  get_full_info(item);
9175  /* fix variable decimals which always is NOT_FIXED_DEC */
9176  if (Field::result_merge_type(fld_type) == INT_RESULT)
9177  decimals= 0;
9178  prev_decimal_int_part= item->decimal_int_part();
9179 #ifdef HAVE_SPATIAL
9180  if (item->field_type() == MYSQL_TYPE_GEOMETRY)
9181  geometry_type= item->get_geometry_type();
9182 #endif /* HAVE_SPATIAL */
9183 }
9184 
9185 
9194 {
9195  return Field::result_merge_type(fld_type);
9196 }
9197 
9198 
9206 enum_field_types Item_type_holder::get_real_type(Item *item)
9207 {
9208  switch(item->type())
9209  {
9210  case FIELD_ITEM:
9211  {
9212  /*
9213  Item_fields::field_type ask Field_type() but sometimes field return
9214  a different type, like for enum/set, so we need to ask real type.
9215  */
9216  Field *field= ((Item_field *) item)->field;
9217  enum_field_types type= field->real_type();
9218  if (field->is_created_from_null_item)
9219  return MYSQL_TYPE_NULL;
9220  /* work around about varchar type field detection */
9221  if (type == MYSQL_TYPE_STRING && field->type() == MYSQL_TYPE_VAR_STRING)
9222  return MYSQL_TYPE_VAR_STRING;
9223  return type;
9224  }
9225  case SUM_FUNC_ITEM:
9226  {
9227  /*
9228  Argument of aggregate function sometimes should be asked about field
9229  type
9230  */
9231  Item_sum *item_sum= (Item_sum *) item;
9232  if (item_sum->keep_field_type())
9233  return get_real_type(item_sum->get_arg(0));
9234  break;
9235  }
9236  case FUNC_ITEM:
9237  if (((Item_func *) item)->functype() == Item_func::GUSERVAR_FUNC)
9238  {
9239  /*
9240  There are work around of problem with changing variable type on the
9241  fly and variable always report "string" as field type to get
9242  acceptable information for client in send_field, so we make field
9243  type from expression type.
9244  */
9245  switch (item->result_type()) {
9246  case STRING_RESULT:
9247  return MYSQL_TYPE_VAR_STRING;
9248  case INT_RESULT:
9249  return MYSQL_TYPE_LONGLONG;
9250  case REAL_RESULT:
9251  return MYSQL_TYPE_DOUBLE;
9252  case DECIMAL_RESULT:
9253  return MYSQL_TYPE_NEWDECIMAL;
9254  case ROW_RESULT:
9255  default:
9256  DBUG_ASSERT(0);
9257  return MYSQL_TYPE_VAR_STRING;
9258  }
9259  }
9260  break;
9261  default:
9262  break;
9263  }
9264  return item->field_type();
9265 }
9266 
9280 bool Item_type_holder::join_types(THD *thd, Item *item)
9281 {
9282  uint max_length_orig= max_length;
9283  uint decimals_orig= decimals;
9284  DBUG_ENTER("Item_type_holder::join_types");
9285  DBUG_PRINT("info:", ("was type %d len %d, dec %d name %s",
9286  fld_type, max_length, decimals,
9287  (item_name.is_set() ? item_name.ptr() : "<NULL>")));
9288  DBUG_PRINT("info:", ("in type %d len %d, dec %d",
9289  get_real_type(item),
9290  item->max_length, item->decimals));
9291  fld_type= Field::field_type_merge(fld_type, get_real_type(item));
9292  {
9293  int item_decimals= item->decimals;
9294  /* fix variable decimals which always is NOT_FIXED_DEC */
9295  if (Field::result_merge_type(fld_type) == INT_RESULT)
9296  item_decimals= 0;
9297  decimals= max<int>(decimals, item_decimals);
9298  }
9299  if (Field::result_merge_type(fld_type) == DECIMAL_RESULT)
9300  {
9301  decimals= min<int>(max(decimals, item->decimals), DECIMAL_MAX_SCALE);
9302  int item_int_part= item->decimal_int_part();
9303  int item_prec = max(prev_decimal_int_part, item_int_part) + decimals;
9304  int precision= min<uint>(item_prec, DECIMAL_MAX_PRECISION);
9305  unsigned_flag&= item->unsigned_flag;
9306  max_length= my_decimal_precision_to_length_no_truncation(precision,
9307  decimals,
9308  unsigned_flag);
9309  }
9310 
9311  switch (Field::result_merge_type(fld_type))
9312  {
9313  case STRING_RESULT:
9314  {
9315  const char *old_cs, *old_derivation;
9316  uint32 old_max_chars= max_length / collation.collation->mbmaxlen;
9317  old_cs= collation.collation->name;
9318  old_derivation= collation.derivation_name();
9319  if (collation.aggregate(item->collation, MY_COLL_ALLOW_CONV))
9320  {
9321  my_error(ER_CANT_AGGREGATE_2COLLATIONS, MYF(0),
9322  old_cs, old_derivation,
9323  item->collation.collation->name,
9324  item->collation.derivation_name(),
9325  "UNION");
9326  DBUG_RETURN(TRUE);
9327  }
9328  /*
9329  To figure out max_length, we have to take into account possible
9330  expansion of the size of the values because of character set
9331  conversions.
9332  */
9333  if (collation.collation != &my_charset_bin)
9334  {
9335  max_length= max(old_max_chars * collation.collation->mbmaxlen,
9336  display_length(item) /
9337  item->collation.collation->mbmaxlen *
9338  collation.collation->mbmaxlen);
9339  }
9340  else
9341  set_if_bigger(max_length, display_length(item));
9342  break;
9343  }
9344  case REAL_RESULT:
9345  {
9346  if (decimals != NOT_FIXED_DEC)
9347  {
9348  /*
9349  For FLOAT(M,D)/DOUBLE(M,D) do not change precision
9350  if both fields have the same M and D
9351  */
9352  if (item->max_length != max_length_orig ||
9353  item->decimals != decimals_orig)
9354  {
9355  int delta1= max_length_orig - decimals_orig;
9356  int delta2= item->max_length - item->decimals;
9357  max_length= max(delta1, delta2) + decimals;
9358  if (fld_type == MYSQL_TYPE_FLOAT && max_length > FLT_DIG + 2)
9359  {
9360  max_length= MAX_FLOAT_STR_LENGTH;
9361  decimals= NOT_FIXED_DEC;
9362  }
9363  else if (fld_type == MYSQL_TYPE_DOUBLE && max_length > DBL_DIG + 2)
9364  {
9365  max_length= MAX_DOUBLE_STR_LENGTH;
9366  decimals= NOT_FIXED_DEC;
9367  }
9368  }
9369  }
9370  else
9371  max_length= (fld_type == MYSQL_TYPE_FLOAT) ? FLT_DIG+6 : DBL_DIG+7;
9372  break;
9373  }
9374  default:
9375  max_length= max(max_length, display_length(item));
9376  };
9377  maybe_null|= item->maybe_null;
9378  get_full_info(item);
9379 
9380  /* Remember decimal integer part to be used in DECIMAL_RESULT handleng */
9381  prev_decimal_int_part= decimal_int_part();
9382  DBUG_PRINT("info", ("become type: %d len: %u dec: %u",
9383  (int) fld_type, max_length, (uint) decimals));
9384  DBUG_RETURN(FALSE);
9385 }
9386 
9397 {
9398  if (item->type() == Item::FIELD_ITEM)
9399  return ((Item_field *)item)->max_disp_length();
9400 
9401  switch (item->field_type())
9402  {
9403  case MYSQL_TYPE_DECIMAL:
9404  case MYSQL_TYPE_TIMESTAMP:
9405  case MYSQL_TYPE_DATE:
9406  case MYSQL_TYPE_TIME:
9407  case MYSQL_TYPE_DATETIME:
9408  case MYSQL_TYPE_YEAR:
9409  case MYSQL_TYPE_NEWDATE:
9410  case MYSQL_TYPE_VARCHAR:
9411  case MYSQL_TYPE_BIT:
9412  case MYSQL_TYPE_NEWDECIMAL:
9413  case MYSQL_TYPE_ENUM:
9414  case MYSQL_TYPE_SET:
9415  case MYSQL_TYPE_TINY_BLOB:
9416  case MYSQL_TYPE_MEDIUM_BLOB:
9417  case MYSQL_TYPE_LONG_BLOB:
9418  case MYSQL_TYPE_BLOB:
9419  case MYSQL_TYPE_VAR_STRING:
9420  case MYSQL_TYPE_STRING:
9421  case MYSQL_TYPE_GEOMETRY:
9422  return item->max_length;
9423  case MYSQL_TYPE_TINY:
9424  return 4;
9425  case MYSQL_TYPE_SHORT:
9426  return 6;
9427  case MYSQL_TYPE_LONG:
9428  return MY_INT32_NUM_DECIMAL_DIGITS;
9429  case MYSQL_TYPE_FLOAT:
9430  return 25;
9431  case MYSQL_TYPE_DOUBLE:
9432  return 53;
9433  case MYSQL_TYPE_NULL:
9434  return 0;
9435  case MYSQL_TYPE_LONGLONG:
9436  return 20;
9437  case MYSQL_TYPE_INT24:
9438  return 8;
9439  default:
9440  DBUG_ASSERT(0); // we should never go there
9441  return 0;
9442  }
9443 }
9444 
9445 
9457 {
9458  /*
9459  The field functions defines a field to be not null if null_ptr is not 0
9460  */
9461  uchar *null_ptr= maybe_null ? (uchar*) "" : 0;
9462  Field *field;
9463 
9464  switch (fld_type) {
9465  case MYSQL_TYPE_ENUM:
9466  DBUG_ASSERT(enum_set_typelib);
9467  field= new Field_enum((uchar *) 0, max_length, null_ptr, 0,
9468  Field::NONE, item_name.ptr(),
9469  get_enum_pack_length(enum_set_typelib->count),
9470  enum_set_typelib, collation.collation);
9471  if (field)
9472  field->init(table);
9473  return field;
9474  case MYSQL_TYPE_SET:
9475  DBUG_ASSERT(enum_set_typelib);
9476  field= new Field_set((uchar *) 0, max_length, null_ptr, 0,
9477  Field::NONE, item_name.ptr(),
9478  get_set_pack_length(enum_set_typelib->count),
9479  enum_set_typelib, collation.collation);
9480  if (field)
9481  field->init(table);
9482  return field;
9483  case MYSQL_TYPE_NULL:
9484  return make_string_field(table);
9485  default:
9486  break;
9487  }
9488  return tmp_table_field_from_field_type(table, 0);
9489 }
9490 
9491 
9499 {
9500  if (fld_type == MYSQL_TYPE_ENUM ||
9501  fld_type == MYSQL_TYPE_SET)
9502  {
9503  if (item->type() == Item::SUM_FUNC_ITEM &&
9504  (((Item_sum*)item)->sum_func() == Item_sum::MAX_FUNC ||
9505  ((Item_sum*)item)->sum_func() == Item_sum::MIN_FUNC))
9506  item = ((Item_sum*)item)->get_arg(0);
9507  /*
9508  We can have enum/set type after merging only if we have one enum|set
9509  field (or MIN|MAX(enum|set field)) and number of NULL fields
9510  */
9511  DBUG_ASSERT((enum_set_typelib &&
9512  get_real_type(item) == MYSQL_TYPE_NULL) ||
9513  (!enum_set_typelib &&
9514  item->type() == Item::FIELD_ITEM &&
9515  (get_real_type(item) == MYSQL_TYPE_ENUM ||
9516  get_real_type(item) == MYSQL_TYPE_SET) &&
9517  ((Field_enum*)((Item_field *) item)->field)->typelib));
9518  if (!enum_set_typelib)
9519  {
9520  enum_set_typelib= ((Field_enum*)((Item_field *) item)->field)->typelib;
9521  }
9522  }
9523 }
9524 
9525 
9526 double Item_type_holder::val_real()
9527 {
9528  DBUG_ASSERT(0); // should never be called
9529  return 0.0;
9530 }
9531 
9532 
9533 longlong Item_type_holder::val_int()
9534 {
9535  DBUG_ASSERT(0); // should never be called
9536  return 0;
9537 }
9538 
9539 my_decimal *Item_type_holder::val_decimal(my_decimal *)
9540 {
9541  DBUG_ASSERT(0); // should never be called
9542  return 0;
9543 }
9544 
9545 String *Item_type_holder::val_str(String*)
9546 {
9547  DBUG_ASSERT(0); // should never be called
9548  return 0;
9549 }
9550 
9551 void Item_result_field::cleanup()
9552 {
9553  DBUG_ENTER("Item_result_field::cleanup()");
9554  Item::cleanup();
9555  result_field= 0;
9556  DBUG_VOID_RETURN;
9557 }
9558 
9566 void dummy_error_processor(THD *thd, void *data)
9567 {}
9568 
9577 void view_error_processor(THD *thd, void *data)
9578 {
9579  ((TABLE_LIST *)data)->hide_view_error(thd);
9580 }