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