MySQL  8.0.18
Source Code Documentation
item.h
Go to the documentation of this file.
1 #ifndef ITEM_INCLUDED
2 #define ITEM_INCLUDED
3 
4 /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
5 
6  This program is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License, version 2.0,
8  as published by the Free Software Foundation.
9 
10  This program is also distributed with certain software (including
11  but not limited to OpenSSL) that is licensed under separate terms,
12  as designated in a particular file or component or in included license
13  documentation. The authors of MySQL hereby grant you an additional
14  permission to link the program and your derivative works with the
15  separately licensed software that they have included with MySQL.
16 
17  This program is distributed in the hope that it will be useful,
18  but WITHOUT ANY WARRANTY; without even the implied warranty of
19  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20  GNU General Public License, version 2.0, for more details.
21 
22  You should have received a copy of the GNU General Public License
23  along with this program; if not, write to the Free Software
24  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
25 
26 #include <float.h>
27 #include <limits.h>
28 #include <math.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <new>
33 #include <string>
34 
35 #include "decimal.h"
36 #include "field_types.h" // enum_field_types
37 #include "lex_string.h"
38 #include "m_ctype.h"
39 #include "m_string.h"
40 #include "memory_debugging.h"
41 #include "my_alloc.h"
42 #include "my_bitmap.h"
43 #include "my_compiler.h"
44 #include "my_dbug.h"
45 #include "my_double2ulonglong.h"
46 #include "my_inttypes.h"
47 #include "my_sys.h"
48 #include "my_table_map.h"
49 #include "my_time.h"
51 #include "mysql_com.h"
52 #include "mysql_time.h"
53 #include "sql/enum_query_type.h"
54 #include "sql/field.h" // Derivation
55 #include "sql/mem_root_array.h"
56 #include "sql/my_decimal.h" // my_decimal
57 #include "sql/parse_tree_node_base.h" // Parse_tree_node
58 #include "sql/sql_array.h" // Bounds_checked_array
59 #include "sql/sql_const.h"
60 #include "sql/table.h"
61 #include "sql/table_trigger_field_support.h" // Table_trigger_field_support
62 #include "sql/thr_malloc.h"
63 #include "sql/trigger_def.h" // enum_trigger_variable_type
64 #include "sql_string.h"
65 #include "template_utils.h"
66 
67 class Item;
68 class Item_field;
69 class Json_wrapper;
70 class Protocol;
71 class SELECT_LEX;
72 class Security_context;
73 class THD;
74 class user_var_entry;
75 struct TYPELIB;
76 template <class T>
77 class List;
78 template <class T>
80 template <typename T>
81 class SQL_I_List;
82 
84 
85 void item_init(void); /* Init item functions */
86 
87 /**
88  Default condition filtering (selectivity) values used by
89  get_filtering_effect() and friends when better estimates
90  (statistics) are not available for a predicate.
91 */
92 /**
93  For predicates that are always satisfied. Must be 1.0 or the filter
94  calculation logic will break down.
95 */
96 #define COND_FILTER_ALLPASS 1.0f
97 /// Filtering effect for equalities: col1 = col2
98 #define COND_FILTER_EQUALITY 0.1f
99 /// Filtering effect for inequalities: col1 > col2
100 #define COND_FILTER_INEQUALITY 0.3333f
101 /// Filtering effect for between: col1 BETWEEN a AND b
102 #define COND_FILTER_BETWEEN 0.1111f
103 /**
104  Value is out-of-date, will need recalculation.
105  This is used by post-greedy-search logic which changes the access method and
106  thus makes obsolete the filtering value calculated by best_access_path(). For
107  example, test_if_skip_sort_order().
108 */
109 #define COND_FILTER_STALE -1.0f
110 /**
111  A special subcase of the above:
112  - if this is table/index/range scan, and
113  - rows_fetched is how many rows we will examine, and
114  - rows_fetched is less than the number of rows in the table (as determined
115  by test_if_cheaper_ordering() and test_if_skip_sort_order()).
116  Unlike the ordinary case where rows_fetched:
117  - is set by calculate_scan_cost(), and
118  - is how many rows pass the constant condition (so, less than we will
119  examine), and
120  - the actual rows_fetched to show in EXPLAIN is the number of rows in the
121  table (== rows which we will examine), and
122  - the constant condition's effect has to be moved to filter_effect for
123  EXPLAIN.
124 */
125 #define COND_FILTER_STALE_NO_CONST -2.0f
126 
127 static inline uint32 char_to_byte_length_safe(uint32 char_length_arg,
128  uint32 mbmaxlen_arg) {
129  ulonglong tmp = ((ulonglong)char_length_arg) * mbmaxlen_arg;
130  return (tmp > UINT_MAX32) ? (uint32)UINT_MAX32 : (uint32)tmp;
131 }
132 
134  Item_result result_type,
135  uint8 decimals) {
136  if (is_temporal_type(real_type_to_type(data_type)))
137  return decimals ? DECIMAL_RESULT : INT_RESULT;
138  if (result_type == STRING_RESULT) return REAL_RESULT;
139  return result_type;
140 }
141 
142 /*
143  "Declared Type Collation"
144  A combination of collation and its derivation.
145 
146  Flags for collation aggregation modes:
147  MY_COLL_ALLOW_SUPERSET_CONV - allow conversion to a superset
148  MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
149  (i.e. constant).
150  MY_COLL_ALLOW_CONV - allow any kind of conversion
151  (combination of the above two)
152  MY_COLL_ALLOW_NUMERIC_CONV - if all items were numbers, convert to
153  @@character_set_connection
154  MY_COLL_DISALLOW_NONE - don't allow return DERIVATION_NONE
155  (e.g. when aggregating for comparison)
156  MY_COLL_CMP_CONV - combination of MY_COLL_ALLOW_CONV
157  and MY_COLL_DISALLOW_NONE
158 */
159 
160 #define MY_COLL_ALLOW_SUPERSET_CONV 1
161 #define MY_COLL_ALLOW_COERCIBLE_CONV 2
162 #define MY_COLL_DISALLOW_NONE 4
163 #define MY_COLL_ALLOW_NUMERIC_CONV 8
164 
165 #define MY_COLL_ALLOW_CONV \
166  (MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV)
167 #define MY_COLL_CMP_CONV (MY_COLL_ALLOW_CONV | MY_COLL_DISALLOW_NONE)
168 
169 class DTCollation {
170  public:
174 
178  }
183  }
184  DTCollation(const CHARSET_INFO *collation_arg, Derivation derivation_arg) {
185  collation = collation_arg;
186  derivation = derivation_arg;
187  set_repertoire_from_charset(collation_arg);
188  }
189  void set(const DTCollation &dt) {
190  collation = dt.collation;
191  derivation = dt.derivation;
192  repertoire = dt.repertoire;
193  }
194  void set(const CHARSET_INFO *collation_arg, Derivation derivation_arg) {
195  collation = collation_arg;
196  derivation = derivation_arg;
197  set_repertoire_from_charset(collation_arg);
198  }
199  void set(const CHARSET_INFO *collation_arg, Derivation derivation_arg,
200  uint repertoire_arg) {
201  collation = collation_arg;
202  derivation = derivation_arg;
203  repertoire = repertoire_arg;
204  }
205  void set_numeric() {
209  }
210  void set(const CHARSET_INFO *collation_arg) {
211  collation = collation_arg;
212  set_repertoire_from_charset(collation_arg);
213  }
214  void set(Derivation derivation_arg) { derivation = derivation_arg; }
215  void set_repertoire(uint repertoire_arg) { repertoire = repertoire_arg; }
216  bool aggregate(DTCollation &dt, uint flags = 0);
217  bool set(DTCollation &dt1, DTCollation &dt2, uint flags = 0) {
218  set(dt1);
219  return aggregate(dt2, flags);
220  }
221  const char *derivation_name() const {
222  switch (derivation) {
223  case DERIVATION_NUMERIC:
224  return "NUMERIC";
226  return "IGNORABLE";
228  return "COERCIBLE";
229  case DERIVATION_IMPLICIT:
230  return "IMPLICIT";
231  case DERIVATION_SYSCONST:
232  return "SYSCONST";
233  case DERIVATION_EXPLICIT:
234  return "EXPLICIT";
235  case DERIVATION_NONE:
236  return "NONE";
237  default:
238  return "UNKNOWN";
239  }
240  }
241 };
242 
243 /**
244  Class used as argument to Item::walk() together with mark_field_in_map()
245 */
246 class Mark_field {
247  public:
250 
251  /**
252  If == NULL, update map of any table.
253  If <> NULL, update map of only this table.
254  */
255  TABLE *const table;
256  /// How to mark the map.
258 };
259 
260 /**
261  Class used as argument to Item::walk() together with used_tables_for_level()
262 */
263 class Used_tables {
264  public:
266 
267  SELECT_LEX *const select; ///< Level for which data is accumulated
268  table_map used_tables; ///< Accumulated used tables data
269 };
270 
271 /*************************************************************************/
272 
273 /**
274  Storage for name strings.
275  Enpowers Simple_cstring with allocation routines from the sql_strmake family.
276 
277  This class must stay as small as possible as we often
278  pass it into functions using call-by-value evaluation.
279 
280  Don't add new members or virual methods into this class!
281 */
282 class Name_string : public Simple_cstring {
283  private:
284  void set_or_copy(const char *str, size_t length, bool is_null_terminated) {
285  if (is_null_terminated)
286  set(str, length);
287  else
288  copy(str, length);
289  }
290 
291  public:
293  /*
294  Please do NOT add constructor Name_string(const char *str) !
295  It will involve hidden strlen() call, which can affect
296  performance negatively. Use Name_string(str, len) instead.
297  */
298  Name_string(const char *str, size_t length) : Simple_cstring(str, length) {}
299  Name_string(const LEX_STRING str) : Simple_cstring(str) {}
301  Name_string(const char *str, size_t length, bool is_null_terminated)
302  : Simple_cstring() {
303  set_or_copy(str, length, is_null_terminated);
304  }
305  Name_string(const LEX_STRING str, bool is_null_terminated)
306  : Simple_cstring() {
307  set_or_copy(str.str, str.length, is_null_terminated);
308  }
309  /**
310  Allocate space using sql_strmake() or sql_strmake_with_convert().
311  */
312  void copy(const char *str, size_t length, const CHARSET_INFO *cs);
313  /**
314  Variants for copy(), for various argument combinations.
315  */
316  void copy(const char *str, size_t length) {
318  }
319  void copy(const char *str) {
320  copy(str, (str ? strlen(str) : 0), system_charset_info);
321  }
322  void copy(const LEX_STRING lex) { copy(lex.str, lex.length); }
323  void copy(const LEX_STRING *lex) { copy(lex->str, lex->length); }
324  void copy(const Name_string str) { copy(str.ptr(), str.length()); }
325  /**
326  Compare name to another name in C string, case insensitively.
327  */
328  bool eq(const char *str) const {
329  DBUG_ASSERT(str && ptr());
330  return my_strcasecmp(system_charset_info, ptr(), str) == 0;
331  }
332  bool eq_safe(const char *str) const { return is_set() && str && eq(str); }
333  /**
334  Compare name to another name in Name_string, case insensitively.
335  */
336  bool eq(const Name_string name) const { return eq(name.ptr()); }
337  bool eq_safe(const Name_string name) const {
338  return is_set() && name.is_set() && eq(name);
339  }
340 };
341 
342 #define NAME_STRING(x) Name_string(STRING_WITH_LEN(x))
343 
344 extern const Name_string null_name_string;
345 
346 /**
347  Storage for Item names.
348  Adds "autogenerated" flag and warning functionality to Name_string.
349 */
351  private:
352  bool m_is_autogenerated; /* indicates if name of this Item
353  was autogenerated or set by user */
354  public:
358  /**
359  Set m_is_autogenerated flag to the given value.
360  */
363  }
364  /**
365  Return the auto-generated flag.
366  */
367  bool is_autogenerated() const { return m_is_autogenerated; }
368  using Name_string::copy;
369  /**
370  Copy name together with autogenerated flag.
371  Produce a warning if name was cut.
372  */
373  void copy(const char *str_arg, size_t length_arg, const CHARSET_INFO *cs_arg,
374  bool is_autogenerated_arg);
375 };
376 
377 /*
378  Instances of Name_resolution_context store the information necesary for
379  name resolution of Items and other context analysis of a query made in
380  fix_fields().
381 
382  This structure is a part of SELECT_LEX, a pointer to this structure is
383  assigned when an item is created (which happens mostly during parsing
384  (sql_yacc.yy)), but the structure itself will be initialized after parsing
385  is complete
386 
387  TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to
388  separate SELECT_LEX which allow to remove tricks of changing this
389  structure before and after INSERT/CREATE and its SELECT to make correct
390  field name resolution.
391 */
393  /*
394  The name resolution context to search in when an Item cannot be
395  resolved in this context (the context of an outer select)
396  */
398  /// Link to next name res context with the same query block as the base
400 
401  /*
402  List of tables used to resolve the items of this context. Usually these
403  are tables from the FROM clause of SELECT statement. The exceptions are
404  INSERT ... SELECT and CREATE ... SELECT statements, where SELECT
405  subquery is not moved to a separate SELECT_LEX. For these types of
406  statements we have to change this member dynamically to ensure correct
407  name resolution of different parts of the statement.
408  */
410  /*
411  In most cases the two table references below replace 'table_list' above
412  for the purpose of name resolution. The first and last name resolution
413  table references allow us to search only in a sub-tree of the nested
414  join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING
415  and JOIN ... ON.
416  */
418  /*
419  Last table to search in the list of leaf table references that begins
420  with first_name_resolution_table.
421  */
423 
424  /*
425  SELECT_LEX item belong to, in case of merged VIEW it can differ from
426  SELECT_LEX where item was created, so we can't use table_list/field_list
427  from there
428  */
430 
431  /*
432  Processor of errors caused during Item name resolving, now used only to
433  hide underlying tables in errors about views (i.e. it substitute some
434  errors for views)
435  */
438 
439  /**
440  When true, items are resolved in this context against
441  SELECT_LEX::item_list, SELECT_lex::group_list and
442  this->table_list. If false, items are resolved only against
443  this->table_list.
444 
445  @see SELECT_LEX::item_list, SELECT_LEX::group_list
446  */
448 
449  /*
450  Security context of this name resolution context. It's used for views
451  and is non-zero only if the view is defined with SQL SECURITY DEFINER.
452  */
454 
456  : outer_context(NULL),
458  table_list(NULL),
459  select_lex(NULL),
461  security_ctx(NULL) {
462  DBUG_PRINT("outer_field", ("creating ctx %p", this));
463  }
464 
465  void init() {
466  resolve_in_select_list = false;
467  view_error_handler = false;
470  }
471 
474  resolve_in_select_list = false;
475  }
476 };
477 
478 /**
479  Struct used to pass around arguments to/from
480  check_function_as_value_generator
481 */
484  int default_error_code, Value_generator_source val_gen_src)
485  : err_code(default_error_code), source(val_gen_src) {}
486  /// the order of the column in table
487  int col_index{-1};
488  /// the error code found during check(if any)
489  int err_code;
490  /*
491  If it is a generated column, default expression or check constraint
492  expresion value generator.
493  */
495  /// the name of the function which is not allowed
496  const char *banned_function_name{nullptr};
497 
498  /// Return the correct error code, based on whether or not if we are checking
499  /// for disallowed functions in generated column expressions, in default
500  /// value expressions or in check constraint expression.
502  return ((source == VGS_GENERATED_COLUMN)
503  ? ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED
505  ? ER_DEFAULT_VAL_GENERATED_FUNCTION_IS_NOT_ALLOWED
506  : ER_CHECK_CONSTRAINT_FUNCTION_IS_NOT_ALLOWED);
507  }
508 };
509 /*
510  Store and restore the current state of a name resolution context.
511 */
512 
514  private:
520 
521  public:
522  Name_resolution_context_state() {} /* Remove gcc warning */
523 
524  public:
525  /* Save the state of a name resolution context. */
526  void save_state(Name_resolution_context *context, TABLE_LIST *table_list) {
527  save_table_list = context->table_list;
530  save_next_local = table_list->next_local;
532  }
533 
534  /* Restore a name resolution context from saved state. */
535  void restore_state(Name_resolution_context *context, TABLE_LIST *table_list) {
536  table_list->next_local = save_next_local;
538  context->table_list = save_table_list;
541  }
542 
545  }
546 };
547 
548 /*
549  This enum is used to report information about monotonicity of function
550  represented by Item* tree.
551  Monotonicity is defined only for Item* trees that represent table
552  partitioning expressions (i.e. have no subselects/user vars/PS parameters
553  etc etc). An Item* tree is assumed to have the same monotonicity properties
554  as its correspoinding function F:
555 
556  [signed] longlong F(field1, field2, ...) {
557  put values of field_i into table record buffer;
558  return item->val_int();
559  }
560 
561  NOTE
562  At the moment function monotonicity is not well defined (and so may be
563  incorrect) for Item trees with parameters/return types that are different
564  from INT_RESULT, may be NULL, or are unsigned.
565  It will be possible to address this issue once the related partitioning bugs
566  (BUG#16002, BUG#15447, BUG#13436) are fixed.
567 
568  The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns
569  NULL which puts those rows into the NULL partition, but
570  '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed
571  for this (see Bug#20577).
572 */
573 
574 typedef enum monotonicity_info {
575  NON_MONOTONIC, /* none of the below holds */
576  MONOTONIC_INCREASING, /* F() is unary and (x < y) => (F(x) <= F(y)) */
577  MONOTONIC_INCREASING_NOT_NULL, /* But only for valid/real x and y */
578  MONOTONIC_STRICT_INCREASING, /* F() is unary and (x < y) => (F(x) < F(y)) */
579  MONOTONIC_STRICT_INCREASING_NOT_NULL /* But only for valid/real x and y */
581 
582 /**
583  A type for SQL-like 3-valued Booleans: true/false/unknown.
584 */
585 class Bool3 {
586  public:
587  /// @returns an instance set to "FALSE"
588  static const Bool3 false3() { return Bool3(v_FALSE); }
589  /// @returns an instance set to "UNKNOWN"
590  static const Bool3 unknown3() { return Bool3(v_UNKNOWN); }
591  /// @returns an instance set to "TRUE"
592  static const Bool3 true3() { return Bool3(v_TRUE); }
593 
594  bool is_true() const { return m_val == v_TRUE; }
595  bool is_unknown() const { return m_val == v_UNKNOWN; }
596  bool is_false() const { return m_val == v_FALSE; }
597 
598  private:
600  /// This is private; instead, use false3()/etc.
601  Bool3(value v) : m_val(v) {}
602 
604  /*
605  No operator to convert Bool3 to bool (or int) - intentionally: how
606  would you map UNKNOWN3 to true/false?
607  It is because we want to block such conversions that Bool3 is a class
608  instead of a plain enum.
609  */
610 };
611 
612 /*************************************************************************/
613 
614 class sp_rcontext;
615 
617  public:
618  /*
619  Set required privileges for accessing the parameter.
620 
621  SYNOPSIS
622  set_required_privilege()
623  rw if 'rw' is true then we are going to read and set the
624  parameter, so SELECT and UPDATE privileges might be
625  required, otherwise we only reading it and SELECT
626  privilege might be required.
627  */
630  virtual void set_required_privilege(bool rw MY_ATTRIBUTE((unused))) {}
631 
632  /*
633  Set parameter value.
634 
635  SYNOPSIS
636  set_value()
637  thd thread handle
638  ctx context to which parameter belongs (if it is local
639  variable).
640  it item which represents new value
641 
642  RETURN
643  false if parameter value has been set,
644  true if error has occurred.
645  */
646  virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it) = 0;
647 
648  virtual void set_out_param_info(Send_field *info MY_ATTRIBUTE((unused))) {}
649 
650  virtual const Send_field *get_out_param_info() const { return NULL; }
651 };
652 
653 /*
654  Analyzer function
655  SYNOPSIS
656  argp in/out IN: Analysis parameter
657  OUT: Parameter to be passed to the transformer
658 
659  RETURN
660  true Invoke the transformer
661  false Don't do it
662 
663 */
664 typedef bool (Item::*Item_analyzer)(uchar **argp);
665 typedef Item *(Item::*Item_transformer)(uchar *arg);
666 typedef void (*Cond_traverser)(const Item *item, void *arg);
667 
668 class Item : public Parse_tree_node {
670 
671  friend class udf_handler;
672  virtual bool is_expensive_processor(uchar *) { return false; }
673 
674  protected:
675  /**
676  Sets the result value of the function an empty string, using the current
677  character set. No memory is allocated.
678  @retval A pointer to the str_value member.
679  */
682  return &str_value;
683  }
684 
685  public:
686  Item(const Item &) = delete;
687  void operator=(Item &) = delete;
688  static void *operator new(size_t size) noexcept {
689  return (*THR_MALLOC)->Alloc(size);
690  }
691  static void *operator new(size_t size, MEM_ROOT *mem_root,
692  const std::nothrow_t &arg MY_ATTRIBUTE((unused)) =
693  std::nothrow) noexcept {
694  return mem_root->Alloc(size);
695  }
696 
697  static void operator delete(void *ptr MY_ATTRIBUTE((unused)),
698  size_t size MY_ATTRIBUTE((unused))) {
699  TRASH(ptr, size);
700  }
701  static void operator delete(void *, MEM_ROOT *,
702  const std::nothrow_t &)noexcept {}
703 
704  enum Type {
735  };
736 
738 
740 
741  /// How to cache constant JSON data
743  /// Don't cache
745  /// Source data is a JSON string, parse and cache result
747  /// Source data is SQL scalar, convert and cache result
749  };
750 
751  enum Bool_test ///< Modifier for result transformation
752  { BOOL_IS_TRUE = 0x00,
759  BOOL_NEGATED = 0x07,
762  };
763 
764  /**
765  Provide data type for a user or system variable, based on the type of
766  the item that is assigned to the variable.
767 
768  @note MYSQL_TYPE_VARCHAR is returned for all string types, but must be
769  further adjusted based on maximum string length by the caller.
770 
771  @param src_type Source type that variable's type is derived from
772  */
774  switch (src_type) {
775  case MYSQL_TYPE_TINY:
776  case MYSQL_TYPE_SHORT:
777  case MYSQL_TYPE_INT24:
778  case MYSQL_TYPE_LONG:
779  case MYSQL_TYPE_LONGLONG:
780  return MYSQL_TYPE_LONGLONG;
781  case MYSQL_TYPE_DECIMAL:
783  return MYSQL_TYPE_NEWDECIMAL;
784  case MYSQL_TYPE_FLOAT:
785  case MYSQL_TYPE_DOUBLE:
786  return MYSQL_TYPE_DOUBLE;
787  case MYSQL_TYPE_VARCHAR:
789  case MYSQL_TYPE_STRING:
790  return MYSQL_TYPE_VARCHAR;
791  case MYSQL_TYPE_YEAR:
792  return MYSQL_TYPE_LONGLONG;
794  case MYSQL_TYPE_DATE:
795  case MYSQL_TYPE_TIME:
796  case MYSQL_TYPE_DATETIME:
797  case MYSQL_TYPE_NEWDATE:
798  case MYSQL_TYPE_BIT:
801  case MYSQL_TYPE_TIME2:
802  case MYSQL_TYPE_JSON:
803  case MYSQL_TYPE_ENUM:
804  case MYSQL_TYPE_SET:
805  case MYSQL_TYPE_GEOMETRY:
806  case MYSQL_TYPE_NULL:
808  case MYSQL_TYPE_BLOB:
811  return MYSQL_TYPE_VARCHAR;
812  default:
813  DBUG_ASSERT(false);
814  return MYSQL_TYPE_NULL;
815  }
816  }
817 
818  /// Item constructor for general use.
819  Item();
820 
821  /**
822  Constructor used by Item_field, Item_ref & aggregate functions.
823  Used for duplicating lists in processing queries with temporary tables.
824 
825  Also used for Item_cond_and/Item_cond_or for creating top AND/OR structure
826  of WHERE clause to protect it of optimisation changes in prepared statements
827  */
828  Item(THD *thd, const Item *item);
829 
830  /**
831  Parse-time context-independent constructor.
832 
833  This constructor and caller constructors of child classes must not
834  access/change thd->lex (including thd->lex->current_select(),
835  thd->m_parser_state etc structures).
836 
837  If we need to finalize the construction of the object, then we move
838  all context-sensitive code to the itemize() virtual function.
839 
840  The POS parameter marks this constructor and other context-independent
841  constructors of child classes for easy recognition/separation from other
842  (context-dependent) constructors.
843  */
844  explicit Item(const POS &);
845 
846  virtual ~Item() override {
847 #ifdef EXTRA_DEBUG
848  item_name.set(0);
849 #endif
850  } /*lint -e1509 */
851 
852  private:
853  /*
854  Hide the contextualize*() functions: call/override the itemize()
855  in Item class tree instead.
856 
857  Note: contextualize_() is an intermediate function. Remove it together
858  with Parse_tree_node::contextualize_().
859  */
860  bool contextualize(Parse_context *) override {
861  DBUG_ASSERT(0);
862  return true;
863  }
864  bool contextualize_(Parse_context *) override {
865  DBUG_ASSERT(0);
866  return true;
867  }
868 
869  protected:
870  /**
871  Helper function to skip itemize() for grammar-allocated items
872 
873  @param [out] res pointer to "this"
874 
875  @retval true can skip itemize()
876  @retval false can't skip: the item is allocated directly by the parser
877  */
878  bool skip_itemize(Item **res) {
879  *res = this;
880  return !is_parser_item;
881  }
882 
883  /*
884  Checks if the function should return binary result based on the items
885  provided as parameter.
886  Function should only be used by Item_bit_func*
887 
888  @param a item to check
889  @param b item to check, may be nullptr
890 
891  @returns true if binary result.
892  */
893  static bool bit_func_returns_binary(const Item *a, const Item *b);
894 
895  public:
896  /**
897  The same as contextualize()/contextualize_() but with additional parameter
898 
899  This function finalize the construction of Item objects (see the Item(POS)
900  constructor): we can access/change parser contexts from the itemize()
901  function.
902 
903  @param pc current parse context
904  @param [out] res pointer to "this" or to a newly allocated
905  replacement object to use in the Item tree instead
906 
907  @retval false success
908  @retval true syntax/OOM/etc error
909  */
910  virtual bool itemize(Parse_context *pc, Item **res);
911 
912  void rename(char *new_name);
913  void init_make_field(Send_field *tmp_field, enum enum_field_types type);
914  virtual void cleanup();
915  virtual void make_field(Send_field *field);
916  virtual Field *make_string_field(TABLE *table);
917  virtual bool fix_fields(THD *, Item **);
918  /**
919  Fix after tables have been moved from one select_lex level to the parent
920  level, e.g by semijoin conversion.
921  Basically re-calculate all attributes dependent on the tables.
922 
923  @param parent_select select_lex that tables are moved to.
924  @param removed_select select_lex that tables are moved away from,
925  child of parent_select.
926  */
927  virtual void fix_after_pullout(
928  SELECT_LEX *parent_select MY_ATTRIBUTE((unused)),
929  SELECT_LEX *removed_select MY_ATTRIBUTE((unused))) {}
930  /*
931  should be used in case where we are sure that we do not need
932  complete fix_fields() procedure.
933  */
934  inline void quick_fix_field() { fixed = 1; }
935  virtual void set_can_use_prefix_key() {}
936 
937  protected:
938  /**
939  Helper function which does all of the work for
940  save_in_field(Field*, bool), except some error checking common to
941  all subclasses, which is performed by save_in_field() itself.
942 
943  Subclasses that need to specialize the behaviour of
944  save_in_field(), should override this function instead of
945  save_in_field().
946 
947  @param[in,out] field the field to save the item into
948  @param no_conversions whether or not to allow conversions of the value
949 
950  @return the status from saving into the field
951  @retval TYPE_OK item saved without any errors or warnings
952  @retval != TYPE_OK there were errors or warnings when saving the item
953  */
955  bool no_conversions);
956 
957  public:
958  /**
959  Save the item into a field but do not emit any warnings.
960 
961  @param field field to save the item into
962  @param no_conversions whether or not to allow conversions of the value
963 
964  @return the status from saving into the field
965  @retval TYPE_OK item saved without any issues
966  @retval != TYPE_OK there were issues saving the item
967  */
969  bool no_conversions);
970  /**
971  Save a temporal value in packed longlong format into a Field.
972  Used in optimizer.
973 
974  Subclasses that need to specialize this function, should override
975  save_in_field_inner().
976 
977  @param[in,out] field the field to save the item into
978  @param no_conversions whether or not to allow conversions of the value
979 
980  @return the status from saving into the field
981  @retval TYPE_OK item saved without any errors or warnings
982  @retval != TYPE_OK there were errors or warnings when saving the item
983  */
984  type_conversion_status save_in_field(Field *field, bool no_conversions);
985 
986  virtual void save_org_in_field(Field *field) { save_in_field(field, true); }
987 
988  virtual bool send(Protocol *protocol, String *str);
989  bool evaluate(THD *thd, String *str);
990  virtual bool eq(const Item *, bool binary_cmp) const;
991  virtual Item_result result_type() const { return REAL_RESULT; }
992  /**
993  Result type when an item appear in a numeric context.
994  See Field::numeric_context_result_type() for more comments.
995  */
998  }
999  /**
1000  Similar to result_type() but makes DATE, DATETIME, TIMESTAMP
1001  pretend to be numbers rather than strings.
1002  */
1005  : result_type();
1006  }
1007 
1008  /// Retrieve the derived data type of the Item.
1009  inline enum_field_types data_type() const {
1010  return static_cast<enum_field_types>(m_data_type);
1011  }
1012 
1013  /**
1014  Set the data type of the current Item. It is however recommended to
1015  use one of the type-specific setters if possible.
1016 
1017  @param data_type The data type of this Item.
1018  */
1020  m_data_type = static_cast<uint8>(data_type);
1021  }
1022 
1023  inline void set_data_type_bool() {
1026  max_length = 1;
1027  }
1028 
1029  /**
1030  Set the data type of the Item to be longlong.
1031  Maximum display width is set to be the maximum of a 64-bit integer,
1032  but it may be adjusted later. The unsigned property is not affected.
1033  */
1034  inline void set_data_type_longlong() {
1037  fix_char_length(21);
1038  }
1039 
1040  /**
1041  Set the data type of the Item to be decimal.
1042  The unsigned property must have been set before calling this function.
1043 
1044  @param precision Number of digits of precision
1045  @param dec Number of digits after decimal point.
1046  */
1047  inline void set_data_type_decimal(uint8 precision, uint8 dec) {
1050  decimals = dec;
1052  precision, dec, unsigned_flag));
1053  }
1054 
1055  /// Set the data type of the Item to be double precision floating point.
1056  inline void set_data_type_double() {
1061  }
1062 
1063  /// Set the data type of the Item to be single precision floating point.
1064  inline void set_data_type_float() {
1069  }
1070 
1071  /// Initialize an Item to be of VARCHAR type, other properties undetermined.
1075  }
1076 
1077  /**
1078  Set the Item to be variable length string. Actual type is determined from
1079  maximum string size. Collation must have been set before calling function.
1080 
1081  @param max_l Maximum number of characters in string
1082  */
1083  inline void set_data_type_string(uint32 max_l) {
1085  if (max_length < 65536)
1087  else if (max_length < 16777216)
1089  else
1091  }
1092 
1093  /**
1094  Set the Item to be variable length string. Like function above, but with
1095  larger string length precision.
1096 
1097  @param max_char_length_arg Maximum number of characters in string
1098  */
1099  inline void set_data_type_string(ulonglong max_char_length_arg) {
1100  ulonglong max_result_length =
1101  max_char_length_arg * collation.collation->mbmaxlen;
1102  if (max_result_length >= MAX_BLOB_WIDTH) {
1103  max_result_length = MAX_BLOB_WIDTH;
1104  maybe_null = true;
1105  }
1107  uint32(max_result_length / collation.collation->mbmaxlen));
1108  }
1109 
1110  /**
1111  Set the Item to be variable length string. Like function above, but will
1112  also set character set and collation.
1113 
1114  @param max_l Maximum number of characters in string
1115  @param cs Pointer to character set and collation struct
1116  */
1117  inline void set_data_type_string(ulonglong max_l, const CHARSET_INFO *cs) {
1118  collation.collation = cs;
1119  set_data_type_string(max_l);
1120  }
1121 
1122  /**
1123  Set the Item to be variable length string. Like function above, but will
1124  also set full collation information.
1125 
1126  @param max_l Maximum number of characters in string
1127  @param coll Ref to collation data, including derivation and repertoire
1128  */
1129  inline void set_data_type_string(uint32 max_l, const DTCollation &coll) {
1130  collation.set(coll);
1131  set_data_type_string(max_l);
1132  }
1133 
1134  /**
1135  Set the Item to be fixed length string. Collation must have been set
1136  before calling function.
1137 
1138  @param max_l Number of characters in string
1139  */
1140  inline void set_data_type_char(uint32 max_l) {
1142  DBUG_ASSERT(max_length < 65536);
1144  }
1145 
1146  /**
1147  Set the Item to be fixed length string. Like function above, but will
1148  also set character set and collation.
1149 
1150  @param max_l Maximum number of characters in string
1151  @param cs Pointer to character set and collation struct
1152  */
1153  inline void set_data_type_char(uint32 max_l, const CHARSET_INFO *cs) {
1154  collation.collation = cs;
1155  set_data_type_char(max_l);
1156  }
1157 
1158  /**
1159  Set the Item to be of BLOB type.
1160 
1161  @param max_l Maximum number of bytes in data type
1162  */
1163  inline void set_data_type_blob(uint32 max_l) {
1165  max_length = max_l;
1166  }
1167 
1168  /// Set all type properties for Item of DATE type.
1169  inline void set_data_type_date() {
1172  decimals = 0;
1174  }
1175 
1176  /**
1177  Set all type properties for Item of TIME type.
1178 
1179  @param fsp Fractional seconds precision
1180  */
1181  inline void set_data_type_time(uint8 fsp) {
1184  decimals = fsp;
1185  max_length = MAX_TIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1186  }
1187 
1188  /**
1189  Set all properties for Item of DATETIME type.
1190 
1191  @param fsp Fractional seconds precision
1192  */
1193  inline void set_data_type_datetime(uint8 fsp) {
1196  decimals = fsp;
1197  max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1198  }
1199 
1200  /**
1201  Set all properties for Item of TIMESTAMP type.
1202 
1203  @param fsp Fractional seconds precision
1204  */
1205  inline void set_data_type_timestamp(uint8 fsp) {
1208  decimals = fsp;
1209  max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1210  }
1211 
1212  /**
1213  Set the data type of the Item to be JSON.
1214  */
1220  }
1221 
1222  /**
1223  Set the data type of the Item to be YEAR.
1224  */
1228  max_length = 4;
1229  }
1230 
1231  /**
1232  Set the Item to be of GEOMETRY type.
1233  */
1234  inline void set_data_type_geometry() {
1238  }
1239 
1240  /**
1241  Set type information of Item from "result" information.
1242  For String types, type is set based on maximum string size.
1243  For other types, the associated type with the largest precision is set.
1244 
1245  @param result Either Integer, Decimal, Double or String
1246  @param length Maximum string size, used only for String result.
1247  */
1249  switch (result) {
1250  case INT_RESULT:
1252  break;
1253  case DECIMAL_RESULT:
1255  break;
1256  case REAL_RESULT:
1258  break;
1259  case STRING_RESULT:
1261  break;
1262  case ROW_RESULT:
1263  case INVALID_RESULT:
1264  default:
1265  DBUG_ASSERT(false);
1266  break;
1267  }
1268  }
1269 
1270  /**
1271  Set data type properties of the item from the properties of another item.
1272 
1273  @param item Item to set data type properties from.
1274  */
1275  inline void set_data_type_from_item(Item *item) {
1276  set_data_type(item->data_type());
1277  collation = item->collation;
1278  max_length = item->max_length;
1279  decimals = item->decimals;
1280  unsigned_flag = item->unsigned_flag;
1281  }
1282 
1283  /**
1284  Determine correct string field type, based on string length
1285 
1286  @param max_bytes Maximum string size, in number of bytes @todo
1287  */
1289  if (max_bytes >= 16777216)
1290  return MYSQL_TYPE_LONG_BLOB;
1291  else if (max_bytes >= 65536)
1292  return MYSQL_TYPE_MEDIUM_BLOB;
1293  else
1294  return MYSQL_TYPE_VARCHAR;
1295  }
1296 
1297  virtual Item_result cast_to_int_type() const { return result_type(); }
1298  virtual enum Type type() const = 0;
1299 
1301 
1302  /*
1303  Return information about function monotonicity. See comment for
1304  enum_monotonicity_info for details. This function can only be called
1305  after fix_fields() call.
1306  */
1308  return NON_MONOTONIC;
1309  }
1310 
1311  /// For template-compatibility with Field
1312  inline bool is_null_value() { return null_value; }
1313  /*
1314  Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$
1315  const2"
1316 
1317  SYNOPSIS
1318  val_int_endpoint()
1319  left_endp false <=> The interval is "x < const" or "x <= const"
1320  true <=> The interval is "x > const" or "x >= const"
1321 
1322  incl_endp IN false <=> the comparison is '<' or '>'
1323  true <=> the comparison is '<=' or '>='
1324  OUT The same but for the "F(x) $CMP$ F(const)" comparison
1325 
1326  DESCRIPTION
1327  This function is defined only for unary monotonic functions. The caller
1328  supplies the source half-interval
1329 
1330  x $CMP$ const
1331 
1332  The value of const is supplied implicitly as the value this item's
1333  argument, the form of $CMP$ comparison is specified through the
1334  function's arguments. The calle returns the result interval
1335 
1336  F(x) $CMP2$ F(const)
1337 
1338  passing back F(const) as the return value, and the form of $CMP2$
1339  through the out parameter. NULL values are assumed to be comparable and
1340  be less than any non-NULL values.
1341 
1342  RETURN
1343  The output range bound, which equal to the value of val_int()
1344  - If the value of the function is NULL then the bound is the
1345  smallest possible value of LLONG_MIN
1346  */
1347  virtual longlong val_int_endpoint(bool left_endp MY_ATTRIBUTE((unused)),
1348  bool *incl_endp MY_ATTRIBUTE((unused))) {
1349  DBUG_ASSERT(0);
1350  return 0;
1351  }
1352 
1353  /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */
1354  /*
1355  Return double precision floating point representation of item.
1356 
1357  SYNOPSIS
1358  val_real()
1359 
1360  RETURN
1361  In case of NULL value return 0.0 and set null_value flag to true.
1362  If value is not null null_value flag will be reset to false.
1363  */
1364  virtual double val_real() = 0;
1365  /*
1366  Return integer representation of item.
1367 
1368  SYNOPSIS
1369  val_int()
1370 
1371  RETURN
1372  In case of NULL value return 0 and set null_value flag to true.
1373  If value is not null null_value flag will be reset to false.
1374  */
1375  virtual longlong val_int() = 0;
1376  /**
1377  Return date value of item in packed longlong format.
1378  */
1379  virtual longlong val_date_temporal();
1380  /**
1381  Return time value of item in packed longlong format.
1382  */
1383  virtual longlong val_time_temporal();
1384  /**
1385  Return date or time value of item in packed longlong format,
1386  depending on item field type.
1387  */
1389  if (data_type() == MYSQL_TYPE_TIME) return val_time_temporal();
1391  return val_date_temporal();
1392  }
1393  /**
1394  Get date or time value in packed longlong format.
1395  Before conversion from MYSQL_TIME to packed format,
1396  the MYSQL_TIME value is rounded to "dec" fractional digits.
1397  */
1399 
1400  /*
1401  This is just a shortcut to avoid the cast. You should still use
1402  unsigned_flag to check the sign of the item.
1403  */
1404  inline ulonglong val_uint() { return (ulonglong)val_int(); }
1405  /*
1406  Return string representation of this item object.
1407 
1408  SYNOPSIS
1409  val_str()
1410  str an allocated buffer this or any nested Item object can use to
1411  store return value of this method.
1412 
1413  NOTE
1414  Buffer passed via argument should only be used if the item itself
1415  doesn't have an own String buffer. In case when the item maintains
1416  it's own string buffer, it's preferable to return it instead to
1417  minimize number of mallocs/memcpys.
1418  The caller of this method can modify returned string, but only in case
1419  when it was allocated on heap, (is_alloced() is true). This allows
1420  the caller to efficiently use a buffer allocated by a child without
1421  having to allocate a buffer of it's own. The buffer, given to
1422  val_str() as argument, belongs to the caller and is later used by the
1423  caller at it's own choosing.
1424  A few implications from the above:
1425  - unless you return a string object which only points to your buffer
1426  but doesn't manages it you should be ready that it will be
1427  modified.
1428  - even for not allocated strings (is_alloced() == false) the caller
1429  can change charset (see Item_func_{typecast/binary}. XXX: is this
1430  a bug?
1431  - still you should try to minimize data copying and return internal
1432  object whenever possible.
1433 
1434  RETURN
1435  In case of NULL value or error, return error_str() as this function will
1436  check if the return value may be null, and it will either set null_value
1437  to true and return nullptr or to false and it will return empty string.
1438  If value is not null set null_value flag to false before returning it.
1439  */
1440  virtual String *val_str(String *str) = 0;
1441 
1442  /*
1443  Returns string representation of this item in ASCII format.
1444 
1445  SYNOPSIS
1446  val_str_ascii()
1447  str - similar to val_str();
1448 
1449  NOTE
1450  This method is introduced for performance optimization purposes.
1451 
1452  1. val_str() result of some Items in string context
1453  depends on @@character_set_results.
1454  @@character_set_results can be set to a "real multibyte" character
1455  set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples
1456  below for convenience.)
1457 
1458  So the default string result of such functions
1459  in these circumstances is real multi-byte character set, like UTF32.
1460 
1461  For example, all numbers in string context
1462  return result in @@character_set_results:
1463 
1464  SELECT CONCAT(20010101); -> UTF32
1465 
1466  We do sprintf() first (to get ASCII representation)
1467  and then convert to UTF32;
1468 
1469  So these kind "data sources" can use ASCII representation
1470  internally, but return multi-byte data only because
1471  @@character_set_results wants so.
1472  Therefore, conversion from ASCII to UTF32 is applied internally.
1473 
1474 
1475  2. Some other functions need in fact ASCII input.
1476 
1477  For example,
1478  inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT().
1479 
1480  Similar, fields of certain type, like DATE, TIME,
1481  when you insert string data into them, expect in fact ASCII input.
1482  If they get non-ASCII input, for example UTF32, they
1483  convert input from UTF32 to ASCII, and then use ASCII
1484  representation to do further processing.
1485 
1486 
1487  3. Now imagine we pass result of a data source of the first type
1488  to a data destination of the second type.
1489 
1490  What happens:
1491  a. data source converts data from ASCII to UTF32, because
1492  @@character_set_results wants so and passes the result to
1493  data destination.
1494  b. data destination gets UTF32 string.
1495  c. data destination converts UTF32 string to ASCII,
1496  because it needs ASCII representation to be able to handle data
1497  correctly.
1498 
1499  As a result we get two steps of unnecessary conversion:
1500  From ASCII to UTF32, then from UTF32 to ASCII.
1501 
1502  A better way to handle these situations is to pass ASCII
1503  representation directly from the source to the destination.
1504 
1505  This is why val_str_ascii() introduced.
1506 
1507  RETURN
1508  Similar to val_str()
1509  */
1510  virtual String *val_str_ascii(String *str);
1511 
1512  /*
1513  Return decimal representation of item with fixed point.
1514 
1515  SYNOPSIS
1516  val_decimal()
1517  decimal_buffer buffer which can be used by Item for returning value
1518  (but can be not)
1519 
1520  NOTE
1521  Returned value should not be changed if it is not the same which was
1522  passed via argument.
1523 
1524  RETURN
1525  Return pointer on my_decimal (it can be other then passed via argument)
1526  if value is not NULL (null_value flag will be reset to false).
1527  In case of NULL value it return 0 pointer and set null_value flag
1528  to true.
1529  */
1530  virtual my_decimal *val_decimal(my_decimal *decimal_buffer) = 0;
1531  /*
1532  Return boolean value of item.
1533 
1534  RETURN
1535  false value is false or NULL
1536  true value is true (not equal to 0)
1537  */
1538  virtual bool val_bool();
1539 
1540  /**
1541  Get a JSON value from an Item.
1542 
1543  All subclasses that can return a JSON value, should override this
1544  function. The function in the base class is not expected to be
1545  called. If it is called, it most likely means that some subclass
1546  is missing an override of val_json().
1547 
1548  @param[in,out] result The resulting Json_wrapper.
1549 
1550  @return false if successful, true on failure
1551  */
1552  /* purecov: begin deadcode */
1553  virtual bool val_json(Json_wrapper *result MY_ATTRIBUTE((unused))) {
1554  DBUG_ASSERT(false);
1555  my_error(ER_NOT_SUPPORTED_YET, MYF(0), "item type for JSON");
1556  return error_json();
1557  }
1558  /* purecov: end */
1559 
1560  /**
1561  Calculate the filter contribution that is relevant for table
1562  'filter_for_table' for this item.
1563 
1564  @param thd Thread handler
1565  @param filter_for_table The table we are calculating filter effect for
1566  @param read_tables Tables earlier in the join sequence.
1567  Predicates for table 'filter_for_table' that
1568  rely on values from these tables can be part of
1569  the filter effect.
1570  @param fields_to_ignore Fields in 'filter_for_table' that should not
1571  be part of the filter calculation. The filtering
1572  effect of these fields is already part of the
1573  calculation somehow (e.g. because there is a
1574  predicate "col = <const>", and the optimizer
1575  has decided to do ref access on 'col').
1576  @param rows_in_table The number of rows in table 'filter_for_table'
1577 
1578  @return the filtering effect (between 0 and 1) this
1579  Item contributes with.
1580  */
1581  virtual float get_filtering_effect(
1582  THD *thd MY_ATTRIBUTE((unused)),
1583  table_map filter_for_table MY_ATTRIBUTE((unused)),
1584  table_map read_tables MY_ATTRIBUTE((unused)),
1585  const MY_BITMAP *fields_to_ignore MY_ATTRIBUTE((unused)),
1586  double rows_in_table MY_ATTRIBUTE((unused))) {
1587  // Filtering effect cannot be calculated for a table already read.
1588  DBUG_ASSERT((read_tables & filter_for_table) == 0);
1589  return COND_FILTER_ALLPASS;
1590  }
1591 
1592  /**
1593  Get the value to return from val_json() in case of errors.
1594 
1595  @see Item::error_bool
1596 
1597  @return The value val_json() should return, which is true.
1598  */
1599  bool error_json() {
1601  return true;
1602  }
1603 
1604  /**
1605  Convert a non-temporal type to date
1606  */
1607  bool get_date_from_non_temporal(MYSQL_TIME *ltime, my_time_flags_t fuzzydate);
1608 
1609  /**
1610  Convert a non-temporal type to time
1611  */
1613 
1614  protected:
1615  /* Helper functions, see item_sum.cc */
1622  my_decimal *val_decimal_from_real(my_decimal *decimal_value);
1623  my_decimal *val_decimal_from_int(my_decimal *decimal_value);
1625  my_decimal *val_decimal_from_date(my_decimal *decimal_value);
1626  my_decimal *val_decimal_from_time(my_decimal *decimal_value);
1631  double val_real_from_decimal();
1632 
1633  /**
1634  Get the value to return from val_bool() in case of errors.
1635 
1636  This function is called from val_bool() when an error has occurred
1637  and we need to return something to abort evaluation of the
1638  item. The expected pattern in val_bool() is
1639 
1640  if (@<error condition@>)
1641  {
1642  my_error(...)
1643  return error_bool();
1644  }
1645 
1646  @return The value val_bool() should return.
1647  */
1648  bool error_bool() {
1650  return false;
1651  }
1652 
1653  /**
1654  Get the value to return from val_int() in case of errors.
1655 
1656  @see Item::error_bool
1657 
1658  @return The value val_int() should return.
1659  */
1660  int error_int() {
1662  return 0;
1663  }
1664 
1665  /**
1666  Get the value to return from val_real() in case of errors.
1667 
1668  @see Item::error_bool
1669 
1670  @return The value val_real() should return.
1671  */
1672  double error_real() {
1674  return 0.0;
1675  }
1676 
1677  /**
1678  Get the value to return from val_str() in case of errors.
1679 
1680  @see Item::error_bool
1681 
1682  @return The value val_str() should return.
1683  */
1686  return null_value ? NULL : make_empty_result();
1687  }
1688 
1689  /**
1690  Gets the value to return from val_str() when returning a NULL value.
1691  @return The value val_str() should return.
1692  */
1695  null_value = true;
1696  return nullptr;
1697  }
1698 
1699  /**
1700  Convert val_str() to date in MYSQL_TIME
1701  */
1703  /**
1704  Convert val_real() to date in MYSQL_TIME
1705  */
1707  /**
1708  Convert val_decimal() to date in MYSQL_TIME
1709  */
1711  /**
1712  Convert val_int() to date in MYSQL_TIME
1713  */
1715  /**
1716  Convert get_time() from time to date in MYSQL_TIME
1717  */
1718  bool get_date_from_time(MYSQL_TIME *ltime);
1719 
1720  /**
1721  Convert a numeric type to date
1722  */
1723  bool get_date_from_numeric(MYSQL_TIME *ltime, my_time_flags_t fuzzydate);
1724 
1725  /**
1726  Convert val_str() to time in MYSQL_TIME
1727  */
1728  bool get_time_from_string(MYSQL_TIME *ltime);
1729  /**
1730  Convert val_real() to time in MYSQL_TIME
1731  */
1732  bool get_time_from_real(MYSQL_TIME *ltime);
1733  /**
1734  Convert val_decimal() to time in MYSQL_TIME
1735  */
1736  bool get_time_from_decimal(MYSQL_TIME *ltime);
1737  /**
1738  Convert val_int() to time in MYSQL_TIME
1739  */
1740  bool get_time_from_int(MYSQL_TIME *ltime);
1741  /**
1742  Convert date to time
1743  */
1744  bool get_time_from_date(MYSQL_TIME *ltime);
1745  /**
1746  Convert datetime to time
1747  */
1748  bool get_time_from_datetime(MYSQL_TIME *ltime);
1749 
1750  /**
1751  Convert a numeric type to time
1752  */
1753  bool get_time_from_numeric(MYSQL_TIME *ltime);
1754 
1755  public:
1759 
1761  DBUG_TRACE;
1762  return 0;
1763  }
1764  /* This is also used to create fields in CREATE ... SELECT: */
1765  virtual Field *tmp_table_field(TABLE *) { return 0; }
1766  virtual const char *full_name() const {
1767  return item_name.is_set() ? item_name.ptr() : "???";
1768  }
1769 
1770  /* bit map of tables used by item */
1771  virtual table_map used_tables() const { return (table_map)0L; }
1772 
1773  /*
1774  Return table map of tables that can't be NULL tables (tables that are
1775  used in a context where if they would contain a NULL row generated
1776  by a LEFT or RIGHT join, the item would not be true).
1777  This expression is used on WHERE item to determinate if a LEFT JOIN can be
1778  converted to a normal join.
1779  Generally this function should return used_tables() if the function
1780  would return null if any of the arguments are null
1781  As this is only used in the beginning of optimization, the value don't
1782  have to be updated in update_used_tables()
1783  */
1784  virtual table_map not_null_tables() const { return used_tables(); }
1785 
1786  /**
1787  Returns true if this is a simple constant item like an integer, not
1788  a constant expression. Used in the optimizer to propagate basic constants.
1789  It is assumed that val_xxx() does not modify the item's state for
1790  such items. It is also assumed that val_str() can be called with nullptr
1791  as argument as val_str() will return an internally cached const string.
1792  */
1793  virtual bool basic_const_item() const { return false; }
1794  /**
1795  @return cloned item if it is constant
1796  @retval nullptr if this is not const
1797  */
1798  virtual Item *clone_item() const { return nullptr; }
1799  virtual cond_result eq_cmp_result() const { return COND_OK; }
1800  inline uint float_length(uint decimals_par) const {
1801  return decimals != DECIMAL_NOT_SPECIFIED ? (DBL_DIG + 2 + decimals_par)
1802  : DBL_DIG + 8;
1803  }
1804  virtual uint decimal_precision() const;
1805  inline int decimal_int_part() const {
1807  }
1808  /**
1809  TIME precision of the item: 0..6
1810  */
1811  virtual uint time_precision();
1812  /**
1813  DATETIME precision of the item: 0..6
1814  */
1815  virtual uint datetime_precision();
1816  /**
1817  Returns true if item is constant, regardless of query evaluation state.
1818  An expression is constant if it:
1819  - refers no tables.
1820  - refers no subqueries that refers any tables.
1821  - refers no non-deterministic functions.
1822  - refers no statement parameters.
1823  - contains no group expression under rollup
1824  */
1825  bool const_item() const { return (used_tables() == 0); }
1826  /**
1827  Returns true if item is constant during one query execution.
1828  If const_for_execution() is true but const_item() is false, value is
1829  not available before tables have been locked and parameters have been
1830  assigned values. This applies to
1831  - statement parameters
1832  - non-dependent subqueries
1833  - deterministic stored functions that contain SQL code.
1834  For items where the default implementation of used_tables() and
1835  const_item() are effective, const_item() will always return true.
1836  */
1837  bool const_for_execution() const {
1838  return !(used_tables() & ~INNER_TABLE_BIT);
1839  }
1840 
1841  /**
1842  Return true if this is a const item that may be evaluated in
1843  the current phase of statement processing.
1844  - No evaluation is performed when analyzing a view, otherwise:
1845  - Items that have the const_item() property can always be evaluated.
1846  - Items that have the const_for_execution() property can be evaluated when
1847  tables are locked (ie during optimization or execution).
1848 
1849  This function should be used in the following circumstances:
1850  - during preparation to check whether an item can be permanently transformed
1851  - to check that an item is constant in functions that may be used in both
1852  the preparation and optimization phases.
1853 
1854  This function should not be used by code that is called during optimization
1855  and/or execution only. Use const_for_execution() in this case.
1856  */
1857  bool may_evaluate_const(const THD *thd) const;
1858 
1859  /**
1860  This method is used for to:
1861  - to generate a view definition query (SELECT-statement);
1862  - to generate a SQL-query for EXPLAIN EXTENDED;
1863  - to generate a SQL-query to be shown in INFORMATION_SCHEMA;
1864  - to generate a SQL-query that looks like a prepared statement for
1865  query_rewrite
1866  - debug.
1867 
1868  For more information about view definition query, INFORMATION_SCHEMA
1869  query and why they should be generated from the Item-tree, @see
1870  mysql_register_view().
1871  */
1872  virtual void print(const THD *, String *str, enum_query_type) const {
1873  str->append(full_name());
1874  }
1875 
1876  void print_item_w_name(const THD *thd, String *,
1877  enum_query_type query_type) const;
1878  /**
1879  Prints the item when it's part of ORDER BY and GROUP BY.
1880  @param thd Thread handle
1881  @param str String to print to
1882  @param query_type How to format the item
1883  @param used_alias Whether item was referenced with alias.
1884  */
1885  void print_for_order(const THD *thd, String *str, enum_query_type query_type,
1886  bool used_alias) const;
1887 
1888  virtual void update_used_tables() {}
1889 
1891  /* Called for items that really have to be split */
1892  void split_sum_func2(THD *thd, Ref_item_array ref_item_array,
1893  List<Item> &fields, Item **ref, bool skip_registered);
1894  virtual bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) = 0;
1895  virtual bool get_time(MYSQL_TIME *ltime) = 0;
1896  /**
1897  Get timestamp in "struct timeval" format.
1898  @retval false on success
1899  @retval true on error
1900  */
1901  virtual bool get_timeval(struct timeval *tm, int *warnings);
1902  /*
1903  The method allows to determine nullness of a complex expression
1904  without fully evaluating it, instead of calling val*() then
1905  checking null_value. Used in Item_func_isnull/Item_func_isnotnull
1906  and Item_sum_count/Item_sum_count_distinct.
1907  Any new item which can be NULL must implement this method.
1908  */
1909  virtual bool is_null() { return false; }
1910 
1911  /// Make sure the null_value member has a correct value.
1912  bool update_null_value();
1913 
1914  /**
1915  Apply the IS TRUE truth property, meaning that an UNKNOWN result and a
1916  FALSE result are treated the same.
1917 
1918  This property is applied e.g to all conditions in WHERE, HAVING and ON
1919  clauses, and is recursively applied to operands of AND, OR
1920  operators. Some items (currently AND and subquery predicates) may enable
1921  special optimizations when they have this property.
1922  */
1923  virtual void apply_is_true() {}
1924  /*
1925  set field of temporary table for Item which can be switched on temporary
1926  table during query processing (grouping and so on). @see
1927  Item_result_field.
1928  */
1929  virtual void set_result_field(Field *) {}
1930  virtual bool is_result_field() const { return false; }
1931  virtual Field *get_result_field() const { return nullptr; }
1932  virtual bool is_bool_func() const { return false; }
1933  virtual void save_in_result_field(
1934  bool no_conversions MY_ATTRIBUTE((unused))) {}
1935  /*
1936  Set value of aggregate function in case of no rows for grouping were found.
1937  Also used for subqueries with outer references in SELECT list.
1938  */
1939  virtual void no_rows_in_result() {}
1940  virtual Item *copy_or_same(THD *) { return this; }
1941  virtual Item *copy_andor_structure(THD *) { return this; }
1942  virtual Item *real_item() { return this; }
1944  return runtime_item ? real_item() : this;
1945  }
1946  virtual void set_runtime_created() { runtime_item = true; }
1947  virtual Item *get_tmp_table_item(THD *thd) {
1948  DBUG_TRACE;
1949  Item *result = copy_or_same(thd);
1950  return result;
1951  }
1952 
1953  static const CHARSET_INFO *default_charset();
1954  virtual const CHARSET_INFO *compare_collation() const { return nullptr; }
1955 
1956  /*
1957  For backward compatibility, to make numeric
1958  data types return "binary" charset in client-side metadata.
1959  */
1960  virtual const CHARSET_INFO *charset_for_protocol() const {
1962  : &my_charset_bin;
1963  }
1964 
1965  /**
1966  Traverses a tree of Items in prefix and/or postfix order.
1967  Optionally walks into subqueries.
1968 
1969  @param processor processor function to be invoked per item
1970  returns true to abort traversal, false to continue
1971  @param walk controls how to traverse the item tree
1972  enum_walk::PREFIX: call processor before invoking
1973  children enum_walk::POSTFIX: call processor after invoking children
1974  enum_walk::SUBQUERY go down into subqueries
1975  walk values are bit-coded and may be combined.
1976  Omitting both enum_walk::PREFIX and enum_walk::POSTFIX
1977  is undefined behaviour.
1978  @param arg Optional pointer to a walk-specific object
1979 
1980  @retval false walk succeeded
1981  @retval true walk aborted
1982  by agreement, an error may have been reported
1983  */
1984 
1985  virtual bool walk(Item_processor processor,
1986  enum_walk walk MY_ATTRIBUTE((unused)), uchar *arg) {
1987  return (this->*processor)(arg);
1988  }
1989 
1990  /** @see WalkItem */
1991  template <class T>
1993  return (*reinterpret_cast<T *>(arg))(this);
1994  }
1995 
1996  /**
1997  Perform a generic transformation of the Item tree, by adding zero or
1998  more additional Item objects to it.
1999 
2000  @param transformer Transformer function
2001  @param[in,out] arg Pointer to struct used by transformer function
2002 
2003  @returns Returned item tree after transformation, NULL if error
2004 
2005  @details
2006 
2007  Transformation is performed as follows:
2008 
2009  transform()
2010  {
2011  transform children if any;
2012  return this->*some_transformer(...);
2013  }
2014 
2015  Note that unlike Item::compile(), transform() does not support an analyzer
2016  function, ie. all children are unconditionally invoked.
2017 
2018  @todo Let compile() handle all transformations during optimization, and
2019  let transform() handle transformations during preparation only.
2020  Then there would be no need to call change_item_tree() during
2021  transformation.
2022  */
2023  virtual Item *transform(Item_transformer transformer, uchar *arg);
2024 
2025  /**
2026  Perform a generic "compilation" of the Item tree, ie transform the Item tree
2027  by adding zero or more Item objects to it.
2028 
2029  @param analyzer Analyzer function, see details section
2030  @param[in,out] arg_p Pointer to struct used by analyzer function
2031  @param transformer Transformer function, see details section
2032  @param[in,out] arg_t Pointer to struct used by transformer function
2033 
2034  @returns Returned item tree after transformation, NULL if error
2035 
2036  @details
2037 
2038  The process of this transformation is assumed to be as follows:
2039 
2040  compile()
2041  {
2042  if (this->*some_analyzer(...))
2043  {
2044  compile children if any;
2045  return this->*some_transformer(...);
2046  }
2047  else
2048  return this;
2049  }
2050 
2051  i.e. analysis is performed top-down while transformation is done
2052  bottom-up. If no transformation is applied, the item is returned unchanged.
2053  A transformation error is indicated by returning a NULL pointer. Notice
2054  that the analyzer function should never cause an error.
2055 
2056  The function is supposed to be used during the optimization stage of
2057  query execution. All new allocations are recorded using
2058  THD::change_item_tree() so that they can be rolled back after execution.
2059 
2060  @todo Pass THD to compile() function, thus no need to use current_thd.
2061  */
2062  virtual Item *compile(Item_analyzer analyzer, uchar **arg_p,
2063  Item_transformer transformer, uchar *arg_t) {
2064  if ((this->*analyzer)(arg_p)) return ((this->*transformer)(arg_t));
2065  return this;
2066  }
2067 
2068  virtual void traverse_cond(Cond_traverser traverser, void *arg,
2069  traverse_order) {
2070  (*traverser)(this, arg);
2071  }
2072 
2073  /*
2074  This is used to get the most recent version of any function in
2075  an item tree. The version is the version where a MySQL function
2076  was introduced in. So any function which is added should use
2077  this function and set the int_arg to maximum of the input data
2078  and their own version info.
2079  */
2080  virtual bool intro_version(uchar *) { return false; }
2081 
2082  /// cleanup() item if it is resolved ('fixed').
2084  if (fixed) cleanup();
2085  return false;
2086  }
2087 
2088  virtual bool collect_item_field_processor(uchar *) { return false; }
2089 
2090  /**
2091  Item::walk function. Set bit in table->tmp_set for all fields in
2092  table 'arg' that are referred to by the Item.
2093  */
2094  virtual bool add_field_to_set_processor(uchar *) { return false; }
2095 
2096  /// A processor to handle the select lex visitor framework.
2097  virtual bool visitor_processor(uchar *arg);
2098 
2099  /**
2100  Item::walk function. Set bit in table->cond_set for all fields of
2101  all tables that are referred to by the Item.
2102  */
2103  virtual bool add_field_to_cond_set_processor(uchar *) { return false; }
2104 
2105  /**
2106  Visitor interface for removing all column expressions (Item_field) in
2107  this expression tree from a bitmap. @see walk()
2108 
2109  @param arg A MY_BITMAP* cast to unsigned char*, where the bits represent
2110  Field::field_index values.
2111  */
2112  virtual bool remove_column_from_bitmap(uchar *arg MY_ATTRIBUTE((unused))) {
2113  return false;
2114  }
2115  virtual bool find_item_in_field_list_processor(uchar *) { return false; }
2116  virtual bool change_context_processor(uchar *) { return false; }
2117  virtual bool find_item_processor(uchar *arg) { return this == (void *)arg; }
2119  return !basic_const_item();
2120  }
2121  /// Is this an Item_field which references the given Field argument?
2122  virtual bool find_field_processor(uchar *) { return false; }
2123  /// Wrap incompatible arguments in CAST nodes to the expected data types
2124  virtual bool cast_incompatible_args(uchar *) { return false; }
2125  /**
2126  Mark underlying field in read or write map of a table.
2127 
2128  @param arg Mark_field object
2129  */
2130  virtual bool mark_field_in_map(uchar *arg MY_ATTRIBUTE((unused))) {
2131  return false;
2132  }
2133  /**
2134  @returns true if the expression contains a reference to
2135  an expression of the SELECT list of the given query block.
2136  @param arg query block to search in.
2137  */
2138  virtual bool references_select_expr_of(uchar *arg MY_ATTRIBUTE((unused))) {
2139  return false;
2140  }
2141 
2142  protected:
2143  /**
2144  Helper function for mark_field_in_map(uchar *arg).
2145 
2146  @param mark_field Mark_field object
2147  @param field Field to be marked for read/write
2148  */
2149  static inline bool mark_field_in_map(Mark_field *mark_field, Field *field) {
2150  TABLE *table = mark_field->table;
2151  if (table != NULL && table != field->table) return false;
2152 
2153  table = field->table;
2154  table->mark_column_used(field, mark_field->mark);
2155 
2156  return false;
2157  }
2158 
2159  public:
2160  /**
2161  Reset execution state for such window function types
2162  as determined by arg
2163 
2164  @param arg pointing to a bool which, if true, says to reset state
2165  for framing window function, else for non-framing
2166  */
2167  virtual bool reset_wf_state(uchar *arg MY_ATTRIBUTE((unused))) {
2168  return false;
2169  }
2170 
2171  /**
2172  Return used table information for the specified query block (level).
2173  For a field that is resolved from this query block, return the table number.
2174  For a field that is resolved from a query block outer to the specified one,
2175  return OUTER_REF_TABLE_BIT
2176 
2177  @param[in,out] arg pointer to an instance of class Used_tables, which is
2178  constructed with the query block as argument.
2179  The used tables information is accumulated in the field
2180  used_tables in this class.
2181 
2182  @note This function is used to update used tables information after
2183  merging a query block (a subquery) with its parent.
2184  */
2185  virtual bool used_tables_for_level(uchar *arg MY_ATTRIBUTE((unused))) {
2186  return false;
2187  }
2188  /**
2189  Check privileges.
2190 
2191  @param thd thread handle
2192  */
2193  virtual bool check_column_privileges(uchar *thd MY_ATTRIBUTE((unused))) {
2194  return false;
2195  }
2196  virtual bool inform_item_in_cond_of_tab(uchar *) { return false; }
2197 
2199  /**
2200  Pointer to Cleanup_after_removal_context containing from which
2201  select the walk started, i.e., the SELECT_LEX that contained the clause
2202  that was removed.
2203  */
2205 
2207  };
2208  /**
2209  Clean up after removing the item from the item tree.
2210 
2211  @param arg pointer to a Cleanup_after_removal_context object
2212  */
2213  virtual bool clean_up_after_removal(uchar *arg MY_ATTRIBUTE((unused))) {
2214  return false;
2215  }
2216 
2217  /**
2218  Propagate components that use referenced columns from derived tables.
2219  Some columns from derived tables may be determined to be unused, but
2220  may actually reference other columns that are used. This function will
2221  return true for such columns when called with Item::walk(), which then
2222  means that this column can also be marked as used.
2223  @see also SELECT_LEX::delete_unused_merged_columns().
2224  */
2226 
2227  /**
2228  Called by Item::walk() to set all the referenced items' derived_used flag.
2229  */
2231  set_derived_used();
2232  return false;
2233  }
2234 
2235  /// @see Distinct_check::check_query()
2236  virtual bool aggregate_check_distinct(uchar *) { return false; }
2237  /// @see Group_check::check_query()
2238  virtual bool aggregate_check_group(uchar *) { return false; }
2239  /// @see Group_check::analyze_conjunct()
2240  virtual bool is_strong_side_column_not_in_fd(uchar *) { return false; }
2241  /// @see Group_check::is_in_fd_of_underlying()
2242  virtual bool is_column_not_in_fd(uchar *) { return false; }
2243  virtual Bool3 local_column(const SELECT_LEX *) const {
2244  return Bool3::false3();
2245  }
2246 
2247  /**
2248  Check if an aggregate is referenced from within the GROUP BY
2249  clause of the query block in which it is aggregated. Such
2250  references will be rejected.
2251  @see Item_ref::fix_fields()
2252  @retval true if this is an aggregate which is referenced from
2253  the GROUP BY clause of the aggregating query block
2254  @retval false otherwise
2255  */
2256  virtual bool has_aggregate_ref_in_group_by(uchar *) { return false; }
2257 
2258  virtual bool cache_const_expr_analyzer(uchar **cache_item);
2260 
2261  virtual bool equality_substitution_analyzer(uchar **) { return false; }
2262 
2263  virtual Item *equality_substitution_transformer(uchar *) { return this; }
2264 
2265  /**
2266  Check if a partition function is allowed.
2267 
2268  @return whether a partition function is not accepted
2269 
2270  @details
2271  check_partition_func_processor is used to check if a partition function
2272  uses an allowed function. An allowed function will always ensure that
2273  X=Y guarantees that also part_function(X)=part_function(Y) where X is
2274  a set of partition fields and so is Y. The problems comes mainly from
2275  character sets where two equal strings can be quite unequal. E.g. the
2276  german character for double s is equal to 2 s.
2277 
2278  The default is that an item is not allowed
2279  in a partition function. Allowed functions
2280  can never depend on server version, they cannot depend on anything
2281  related to the environment. They can also only depend on a set of
2282  fields in the table itself. They cannot depend on other tables and
2283  cannot contain any queries and cannot contain udf's or similar.
2284  If a new Item class is defined and it inherits from a class that is
2285  allowed in a partition function then it is very important to consider
2286  whether this should be inherited to the new class. If not the function
2287  below should be defined in the new Item class.
2288 
2289  The general behaviour is that most integer functions are allowed.
2290  If the partition function contains any multi-byte collations then
2291  the function check_part_func_fields will report an error on the
2292  partition function independent of what functions are used. So the
2293  only character sets allowed are single character collation and
2294  even for those only a limited set of functions are allowed. The
2295  problem with multi-byte collations is that almost every string
2296  function has the ability to change things such that two strings
2297  that are equal will not be equal after manipulated by a string
2298  function. E.g. two strings one contains a double s, there is a
2299  special german character that is equal to two s. Now assume a
2300  string function removes one character at this place, then in
2301  one the double s will be removed and in the other there will
2302  still be one s remaining and the strings are no longer equal
2303  and thus the partition function will not sort equal strings into
2304  the same partitions.
2305 
2306  So the check if a partition function is valid is two steps. First
2307  check that the field types are valid, next check that the partition
2308  function is valid. The current set of partition functions valid
2309  assumes that there are no multi-byte collations amongst the partition
2310  fields.
2311  */
2312  virtual bool check_partition_func_processor(uchar *) { return true; }
2313  virtual bool subst_argument_checker(uchar **arg) {
2314  if (*arg) *arg = NULL;
2315  return true;
2316  }
2317  virtual bool explain_subquery_checker(uchar **) { return true; }
2318  virtual Item *explain_subquery_propagator(uchar *) { return this; }
2319 
2320  virtual Item *equal_fields_propagator(uchar *) { return this; }
2321  virtual bool set_no_const_sub(uchar *) { return false; }
2322  virtual Item *replace_equal_field(uchar *) { return this; }
2323  /*
2324  Check if an expression value has allowed arguments, like DATE/DATETIME
2325  for date functions. Also used by partitioning code to reject
2326  timezone-dependent expressions in a (sub)partitioning function.
2327  */
2328  virtual bool check_valid_arguments_processor(uchar *) { return false; }
2329 
2330  /**
2331  Check if this item is allowed for a virtual column or inside a
2332  default expression. Should be overridden in child classes.
2333 
2334  @param[in,out] args Due to the limitation of Item::walk()
2335  it is declared as a pointer to uchar, underneath there's a actually a
2336  structure of type Check_function_as_value_generator_parameters.
2337  It is used mainly in Item_field.
2338 
2339  @returns true if function is not accepted
2340  */
2341  virtual bool check_function_as_value_generator(uchar *args);
2342 
2343  /**
2344  Check if a generated expression depends on DEFAULT function with
2345  specific column name as argument.
2346 
2347  @param[in] args Name of column used as DEFAULT function argument.
2348 
2349  @returns false if the function is not DEFAULT(args), otherwise true.
2350  */
2352  uchar *args MY_ATTRIBUTE((unused))) {
2353  return false;
2354  }
2355 
2356  /*
2357  For SP local variable returns pointer to Item representing its
2358  current value and pointer to current Item otherwise.
2359  */
2360  virtual Item *this_item() { return this; }
2361  virtual const Item *this_item() const { return this; }
2362 
2363  /*
2364  For SP local variable returns address of pointer to Item representing its
2365  current value and pointer passed via parameter otherwise.
2366  */
2367  virtual Item **this_item_addr(THD *, Item **addr_arg) { return addr_arg; }
2368 
2369  // Row emulation
2370  virtual uint cols() const { return 1; }
2371  virtual Item *element_index(uint) { return this; }
2372  virtual Item **addr(uint) { return 0; }
2373  virtual bool check_cols(uint c);
2374  // It is not row => null inside is impossible
2375  virtual bool null_inside() { return 0; }
2376  // used in row subselects to get value of elements
2377  virtual void bring_value() {}
2378 
2379  Field *tmp_table_field_from_field_type(TABLE *table, bool fixed_length);
2380  virtual Item_field *field_for_view_update() { return 0; }
2381  /**
2382  Informs an item that it is wrapped in a truth test, in case it wants to
2383  transforms itself to implement this test by itself.
2384  @param thd Thread handle
2385  @param test Truth test
2386  */
2387  virtual Item *truth_transformer(THD *thd MY_ATTRIBUTE((unused)),
2388  Bool_test test MY_ATTRIBUTE((unused))) {
2389  return nullptr;
2390  }
2391  virtual Item *update_value_transformer(uchar *) { return this; }
2392  virtual Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs);
2393  void delete_self() {
2394  cleanup();
2395  delete this;
2396  }
2397 
2398  /** @return whether the item is local to a stored procedure */
2399  virtual bool is_splocal() const { return false; }
2400 
2401  /*
2402  Return Settable_routine_parameter interface of the Item. Return 0
2403  if this Item is not Settable_routine_parameter.
2404  */
2406  return 0;
2407  }
2408  inline bool is_temporal_with_date() const {
2410  }
2411  inline bool is_temporal_with_date_and_time() const {
2413  }
2414  inline bool is_temporal_with_time() const {
2416  }
2417  inline bool is_temporal() const {
2419  }
2420  /**
2421  Check whether this and the given item has compatible comparison context.
2422  Used by the equality propagation. See Item_field::equal_fields_propagator.
2423 
2424  @return
2425  true if the context is the same or if fields could be
2426  compared as DATETIME values by the Arg_comparator.
2427  false otherwise.
2428  */
2429  inline bool has_compatible_context(Item *item) const {
2430  /* Same context. */
2432  return true;
2433  /* DATETIME comparison context. */
2434  if (is_temporal_with_date())
2435  return item->is_temporal_with_date() ||
2436  item->cmp_context == STRING_RESULT;
2437  if (item->is_temporal_with_date())
2439  return false;
2440  }
2442  return Field::GEOM_GEOMETRY;
2443  }
2444  String *check_well_formed_result(String *str, bool send_error, bool truncate);
2445  bool eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO *cs);
2446 
2447  /*
2448  Test whether an expression is expensive to compute. Used during
2449  optimization to avoid computing expensive expressions during this
2450  phase. Also used to force temp tables when sorting on expensive
2451  functions.
2452  TODO:
2453  Normally we should have a method:
2454  cost Item::execution_cost(),
2455  where 'cost' is either 'double' or some structure of various cost
2456  parameters.
2457  */
2458  virtual bool is_expensive() {
2459  if (is_expensive_cache < 0)
2462  return is_expensive_cache;
2463  }
2464 
2465  /**
2466  @return maximum number of characters that this Item can store
2467  If Item is of string or blob type, return max string length in bytes
2468  divided by bytes per character, otherwise return max_length.
2469  @todo - check if collation for other types should have mbmaxlen = 1
2470  */
2472  /*
2473  Length of e.g. 5.5e5 in an expression such as GREATEST(5.5e5, '5') is 5
2474  (length of that string) although length of the actual value is 6.
2475  Return MAX_DOUBLE_STR_LENGTH to prevent truncation of data without having
2476  to evaluate the value of the item.
2477  */
2478  uint32 max_len =
2480  if (result_type() == STRING_RESULT)
2481  return max_len / collation.collation->mbmaxlen;
2482  return max_len;
2483  }
2484 
2485  inline void fix_char_length(uint32 max_char_length_arg) {
2486  max_length = char_to_byte_length_safe(max_char_length_arg,
2488  }
2489 
2490  /*
2491  Return true if the item points to a column of an outer-joined table.
2492  */
2493  virtual bool is_outer_field() const {
2494  DBUG_ASSERT(fixed);
2495  return false;
2496  }
2497 
2498  /**
2499  Check if an item either is a blob field, or will be represented as a BLOB
2500  field if a field is created based on this item.
2501 
2502  @retval true If a field based on this item will be a BLOB field,
2503  @retval false Otherwise.
2504  */
2505  bool is_blob_field() const;
2506 
2507  protected:
2508  /// Set accumulated properties for an Item
2509  void set_accum_properties(const Item *item) {
2511  }
2512 
2513  /// Add more accumulated properties to an Item
2514  void add_accum_properties(const Item *item) {
2516  }
2517 
2518  /// Set the "has subquery" property
2520 
2521  /// Set the "has stored program" property
2523 
2524  public:
2525  /// @return true if this item or any of its decendents contains a subquery.
2526  bool has_subquery() const { return m_accum_properties & PROP_SUBQUERY; }
2527 
2528  /// @return true if this item or any of its decendents refers a stored func.
2529  bool has_stored_program() const {
2531  }
2532 
2533  /// @return true if this item or any of its decendents is an aggregated func.
2535 
2536  /// Set the "has aggregation" property
2538 
2539  /// Reset the "has aggregation" property
2541 
2542  /// @return true if this item or any of its decendents is a window func.
2544 
2545  /// Set the "has window function" property
2547 
2548  /**
2549  @return true if this item or any of its decendents within the same query
2550  has a reference to a ROLLUP expression
2551  */
2553 
2554  /// Set the property: this item (tree) contains a reference to a ROLLUP expr
2556 
2557  /**
2558  @return true if this item or any of underlying items is a GROUPING function
2559  */
2560  bool has_grouping_func() const {
2562  }
2563 
2564  /// Set the property: this item is a call to GROUPING
2566 
2567  /// Whether this Item was created by the IN->EXISTS subquery transformation
2568  virtual bool created_by_in2exists() const { return false; }
2569 
2570  // @return true if an expression in select list of derived table is used
2571  bool is_derived_used() const { return derived_used; }
2572 
2574  if (has_subquery())
2576  }
2577 
2578  /**
2579  Analyzer function for GC substitution. @see substitute_gc()
2580  */
2581  virtual bool gc_subst_analyzer(uchar **) { return false; }
2582  /**
2583  Transformer function for GC substitution. @see substitute_gc()
2584  */
2585  virtual Item *gc_subst_transformer(uchar *) { return this; }
2586 
2587  /**
2588  A processor that replaces any Fields with a Create_field_wrapper. This
2589  will allow us to resolve functions during CREATE TABLE, where we only have
2590  Create_field available and not Field. Used for functional index
2591  implementation.
2592  */
2593  virtual bool replace_field_processor(uchar *) { return false; }
2594  /**
2595  Check if this item is of a type that is eligible for GC
2596  substitution. All items that belong to subclasses of Item_func are
2597  eligible for substitution. @see substitute_gc()
2598  */
2600  const Type t = type();
2601  return t == FUNC_ITEM || t == COND_ITEM;
2602  }
2603 
2604  void aggregate_decimal_properties(Item **item, uint nitems);
2605  void aggregate_float_properties(Item **item, uint nitems);
2606  void aggregate_char_length(Item **args, uint nitems);
2607  void aggregate_temporal_properties(Item **item, uint nitems);
2608  bool aggregate_string_properties(const char *name, Item **item, uint nitems);
2609  void aggregate_num_type(Item_result result_type, Item **item, uint nitems);
2610 
2611  /**
2612  This function applies only to Item_field objects referred to by an Item_ref
2613  object that has been marked as a const_item.
2614 
2615  @param arg Keep track of whether an Item_ref refers to an Item_field.
2616  */
2617  virtual bool repoint_const_outer_ref(uchar *arg MY_ATTRIBUTE((unused))) {
2618  return false;
2619  }
2620  virtual Field *get_orig_field() { return NULL; }
2621  virtual void set_orig_field(Field *) {}
2622  virtual bool strip_db_table_name_processor(uchar *) { return false; }
2623 
2624  private:
2625  virtual bool subq_opt_away_processor(uchar *) { return false; }
2626 
2627  // Set an expression from select list of derived table as used.
2628  void set_derived_used() { derived_used = true; }
2629 
2630  public: // Start of data fields
2631  /**
2632  Intrusive list pointer for free list. If not null, points to the next
2633  Item on some Query_arena's free list. For instance, stored procedures
2634  have their own Query_arena's.
2635 
2636  @see Query_arena::free_list
2637  */
2639 
2640  protected:
2641  /// str_values's main purpose is to cache the value in save_in_field
2643 
2644  public:
2645  /**
2646  Character set and collation properties assigned for this Item.
2647  Used if Item represents a character string expression.
2648  */
2650  Item_name_string item_name; ///< Name from query
2651  Item_name_string orig_name; ///< Original item name (if it was renamed)
2652  /**
2653  Maximum length of result of evaluating this item, in number of bytes.
2654  - For character or blob data types, max char length multiplied by max
2655  character size (collation.mbmaxlen).
2656  - For decimal type, it is the precision in digits plus sign (unless
2657  unsigned) plus decimal point (unless it has zero decimals).
2658  - For other numeric types, the default or specific display length.
2659  - For date/time types, the display length (10 for DATE, 10 + optional FSP
2660  for TIME, 19 + optional fsp for datetime/timestamp).
2661  - For bit, the number of bits.
2662  - For enum, the string length of the widest enum element.
2663  - For set, the sum of the string length of each set element plus separators.
2664  - For geometry, the maximum size of a BLOB (it's underlying storage type).
2665  - For json, the maximum size of a BLOB (it's underlying storage type).
2666  */
2667  uint32 max_length; ///< Maximum length, in bytes
2668  enum item_marker ///< Values for member 'marker'
2675  /**
2676  This member has several successive meanings, depending on the phase we're
2677  in:
2678  - when doing constant propagation (e.g. change_cond_ref_to_const(), to
2679  remember that we have already processed the item).
2680  - when creating an internal temporary table: says how to store BIT fields
2681  - when analyzing functional dependencies for only_full_group_by (says
2682  whether a nullable column can be treated at not nullable)
2683  - when we change DISTINCT to GROUP BY: used for book-keeping of
2684  fields.
2685  - when pushing index conditions: it says whether a condition uses only
2686  indexed columns.
2687  The important property is that a phase must have a value (or few values)
2688  which is reserved for this phase. If it wants to set "marked", it assigns
2689  the value; it it wants to test if it is marked, it tests marker !=
2690  value. If the value has been assigned and the phase wants to cancel it can
2691  set marker to MARKER_NONE, which is a magic number which no phase
2692  reserves.
2693  A phase can expect 'marker' to be MARKER_NONE at the start of execution of
2694  a normal statement, at the start of preparation of a PS, and at the start
2695  of execution of a PS.
2696  A phase should not expect marker's value to survive after the phase's
2697  end - as a following phase may change it.
2698  */
2700  Item_result cmp_context; ///< Comparison context
2701  private:
2702  const bool is_parser_item; ///< true if allocated directly by parser
2703  /*
2704  If this item was created in runtime memroot, it cannot be used for
2705  substitution in subquery transformation process
2706  */
2708  int8 is_expensive_cache; ///< Cache of result of is_expensive()
2709  uint8 m_data_type; ///< Data type assigned to Item
2710  public:
2711  bool fixed; ///< True if item has been resolved
2712  /**
2713  Number of decimals in result when evaluating this item
2714  - For integer type, always zero.
2715  - For decimal type, number of decimals.
2716  - For float type, it may be DECIMAL_NOT_SPECIFIED
2717  - For time, datetime and timestamp, number of decimals in fractional second
2718  - For string types, may be decimals of cast source or DECIMAL_NOT_SPECIFIED
2719  */
2721  /**
2722  True if this item may be null.
2723 
2724  For items that represent rows, it is true if one of the columns
2725  may be null.
2726 
2727  For items that represent scalar or row subqueries, it is true if
2728  one of the returned columns could be null, or if the subquery
2729  could return zero rows.
2730  */
2732  bool null_value; ///< True if item is null
2734  bool m_is_window_function; ///< True if item represents window func
2735  private:
2736  /**
2737  True if this is an expression from the select list of a derived table
2738  which is actually used by outer query.
2739  */
2741 
2742  protected:
2743  /**
2744  Set of properties that are calculated by accumulation from underlying items.
2745  Computed by constructors and fix_fields() and updated by
2746  update_used_tables(). The properties are accumulated up to the root of the
2747  current item tree, except they are not accumulated across subqueries and
2748  functions.
2749  */
2750  static constexpr uint8 PROP_SUBQUERY = 0x01;
2751  static constexpr uint8 PROP_STORED_PROGRAM = 0x02;
2752  static constexpr uint8 PROP_AGGREGATION = 0x04;
2753  static constexpr uint8 PROP_WINDOW_FUNCTION = 0x08;
2754  /**
2755  Set if the item or one or more of the underlying items contains a
2756  ROLLUP expression. The rolled up expression itself is not so marked.
2757  */
2758  static constexpr uint8 PROP_ROLLUP_EXPR = 0x10;
2759  /**
2760  Set if the item or one or more of the underlying items is a GROUPING
2761  function.
2762  */
2763  static constexpr uint8 PROP_GROUPING_FUNC = 0x20;
2765 
2766  public:
2767  /**
2768  Noop in Item for items that are not subclasses of Item_ident.
2769  Overridden in Item_ident where it sets the
2770  table_name member. Signture matches the requirement of
2771  Item::walk.
2772 
2773  @return true - to signal that walk should continue to sub items.
2774  */
2775  virtual bool set_table_name(uchar *) { return true; }
2776 
2777  /**
2778  Check if this expression can be used for partial update of a given
2779  JSON column.
2780 
2781  For example, the expression `JSON_REPLACE(col, '$.foo', 'bar')`
2782  can be used to partially update the column `foo`.
2783 
2784  @param field the JSON column that is being updated
2785  @return true if this expression can be used for partial update,
2786  false otherwise
2787  */
2789  const Field_json *field MY_ATTRIBUTE((unused))) const {
2790  return false;
2791  }
2792 
2793  /**
2794  Whether the item returns array of its data type
2795  */
2796  virtual bool returns_array() const { return false; }
2797 
2798  /**
2799  A helper funciton to ensure proper usage of CAST(.. AS .. ARRAY)
2800  */
2801  virtual void allow_array_cast() {}
2802 };
2803 
2804 /**
2805  Descriptor of what and how to cache for
2806  Item::cache_const_expr_transformer/analyzer.
2807 
2808 */
2809 
2811  /// Path from the expression's top to the current item in item tree
2812  /// used to track parent of current item for caching JSON data
2814  /// Item to cache. Used as a binary flag, but kept as Item* for assertion
2815  Item *cache_item{nullptr};
2816  /// How to cache JSON data. @see Item::enum_const_item_cache
2818 };
2819 
2820 /**
2821  A helper class to give in a functor to Item::walk(). Use as e.g.:
2822 
2823  bool result = WalkItem(root_item, enum_walk::POSTFIX, [](Item *item) { ... });
2824 
2825  TODO: Make Item::walk() just take in a functor in the first place, instead of
2826  a pointer-to-member and an opaque argument.
2827  */
2828 template <class T>
2829 inline bool WalkItem(Item *item, enum_walk walk, T &&functor) {
2830  return item->walk(&Item::walk_helper_thunk<T>, walk,
2831  reinterpret_cast<uchar *>(&functor));
2832 }
2833 
2834 class sp_head;
2835 
2836 class Item_basic_constant : public Item {
2838 
2839  public:
2841  explicit Item_basic_constant(const POS &pos) : Item(pos), used_table_map(0) {}
2842 
2843  /// @todo add implementation of basic_const_item
2844  /// and remove from subclasses as appropriate.
2845 
2847  table_map used_tables() const override { return used_table_map; }
2848  bool check_function_as_value_generator(uchar *) override { return false; }
2849  /* to prevent drop fixed flag (no need parent cleanup call) */
2850  void cleanup() override {
2851  /*
2852  Restore the original field name as it might not have been allocated
2853  in the statement memory. If the name is auto generated, it must be
2854  done again between subsequent executions of a prepared statement.
2855  */
2857  }
2858  bool basic_const_item() const override { return true; }
2859  void set_str_value(String *str) { str_value = *str; }
2860 };
2861 
2862 /*****************************************************************************
2863  The class is a base class for representation of stored routine variables in
2864  the Item-hierarchy. There are the following kinds of SP-vars:
2865  - local variables (Item_splocal);
2866  - CASE expression (Item_case_expr);
2867 *****************************************************************************/
2868 
2869 class Item_sp_variable : public Item {
2870  protected:
2871  /*
2872  THD, which is stored in fix_fields() and is used in this_item() to avoid
2873  current_thd use.
2874  */
2876 
2877  public:
2879 
2880  public:
2881 #ifndef DBUG_OFF
2882  /*
2883  Routine to which this Item_splocal belongs. Used for checking if correct
2884  runtime context is used for variable handling.
2885  */
2887 #endif
2888 
2889  public:
2890  Item_sp_variable(const Name_string sp_var_name);
2891 
2892  public:
2893  bool fix_fields(THD *thd, Item **) override;
2894 
2895  double val_real() override;
2896  longlong val_int() override;
2897  String *val_str(String *sp) override;
2898  my_decimal *val_decimal(my_decimal *decimal_value) override;
2899  bool val_json(Json_wrapper *result) override;
2900  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
2901  bool get_time(MYSQL_TIME *ltime) override;
2902  bool is_null() override;
2903 
2904  public:
2905  inline void make_field(Send_field *field) override;
2906  bool send(Protocol *protocol, String *str) override {
2907  // Need to override send() in case this_item() is an Item_field with a
2908  // ZEROFILL attribute.
2909  return this_item()->send(protocol, str);
2910  }
2911 
2912  protected:
2914  Field *field, bool no_conversions) override;
2915 };
2916 
2917 /*****************************************************************************
2918  Item_sp_variable inline implementation.
2919 *****************************************************************************/
2920 
2922  Item *it = this_item();
2924  it->make_field(field);
2925 }
2926 
2928  Field *field, bool no_conversions) {
2929  return this_item()->save_in_field(field, no_conversions);
2930 }
2931 
2932 /*****************************************************************************
2933  A reference to local SP variable (incl. reference to SP parameter), used in
2934  runtime.
2935 *****************************************************************************/
2936 
2938  private Settable_routine_parameter {
2940 
2943 
2944  public:
2945  /*
2946  If this variable is a parameter in LIMIT clause.
2947  Used only during NAME_CONST substitution, to not append
2948  NAME_CONST to the resulting query and thus not break
2949  the slave.
2950  */
2952  /*
2953  Position of this reference to SP variable in the statement (the
2954  statement itself is in sp_instr_stmt::m_query).
2955  This is valid only for references to SP variables in statements,
2956  excluding DECLARE CURSOR statement. It is used to replace references to SP
2957  variables with NAME_CONST calls when putting statements into the binary
2958  log.
2959  Value of 0 means that this object doesn't corresponding to reference to
2960  SP variable in query text.
2961  */
2963  /*
2964  Byte length of SP variable name in the statement (see pos_in_query).
2965  The value of this field may differ from the name_length value because
2966  name_length contains byte length of UTF8-encoded item name, but
2967  the query string (see sp_instr_stmt::m_query) is currently stored with
2968  a charset from the SET NAMES statement.
2969  */
2971 
2972  Item_splocal(const Name_string sp_var_name, uint sp_var_idx,
2973  enum_field_types sp_var_type, uint pos_in_q = 0,
2974  uint len_in_q = 0);
2975 
2976  bool is_splocal() const override { return true; }
2977 
2978  Item *this_item() override;
2979  const Item *this_item() const override;
2980  Item **this_item_addr(THD *thd, Item **) override;
2981 
2982  void print(const THD *thd, String *str,
2983  enum_query_type query_type) const override;
2984 
2985  public:
2986  inline uint get_var_idx() const { return m_var_idx; }
2987 
2988  inline enum Type type() const override { return m_type; }
2989  inline Item_result result_type() const override { return m_result_type; }
2990  bool val_json(Json_wrapper *result) override;
2991 
2992  private:
2993  bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
2994 
2995  public:
2997  return this;
2998  }
2999 };
3000 
3001 /*****************************************************************************
3002  A reference to case expression in SP, used in runtime.
3003 *****************************************************************************/
3004 
3006  public:
3007  Item_case_expr(uint case_expr_id);
3008 
3009  public:
3010  Item *this_item() override;
3011  const Item *this_item() const override;
3012  Item **this_item_addr(THD *thd, Item **) override;
3013 
3014  Type type() const override { return this_item()->type(); }
3015  Item_result result_type() const override {
3016  return this_item()->result_type();
3017  }
3018 
3019  public:
3020  /*
3021  NOTE: print() is intended to be used from views and for debug.
3022  Item_case_expr can not occur in views, so here it is only for debug
3023  purposes.
3024  */
3025  void print(const THD *thd, String *str,
3026  enum_query_type query_type) const override;
3027 
3028  private:
3030 };
3031 
3032 /*
3033  NAME_CONST(given_name, const_value).
3034  This 'function' has all properties of the supplied const_value (which is
3035  assumed to be a literal constant), and the name given_name.
3036 
3037  This is used to replace references to SP variables when we write PROCEDURE
3038  statements into the binary log.
3039 
3040  TODO
3041  Together with Item_splocal and Item::this_item() we can actually extract
3042  common a base of this class and Item_splocal. Maybe it is possible to
3043  extract a common base with class Item_ref, too.
3044 */
3045 
3046 class Item_name_const final : public Item {
3047  typedef Item super;
3048 
3052 
3053  public:
3054  Item_name_const(const POS &pos, Item *name_arg, Item *val);
3055 
3056  bool itemize(Parse_context *pc, Item **res) override;
3057  bool fix_fields(THD *, Item **) override;
3058 
3059  enum Type type() const override;
3060  double val_real() override;
3061  longlong val_int() override;
3062  String *val_str(String *sp) override;
3063  my_decimal *val_decimal(my_decimal *) override;
3064  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3065  bool get_time(MYSQL_TIME *ltime) override;
3066  bool is_null() override;
3067  void print(const THD *thd, String *str,
3068  enum_query_type query_type) const override;
3069 
3070  Item_result result_type() const override { return value_item->result_type(); }
3071 
3072  bool cache_const_expr_analyzer(uchar **) override {
3073  // Item_name_const always wraps a literal, so there is no need to cache it.
3074  return false;
3075  }
3076 
3077  protected:
3079  bool no_conversions) override {
3080  return value_item->save_in_field(field, no_conversions);
3081  }
3082 };
3083 
3085  Item **items, uint nitems, uint flags);
3086 bool agg_item_set_converter(DTCollation &coll, const char *fname, Item **args,
3087  uint nargs, uint flags, int item_sep);
3088 bool agg_item_charsets(DTCollation &c, const char *name, Item **items,
3089  uint nitems, uint flags, int item_sep);
3091  const char *name, Item **items,
3092  uint nitems, int item_sep = 1) {
3095  return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3096 }
3098  Item **items, uint nitems,
3099  int item_sep = 1) {
3102  return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3103 }
3105  DTCollation &c, const char *name, Item **items, uint nitems,
3106  int item_sep = 1) {
3109  return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3110 }
3111 
3114 
3115  public:
3116  Item_num() { collation.set_numeric(); } /* Remove gcc warning */
3117  explicit Item_num(const POS &pos) : super(pos) { collation.set_numeric(); }
3118 
3119  virtual Item_num *neg() = 0;
3120  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3121  bool check_partition_func_processor(uchar *) override { return false; }
3122 };
3123 
3124 #define NO_CACHED_FIELD_INDEX ((uint)(-1))
3125 
3126 class Item_ident : public Item {
3127  typedef Item super;
3128 
3129  protected:
3130  /*
3131  We have to store initial values of db_name, table_name and field_name
3132  to be able to restore them during cleanup() because they can be
3133  updated during fix_fields() to values from Field object and life-time
3134  of those is shorter than life-time of Item_field.
3135  */
3136  const char *orig_db_name;
3137  const char *orig_table_name;
3138  const char *orig_field_name;
3139  bool m_alias_of_expr; ///< if this Item's name is alias of SELECT expression
3140 
3141  public:
3142  /**
3143  For regularly resolved column references, 'context' points to a name
3144  resolution context object belonging to the query block which simply
3145  contains the reference. To further clarify, in
3146  SELECT (SELECT t.a) FROM t;
3147  t.a is an Item_ident whose 'context' belongs to the subquery
3148  (context->select_lex == that of the subquery).
3149  For column references that are part of a generated column expression,
3150  'context' points to a temporary name resolution context object during
3151  resolving, but is set to nullptr after resolving is done. Note that
3152  Item_ident::local_column() depends on that.
3153  */
3155  const char *db_name;
3156  const char *table_name;
3157  const char *field_name;
3158 
3159  /*
3160  Cached value of index for this field in table->field array, used by prep.
3161  stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX
3162  if index value is not known.
3163  */
3165  /*
3166  Cached pointer to table which contains this field, used for the same reason
3167  by prep. stmt. too in case then we have not-fully qualified field.
3168  0 - means no cached value.
3169  @todo Notice that this is usually the same as Item_field::table_ref.
3170  cached_table should be replaced by table_ref ASAP.
3171  */
3174 
3175  Item_ident(Name_resolution_context *context_arg, const char *db_name_arg,
3176  const char *table_name_arg, const char *field_name_arg)
3177  : orig_db_name(db_name_arg),
3178  orig_table_name(table_name_arg),
3179  orig_field_name(field_name_arg),
3181  context(context_arg),
3182  db_name(db_name_arg),
3183  table_name(table_name_arg),
3184  field_name(field_name_arg),
3186  cached_table(NULL),
3187  depended_from(NULL) {
3188  item_name.set(field_name_arg);
3189  }
3190 
3191  Item_ident(const POS &pos, const char *db_name_arg,
3192  const char *table_name_arg, const char *field_name_arg)
3193  : super(pos),
3194  orig_db_name(db_name_arg),
3195  orig_table_name(table_name_arg),
3196  orig_field_name(field_name_arg),
3198  db_name(db_name_arg),
3199  table_name(table_name_arg),
3200  field_name(field_name_arg),
3202  cached_table(NULL),
3203  depended_from(NULL) {
3204  item_name.set(field_name_arg);
3205  }
3206 
3207  /// Constructor used by Item_field & Item_*_ref (see Item comment)
3208 
3210  : Item(thd, item),
3211  orig_db_name(item->orig_db_name),
3215  context(item->context),
3216  db_name(item->db_name),
3217  table_name(item->table_name),
3218  field_name(item->field_name),
3220  cached_table(item->cached_table),
3221  depended_from(item->depended_from) {}
3222 
3223  bool itemize(Parse_context *pc, Item **res) override;
3224 
3225  const char *full_name() const override;
3226  void fix_after_pullout(SELECT_LEX *parent_select,
3227  SELECT_LEX *removed_select) override;
3228  void cleanup() override;
3229  bool aggregate_check_distinct(uchar *arg) override;
3230  bool aggregate_check_group(uchar *arg) override;
3231  Bool3 local_column(const SELECT_LEX *sl) const override;
3232 
3233  void print(const THD *thd, String *str,
3234  enum_query_type query_type) const override {
3235  print(thd, str, query_type, db_name, table_name);
3236  }
3237 
3238  /**
3239  Assign the argument to table_name. Argument passed as uchar* to
3240  match requirement of Item::walk.
3241 
3242  @param tn new table_name (should be pointer to const char)
3243  @return true - to signal that walk should continue to sub items.
3244  */
3245  bool set_table_name(uchar *tn) override final {
3246  table_name = pointer_cast<const char *>(tn);
3247  return true;
3248  }
3249 
3250  protected:
3251  /**
3252  Function to print column name for a table
3253 
3254  To print a column for a permanent table (picks up database and table from
3255  Item_ident object):
3256 
3257  item->print(str, qt)
3258 
3259  To print a column for a temporary table:
3260 
3261  item->print(str, qt, specific_db, specific_table)
3262 
3263  Items of temporary table fields have empty/NULL values of table_name and
3264  db_name. To print column names in a 3D form (`database`.`table`.`column`),
3265  this function prints db_name_arg and table_name_arg parameters instead of
3266  this->db_name and this->table_name respectively.
3267 
3268  @param thd Thread handle.
3269  @param [out] str Output string buffer.
3270  @param query_type Bitmap to control printing details.
3271  @param db_name_arg String to output as a column database name.
3272  @param table_name_arg String to output as a column table name.
3273  */
3274  void print(const THD *thd, String *str, enum_query_type query_type,
3275  const char *db_name_arg, const char *table_name_arg) const;
3276 
3277  public:
3278  bool change_context_processor(uchar *cntx) override {
3279  context = reinterpret_cast<Name_resolution_context *>(cntx);
3280  return false;
3281  }
3282 
3283  /// @returns true if this Item's name is alias of SELECT expression
3284  bool is_alias_of_expr() const { return m_alias_of_expr; }
3285  /// Marks that this Item's name is alias of SELECT expression
3287 
3288  bool walk(Item_processor processor, enum_walk walk, uchar *arg) override {
3289  /*
3290  Item_ident processors like aggregate_check*() use
3291  enum_walk::PREFIX|enum_walk::POSTFIX and depend on the processor being
3292  called twice then.
3293  */
3294  return ((walk & enum_walk::PREFIX) && (this->*processor)(arg)) ||
3295  ((walk & enum_walk::POSTFIX) && (this->*processor)(arg));
3296  }
3297 
3298  /**
3299  @returns true if a part of this Item's full name (name or table name) is
3300  an alias.
3301  */
3302  virtual bool alias_name_used() const { return m_alias_of_expr; }
3303  friend bool insert_fields(THD *thd, Name_resolution_context *context,
3304  const char *db_name, const char *table_name,
3305  List_iterator<Item> *it, bool any_privileges);
3306  bool is_strong_side_column_not_in_fd(uchar *arg) override;
3307  bool is_column_not_in_fd(uchar *arg) override;
3308 };
3309 
3311  public:
3313  const char *db_name;
3314  const char *table_name;
3315 
3316  Item_ident_for_show(Field *par_field, const char *db_arg,
3317  const char *table_name_arg)
3318  : field(par_field), db_name(db_arg), table_name(table_name_arg) {}
3319 
3320  enum Type type() const override { return FIELD_ITEM; }
3321  virtual bool fix_fields(THD *thd, Item **ref) override;
3322  double val_real() override { return field->val_real(); }
3323  longlong val_int() override { return field->val_int(); }
3324  String *val_str(String *str) override { return field->val_str(str); }
3326  return field->val_decimal(dec);
3327  }
3328  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
3329  return field->get_date(ltime, fuzzydate);
3330  }
3331  bool get_time(MYSQL_TIME *ltime) override { return field->get_time(ltime); }
3332  void make_field(Send_field *tmp_field) override;
3333  const CHARSET_INFO *charset_for_protocol() const override {
3334  return field->charset_for_protocol();
3335  }
3336 };
3337 
3338 class COND_EQUAL;
3339 class Item_equal;
3340 
3341 class Item_field : public Item_ident {
3343 
3344  protected:
3345  void set_field(Field *field);
3347  bool no_conversions) override;
3348 
3349  public:
3350  /**
3351  Table containing this resolved field. This is required e.g for calculation
3352  of table map. Notice that for the following types of "tables",
3353  no TABLE_LIST object is assigned and hence table_ref is NULL:
3354  - Temporary tables assigned by join optimizer for sorting and aggregation.
3355  - Stored procedure dummy tables.
3356  For fields referencing such tables, table number is always 0, and other
3357  uses of table_ref is not needed.
3358  */
3360  /// Source field
3362  /**
3363  Item's original field. Used to compare fields in Item_field::eq() in order
3364  to get proper result when field is transformed by tmp table.
3365  */
3367  /// Result field
3371  /*
3372  if any_privileges set to true then here real effective privileges will
3373  be stored
3374  */
3376  /* field need any privileges (for VIEW creation) */
3378  /*
3379  if this field is used in a context where covering prefix keys
3380  are supported.
3381  */
3382  bool can_use_prefix_key{false};
3383 
3384  Item_field(Name_resolution_context *context_arg, const char *db_arg,
3385  const char *table_name_arg, const char *field_name_arg);
3386  Item_field(const POS &pos, const char *db_arg, const char *table_name_arg,
3387  const char *field_name_arg);
3388 
3389  /*
3390  Constructor needed to process subquery with temporary tables (see Item).
3391  Notice that it will have no name resolution context.
3392  */
3393  Item_field(THD *thd, Item_field *item);
3394  /*
3395  Ensures that field, table, and database names will live as long as
3396  Item_field (this is important in prepared statements).
3397  */
3398  Item_field(THD *thd, Name_resolution_context *context_arg, Field *field);
3399  /*
3400  If this constructor is used, fix_fields() won't work, because
3401  db_name, table_name and column_name are unknown. It's necessary to call
3402  reset_field() before fix_fields() for all fields created this way.
3403  */
3405 
3406  bool itemize(Parse_context *pc, Item **res) override;
3407 
3408  enum Type type() const override { return FIELD_ITEM; }
3409  bool eq(const Item *item, bool binary_cmp) const override;
3410  double val_real() override;
3411  longlong val_int() override;
3412  longlong val_time_temporal() override;
3413  longlong val_date_temporal() override;
3414  my_decimal *val_decimal(my_decimal *) override;
3415  String *val_str(String *) override;
3416  bool val_json(Json_wrapper *result) override;
3417  bool send(Protocol *protocol, String *str_arg) override;
3418  void reset_field(Field *f);
3419  bool fix_fields(THD *, Item **) override;
3420  void make_field(Send_field *tmp_field) override;
3421  void save_org_in_field(Field *field) override;
3422  table_map used_tables() const override;
3423  enum Item_result result_type() const override { return field->result_type(); }
3426  }
3427  Item_result cast_to_int_type() const override {
3428  return field->cast_to_int_type();
3429  }
3432  }
3433  longlong val_int_endpoint(bool left_endp, bool *incl_endp) override;
3434  Field *get_tmp_table_field() override { return result_field; }
3435  Field *tmp_table_field(TABLE *) override { return result_field; }
3436  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3437  bool get_time(MYSQL_TIME *ltime) override;
3438  bool get_timeval(struct timeval *tm, int *warnings) override;
3439  bool is_null() override {
3440  // NOTE: May return true even if maybe_null is not set!
3441  // This can happen if the underlying TABLE did not have a NULL row
3442  // at set_field() time (ie., table->is_null_row() was false),
3443  // but does now.
3444  return field->is_null();
3445  }
3446  Item *get_tmp_table_item(THD *thd) override;
3447  bool collect_item_field_processor(uchar *arg) override;
3448  bool add_field_to_set_processor(uchar *arg) override;
3449  bool add_field_to_cond_set_processor(uchar *) override;
3450  bool remove_column_from_bitmap(uchar *arg) override;
3451  bool find_item_in_field_list_processor(uchar *arg) override;
3452  bool find_field_processor(uchar *arg) override {
3453  return pointer_cast<Field *>(arg) == field;
3454  }
3455  bool check_function_as_value_generator(uchar *args) override;
3456  bool mark_field_in_map(uchar *arg) override {
3457  auto mark_field = pointer_cast<Mark_field *>(arg);
3458  bool rc = Item::mark_field_in_map(mark_field, field);
3459  if (result_field && result_field != field)
3460  rc |= Item::mark_field_in_map(mark_field, result_field);
3461  return rc;
3462  }
3463  bool used_tables_for_level(uchar *arg) override;
3464  bool check_column_privileges(uchar *arg) override;
3465  bool check_partition_func_processor(uchar *) override { return false; }
3466  void cleanup() override;
3467  Item_equal *find_item_equal(COND_EQUAL *cond_equal) const;
3468  bool subst_argument_checker(uchar **arg) override;
3469  Item *equal_fields_propagator(uchar *arg) override;
3470  bool set_no_const_sub(uchar *) override;
3471  Item *replace_equal_field(uchar *) override;
3473  Item_field *field_for_view_update() override { return this; }
3474  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3475  int fix_outer_field(THD *thd, Field **field, Item **reference);
3476  Item *update_value_transformer(uchar *select_arg) override;
3477  void print(const THD *thd, String *str,
3478  enum_query_type query_type) const override;
3479  bool is_outer_field() const override {
3480  DBUG_ASSERT(fixed);
3482  }
3485  return field->get_geometry_type();
3486  }
3487  const CHARSET_INFO *charset_for_protocol(void) const override {
3488  return field->charset_for_protocol();
3489  }
3490 
3491 #ifndef DBUG_OFF
3492  void dbug_print() const {
3493  fprintf(DBUG_FILE, "<field ");
3494  if (field) {
3495  fprintf(DBUG_FILE, "'%s.%s': ", field->table->alias, field->field_name);
3496  field->dbug_print();
3497  } else
3498  fprintf(DBUG_FILE, "NULL");
3499 
3500  fprintf(DBUG_FILE, ", result_field: ");
3501  if (result_field) {
3502  fprintf(DBUG_FILE, "'%s.%s': ", result_field->table->alias,
3505  } else
3506  fprintf(DBUG_FILE, "NULL");
3507  fprintf(DBUG_FILE, ">\n");
3508  }
3509 #endif
3510 
3511  float get_filtering_effect(THD *thd, table_map filter_for_table,
3512  table_map read_tables,
3513  const MY_BITMAP *fields_to_ignore,
3514  double rows_in_table) override;
3515 
3516  /**
3517  Returns the probability for the predicate "col OP <val>" to be
3518  true for a row in the case where no index statistics or range
3519  estimates are available for 'col'.
3520 
3521  The probability depends on the number of rows in the table: it is by
3522  default 'default_filter', but never lower than 1/max_distinct_values
3523  (e.g. number of rows in the table, or the number of distinct values
3524  possible for the datatype if the field provides that kind of
3525  information).
3526 
3527  @param max_distinct_values The maximum number of distinct values,
3528  typically the number of rows in the table
3529  @param default_filter The default filter for the predicate
3530 
3531  @return the estimated filtering effect for this predicate
3532  */
3533 
3534  float get_cond_filter_default_probability(double max_distinct_values,
3535  float default_filter) const;
3536 
3537  friend class Item_default_value;
3538  friend class Item_insert_value;
3539  friend class SELECT_LEX_UNIT;
3540 
3541  /**
3542  @note that field->table->alias_name_used is reliable only if
3543  thd->lex->need_correct_ident() is true.
3544  */
3545  bool alias_name_used() const override {
3546  return m_alias_of_expr ||
3547  // maybe the qualifying table was given an alias ("t1 AS foo"):
3549  }
3550 
3551  bool repoint_const_outer_ref(uchar *arg) override;
3552  Field *get_orig_field() override { return orig_field; }
3553  void set_orig_field(Field *orig_field_arg) override {
3554  if (orig_field_arg) orig_field = orig_field_arg;
3555  }
3556  bool returns_array() const override { return field && field->is_array(); }
3557 
3558  void set_can_use_prefix_key() override { can_use_prefix_key = true; }
3559 
3560  bool replace_field_processor(uchar *arg) override;
3561  bool strip_db_table_name_processor(uchar *) override;
3562 };
3563 
3566 
3567  void init() {
3568  maybe_null = true;
3569  null_value = true;
3571  max_length = 0;
3572  fixed = true;
3574  }
3575 
3576  protected:
3578  bool no_conversions) override;
3579 
3580  public:
3582  init();
3583  item_name = NAME_STRING("NULL");
3584  }
3585  explicit Item_null(const POS &pos) : super(pos) {
3586  init();
3587  item_name = NAME_STRING("NULL");
3588  }
3589 
3590  Item_null(const Name_string &name_par) {
3591  init();
3592  item_name = name_par;
3593  }
3594 
3595  enum Type type() const override { return NULL_ITEM; }
3596  bool eq(const Item *item, bool binary_cmp) const override;
3597  double val_real() override;
3598  longlong val_int() override;
3599  longlong val_time_temporal() override { return val_int(); }
3600  longlong val_date_temporal() override { return val_int(); }
3601  String *val_str(String *str) override;
3602  my_decimal *val_decimal(my_decimal *) override;
3603  bool get_date(MYSQL_TIME *, my_time_flags_t) override { return true; }
3604  bool get_time(MYSQL_TIME *) override { return true; }
3605  bool val_json(Json_wrapper *wr) override;
3606  bool send(Protocol *protocol, String *str) override;
3607  enum Item_result result_type() const override { return STRING_RESULT; }
3608  Item *clone_item() const override { return new Item_null(item_name); }
3609  bool is_null() override { return true; }
3610 
3611  void print(const THD *, String *str,
3612  enum_query_type query_type) const override {
3613  str->append(query_type == QT_NORMALIZED_FORMAT ? "?" : "NULL");
3614  }
3615 
3616  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3617  bool check_partition_func_processor(uchar *) override { return false; }
3618 };
3619 
3620 /**
3621  An item representing NULL values for use with ROLLUP.
3622 
3623  When grouping WITH ROLLUP, Item_null_result items are created to
3624  represent NULL values in the grouping columns of the ROLLUP rows. To
3625  avoid type problems during execution, these objects are created with
3626  the same field and result types as the fields of the columns they
3627  belong to.
3628  */
3630  /** Result type for this NULL value */
3632 
3633  public:
3637  set_data_type(fld_type);
3638  }
3639  void set_result_field(Field *field) override { result_field = field; }
3640  bool is_result_field() const override { return result_field != nullptr; }
3641  Field *get_result_field() const override { return result_field; }
3642  void save_in_result_field(bool no_conversions) override {
3643  save_in_field(result_field, no_conversions);
3644  }
3645  bool check_partition_func_processor(uchar *) override { return true; }
3646  Item_result result_type() const override { return res_type; }
3650  func_arg->banned_function_name = "NULL";
3651  // This should not happen as SELECT statements are not allowed.
3652  DBUG_ASSERT(false);
3653  return true;
3654  }
3655  enum Type type() const override { return NULL_RESULT_ITEM; }
3656 };
3657 
3658 /// Placeholder ('?') of prepared statement.
3660  typedef Item super;
3661 
3662  protected:
3664  bool no_conversions) override;
3665 
3666  public:
3676  } state;
3677 
3678  /*
3679  A buffer for string and long data values. Historically all allocated
3680  values returned from val_str() were treated as eligible to
3681  modification. I. e. in some cases Item_func_concat can append it's
3682  second argument to return value of the first one. Because of that we
3683  can't return the original buffer holding string data from val_str(),
3684  and have to have one buffer for data and another just pointing to
3685  the data. This is the latter one and it's returned from val_str().
3686  Can not be declared inside the union as it's not a POD type.
3687  */
3690  union {
3692  double real;
3693  /*
3694  Character sets conversion info for string values.
3695  Character sets of client and connection defined at bind time are used
3696  for all conversions, even if one of them is later changed (i.e.
3697  between subsequent calls to mysql_stmt_execute).
3698  */
3699  struct CONVERSION_INFO {
3702  /*
3703  This points at character set of connection if conversion
3704  to it is required (i. e. if placeholder typecode is not BLOB).
3705  Otherwise it's equal to character_set_client (to simplify
3706  check in convert_str_value()).
3707  */
3709  } cs_info;
3711  } value;
3712 
3713  /* Cached values for virtual methods to save us one switch. */
3716 
3717  /*
3718  data_type() is used when this item is used in a temporary table.
3719  This is NOT placeholder metadata sent to client, as this value
3720  is assigned after sending metadata (in setup_one_conversion_function).
3721  For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both
3722  in result set and placeholders metadata, no matter what type you will
3723  supply for this placeholder in mysql_stmt_execute.
3724  */
3725 
3726  /*
3727  Offset of placeholder inside statement text. Used to create
3728  no-placeholders version of this statement for the binary log.
3729  */
3731 
3732  Item_param(const POS &pos, MEM_ROOT *root, uint pos_in_query_arg);
3733 
3734  bool itemize(Parse_context *pc, Item **item) override;
3735 
3736  enum Item_result result_type() const override { return item_result_type; }
3737  enum Type type() const override { return item_type; }
3738 
3739  double val_real() override;
3740  longlong val_int() override;
3741  my_decimal *val_decimal(my_decimal *) override;
3742  String *val_str(String *) override;
3743  bool get_time(MYSQL_TIME *tm) override;
3744  bool get_date(MYSQL_TIME *tm, my_time_flags_t fuzzydate) override;
3745 
3746  void set_null();
3747  void set_int(longlong i, uint32 max_length_arg);
3748  void set_double(double i);
3749  void set_decimal(const char *str, ulong length);
3750  void set_decimal(const my_decimal *dv);
3751  bool set_str(const char *str, size_t length);
3752  bool set_longdata(const char *str, ulong length);
3754  uint32 max_length_arg);
3755  bool set_from_user_var(THD *thd, const user_var_entry *entry);
3756  void reset();
3757  /*
3758  Assign placeholder value from bind data.
3759  */
3760  void (*set_param_func)(Item_param *param, uchar **pos, ulong len);
3761 
3762  const String *query_val_str(const THD *thd, String *str) const;
3763 
3764  bool convert_str_value();
3765 
3766  /*
3767  Parameter is treated as constant during execution, thus it will not be
3768  evaluated during preparation.
3769  */
3770  table_map used_tables() const override {
3771  return state != NO_VALUE ? 0 : INNER_TABLE_BIT;
3772  }
3773  void print(const THD *thd, String *str,
3774  enum_query_type query_type) const override;
3775  bool is_null() override {
3777  return state == NULL_VALUE;
3778  }
3779  bool basic_const_item() const override {
3780  if (state == NO_VALUE || state == TIME_VALUE) return false;
3781  return true;
3782  }
3783 
3784  /*
3785  This method is used to make a copy of a basic constant item when
3786  propagating constants in the optimizer. The reason to create a new
3787  item and not use the existing one is not precisely known (2005/04/16).
3788  Probably we are trying to preserve tree structure of items, in other
3789  words, avoid pointing at one item from two different nodes of the tree.
3790  Return a new basic constant item if parameter value is a basic
3791  constant, assert otherwise. This method is called only if
3792  basic_const_item returned true.
3793  */
3794  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3795  Item *clone_item() const override;
3796  /*
3797  Implement by-value equality evaluation if parameter value
3798  is set and is a basic constant (integer, real or string).
3799  Otherwise return false.
3800  */
3801  bool eq(const Item *item, bool binary_cmp) const override;
3802  /** Item is a argument to a limit clause. */
3805  bool is_non_const_over_literals(uchar *) override { return true; }
3806  /**
3807  This should be called after any modification done to this Item, to
3808  propagate the said modification to all its clones.
3809  */
3810  void sync_clones();
3811  bool add_clone(Item_param *i) { return m_clones.push_back(i); }
3812 
3813  private:
3815  return this;
3816  }
3817 
3818  bool set_value(THD *, sp_rcontext *, Item **it) override;
3819 
3820  void set_out_param_info(Send_field *info) override;
3821 
3822  public:
3823  const Send_field *get_out_param_info() const override;
3824 
3825  void make_field(Send_field *field) override;
3826 
3830  func_arg->err_code = func_arg->get_unnamed_function_error_code();
3831  return true;
3832  }
3833 
3834  private:
3836  /**
3837  If a query expression's text QT, containing a parameter, is internally
3838  duplicated and parsed twice (@see reparse_common_table_expression), the
3839  first parsing will create an Item_param I, and the re-parsing, which
3840  parses a forged "(QT)" parse-this-CTE type of statement, will create an
3841  Item_param J. J should not exist:
3842  - from the point of view of logging: it is not in the original query so it
3843  should not be substituted in the query written to logs (in insert_params()
3844  if with_log is true).
3845  - from the POV of the user:
3846  * user provides one single value for I, not one for I and one for J.
3847  * user expects mysql_stmt_param_count() to return 1, not 2 (count is
3848  sent by the server in send_prep_stmt()).
3849  That is why J is part neither of LEX::param_list, nor of param_array; it
3850  is considered an inferior clone of I; I::m_clones contains J.
3851  The connection between I and J is made once, by comparing their
3852  byte position in the statement, in Item_param::itemize().
3853  J gets its value from I: @see Item_param::sync_clones.
3854  */
3856 };
3857 
3858 class Item_int : public Item_num {
3859  typedef Item_num super;
3860 
3861  public:
3864  : value((longlong)i) {
3866  max_length = length;
3867  fixed = true;
3868  }
3870  : super(pos), value((longlong)i) {
3872  max_length = length;
3873  fixed = true;
3874  }
3877  max_length = length;
3878  fixed = true;
3879  }
3881  : value((longlong)i) {
3883  max_length = length;
3884  fixed = true;
3885  unsigned_flag = true;
3886  }
3887  Item_int(const Item_int *item_arg) {
3888  set_data_type(item_arg->data_type());
3889  value = item_arg->value;
3890  item_name = item_arg->item_name;
3891  max_length = item_arg->max_length;
3892  fixed = true;
3893  }
3894  Item_int(const Name_string &name_arg, longlong i, uint length) : value(i) {
3896  max_length = length;
3897  item_name = name_arg;
3898  fixed = true;
3899  }
3900  Item_int(const POS &pos, const Name_string &name_arg, longlong i, uint length)
3901  : super(pos), value(i) {
3903  max_length = length;
3904  item_name = name_arg;
3905  fixed = true;
3906  }
3907  Item_int(const char *str_arg, uint length) {
3909  init(str_arg, length);
3910  }
3911  Item_int(const POS &pos, const char *str_arg, uint length) : super(pos) {
3913  init(str_arg, length);
3914  }
3915 
3916  Item_int(const POS &pos, const LEX_STRING &num, int dummy_error = 0)
3917  : Item_int(pos, num, my_strtoll10(num.str, NULL, &dummy_error),
3918  static_cast<uint>(num.length)) {}
3919 
3920  private:
3921  void init(const char *str_arg, uint length);
3922 
3923  protected:
3925  bool no_conversions) override;
3926 
3927  public:
3928  enum Type type() const override { return INT_ITEM; }
3929  enum Item_result result_type() const override { return INT_RESULT; }
3930  longlong val_int() override {
3931  DBUG_ASSERT(fixed);
3932  return value;
3933  }
3934  double val_real() override {
3935  DBUG_ASSERT(fixed);
3936  return static_cast<double>(value);
3937  }
3938  my_decimal *val_decimal(my_decimal *) override;
3939  String *val_str(String *) override;
3940  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
3941  return get_date_from_int(ltime, fuzzydate);
3942  }
3943  bool get_time(MYSQL_TIME *ltime) override { return get_time_from_int(ltime); }
3944  Item *clone_item() const override { return new Item_int(this); }
3945  void print(const THD *thd, String *str,
3946  enum_query_type query_type) const override;
3947  Item_num *neg() override {
3948  value = -value;
3949  return this;
3950  }
3951  uint decimal_precision() const override {
3952  return (uint)(max_length - (value < 0));
3953  }
3954  bool eq(const Item *, bool) const override;
3955  bool check_partition_func_processor(uchar *) override { return false; }
3956  bool check_function_as_value_generator(uchar *) override { return false; }
3957 };
3958 
3959 /**
3960  Item_int with value==0 and length==1
3961 */
3962 class Item_int_0 final : public Item_int {
3963  public:
3964  Item_int_0() : Item_int(NAME_STRING("0"), 0, 1) {}
3965  explicit Item_int_0(const POS &pos) : Item_int(pos, NAME_STRING("0"), 0, 1) {}
3966 };
3967 
3968 /*
3969  Item_temporal is used to store numeric representation
3970  of time/date/datetime values for queries like:
3971 
3972  WHERE datetime_column NOT IN
3973  ('2006-04-25 10:00:00','2006-04-25 10:02:00', ...);
3974 
3975  and for SHOW/INFORMATION_SCHEMA purposes (see sql_show.cc)
3976 
3977  TS-TODO: Can't we use Item_time_literal, Item_date_literal,
3978  TS-TODO: and Item_datetime_literal for this purpose?
3979 */
3980 class Item_temporal final : public Item_int {
3981  protected:
3983  bool no_conversions) override;
3984 
3985  public:
3987  DBUG_ASSERT(is_temporal_type(field_type_arg));
3988  set_data_type(field_type_arg);
3989  }
3990  Item_temporal(enum_field_types field_type_arg, const Name_string &name_arg,
3991  longlong i, uint length)
3992  : Item_int(i) {
3993  DBUG_ASSERT(is_temporal_type(field_type_arg));
3994  set_data_type(field_type_arg);
3995  max_length = length;
3996  item_name = name_arg;
3997  fixed = true;
3998  }
3999  Item *clone_item() const override {
4000  return new Item_temporal(data_type(), value);
4001  }
4002  longlong val_time_temporal() override { return val_int(); }
4003  longlong val_date_temporal() override { return val_int(); }
4005  DBUG_ASSERT(0);
4006  return false;
4007  }
4008  bool get_time(MYSQL_TIME *) override {
4009  DBUG_ASSERT(0);
4010  return false;
4011  }
4012 };
4013 
4014 class Item_uint : public Item_int {
4015  protected:
4017  bool no_conversions) override;
4018 
4019  public:
4020  Item_uint(const char *str_arg, uint length) : Item_int(str_arg, length) {
4021  unsigned_flag = 1;
4022  }
4023  Item_uint(const POS &pos, const char *str_arg, uint length)
4024  : Item_int(pos, str_arg, length) {
4025  unsigned_flag = 1;
4026  }
4027 
4030  : Item_int(name_arg, i, length) {
4031  unsigned_flag = true;
4032  }
4033  double val_real() override {
4034  DBUG_ASSERT(fixed);
4035  return ulonglong2double(static_cast<ulonglong>(value));
4036  }
4037  String *val_str(String *) override;
4038 
4039  Item *clone_item() const override {
4040  return new Item_uint(item_name, value, max_length);
4041  }
4042  void print(const THD *thd, String *str,
4043  enum_query_type query_type) const override;
4044  Item_num *neg() override;
4045  uint decimal_precision() const override { return max_length; }
4046 };
4047 
4048 /* decimal (fixed point) constant */
4049 class Item_decimal : public Item_num {
4050  typedef Item_num super;
4051 
4052  protected:
4055  bool no_conversions) override;
4056 
4057  public:
4058  Item_decimal(const POS &pos, const char *str_arg, uint length,
4059  const CHARSET_INFO *charset);
4060  Item_decimal(const Name_string &name_arg, const my_decimal *val_arg,
4061  uint decimal_par, uint length);
4062  Item_decimal(my_decimal *value_par);
4063  Item_decimal(longlong val, bool unsig);
4064  Item_decimal(double val);
4065  Item_decimal(const uchar *bin, int precision, int scale);
4066 
4067  enum Type type() const override { return DECIMAL_ITEM; }
4068  enum Item_result result_type() const override { return DECIMAL_RESULT; }
4069  longlong val_int() override;
4070  double val_real() override;
4071  String *val_str(String *) override;
4073  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4074  return get_date_from_decimal(ltime, fuzzydate);
4075  }
4076  bool get_time(MYSQL_TIME *ltime) override {
4077  return get_time_from_decimal(ltime);
4078  }
4079  Item *clone_item() const override {
4081  }
4082  void print(const THD *thd, String *str,
4083  enum_query_type query_type) const override;
4084  Item_num *neg() override {
4087  return this;
4088  }
4089  uint decimal_precision() const override { return decimal_value.precision(); }
4090  bool eq(const Item *, bool binary_cmp) const override;
4091  void set_decimal_value(const my_decimal *value_par);
4092  bool check_partition_func_processor(uchar *) override { return false; }
4093 };
4094 
4095 class Item_float : public Item_num {
4096  typedef Item_num super;
4097 
4099 
4100  public:
4101  double value;
4102  // Item_real() :value(0) {}
4103  Item_float(const char *str_arg, uint length) { init(str_arg, length); }
4104  Item_float(const POS &pos, const char *str_arg, uint length) : super(pos) {
4105  init(str_arg, length);
4106  }
4107 
4108  Item_float(const Name_string name_arg, double val_arg, uint decimal_par,
4109  uint length)
4110  : value(val_arg) {
4111  presentation = name_arg;
4112  item_name = name_arg;
4114  decimals = (uint8)decimal_par;
4115  max_length = length;
4116  fixed = 1;
4117  }
4118  Item_float(const POS &pos, const Name_string name_arg, double val_arg,
4119  uint decimal_par, uint length)
4120  : super(pos), value(val_arg) {
4121  presentation = name_arg;
4122  item_name = name_arg;
4124  decimals = (uint8)decimal_par;
4125  max_length = length;
4126  fixed = 1;
4127  }
4128 
4129  Item_float(double value_par, uint decimal_par) : value(value_par) {
4131  decimals = (uint8)decimal_par;
4132  max_length = float_length(decimal_par);
4133  fixed = 1;
4134  }
4135 
4136  private:
4137  void init(const char *str_arg, uint length);
4138 
4139  protected:
4141  bool no_conversions) override;
4142 
4143  public:
4144  enum Type type() const override { return REAL_ITEM; }
4145  double val_real() override {
4146  DBUG_ASSERT(fixed);
4147  return value;
4148  }
4149  longlong val_int() override {
4150  DBUG_ASSERT(fixed == 1);
4151  if (value <= (double)LLONG_MIN) {
4152  return LLONG_MIN;
4153  } else if (value >= (double)(ulonglong)LLONG_MAX) {
4154  return LLONG_MAX;
4155  }
4156  return (longlong)rint(value);
4157  }
4158  String *val_str(String *) override;
4159  my_decimal *val_decimal(my_decimal *) override;
4160  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4161  return get_date_from_real(ltime, fuzzydate);
4162  }
4163  bool get_time(MYSQL_TIME *ltime) override {
4164  return get_time_from_real(ltime);
4165  }
4166  Item *clone_item() const override {
4167  return new Item_float(item_name, value, decimals, max_length);
4168  }
4169  Item_num *neg() override {
4170  value = -value;
4171  return this;
4172  }
4173  void print(const THD *thd, String *str,
4174  enum_query_type query_type) const override;
4175  bool eq(const Item *, bool binary_cmp) const override;
4176 };
4177 
4178 class Item_func_pi : public Item_float {
4180 
4181  public:
4183  : Item_float(pos, null_name_string, M_PI, 6, 8),
4184  func_name(NAME_STRING("pi()")) {}
4185 
4186  void print(const THD *, String *str, enum_query_type) const override {
4187  str->append(func_name);
4188  }
4189 
4190  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4191 };
4192 
4195 
4196  protected:
4197  explicit Item_string(const POS &pos) : super(pos), m_cs_specified(false) {
4199  }
4200 
4201  void init(const char *str, size_t length, const CHARSET_INFO *cs,
4202  Derivation dv, uint repertoire) {
4205  collation.set(cs, dv, repertoire);
4206  /*
4207  We have to have a different max_length than 'length' here to
4208  ensure that we get the right length if we do use the item
4209  to create a new table. In this case max_length must be the maximum
4210  number of chars for a string of this type because we in Create_field::
4211  divide the max_length with mbmaxlen).
4212  */
4213  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4214  item_name.copy(str, length, cs);
4216  // it is constant => can be used without fix_fields (and frequently used)
4217  fixed = 1;
4218  /*
4219  Check if the string has any character that can't be
4220  interpreted using the relevant charset.
4221  */
4222  check_well_formed_result(&str_value, false, false);
4223  }
4225  bool no_conversions) override;
4226 
4227  public:
4228  /* Create from a string, set name from the string itself. */
4229  Item_string(const char *str, size_t length, const CHARSET_INFO *cs,
4231  uint repertoire = MY_REPERTOIRE_UNICODE30)
4232  : m_cs_specified(false) {
4233  init(str, length, cs, dv, repertoire);
4234  }
4235  Item_string(const POS &pos, const char *str, size_t length,
4237  uint repertoire = MY_REPERTOIRE_UNICODE30)
4238  : super(pos), m_cs_specified(false) {
4239  init(str, length, cs, dv, repertoire);
4240  }
4241 
4242  /* Just create an item and do not fill string representation */
4244  : m_cs_specified(false) {
4245  collation.set(cs, dv);
4247  max_length = 0;
4249  fixed = 1;
4250  }
4251 
4252  /* Create from the given name and string. */
4253  Item_string(const Name_string name_par, const char *str, size_t length,
4255  uint repertoire = MY_REPERTOIRE_UNICODE30)
4256  : m_cs_specified(false) {
4258  collation.set(cs, dv, repertoire);
4260  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4261  item_name = name_par;
4263  // it is constant => can be used without fix_fields (and frequently used)
4264  fixed = 1;
4265  }
4266  Item_string(const POS &pos, const Name_string name_par, const char *str,
4267  size_t length, const CHARSET_INFO *cs,
4269  uint repertoire = MY_REPERTOIRE_UNICODE30)
4270  : super(pos), m_cs_specified(false) {
4272  collation.set(cs, dv, repertoire);
4274  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4275  item_name = name_par;
4277  // it is constant => can be used without fix_fields (and frequently used)
4278  fixed = 1;
4279  }
4280 
4281  /* Create from the given name and string. */
4282  Item_string(const POS &pos, const Name_string name_par,
4283  const LEX_CSTRING &literal, const CHARSET_INFO *cs,
4285  uint repertoire = MY_REPERTOIRE_UNICODE30)
4286  : super(pos), m_cs_specified(false) {
4287  str_value.set_or_copy_aligned(literal.str ? literal.str : "",
4288  literal.str ? literal.length : 0, cs);
4289  collation.set(cs, dv, repertoire);
4291  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4292  item_name = name_par;
4294  // it is constant => can be used without fix_fields (and frequently used)
4295  fixed = 1;
4296  }
4297 
4298  /*
4299  This is used in stored procedures to avoid memory leaks and
4300  does a deep copy of its argument.
4301  */
4302  void set_str_with_copy(const char *str_arg, uint length_arg) {
4303  str_value.copy(str_arg, length_arg, collation.collation);
4304  max_length = static_cast<uint32>(str_value.numchars() *
4306  }
4310  }
4311  enum Type type() const override { return STRING_ITEM; }
4312  double val_real() override;
4313  longlong val_int() override;
4314  String *val_str(String *) override {
4315  DBUG_ASSERT(fixed == 1);
4316  return &str_value;
4317  }
4318  my_decimal *val_decimal(my_decimal *) override;
4319  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4320  return get_date_from_string(ltime, fuzzydate);
4321  }
4322  bool get_time(MYSQL_TIME *ltime) override {
4323  return get_time_from_string(ltime);
4324  }
4325  enum Item_result result_type() const override { return STRING_RESULT; }
4326  bool eq(const Item *item, bool binary_cmp) const override;
4327  Item *clone_item() const override {
4328  return new Item_string(static_cast<Name_string>(item_name), str_value.ptr(),
4330  }
4331  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4332  Item *charset_converter(THD *thd, const CHARSET_INFO *tocs, bool lossless);
4333  inline void append(char *str, size_t length) {
4334  str_value.append(str, length);
4335  max_length = static_cast<uint32>(str_value.numchars() *
4337  }
4338  void print(const THD *thd, String *str,
4339  enum_query_type query_type) const override;
4340  bool check_partition_func_processor(uchar *) override { return false; }
4341 
4342  /**
4343  Return true if character-set-introducer was explicitly specified in the
4344  original query for this item (text literal).
4345 
4346  This operation is to be called from Item_string::print(). The idea is
4347  that when a query is generated (re-constructed) from the Item-tree,
4348  character-set-introducers should appear only for those literals, where
4349  they were explicitly specified by the user. Otherwise, that may lead to
4350  loss collation information (character set introducers implies default
4351  collation for the literal).
4352 
4353  Basically, that makes sense only for views and hopefully will be gone
4354  one day when we start using original query as a view definition.
4355 
4356  @return This operation returns the value of m_cs_specified attribute.
4357  @retval true if character set introducer was explicitly specified in
4358  the original query.
4359  @retval false otherwise.
4360  */
4361  inline bool is_cs_specified() const { return m_cs_specified; }
4362 
4363  /**
4364  Set the value of m_cs_specified attribute.
4365 
4366  m_cs_specified attribute shows whether character-set-introducer was
4367  explicitly specified in the original query for this text literal or
4368  not. The attribute makes sense (is used) only for views.
4369 
4370  This operation is to be called from the parser during parsing an input
4371  query.
4372  */
4373  inline void set_cs_specified(bool cs_specified) {
4374  m_cs_specified = cs_specified;
4375  }
4376 
4378 
4379  private:
4381 };
4382 
4384  const char *cptr, const char *end);
4385 double double_from_string_with_check(const CHARSET_INFO *cs, const char *cptr,
4386  const char *end);
4387 
4390 
4391  public:
4392  Item_static_string_func(const Name_string &name_par, const char *str,
4393  size_t length, const CHARSET_INFO *cs,
4395  : Item_string(null_name_string, str, length, cs, dv),
4396  func_name(name_par) {}
4397  Item_static_string_func(const POS &pos, const Name_string &name_par,
4398  const char *str, size_t length,
4399  const CHARSET_INFO *cs,
4401  : Item_string(pos, null_name_string, str, length, cs, dv),
4402  func_name(name_par) {}
4403 
4404  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4405 
4406  void print(const THD *, String *str, enum_query_type) const override {
4407  str->append(func_name);
4408  }
4409 
4410  bool check_partition_func_processor(uchar *) override { return true; }
4414  func_arg->banned_function_name = func_name.ptr();
4415  return true;
4416  }
4417 };
4418 
4419 /* for show tables */
4421  public:
4423  const CHARSET_INFO *cs = NULL)
4424  : Item_string(name, NullS, 0, cs) {
4425  max_length = static_cast<uint32>(length);
4426  }
4427 };
4428 
4430  public:
4431  Item_blob(const char *name, size_t length)
4433  &my_charset_bin) {
4435  }
4436  enum Type type() const override { return TYPE_HOLDER; }
4440  func_arg->err_code = func_arg->get_unnamed_function_error_code();
4441  return true;
4442  }
4443 };
4444 
4445 /**
4446  Item_empty_string -- is a utility class to put an item into List<Item>
4447  which is then used in protocol.send_result_set_metadata() when sending SHOW
4448  output to the client.
4449 */
4450 
4452  public:
4453  Item_empty_string(const char *header, size_t length,
4454  const CHARSET_INFO *cs = NULL)
4455  : Item_partition_func_safe_string(Name_string(header, strlen(header)), 0,
4456  cs ? cs : &my_charset_utf8_general_ci) {
4457  max_length = static_cast<uint32>(length * collation.collation->mbmaxlen);
4458  }
4459  void make_field(Send_field *field) override;
4460 };
4461 
4462 class Item_return_int : public Item_int {
4463  public:
4464  Item_return_int(const char *name_arg, uint length,
4465  enum_field_types field_type_arg, longlong value_arg = 0)
4466  : Item_int(Name_string(name_arg, name_arg ? strlen(name_arg) : 0),
4467  value_arg, length) {
4468  set_data_type(field_type_arg);
4469  unsigned_flag = true;
4470  }
4471 };
4472 
4475 
4476  protected:
4478  bool no_conversions) override;
4479 
4480  public:
4481  Item_hex_string();
4482  explicit Item_hex_string(const POS &pos) : super(pos) {
4484  }
4485 
4486  Item_hex_string(const char *str, uint str_length);
4487  Item_hex_string(const POS &pos, const LEX_STRING &literal);
4488 
4489  enum Type type() const override { return VARBIN_ITEM; }
4490  double val_real() override {
4491  DBUG_ASSERT(fixed);
4492  return (double)(ulonglong)Item_hex_string::val_int();
4493  }
4494  longlong val_int() override;
4495  Item *clone_item() const override {
4496  return new Item_hex_string(str_value.ptr(), max_length);
4497  }
4498  String *val_str(String *) override {
4499  DBUG_ASSERT(fixed);
4500  return &str_value;
4501  }
4502  my_decimal *val_decimal(my_decimal *) override;
4503  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4504  return get_date_from_string(ltime, fuzzydate);
4505  }
4506  bool get_time(MYSQL_TIME *ltime) override {
4507  return get_time_from_string(ltime);
4508  }
4509  Item_result result_type() const override { return STRING_RESULT; }
4511  return INT_RESULT;
4512  }
4513  Item_result cast_to_int_type() const override { return INT_RESULT; }
4514  void print(const THD *thd, String *str,
4515  enum_query_type query_type) const override;
4516  bool eq(const Item *item, bool binary_cmp) const override;
4517  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4518  bool check_partition_func_processor(uchar *) override { return false; }
4519  static LEX_CSTRING make_hex_str(const char *str, size_t str_length);
4520 
4521  private:
4522  void hex_string_init(const char *str, uint str_length);
4523 };
4524 
4527 
4528  public:
4529  Item_bin_string(const char *str, size_t str_length) {
4530  bin_string_init(str, str_length);
4531  }
4532  Item_bin_string(const POS &pos, const LEX_STRING &literal) : super(pos) {
4533  bin_string_init(literal.str, literal.length);
4534  }
4535 
4536  static LEX_CSTRING make_bin_str(const char *str, size_t str_length);
4537 
4538  private:
4539  void bin_string_init(const char *str, size_t str_length);
4540 };
4541 
4542 /**
4543  Item with result field.
4544 
4545  It adds to an Item a "result_field" Field member. This is for an item which
4546  may have a result (e.g. Item_func), and may store this result into a field;
4547  usually this field is a column of an internal temporary table. So the
4548  function may be evaluated by save_in_field(), storing result into
4549  result_field in tmp table. Then this result can be copied from tmp table to
4550  a following tmp table (e.g. GROUP BY table then ORDER BY table), or to a row
4551  buffer and back, as we want to avoid multiple evaluations of the Item, first
4552  because of performance, second because that evaluation may have side
4553  effects, e.g. SLEEP, GET_LOCK, RAND, window functions doing
4554  accumulations...
4555  Item_field and Item_ref also have a "result_field" for a similar goal.
4556  Literals don't need such "result_field" as their value is readily
4557  available.
4558 */
4559 class Item_result_field : public Item {
4560  public:
4561  Field *result_field; /* Save result here */
4563  explicit Item_result_field(const POS &pos) : Item(pos), result_field(0) {}
4564 
4565  // Constructor used for Item_sum/Item_cond_and/or (see Item comment)
4567  : Item(thd, item), result_field(item->result_field) {}
4568  ~Item_result_field() override {} /* Required with gcc 2.95 */
4569  Field *get_tmp_table_field() override { return result_field; }
4570  Field *tmp_table_field(TABLE *) override { return result_field; }
4571  table_map used_tables() const override { return 1; }
4572 
4573  /**
4574  Resolve type-related information for this item, such as result field type,
4575  maximum size, precision, signedness, character set and collation.
4576  Also check compatibility of argument types and return error when applicable.
4577  Also adjust nullability when applicable.
4578 
4579  @param thd thread handler
4580  @returns false if success, true if error
4581  */
4582  virtual bool resolve_type(THD *thd) = 0;
4583 
4584  void set_result_field(Field *field) override { result_field = field; }
4585  bool is_result_field() const override { return true; }
4586  Field *get_result_field() const override { return result_field; }
4587  void save_in_result_field(bool no_conversions) override {
4588  DBUG_TRACE;
4589  save_in_field(result_field, no_conversions);
4590  return;
4591  }
4592 
4593  void cleanup() override;
4594  /*
4595  This method is used for debug purposes to print the name of an
4596  item to the debug log. The second use of this method is as
4597  a helper function of print() and error messages, where it is
4598  applicable. To suit both goals it should return a meaningful,
4599  distinguishable and syntactically correct string. This method
4600  should not be used for runtime type identification, use enum
4601  {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
4602  instead.
4603  Added here, to the parent class of both Item_func and Item_sum.
4604  */
4605  virtual const char *func_name() const = 0;
4606  bool check_function_as_value_generator(uchar *) override { return false; }
4607  bool mark_field_in_map(uchar *arg) override {
4608  bool rc = Item::mark_field_in_map(arg);
4609  if (result_field) // most likely result_field will be read too
4610  rc |= Item::mark_field_in_map(pointer_cast<Mark_field *>(arg),
4611  result_field);
4612  return rc;
4613  }
4614 
4616  if (realval < LLONG_MIN || realval > LLONG_MAX) {
4618  return error_int();
4619  }
4620  // Rounding error, llrint() may return LLONG_MIN.
4621  const longlong retval = realval == LLONG_MAX ? LLONG_MAX : llrint(realval);
4622  return retval;
4623  }
4624 
4625  void raise_numeric_overflow(const char *type_name);
4626 
4628  raise_numeric_overflow("DOUBLE");
4629  return 0.0;
4630  }
4631 
4633  raise_numeric_overflow(unsigned_flag ? "BIGINT UNSIGNED" : "BIGINT");
4634  return 0;
4635  }
4636 
4638  raise_numeric_overflow(unsigned_flag ? "DECIMAL UNSIGNED" : "DECIMAL");
4639  return E_DEC_OVERFLOW;
4640  }
4641 };
4642 
4643 class Item_ref : public Item_ident {
4644  protected:
4645  void set_properties();
4647  bool no_conversions) override;
4648 
4649  public:
4651  Field *result_field; /* Save result here */
4653 
4654  private:
4655  /**
4656  'ref' can be set (to non-NULL) in the constructor or afterwards.
4657  The second case means that we are doing resolution, possibly pointing
4658  'ref' to a non-permanent Item. To not have 'ref' become dangling at the
4659  end of execution, and to start clean for the resolution of the next
4660  execution, 'ref' must be restored to NULL. rollback_item_tree_changes()
4661  does not handle restoration of Item** values, so we need this dedicated
4662  Boolean.
4663  */
4664  const bool chop_ref;
4665 
4666  public:
4667  Item_ref(Name_resolution_context *context_arg, const char *db_arg,
4668  const char *table_name_arg, const char *field_name_arg)
4669  : Item_ident(context_arg, db_arg, table_name_arg, field_name_arg),
4670  result_field(0),
4671  ref(NULL),
4672  chop_ref(!ref) {}
4673  Item_ref(const POS &pos, const char *db_arg, const char *table_name_arg,
4674  const char *field_name_arg)
4675  : Item_ident(pos, db_arg, table_name_arg, field_name_arg),
<