MySQL  8.0.17
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(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 occurred.
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 {
687  return (*THR_MALLOC)->Alloc(size);
688  }
689  static void *operator new(size_t size, MEM_ROOT *mem_root,
690  const std::nothrow_t &arg MY_ATTRIBUTE((unused)) =
691  std::nothrow) noexcept {
692  return mem_root->Alloc(size);
693  }
694 
695  static void operator delete(void *ptr MY_ATTRIBUTE((unused)),
696  size_t size MY_ATTRIBUTE((unused))) {
697  TRASH(ptr, size);
698  }
699  static void operator delete(void *, MEM_ROOT *,
700  const std::nothrow_t &)noexcept {}
701 
702  enum Type {
733  };
734 
736 
738 
739  /// How to cache constant JSON data
741  /// Don't cache
743  /// Source data is a JSON string, parse and cache result
745  /// Source data is SQL scalar, convert and cache result
747  };
748 
749  enum Bool_test ///< Modifier for result transformation
750  { BOOL_IS_TRUE = 0x00,
757  BOOL_NEGATED = 0x07,
760  };
761 
762  /**
763  Provide data type for a user or system variable, based on the type of
764  the item that is assigned to the variable.
765 
766  @note MYSQL_TYPE_VARCHAR is returned for all string types, but must be
767  further adjusted based on maximum string length by the caller.
768 
769  @param src_type Source type that variable's type is derived from
770  */
772  switch (src_type) {
773  case MYSQL_TYPE_TINY:
774  case MYSQL_TYPE_SHORT:
775  case MYSQL_TYPE_INT24:
776  case MYSQL_TYPE_LONG:
777  case MYSQL_TYPE_LONGLONG:
778  return MYSQL_TYPE_LONGLONG;
779  case MYSQL_TYPE_DECIMAL:
781  return MYSQL_TYPE_NEWDECIMAL;
782  case MYSQL_TYPE_FLOAT:
783  case MYSQL_TYPE_DOUBLE:
784  return MYSQL_TYPE_DOUBLE;
785  case MYSQL_TYPE_VARCHAR:
787  case MYSQL_TYPE_STRING:
788  return MYSQL_TYPE_VARCHAR;
789  case MYSQL_TYPE_YEAR:
790  return MYSQL_TYPE_LONGLONG;
792  case MYSQL_TYPE_DATE:
793  case MYSQL_TYPE_TIME:
794  case MYSQL_TYPE_DATETIME:
795  case MYSQL_TYPE_NEWDATE:
796  case MYSQL_TYPE_BIT:
799  case MYSQL_TYPE_TIME2:
800  case MYSQL_TYPE_JSON:
801  case MYSQL_TYPE_ENUM:
802  case MYSQL_TYPE_SET:
803  case MYSQL_TYPE_GEOMETRY:
804  case MYSQL_TYPE_NULL:
806  case MYSQL_TYPE_BLOB:
809  return MYSQL_TYPE_VARCHAR;
810  default:
811  DBUG_ASSERT(false);
812  return MYSQL_TYPE_NULL;
813  }
814  }
815 
816  /// Item constructor for general use.
817  Item();
818 
819  /**
820  Constructor used by Item_field, Item_ref & aggregate functions.
821  Used for duplicating lists in processing queries with temporary tables.
822 
823  Also used for Item_cond_and/Item_cond_or for creating top AND/OR structure
824  of WHERE clause to protect it of optimisation changes in prepared statements
825  */
826  Item(THD *thd, Item *item);
827 
828  /**
829  Parse-time context-independent constructor.
830 
831  This constructor and caller constructors of child classes must not
832  access/change thd->lex (including thd->lex->current_select(),
833  thd->m_parser_state etc structures).
834 
835  If we need to finalize the construction of the object, then we move
836  all context-sensitive code to the itemize() virtual function.
837 
838  The POS parameter marks this constructor and other context-independent
839  constructors of child classes for easy recognition/separation from other
840  (context-dependent) constructors.
841  */
842  explicit Item(const POS &);
843 
844  virtual ~Item() override {
845 #ifdef EXTRA_DEBUG
846  item_name.set(0);
847 #endif
848  } /*lint -e1509 */
849 
850  private:
851  /*
852  Hide the contextualize*() functions: call/override the itemize()
853  in Item class tree instead.
854 
855  Note: contextualize_() is an intermediate function. Remove it together
856  with Parse_tree_node::contextualize_().
857  */
858  bool contextualize(Parse_context *) override {
859  DBUG_ASSERT(0);
860  return true;
861  }
862  bool contextualize_(Parse_context *) override {
863  DBUG_ASSERT(0);
864  return true;
865  }
866 
867  protected:
868  /**
869  Helper function to skip itemize() for grammar-allocated items
870 
871  @param [out] res pointer to "this"
872 
873  @retval true can skip itemize()
874  @retval false can't skip: the item is allocated directly by the parser
875  */
876  bool skip_itemize(Item **res) {
877  *res = this;
878  return !is_parser_item;
879  }
880 
881  /*
882  Checks if the function should return binary result based on the items
883  provided as parameter.
884  Function should only be used by Item_bit_func*
885 
886  @param a item to check
887  @param b item to check, may be nullptr
888 
889  @returns true if binary result.
890  */
891  static bool bit_func_returns_binary(const Item *a, const Item *b);
892 
893  public:
894  /**
895  The same as contextualize()/contextualize_() but with additional parameter
896 
897  This function finalize the construction of Item objects (see the Item(POS)
898  constructor): we can access/change parser contexts from the itemize()
899  function.
900 
901  @param pc current parse context
902  @param [out] res pointer to "this" or to a newly allocated
903  replacement object to use in the Item tree instead
904 
905  @retval false success
906  @retval true syntax/OOM/etc error
907  */
908  virtual bool itemize(Parse_context *pc, Item **res);
909 
910  void rename(char *new_name);
911  void init_make_field(Send_field *tmp_field, enum enum_field_types type);
912  virtual void cleanup();
913  virtual void make_field(Send_field *field);
914  virtual Field *make_string_field(TABLE *table);
915  virtual bool fix_fields(THD *, Item **);
916  /**
917  Fix after tables have been moved from one select_lex level to the parent
918  level, e.g by semijoin conversion.
919  Basically re-calculate all attributes dependent on the tables.
920 
921  @param parent_select select_lex that tables are moved to.
922  @param removed_select select_lex that tables are moved away from,
923  child of parent_select.
924  */
925  virtual void fix_after_pullout(
926  SELECT_LEX *parent_select MY_ATTRIBUTE((unused)),
927  SELECT_LEX *removed_select MY_ATTRIBUTE((unused))) {}
928  /*
929  should be used in case where we are sure that we do not need
930  complete fix_fields() procedure.
931  */
932  inline void quick_fix_field() { fixed = 1; }
933  virtual void set_can_use_prefix_key() {}
934 
935  protected:
936  /**
937  Helper function which does all of the work for
938  save_in_field(Field*, bool), except some error checking common to
939  all subclasses, which is performed by save_in_field() itself.
940 
941  Subclasses that need to specialize the behaviour of
942  save_in_field(), should override this function instead of
943  save_in_field().
944 
945  @param[in,out] field the field to save the item into
946  @param no_conversions whether or not to allow conversions of the value
947 
948  @return the status from saving into the field
949  @retval TYPE_OK item saved without any errors or warnings
950  @retval != TYPE_OK there were errors or warnings when saving the item
951  */
953  bool no_conversions);
954 
955  public:
956  /**
957  Save the item into a field but do not emit any warnings.
958 
959  @param field field to save the item into
960  @param no_conversions whether or not to allow conversions of the value
961 
962  @return the status from saving into the field
963  @retval TYPE_OK item saved without any issues
964  @retval != TYPE_OK there were issues saving the item
965  */
967  bool no_conversions);
968  /**
969  Save a temporal value in packed longlong format into a Field.
970  Used in optimizer.
971 
972  Subclasses that need to specialize this function, should override
973  save_in_field_inner().
974 
975  @param[in,out] field the field to save the item into
976  @param no_conversions whether or not to allow conversions of the value
977 
978  @return the status from saving into the field
979  @retval TYPE_OK item saved without any errors or warnings
980  @retval != TYPE_OK there were errors or warnings when saving the item
981  */
982  type_conversion_status save_in_field(Field *field, bool no_conversions);
983 
984  virtual void save_org_in_field(Field *field) { save_in_field(field, true); }
985 
986  virtual bool send(Protocol *protocol, String *str);
987  bool evaluate(THD *thd, String *str);
988  virtual bool eq(const Item *, bool binary_cmp) const;
989  virtual Item_result result_type() const { return REAL_RESULT; }
990  /**
991  Result type when an item appear in a numeric context.
992  See Field::numeric_context_result_type() for more comments.
993  */
996  }
997  /**
998  Similar to result_type() but makes DATE, DATETIME, TIMESTAMP
999  pretend to be numbers rather than strings.
1000  */
1003  : result_type();
1004  }
1005 
1006  /// Retrieve the derived data type of the Item.
1007  inline enum_field_types data_type() const {
1008  return static_cast<enum_field_types>(m_data_type);
1009  }
1010 
1011  /**
1012  Set the data type of the current Item. It is however recommended to
1013  use one of the type-specific setters if possible.
1014 
1015  @param data_type The data type of this Item.
1016  */
1018  m_data_type = static_cast<uint8>(data_type);
1019  }
1020 
1021  inline void set_data_type_bool() {
1024  max_length = 1;
1025  }
1026 
1027  /**
1028  Set the data type of the Item to be longlong.
1029  Maximum display width is set to be the maximum of a 64-bit integer,
1030  but it may be adjusted later. The unsigned property is not affected.
1031  */
1032  inline void set_data_type_longlong() {
1035  fix_char_length(21);
1036  }
1037 
1038  /**
1039  Set the data type of the Item to be decimal.
1040  The unsigned property must have been set before calling this function.
1041 
1042  @param precision Number of digits of precision
1043  @param dec Number of digits after decimal point.
1044  */
1045  inline void set_data_type_decimal(uint8 precision, uint8 dec) {
1048  decimals = dec;
1050  precision, dec, unsigned_flag));
1051  }
1052 
1053  /// Set the data type of the Item to be double precision floating point.
1054  inline void set_data_type_double() {
1059  }
1060 
1061  /// Set the data type of the Item to be single precision floating point.
1062  inline void set_data_type_float() {
1067  }
1068 
1069  /// Initialize an Item to be of VARCHAR type, other properties undetermined.
1073  }
1074 
1075  /**
1076  Set the Item to be variable length string. Actual type is determined from
1077  maximum string size. Collation must have been set before calling function.
1078 
1079  @param max_l Maximum number of characters in string
1080  */
1081  inline void set_data_type_string(uint32 max_l) {
1083  if (max_length < 65536)
1085  else if (max_length < 16777216)
1087  else
1089  }
1090 
1091  /**
1092  Set the Item to be variable length string. Like function above, but with
1093  larger string length precision.
1094 
1095  @param max_char_length_arg Maximum number of characters in string
1096  */
1097  inline void set_data_type_string(ulonglong max_char_length_arg) {
1098  ulonglong max_result_length =
1099  max_char_length_arg * collation.collation->mbmaxlen;
1100  if (max_result_length >= MAX_BLOB_WIDTH) {
1101  max_result_length = MAX_BLOB_WIDTH;
1102  maybe_null = true;
1103  }
1105  uint32(max_result_length / collation.collation->mbmaxlen));
1106  }
1107 
1108  /**
1109  Set the Item to be variable length string. Like function above, but will
1110  also set character set and collation.
1111 
1112  @param max_l Maximum number of characters in string
1113  @param cs Pointer to character set and collation struct
1114  */
1115  inline void set_data_type_string(ulonglong max_l, const CHARSET_INFO *cs) {
1116  collation.collation = cs;
1117  set_data_type_string(max_l);
1118  }
1119 
1120  /**
1121  Set the Item to be variable length string. Like function above, but will
1122  also set full collation information.
1123 
1124  @param max_l Maximum number of characters in string
1125  @param coll Ref to collation data, including derivation and repertoire
1126  */
1127  inline void set_data_type_string(uint32 max_l, const DTCollation &coll) {
1128  collation.set(coll);
1129  set_data_type_string(max_l);
1130  }
1131 
1132  /**
1133  Set the Item to be fixed length string. Collation must have been set
1134  before calling function.
1135 
1136  @param max_l Number of characters in string
1137  */
1138  inline void set_data_type_char(uint32 max_l) {
1140  DBUG_ASSERT(max_length < 65536);
1142  }
1143 
1144  /**
1145  Set the Item to be fixed length string. Like function above, but will
1146  also set character set and collation.
1147 
1148  @param max_l Maximum number of characters in string
1149  @param cs Pointer to character set and collation struct
1150  */
1151  inline void set_data_type_char(uint32 max_l, const CHARSET_INFO *cs) {
1152  collation.collation = cs;
1153  set_data_type_char(max_l);
1154  }
1155 
1156  /**
1157  Set the Item to be of BLOB type.
1158 
1159  @param max_l Maximum number of bytes in data type
1160  */
1161  inline void set_data_type_blob(uint32 max_l) {
1163  max_length = max_l;
1164  }
1165 
1166  /// Set all type properties for Item of DATE type.
1167  inline void set_data_type_date() {
1170  decimals = 0;
1172  }
1173 
1174  /**
1175  Set all type properties for Item of TIME type.
1176 
1177  @param fsp Fractional seconds precision
1178  */
1179  inline void set_data_type_time(uint8 fsp) {
1182  decimals = fsp;
1183  max_length = MAX_TIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1184  }
1185 
1186  /**
1187  Set all properties for Item of DATETIME type.
1188 
1189  @param fsp Fractional seconds precision
1190  */
1191  inline void set_data_type_datetime(uint8 fsp) {
1194  decimals = fsp;
1195  max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1196  }
1197 
1198  /**
1199  Set all properties for Item of TIMESTAMP type.
1200 
1201  @param fsp Fractional seconds precision
1202  */
1203  inline void set_data_type_timestamp(uint8 fsp) {
1206  decimals = fsp;
1207  max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1208  }
1209 
1210  /**
1211  Set the data type of the Item to be JSON.
1212  */
1218  }
1219 
1220  /**
1221  Set the data type of the Item to be YEAR.
1222  */
1226  max_length = 4;
1227  }
1228 
1229  /**
1230  Set the Item to be of GEOMETRY type.
1231  */
1232  inline void set_data_type_geometry() {
1236  }
1237 
1238  /**
1239  Set type information of Item from "result" information.
1240  For String types, type is set based on maximum string size.
1241  For other types, the associated type with the largest precision is set.
1242 
1243  @param result Either Integer, Decimal, Double or String
1244  @param length Maximum string size, used only for String result.
1245  */
1247  switch (result) {
1248  case INT_RESULT:
1250  break;
1251  case DECIMAL_RESULT:
1253  break;
1254  case REAL_RESULT:
1256  break;
1257  case STRING_RESULT:
1259  break;
1260  case ROW_RESULT:
1261  case INVALID_RESULT:
1262  default:
1263  DBUG_ASSERT(false);
1264  break;
1265  }
1266  }
1267 
1268  /**
1269  Set data type properties of the item from the properties of another item.
1270 
1271  @param item Item to set data type properties from.
1272  */
1273  inline void set_data_type_from_item(Item *item) {
1274  set_data_type(item->data_type());
1275  collation = item->collation;
1276  max_length = item->max_length;
1277  decimals = item->decimals;
1278  unsigned_flag = item->unsigned_flag;
1279  }
1280 
1281  /**
1282  Determine correct string field type, based on string length
1283 
1284  @param max_bytes Maximum string size, in number of bytes @todo
1285  */
1287  if (max_bytes >= 16777216)
1288  return MYSQL_TYPE_LONG_BLOB;
1289  else if (max_bytes >= 65536)
1290  return MYSQL_TYPE_MEDIUM_BLOB;
1291  else
1292  return MYSQL_TYPE_VARCHAR;
1293  }
1294 
1295  virtual Item_result cast_to_int_type() const { return result_type(); }
1296  virtual enum Type type() const = 0;
1297 
1299 
1300  /*
1301  Return information about function monotonicity. See comment for
1302  enum_monotonicity_info for details. This function can only be called
1303  after fix_fields() call.
1304  */
1306  return NON_MONOTONIC;
1307  }
1308 
1309  /// For template-compatibility with Field
1310  inline bool is_null_value() { return null_value; }
1311  /*
1312  Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$
1313  const2"
1314 
1315  SYNOPSIS
1316  val_int_endpoint()
1317  left_endp false <=> The interval is "x < const" or "x <= const"
1318  true <=> The interval is "x > const" or "x >= const"
1319 
1320  incl_endp IN false <=> the comparison is '<' or '>'
1321  true <=> the comparison is '<=' or '>='
1322  OUT The same but for the "F(x) $CMP$ F(const)" comparison
1323 
1324  DESCRIPTION
1325  This function is defined only for unary monotonic functions. The caller
1326  supplies the source half-interval
1327 
1328  x $CMP$ const
1329 
1330  The value of const is supplied implicitly as the value this item's
1331  argument, the form of $CMP$ comparison is specified through the
1332  function's arguments. The calle returns the result interval
1333 
1334  F(x) $CMP2$ F(const)
1335 
1336  passing back F(const) as the return value, and the form of $CMP2$
1337  through the out parameter. NULL values are assumed to be comparable and
1338  be less than any non-NULL values.
1339 
1340  RETURN
1341  The output range bound, which equal to the value of val_int()
1342  - If the value of the function is NULL then the bound is the
1343  smallest possible value of LLONG_MIN
1344  */
1345  virtual longlong val_int_endpoint(bool left_endp MY_ATTRIBUTE((unused)),
1346  bool *incl_endp MY_ATTRIBUTE((unused))) {
1347  DBUG_ASSERT(0);
1348  return 0;
1349  }
1350 
1351  /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */
1352  /*
1353  Return double precision floating point representation of item.
1354 
1355  SYNOPSIS
1356  val_real()
1357 
1358  RETURN
1359  In case of NULL value return 0.0 and set null_value flag to true.
1360  If value is not null null_value flag will be reset to false.
1361  */
1362  virtual double val_real() = 0;
1363  /*
1364  Return integer representation of item.
1365 
1366  SYNOPSIS
1367  val_int()
1368 
1369  RETURN
1370  In case of NULL value return 0 and set null_value flag to true.
1371  If value is not null null_value flag will be reset to false.
1372  */
1373  virtual longlong val_int() = 0;
1374  /**
1375  Return date value of item in packed longlong format.
1376  */
1377  virtual longlong val_date_temporal();
1378  /**
1379  Return time value of item in packed longlong format.
1380  */
1381  virtual longlong val_time_temporal();
1382  /**
1383  Return date or time value of item in packed longlong format,
1384  depending on item field type.
1385  */
1387  if (data_type() == MYSQL_TYPE_TIME) return val_time_temporal();
1389  return val_date_temporal();
1390  }
1391  /**
1392  Get date or time value in packed longlong format.
1393  Before conversion from MYSQL_TIME to packed format,
1394  the MYSQL_TIME value is rounded to "dec" fractional digits.
1395  */
1397 
1398  /*
1399  This is just a shortcut to avoid the cast. You should still use
1400  unsigned_flag to check the sign of the item.
1401  */
1402  inline ulonglong val_uint() { return (ulonglong)val_int(); }
1403  /*
1404  Return string representation of this item object.
1405 
1406  SYNOPSIS
1407  val_str()
1408  str an allocated buffer this or any nested Item object can use to
1409  store return value of this method.
1410 
1411  NOTE
1412  Buffer passed via argument should only be used if the item itself
1413  doesn't have an own String buffer. In case when the item maintains
1414  it's own string buffer, it's preferable to return it instead to
1415  minimize number of mallocs/memcpys.
1416  The caller of this method can modify returned string, but only in case
1417  when it was allocated on heap, (is_alloced() is true). This allows
1418  the caller to efficiently use a buffer allocated by a child without
1419  having to allocate a buffer of it's own. The buffer, given to
1420  val_str() as argument, belongs to the caller and is later used by the
1421  caller at it's own choosing.
1422  A few implications from the above:
1423  - unless you return a string object which only points to your buffer
1424  but doesn't manages it you should be ready that it will be
1425  modified.
1426  - even for not allocated strings (is_alloced() == false) the caller
1427  can change charset (see Item_func_{typecast/binary}. XXX: is this
1428  a bug?
1429  - still you should try to minimize data copying and return internal
1430  object whenever possible.
1431 
1432  RETURN
1433  In case of NULL value or error, return error_str() as this function will
1434  check if the return value may be null, and it will either set null_value
1435  to true and return nullptr or to false and it will return empty string.
1436  If value is not null set null_value flag to false before returning it.
1437  */
1438  virtual String *val_str(String *str) = 0;
1439 
1440  /*
1441  Returns string representation of this item in ASCII format.
1442 
1443  SYNOPSIS
1444  val_str_ascii()
1445  str - similar to val_str();
1446 
1447  NOTE
1448  This method is introduced for performance optimization purposes.
1449 
1450  1. val_str() result of some Items in string context
1451  depends on @@character_set_results.
1452  @@character_set_results can be set to a "real multibyte" character
1453  set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples
1454  below for convenience.)
1455 
1456  So the default string result of such functions
1457  in these circumstances is real multi-byte character set, like UTF32.
1458 
1459  For example, all numbers in string context
1460  return result in @@character_set_results:
1461 
1462  SELECT CONCAT(20010101); -> UTF32
1463 
1464  We do sprintf() first (to get ASCII representation)
1465  and then convert to UTF32;
1466 
1467  So these kind "data sources" can use ASCII representation
1468  internally, but return multi-byte data only because
1469  @@character_set_results wants so.
1470  Therefore, conversion from ASCII to UTF32 is applied internally.
1471 
1472 
1473  2. Some other functions need in fact ASCII input.
1474 
1475  For example,
1476  inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT().
1477 
1478  Similar, fields of certain type, like DATE, TIME,
1479  when you insert string data into them, expect in fact ASCII input.
1480  If they get non-ASCII input, for example UTF32, they
1481  convert input from UTF32 to ASCII, and then use ASCII
1482  representation to do further processing.
1483 
1484 
1485  3. Now imagine we pass result of a data source of the first type
1486  to a data destination of the second type.
1487 
1488  What happens:
1489  a. data source converts data from ASCII to UTF32, because
1490  @@character_set_results wants so and passes the result to
1491  data destination.
1492  b. data destination gets UTF32 string.
1493  c. data destination converts UTF32 string to ASCII,
1494  because it needs ASCII representation to be able to handle data
1495  correctly.
1496 
1497  As a result we get two steps of unnecessary conversion:
1498  From ASCII to UTF32, then from UTF32 to ASCII.
1499 
1500  A better way to handle these situations is to pass ASCII
1501  representation directly from the source to the destination.
1502 
1503  This is why val_str_ascii() introduced.
1504 
1505  RETURN
1506  Similar to val_str()
1507  */
1508  virtual String *val_str_ascii(String *str);
1509 
1510  /*
1511  Return decimal representation of item with fixed point.
1512 
1513  SYNOPSIS
1514  val_decimal()
1515  decimal_buffer buffer which can be used by Item for returning value
1516  (but can be not)
1517 
1518  NOTE
1519  Returned value should not be changed if it is not the same which was
1520  passed via argument.
1521 
1522  RETURN
1523  Return pointer on my_decimal (it can be other then passed via argument)
1524  if value is not NULL (null_value flag will be reset to false).
1525  In case of NULL value it return 0 pointer and set null_value flag
1526  to true.
1527  */
1528  virtual my_decimal *val_decimal(my_decimal *decimal_buffer) = 0;
1529  /*
1530  Return boolean value of item.
1531 
1532  RETURN
1533  false value is false or NULL
1534  true value is true (not equal to 0)
1535  */
1536  virtual bool val_bool();
1537 
1538  /**
1539  Get a JSON value from an Item.
1540 
1541  All subclasses that can return a JSON value, should override this
1542  function. The function in the base class is not expected to be
1543  called. If it is called, it most likely means that some subclass
1544  is missing an override of val_json().
1545 
1546  @param[in,out] result The resulting Json_wrapper.
1547 
1548  @return false if successful, true on failure
1549  */
1550  /* purecov: begin deadcode */
1551  virtual bool val_json(Json_wrapper *result MY_ATTRIBUTE((unused))) {
1552  DBUG_ASSERT(false);
1553  my_error(ER_NOT_SUPPORTED_YET, MYF(0), "item type for JSON");
1554  return error_json();
1555  }
1556  /* purecov: end */
1557 
1558  /**
1559  Calculate the filter contribution that is relevant for table
1560  'filter_for_table' for this item.
1561 
1562  @param thd Thread handler
1563  @param filter_for_table The table we are calculating filter effect for
1564  @param read_tables Tables earlier in the join sequence.
1565  Predicates for table 'filter_for_table' that
1566  rely on values from these tables can be part of
1567  the filter effect.
1568  @param fields_to_ignore Fields in 'filter_for_table' that should not
1569  be part of the filter calculation. The filtering
1570  effect of these fields is already part of the
1571  calculation somehow (e.g. because there is a
1572  predicate "col = <const>", and the optimizer
1573  has decided to do ref access on 'col').
1574  @param rows_in_table The number of rows in table 'filter_for_table'
1575 
1576  @return the filtering effect (between 0 and 1) this
1577  Item contributes with.
1578  */
1579  virtual float get_filtering_effect(
1580  THD *thd MY_ATTRIBUTE((unused)),
1581  table_map filter_for_table MY_ATTRIBUTE((unused)),
1582  table_map read_tables MY_ATTRIBUTE((unused)),
1583  const MY_BITMAP *fields_to_ignore MY_ATTRIBUTE((unused)),
1584  double rows_in_table MY_ATTRIBUTE((unused))) {
1585  // Filtering effect cannot be calculated for a table already read.
1586  DBUG_ASSERT((read_tables & filter_for_table) == 0);
1587  return COND_FILTER_ALLPASS;
1588  }
1589 
1590  /**
1591  Get the value to return from val_json() in case of errors.
1592 
1593  @see Item::error_bool
1594 
1595  @return The value val_json() should return, which is true.
1596  */
1597  bool error_json() {
1599  return true;
1600  }
1601 
1602  /**
1603  Convert a non-temporal type to date
1604  */
1605  bool get_date_from_non_temporal(MYSQL_TIME *ltime, my_time_flags_t fuzzydate);
1606 
1607  /**
1608  Convert a non-temporal type to time
1609  */
1611 
1612  protected:
1613  /* Helper functions, see item_sum.cc */
1620  my_decimal *val_decimal_from_real(my_decimal *decimal_value);
1621  my_decimal *val_decimal_from_int(my_decimal *decimal_value);
1623  my_decimal *val_decimal_from_date(my_decimal *decimal_value);
1624  my_decimal *val_decimal_from_time(my_decimal *decimal_value);
1629  double val_real_from_decimal();
1630 
1631  /**
1632  Get the value to return from val_bool() in case of errors.
1633 
1634  This function is called from val_bool() when an error has occurred
1635  and we need to return something to abort evaluation of the
1636  item. The expected pattern in val_bool() is
1637 
1638  if (@<error condition@>)
1639  {
1640  my_error(...)
1641  return error_bool();
1642  }
1643 
1644  @return The value val_bool() should return.
1645  */
1646  bool error_bool() {
1648  return false;
1649  }
1650 
1651  /**
1652  Get the value to return from val_int() in case of errors.
1653 
1654  @see Item::error_bool
1655 
1656  @return The value val_int() should return.
1657  */
1658  int error_int() {
1660  return 0;
1661  }
1662 
1663  /**
1664  Get the value to return from val_real() in case of errors.
1665 
1666  @see Item::error_bool
1667 
1668  @return The value val_real() should return.
1669  */
1670  double error_real() {
1672  return 0.0;
1673  }
1674 
1675  /**
1676  Get the value to return from val_str() in case of errors.
1677 
1678  @see Item::error_bool
1679 
1680  @return The value val_str() should return.
1681  */
1684  return null_value ? NULL : make_empty_result();
1685  }
1686 
1687  /**
1688  Gets the value to return from val_str() when returning a NULL value.
1689  @return The value val_str() should return.
1690  */
1693  null_value = true;
1694  return nullptr;
1695  }
1696 
1697  /**
1698  Convert val_str() to date in MYSQL_TIME
1699  */
1701  /**
1702  Convert val_real() to date in MYSQL_TIME
1703  */
1705  /**
1706  Convert val_decimal() to date in MYSQL_TIME
1707  */
1709  /**
1710  Convert val_int() to date in MYSQL_TIME
1711  */
1713  /**
1714  Convert get_time() from time to date in MYSQL_TIME
1715  */
1716  bool get_date_from_time(MYSQL_TIME *ltime);
1717 
1718  /**
1719  Convert a numeric type to date
1720  */
1721  bool get_date_from_numeric(MYSQL_TIME *ltime, my_time_flags_t fuzzydate);
1722 
1723  /**
1724  Convert val_str() to time in MYSQL_TIME
1725  */
1726  bool get_time_from_string(MYSQL_TIME *ltime);
1727  /**
1728  Convert val_real() to time in MYSQL_TIME
1729  */
1730  bool get_time_from_real(MYSQL_TIME *ltime);
1731  /**
1732  Convert val_decimal() to time in MYSQL_TIME
1733  */
1734  bool get_time_from_decimal(MYSQL_TIME *ltime);
1735  /**
1736  Convert val_int() to time in MYSQL_TIME
1737  */
1738  bool get_time_from_int(MYSQL_TIME *ltime);
1739  /**
1740  Convert date to time
1741  */
1742  bool get_time_from_date(MYSQL_TIME *ltime);
1743  /**
1744  Convert datetime to time
1745  */
1746  bool get_time_from_datetime(MYSQL_TIME *ltime);
1747 
1748  /**
1749  Convert a numeric type to time
1750  */
1751  bool get_time_from_numeric(MYSQL_TIME *ltime);
1752 
1753  public:
1757 
1759  DBUG_ENTER("Item::get_tmp_table_field");
1760  DBUG_RETURN(0);
1761  }
1762  /* This is also used to create fields in CREATE ... SELECT: */
1763  virtual Field *tmp_table_field(TABLE *) { return 0; }
1764  virtual const char *full_name() const {
1765  return item_name.is_set() ? item_name.ptr() : "???";
1766  }
1767 
1768  /* bit map of tables used by item */
1769  virtual table_map used_tables() const { return (table_map)0L; }
1770 
1771  /*
1772  Return table map of tables that can't be NULL tables (tables that are
1773  used in a context where if they would contain a NULL row generated
1774  by a LEFT or RIGHT join, the item would not be true).
1775  This expression is used on WHERE item to determinate if a LEFT JOIN can be
1776  converted to a normal join.
1777  Generally this function should return used_tables() if the function
1778  would return null if any of the arguments are null
1779  As this is only used in the beginning of optimization, the value don't
1780  have to be updated in update_used_tables()
1781  */
1782  virtual table_map not_null_tables() const { return used_tables(); }
1783  /*
1784  Returns true if this is a simple constant item like an integer, not
1785  a constant expression. Used in the optimizer to propagate basic constants.
1786  It is assumed that val_xxx() does not modify the item's state for
1787  such items. It is also assumed that val_str() can be called with nullptr
1788  as argument as val_str() will return an internally cached const string.
1789  */
1790  virtual bool basic_const_item() const { return false; }
1791  /**
1792  @return cloned item if it is constant
1793  @retval nullptr if this is not const
1794  */
1795  virtual Item *clone_item() const { return nullptr; }
1796  virtual cond_result eq_cmp_result() const { return COND_OK; }
1797  inline uint float_length(uint decimals_par) const {
1798  return decimals != NOT_FIXED_DEC ? (DBL_DIG + 2 + decimals_par)
1799  : DBL_DIG + 8;
1800  }
1801  virtual uint decimal_precision() const;
1802  inline int decimal_int_part() const {
1804  }
1805  /**
1806  TIME precision of the item: 0..6
1807  */
1808  virtual uint time_precision();
1809  /**
1810  DATETIME precision of the item: 0..6
1811  */
1812  virtual uint datetime_precision();
1813  /**
1814  Returns true if item is constant, regardless of query evaluation state.
1815  An expression is constant if it:
1816  - refers no tables.
1817  - refers no subqueries that refers any tables.
1818  - refers no non-deterministic functions.
1819  - refers no statement parameters.
1820  - contains no group expression under rollup
1821  */
1822  bool const_item() const { return (used_tables() == 0); }
1823  /**
1824  Returns true if item is constant during one query execution.
1825  If const_for_execution() is true but const_item() is false, value is
1826  not available before tables have been locked and parameters have been
1827  assigned values. This applies to
1828  - statement parameters
1829  - non-dependent subqueries
1830  - deterministic stored functions that contain SQL code.
1831  For items where the default implementation of used_tables() and
1832  const_item() are effective, const_item() will always return true.
1833  */
1834  bool const_for_execution() const {
1835  return !(used_tables() & ~INNER_TABLE_BIT);
1836  }
1837 
1838  /**
1839  Return true if this is a const item that may be evaluated in
1840  the current phase of statement processing.
1841  - No evaluation is performed when analyzing a view, otherwise:
1842  - Items that have the const_item() property can always be evaluated.
1843  - Items that have the const_for_execution() property can be evaluated when
1844  tables are locked (ie during optimization or execution).
1845 
1846  This function should be used in the following circumstances:
1847  - during preparation to check whether an item can be permanently transformed
1848  - to check that an item is constant in functions that may be used in both
1849  the preparation and optimization phases.
1850 
1851  This function should not be used by code that is called during optimization
1852  and/or execution only. Use const_for_execution() in this case.
1853  */
1854  bool may_evaluate_const(const THD *thd) const;
1855 
1856  /**
1857  This method is used for to:
1858  - to generate a view definition query (SELECT-statement);
1859  - to generate a SQL-query for EXPLAIN EXTENDED;
1860  - to generate a SQL-query to be shown in INFORMATION_SCHEMA;
1861  - to generate a SQL-query that looks like a prepared statement for
1862  query_rewrite
1863  - debug.
1864 
1865  For more information about view definition query, INFORMATION_SCHEMA
1866  query and why they should be generated from the Item-tree, @see
1867  mysql_register_view().
1868  */
1869  virtual void print(const THD *, String *str, enum_query_type) const {
1870  str->append(full_name());
1871  }
1872 
1873  void print_item_w_name(const THD *thd, String *,
1874  enum_query_type query_type) const;
1875  /**
1876  Prints the item when it's part of ORDER BY and GROUP BY.
1877  @param thd Thread handle
1878  @param str String to print to
1879  @param query_type How to format the item
1880  @param used_alias Whether item was referenced with alias.
1881  */
1882  void print_for_order(const THD *thd, String *str, enum_query_type query_type,
1883  bool used_alias) const;
1884 
1885  virtual void update_used_tables() {}
1886 
1888  /* Called for items that really have to be split */
1889  void split_sum_func2(THD *thd, Ref_item_array ref_item_array,
1890  List<Item> &fields, Item **ref, bool skip_registered);
1891  virtual bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) = 0;
1892  virtual bool get_time(MYSQL_TIME *ltime) = 0;
1893  /**
1894  Get timestamp in "struct timeval" format.
1895  @retval false on success
1896  @retval true on error
1897  */
1898  virtual bool get_timeval(struct timeval *tm, int *warnings);
1899  /*
1900  The method allows to determine nullness of a complex expression
1901  without fully evaluating it, instead of calling val*() then
1902  checking null_value. Used in Item_func_isnull/Item_func_isnotnull
1903  and Item_sum_count/Item_sum_count_distinct.
1904  Any new item which can be NULL must implement this method.
1905  */
1906  virtual bool is_null() { return false; }
1907 
1908  /// Make sure the null_value member has a correct value.
1909  bool update_null_value();
1910 
1911  /**
1912  Apply the IS TRUE truth property, meaning that an UNKNOWN result and a
1913  FALSE result are treated the same.
1914 
1915  This property is applied e.g to all conditions in WHERE, HAVING and ON
1916  clauses, and is recursively applied to operands of AND, OR
1917  operators. Some items (currently AND and subquery predicates) may enable
1918  special optimizations when they have this property.
1919  */
1920  virtual void apply_is_true() {}
1921  /*
1922  set field of temporary table for Item which can be switched on temporary
1923  table during query processing (grouping and so on). @see
1924  Item_result_field.
1925  */
1926  virtual void set_result_field(Field *) {}
1927  virtual bool is_result_field() const { return false; }
1928  virtual Field *get_result_field() const { return nullptr; }
1929  virtual bool is_bool_func() const { return false; }
1930  virtual void save_in_result_field(
1931  bool no_conversions MY_ATTRIBUTE((unused))) {}
1932  /*
1933  Set value of aggregate function in case of no rows for grouping were found.
1934  Also used for subqueries with outer references in SELECT list.
1935  */
1936  virtual void no_rows_in_result() {}
1937  virtual Item *copy_or_same(THD *) { return this; }
1938  virtual Item *copy_andor_structure(THD *) { return this; }
1939  virtual Item *real_item() { return this; }
1941  return runtime_item ? real_item() : this;
1942  }
1943  virtual void set_runtime_created() { runtime_item = true; }
1944  virtual Item *get_tmp_table_item(THD *thd) {
1945  DBUG_ENTER("Item::get_tmp_table_item");
1946  Item *result = copy_or_same(thd);
1947  DBUG_RETURN(result);
1948  }
1949 
1950  static const CHARSET_INFO *default_charset();
1951  virtual const CHARSET_INFO *compare_collation() const { return nullptr; }
1952 
1953  /*
1954  For backward compatibility, to make numeric
1955  data types return "binary" charset in client-side metadata.
1956  */
1957  virtual const CHARSET_INFO *charset_for_protocol() const {
1959  : &my_charset_bin;
1960  }
1961 
1962  /**
1963  Traverses a tree of Items in prefix and/or postfix order.
1964  Optionally walks into subqueries.
1965 
1966  @param processor processor function to be invoked per item
1967  returns true to abort traversal, false to continue
1968  @param walk controls how to traverse the item tree
1969  enum_walk::PREFIX: call processor before invoking
1970  children enum_walk::POSTFIX: call processor after invoking children
1971  enum_walk::SUBQUERY go down into subqueries
1972  walk values are bit-coded and may be combined.
1973  Omitting both enum_walk::PREFIX and enum_walk::POSTFIX
1974  is undefined behaviour.
1975  @param arg Optional pointer to a walk-specific object
1976 
1977  @retval false walk succeeded
1978  @retval true walk aborted
1979  by agreement, an error may have been reported
1980  */
1981 
1982  virtual bool walk(Item_processor processor,
1983  enum_walk walk MY_ATTRIBUTE((unused)), uchar *arg) {
1984  return (this->*processor)(arg);
1985  }
1986 
1987  /** @see WalkItem */
1988  template <class T>
1990  return (*reinterpret_cast<T *>(arg))(this);
1991  }
1992 
1993  /**
1994  Perform a generic transformation of the Item tree, by adding zero or
1995  more additional Item objects to it.
1996 
1997  @param transformer Transformer function
1998  @param[in,out] arg Pointer to struct used by transformer function
1999 
2000  @returns Returned item tree after transformation, NULL if error
2001 
2002  @details
2003 
2004  Transformation is performed as follows:
2005 
2006  transform()
2007  {
2008  transform children if any;
2009  return this->*some_transformer(...);
2010  }
2011 
2012  Note that unlike Item::compile(), transform() does not support an analyzer
2013  function, ie. all children are unconditionally invoked.
2014 
2015  @todo Let compile() handle all transformations during optimization, and
2016  let transform() handle transformations during preparation only.
2017  Then there would be no need to call change_item_tree() during
2018  transformation.
2019  */
2020  virtual Item *transform(Item_transformer transformer, uchar *arg);
2021 
2022  /**
2023  Perform a generic "compilation" of the Item tree, ie transform the Item tree
2024  by adding zero or more Item objects to it.
2025 
2026  @param analyzer Analyzer function, see details section
2027  @param[in,out] arg_p Pointer to struct used by analyzer function
2028  @param transformer Transformer function, see details section
2029  @param[in,out] arg_t Pointer to struct used by transformer function
2030 
2031  @returns Returned item tree after transformation, NULL if error
2032 
2033  @details
2034 
2035  The process of this transformation is assumed to be as follows:
2036 
2037  compile()
2038  {
2039  if (this->*some_analyzer(...))
2040  {
2041  compile children if any;
2042  return this->*some_transformer(...);
2043  }
2044  else
2045  return this;
2046  }
2047 
2048  i.e. analysis is performed top-down while transformation is done
2049  bottom-up. If no transformation is applied, the item is returned unchanged.
2050  A transformation error is indicated by returning a NULL pointer. Notice
2051  that the analyzer function should never cause an error.
2052 
2053  The function is supposed to be used during the optimization stage of
2054  query execution. All new allocations are recorded using
2055  THD::change_item_tree() so that they can be rolled back after execution.
2056 
2057  @todo Pass THD to compile() function, thus no need to use current_thd.
2058  */
2059  virtual Item *compile(Item_analyzer analyzer, uchar **arg_p,
2060  Item_transformer transformer, uchar *arg_t) {
2061  if ((this->*analyzer)(arg_p)) return ((this->*transformer)(arg_t));
2062  return this;
2063  }
2064 
2065  virtual void traverse_cond(Cond_traverser traverser, void *arg,
2066  traverse_order) {
2067  (*traverser)(this, arg);
2068  }
2069 
2070  /*
2071  This is used to get the most recent version of any function in
2072  an item tree. The version is the version where a MySQL function
2073  was introduced in. So any function which is added should use
2074  this function and set the int_arg to maximum of the input data
2075  and their own version info.
2076  */
2077  virtual bool intro_version(uchar *) { return false; }
2078 
2079  /// cleanup() item if it is resolved ('fixed').
2081  if (fixed) cleanup();
2082  return false;
2083  }
2084 
2085  virtual bool collect_item_field_processor(uchar *) { return false; }
2086 
2087  /**
2088  Item::walk function. Set bit in table->tmp_set for all fields in
2089  table 'arg' that are referred to by the Item.
2090  */
2091  virtual bool add_field_to_set_processor(uchar *) { return false; }
2092 
2093  /// A processor to handle the select lex visitor framework.
2094  virtual bool visitor_processor(uchar *arg);
2095 
2096  /**
2097  Item::walk function. Set bit in table->cond_set for all fields of
2098  all tables that are referred to by the Item.
2099  */
2100  virtual bool add_field_to_cond_set_processor(uchar *) { return false; }
2101 
2102  /**
2103  Visitor interface for removing all column expressions (Item_field) in
2104  this expression tree from a bitmap. @see walk()
2105 
2106  @param arg A MY_BITMAP* cast to unsigned char*, where the bits represent
2107  Field::field_index values.
2108  */
2109  virtual bool remove_column_from_bitmap(uchar *arg MY_ATTRIBUTE((unused))) {
2110  return false;
2111  }
2112  virtual bool find_item_in_field_list_processor(uchar *) { return false; }
2113  virtual bool change_context_processor(uchar *) { return false; }
2114  virtual bool find_item_processor(uchar *arg) { return this == (void *)arg; }
2116  return !basic_const_item();
2117  }
2118  /// Is this an Item_field which references the given Field argument?
2119  virtual bool find_field_processor(uchar *) { return false; }
2120  /**
2121  Mark underlying field in read or write map of a table.
2122 
2123  @param arg Mark_field object
2124  */
2125  virtual bool mark_field_in_map(uchar *arg MY_ATTRIBUTE((unused))) {
2126  return false;
2127  }
2128  /**
2129  @returns true if the expression contains a reference to
2130  an expression of the SELECT list of the given query block.
2131  @param arg query block to search in.
2132  */
2133  virtual bool references_select_expr_of(uchar *arg MY_ATTRIBUTE((unused))) {
2134  return false;
2135  }
2136 
2137  protected:
2138  /**
2139  Helper function for mark_field_in_map(uchar *arg).
2140 
2141  @param mark_field Mark_field object
2142  @param field Field to be marked for read/write
2143  */
2144  static inline bool mark_field_in_map(Mark_field *mark_field, Field *field) {
2145  TABLE *table = mark_field->table;
2146  if (table != NULL && table != field->table) return false;
2147 
2148  table = field->table;
2149  table->mark_column_used(field, mark_field->mark);
2150 
2151  return false;
2152  }
2153 
2154  public:
2155  /**
2156  Reset execution state for such window function types
2157  as determined by arg
2158 
2159  @param arg pointing to a bool which, if true, says to reset state
2160  for framing window function, else for non-framing
2161  */
2162  virtual bool reset_wf_state(uchar *arg MY_ATTRIBUTE((unused))) {
2163  return false;
2164  }
2165 
2166  /**
2167  Return used table information for the specified query block (level).
2168  For a field that is resolved from this query block, return the table number.
2169  For a field that is resolved from a query block outer to the specified one,
2170  return OUTER_REF_TABLE_BIT
2171 
2172  @param[in,out] arg pointer to an instance of class Used_tables, which is
2173  constructed with the query block as argument.
2174  The used tables information is accumulated in the field
2175  used_tables in this class.
2176 
2177  @note This function is used to update used tables information after
2178  merging a query block (a subquery) with its parent.
2179  */
2180  virtual bool used_tables_for_level(uchar *arg MY_ATTRIBUTE((unused))) {
2181  return false;
2182  }
2183  /**
2184  Check privileges.
2185 
2186  @param thd thread handle
2187  */
2188  virtual bool check_column_privileges(uchar *thd MY_ATTRIBUTE((unused))) {
2189  return false;
2190  }
2191  virtual bool inform_item_in_cond_of_tab(uchar *) { return false; }
2192 
2194  /**
2195  Pointer to Cleanup_after_removal_context containing from which
2196  select the walk started, i.e., the SELECT_LEX that contained the clause
2197  that was removed.
2198  */
2200  /**
2201  True if we are eliminating constant predicates (i.e. always TRUE or FALSE
2202  predicates) in Item_cond::fix_fields. Referenced subqueries via an alias
2203  from the SELECT list will not be removed in such a case, cf.
2204  Item_subselect::clean_up_after_removal.
2205  */
2207 
2209  bool removing_const_preds = false)
2210  : m_root(root), m_removing_const_preds(removing_const_preds) {}
2211  };
2212  /**
2213  Clean up after removing the item from the item tree.
2214 
2215  @param arg pointer to a Cleanup_after_removal_context object
2216  */
2217  virtual bool clean_up_after_removal(uchar *arg MY_ATTRIBUTE((unused))) {
2218  return false;
2219  }
2220 
2221  /**
2222  Propagate components that use referenced columns from derived tables.
2223  Some columns from derived tables may be determined to be unused, but
2224  may actually reference other columns that are used. This function will
2225  return true for such columns when called with Item::walk(), which then
2226  means that this column can also be marked as used.
2227  @see also SELECT_LEX::delete_unused_merged_columns().
2228  */
2230 
2231  /**
2232  Called by Item::walk() to set all the referenced items' derived_used flag.
2233  */
2235  set_derived_used();
2236  return false;
2237  }
2238 
2239  /// @see Distinct_check::check_query()
2240  virtual bool aggregate_check_distinct(uchar *) { return false; }
2241  /// @see Group_check::check_query()
2242  virtual bool aggregate_check_group(uchar *) { return false; }
2243  /// @see Group_check::analyze_conjunct()
2244  virtual bool is_strong_side_column_not_in_fd(uchar *) { return false; }
2245  /// @see Group_check::is_in_fd_of_underlying()
2246  virtual bool is_column_not_in_fd(uchar *) { return false; }
2247  virtual Bool3 local_column(const SELECT_LEX *) const {
2248  return Bool3::false3();
2249  }
2250 
2251  /**
2252  Check if an aggregate is referenced from within the GROUP BY
2253  clause of the query block in which it is aggregated. Such
2254  references will be rejected.
2255  @see Item_ref::fix_fields()
2256  @retval true if this is an aggregate which is referenced from
2257  the GROUP BY clause of the aggregating query block
2258  @retval false otherwise
2259  */
2260  virtual bool has_aggregate_ref_in_group_by(uchar *) { return false; }
2261 
2262  virtual bool cache_const_expr_analyzer(uchar **cache_item);
2264 
2265  virtual bool equality_substitution_analyzer(uchar **) { return false; }
2266 
2267  virtual Item *equality_substitution_transformer(uchar *) { return this; }
2268 
2269  /**
2270  Check if a partition function is allowed.
2271 
2272  @return whether a partition function is not accepted
2273 
2274  @details
2275  check_partition_func_processor is used to check if a partition function
2276  uses an allowed function. An allowed function will always ensure that
2277  X=Y guarantees that also part_function(X)=part_function(Y) where X is
2278  a set of partition fields and so is Y. The problems comes mainly from
2279  character sets where two equal strings can be quite unequal. E.g. the
2280  german character for double s is equal to 2 s.
2281 
2282  The default is that an item is not allowed
2283  in a partition function. Allowed functions
2284  can never depend on server version, they cannot depend on anything
2285  related to the environment. They can also only depend on a set of
2286  fields in the table itself. They cannot depend on other tables and
2287  cannot contain any queries and cannot contain udf's or similar.
2288  If a new Item class is defined and it inherits from a class that is
2289  allowed in a partition function then it is very important to consider
2290  whether this should be inherited to the new class. If not the function
2291  below should be defined in the new Item class.
2292 
2293  The general behaviour is that most integer functions are allowed.
2294  If the partition function contains any multi-byte collations then
2295  the function check_part_func_fields will report an error on the
2296  partition function independent of what functions are used. So the
2297  only character sets allowed are single character collation and
2298  even for those only a limited set of functions are allowed. The
2299  problem with multi-byte collations is that almost every string
2300  function has the ability to change things such that two strings
2301  that are equal will not be equal after manipulated by a string
2302  function. E.g. two strings one contains a double s, there is a
2303  special german character that is equal to two s. Now assume a
2304  string function removes one character at this place, then in
2305  one the double s will be removed and in the other there will
2306  still be one s remaining and the strings are no longer equal
2307  and thus the partition function will not sort equal strings into
2308  the same partitions.
2309 
2310  So the check if a partition function is valid is two steps. First
2311  check that the field types are valid, next check that the partition
2312  function is valid. The current set of partition functions valid
2313  assumes that there are no multi-byte collations amongst the partition
2314  fields.
2315  */
2316  virtual bool check_partition_func_processor(uchar *) { return true; }
2317  virtual bool subst_argument_checker(uchar **arg) {
2318  if (*arg) *arg = NULL;
2319  return true;
2320  }
2321  virtual bool explain_subquery_checker(uchar **) { return true; }
2322  virtual Item *explain_subquery_propagator(uchar *) { return this; }
2323 
2324  virtual Item *equal_fields_propagator(uchar *) { return this; }
2325  virtual bool set_no_const_sub(uchar *) { return false; }
2326  virtual Item *replace_equal_field(uchar *) { return this; }
2327  /*
2328  Check if an expression value has allowed arguments, like DATE/DATETIME
2329  for date functions. Also used by partitioning code to reject
2330  timezone-dependent expressions in a (sub)partitioning function.
2331  */
2332  virtual bool check_valid_arguments_processor(uchar *) { return false; }
2333 
2334  /**
2335  Check if this item is allowed for a virtual column or inside a
2336  default expression. Should be overridden in child classes.
2337 
2338  @param[in,out] args Due to the limitation of Item::walk()
2339  it is declared as a pointer to uchar, underneath there's a actually a
2340  structure of type Check_function_as_value_generator_parameters.
2341  It is used mainly in Item_field.
2342 
2343  @returns true if function is not accepted
2344  */
2345  virtual bool check_function_as_value_generator(uchar *args);
2346 
2347  /**
2348  Check if a generated expression depends on DEFAULT function with
2349  specific column name as argument.
2350 
2351  @param[in] args Name of column used as DEFAULT function argument.
2352 
2353  @returns false if the function is not DEFAULT(args), otherwise true.
2354  */
2356  uchar *args MY_ATTRIBUTE((unused))) {
2357  return false;
2358  }
2359 
2360  /*
2361  For SP local variable returns pointer to Item representing its
2362  current value and pointer to current Item otherwise.
2363  */
2364  virtual Item *this_item() { return this; }
2365  virtual const Item *this_item() const { return this; }
2366 
2367  /*
2368  For SP local variable returns address of pointer to Item representing its
2369  current value and pointer passed via parameter otherwise.
2370  */
2371  virtual Item **this_item_addr(THD *, Item **addr_arg) { return addr_arg; }
2372 
2373  // Row emulation
2374  virtual uint cols() const { return 1; }
2375  virtual Item *element_index(uint) { return this; }
2376  virtual Item **addr(uint) { return 0; }
2377  virtual bool check_cols(uint c);
2378  // It is not row => null inside is impossible
2379  virtual bool null_inside() { return 0; }
2380  // used in row subselects to get value of elements
2381  virtual void bring_value() {}
2382 
2383  Field *tmp_table_field_from_field_type(TABLE *table, bool fixed_length);
2384  virtual Item_field *field_for_view_update() { return 0; }
2385  /**
2386  Informs an item that it is wrapped in a truth test, in case it wants to
2387  transforms itself to implement this test by itself.
2388  @param thd Thread handle
2389  @param test Truth test
2390  */
2391  virtual Item *truth_transformer(THD *thd MY_ATTRIBUTE((unused)),
2392  Bool_test test MY_ATTRIBUTE((unused))) {
2393  return nullptr;
2394  }
2395  virtual Item *update_value_transformer(uchar *) { return this; }
2396  virtual Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs);
2397  void delete_self() {
2398  cleanup();
2399  delete this;
2400  }
2401 
2402  /** @return whether the item is local to a stored procedure */
2403  virtual bool is_splocal() const { return false; }
2404 
2405  /*
2406  Return Settable_routine_parameter interface of the Item. Return 0
2407  if this Item is not Settable_routine_parameter.
2408  */
2410  return 0;
2411  }
2412  inline bool is_temporal_with_date() const {
2414  }
2415  inline bool is_temporal_with_date_and_time() const {
2417  }
2418  inline bool is_temporal_with_time() const {
2420  }
2421  inline bool is_temporal() const {
2423  }
2424  /**
2425  Check whether this and the given item has compatible comparison context.
2426  Used by the equality propagation. See Item_field::equal_fields_propagator.
2427 
2428  @return
2429  true if the context is the same or if fields could be
2430  compared as DATETIME values by the Arg_comparator.
2431  false otherwise.
2432  */
2433  inline bool has_compatible_context(Item *item) const {
2434  /* Same context. */
2436  return true;
2437  /* DATETIME comparison context. */
2438  if (is_temporal_with_date())
2439  return item->is_temporal_with_date() ||
2440  item->cmp_context == STRING_RESULT;
2441  if (item->is_temporal_with_date())
2443  return false;
2444  }
2446  return Field::GEOM_GEOMETRY;
2447  }
2448  String *check_well_formed_result(String *str, bool send_error, bool truncate);
2449  bool eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO *cs);
2450 
2451  /*
2452  Test whether an expression is expensive to compute. Used during
2453  optimization to avoid computing expensive expressions during this
2454  phase. Also used to force temp tables when sorting on expensive
2455  functions.
2456  TODO:
2457  Normally we should have a method:
2458  cost Item::execution_cost(),
2459  where 'cost' is either 'double' or some structure of various cost
2460  parameters.
2461  */
2462  virtual bool is_expensive() {
2463  if (is_expensive_cache < 0)
2466  return is_expensive_cache;
2467  }
2468 
2469  /**
2470  @return maximum number of characters that this Item can store
2471  If Item is of string or blob type, return max string length in bytes
2472  divided by bytes per character, otherwise return max_length.
2473  @todo - check if collation for other types should have mbmaxlen = 1
2474  */
2476  /*
2477  Length of e.g. 5.5e5 in an expression such as GREATEST(5.5e5, '5') is 5
2478  (length of that string) although length of the actual value is 6.
2479  Return MAX_DOUBLE_STR_LENGTH to prevent truncation of data without having
2480  to evaluate the value of the item.
2481  */
2482  uint32 max_len =
2484  if (result_type() == STRING_RESULT)
2485  return max_len / collation.collation->mbmaxlen;
2486  return max_len;
2487  }
2488 
2489  inline void fix_char_length(uint32 max_char_length_arg) {
2490  max_length = char_to_byte_length_safe(max_char_length_arg,
2492  }
2493 
2494  /*
2495  Return true if the item points to a column of an outer-joined table.
2496  */
2497  virtual bool is_outer_field() const {
2498  DBUG_ASSERT(fixed);
2499  return false;
2500  }
2501 
2502  /**
2503  Check if an item either is a blob field, or will be represented as a BLOB
2504  field if a field is created based on this item.
2505 
2506  @retval true If a field based on this item will be a BLOB field,
2507  @retval false Otherwise.
2508  */
2509  bool is_blob_field() const;
2510 
2511  protected:
2512  /// Set accumulated properties for an Item
2513  void set_accum_properties(const Item *item) {
2515  }
2516 
2517  /// Add more accumulated properties to an Item
2518  void add_accum_properties(const Item *item) {
2520  }
2521 
2522  /// Set the "has subquery" property
2524 
2525  /// Set the "has stored program" property
2527 
2528  public:
2529  /// @return true if this item or any of its decendents contains a subquery.
2530  bool has_subquery() const { return m_accum_properties & PROP_SUBQUERY; }
2531 
2532  /// @return true if this item or any of its decendents refers a stored func.
2533  bool has_stored_program() const {
2535  }
2536 
2537  /// @return true if this item or any of its decendents is an aggregated func.
2539 
2540  /// Set the "has aggregation" property
2542 
2543  /// Reset the "has aggregation" property
2545 
2546  /// @return true if this item or any of its decendents is a window func.
2548 
2549  /// Set the "has window function" property
2551 
2552  /**
2553  @return true if this item or any of its decendents within the same query
2554  has a reference to a ROLLUP expression
2555  */
2557 
2558  /// Set the property: this item (tree) contains a reference to a ROLLUP expr
2560 
2561  /**
2562  @return true if this item or any of underlying items is a GROUPING function
2563  */
2564  bool has_grouping_func() const {
2566  }
2567 
2568  /// Set the property: this item is a call to GROUPING
2570 
2571  /// Whether this Item was created by the IN->EXISTS subquery transformation
2572  virtual bool created_by_in2exists() const { return false; }
2573 
2574  // @return true if an expression in select list of derived table is used
2575  bool is_derived_used() const { return derived_used; }
2576 
2578  if (has_subquery())
2580  }
2581 
2582  /**
2583  Analyzer function for GC substitution. @see substitute_gc()
2584  */
2585  virtual bool gc_subst_analyzer(uchar **) { return false; }
2586  /**
2587  Transformer function for GC substitution. @see substitute_gc()
2588  */
2589  virtual Item *gc_subst_transformer(uchar *) { return this; }
2590 
2591  /**
2592  A processor that replaces any Fields with a Create_field_wrapper. This
2593  will allow us to resolve functions during CREATE TABLE, where we only have
2594  Create_field available and not Field. Used for functional index
2595  implementation.
2596  */
2597  virtual bool replace_field_processor(uchar *) { return false; }
2598  /**
2599  Check if this item is of a type that is eligible for GC
2600  substitution. All items that belong to subclasses of Item_func are
2601  eligible for substitution. @see substitute_gc()
2602  */
2604  const Type t = type();
2605  return t == FUNC_ITEM || t == COND_ITEM;
2606  }
2607 
2608  void aggregate_decimal_properties(Item **item, uint nitems);
2609  void aggregate_float_properties(Item **item, uint nitems);
2610  void aggregate_char_length(Item **args, uint nitems);
2611  void aggregate_temporal_properties(Item **item, uint nitems);
2612  bool aggregate_string_properties(const char *name, Item **item, uint nitems);
2613  void aggregate_num_type(Item_result result_type, Item **item, uint nitems);
2614 
2615  /**
2616  This function applies only to Item_field objects referred to by an Item_ref
2617  object that has been marked as a const_item.
2618 
2619  @param arg Keep track of whether an Item_ref refers to an Item_field.
2620  */
2621  virtual bool repoint_const_outer_ref(uchar *arg MY_ATTRIBUTE((unused))) {
2622  return false;
2623  }
2624  virtual Field *get_orig_field() { return NULL; }
2625  virtual void set_orig_field(Field *) {}
2626  virtual bool strip_db_table_name_processor(uchar *) { return false; }
2627 
2628  private:
2629  virtual bool subq_opt_away_processor(uchar *) { return false; }
2630 
2631  // Set an expression from select list of derived table as used.
2632  void set_derived_used() { derived_used = true; }
2633 
2634  public: // Start of data fields
2635  /**
2636  Intrusive list pointer for free list. If not null, points to the next
2637  Item on some Query_arena's free list. For instance, stored procedures
2638  have their own Query_arena's.
2639 
2640  @see Query_arena::free_list
2641  */
2643 
2644  protected:
2645  /// str_values's main purpose is to cache the value in save_in_field
2647 
2648  public:
2649  /**
2650  Character set and collation properties assigned for this Item.
2651  Used if Item represents a character string expression.
2652  */
2654  Item_name_string item_name; ///< Name from query
2655  Item_name_string orig_name; ///< Original item name (if it was renamed)
2656  /**
2657  Maximum length of result of evaluating this item, in number of bytes.
2658  - For character or blob data types, max char length multiplied by max
2659  character size (collation.mbmaxlen).
2660  - For decimal type, it is the precision in digits plus sign (unless
2661  unsigned) plus decimal point (unless it has zero decimals).
2662  - For other numeric types, the default or specific display length.
2663  - For date/time types, the display length (10 for DATE, 10 + optional FSP
2664  for TIME, 19 + optional fsp for datetime/timestamp).
2665  - For bit, the number of bits.
2666  - For enum, the string length of the widest enum element.
2667  - For set, the sum of the string length of each set element plus separators.
2668  - For geometry, the maximum size of a BLOB (it's underlying storage type).
2669  - For json, the maximum size of a BLOB (it's underlying storage type).
2670  */
2671  uint32 max_length; ///< Maximum length, in bytes
2672  enum item_marker ///< Values for member 'marker'
2679  /**
2680  This member has several successive meanings, depending on the phase we're
2681  in:
2682  - when doing constant propagation (e.g. change_cond_ref_to_const(), to
2683  remember that we have already processed the item).
2684  - when creating an internal temporary table: says how to store BIT fields
2685  - when analyzing functional dependencies for only_full_group_by (says
2686  whether a nullable column can be treated at not nullable)
2687  - when we change DISTINCT to GROUP BY: used for book-keeping of
2688  fields.
2689  - when pushing index conditions: it says whether a condition uses only
2690  indexed columns.
2691  The important property is that a phase must have a value (or few values)
2692  which is reserved for this phase. If it wants to set "marked", it assigns
2693  the value; it it wants to test if it is marked, it tests marker !=
2694  value. If the value has been assigned and the phase wants to cancel it can
2695  set marker to MARKER_NONE, which is a magic number which no phase
2696  reserves.
2697  A phase can expect 'marker' to be MARKER_NONE at the start of execution of
2698  a normal statement, at the start of preparation of a PS, and at the start
2699  of execution of a PS.
2700  A phase should not expect marker's value to survive after the phase's
2701  end - as a following phase may change it.
2702  */
2704  Item_result cmp_context; ///< Comparison context
2705  private:
2706  const bool is_parser_item; ///< true if allocated directly by parser
2707  /*
2708  If this item was created in runtime memroot, it cannot be used for
2709  substitution in subquery transformation process
2710  */
2712  int8 is_expensive_cache; ///< Cache of result of is_expensive()
2713  uint8 m_data_type; ///< Data type assigned to Item
2714  public:
2715  bool fixed; ///< True if item has been resolved
2716  /**
2717  Number of decimals in result when evaluating this item
2718  - For integer type, always zero.
2719  - For decimal type, number of decimals.
2720  - For float type, it may be DECIMAL_NOT_SPECIFIED
2721  - For time, datetime and timestamp, number of decimals in fractional second
2722  - For string types, may be decimals of cast source or DECIMAL_NOT_SPECIFIED
2723  */
2725  /**
2726  True if this item may be null.
2727 
2728  For items that represent rows, it is true if one of the columns
2729  may be null.
2730 
2731  For items that represent scalar or row subqueries, it is true if
2732  one of the returned columns could be null, or if the subquery
2733  could return zero rows.
2734  */
2736  bool null_value; ///< True if item is null
2738  bool m_is_window_function; ///< True if item represents window func
2739  private:
2740  /**
2741  True if this is an expression from the select list of a derived table
2742  which is actually used by outer query.
2743  */
2745 
2746  protected:
2747  /**
2748  Set of properties that are calculated by accumulation from underlying items.
2749  Computed by constructors and fix_fields() and updated by
2750  update_used_tables(). The properties are accumulated up to the root of the
2751  current item tree, except they are not accumulated across subqueries and
2752  functions.
2753  */
2754  static constexpr uint8 PROP_SUBQUERY = 0x01;
2755  static constexpr uint8 PROP_STORED_PROGRAM = 0x02;
2756  static constexpr uint8 PROP_AGGREGATION = 0x04;
2757  static constexpr uint8 PROP_WINDOW_FUNCTION = 0x08;
2758  /**
2759  Set if the item or one or more of the underlying items contains a
2760  ROLLUP expression. The rolled up expression itself is not so marked.
2761  */
2762  static constexpr uint8 PROP_ROLLUP_EXPR = 0x10;
2763  /**
2764  Set if the item or one or more of the underlying items is a GROUPING
2765  function.
2766  */
2767  static constexpr uint8 PROP_GROUPING_FUNC = 0x20;
2769 
2770  public:
2771  /**
2772  Noop in Item for items that are not subclasses of Item_ident.
2773  Overridden in Item_ident where it sets the
2774  table_name member. Signture matches the requirement of
2775  Item::walk.
2776 
2777  @return true - to signal that walk should continue to sub items.
2778  */
2779  virtual bool set_table_name(uchar *) { return true; }
2780 
2781  /**
2782  Check if this expression can be used for partial update of a given
2783  JSON column.
2784 
2785  For example, the expression `JSON_REPLACE(col, '$.foo', 'bar')`
2786  can be used to partially update the column `foo`.
2787 
2788  @param field the JSON column that is being updated
2789  @return true if this expression can be used for partial update,
2790  false otherwise
2791  */
2793  const Field_json *field MY_ATTRIBUTE((unused))) const {
2794  return false;
2795  }
2796 
2797  /**
2798  Whether the item returns array of its data type
2799  */
2800  virtual bool returns_array() const { return false; }
2801 
2802  /**
2803  A helper funciton to ensure proper usage of CAST(.. AS .. ARRAY)
2804  */
2805  virtual void allow_array_cast() {}
2806 };
2807 
2808 /**
2809  Descriptor of what and how to cache for
2810  Item::cache_const_expr_transformer/analyzer.
2811 
2812 */
2813 
2815  /// Path from the expression's top to the current item in item tree
2816  /// used to track parent of current item for caching JSON data
2818  /// Item to cache. Used as a binary flag, but kept as Item* for assertion
2819  Item *cache_item{nullptr};
2820  /// How to cache JSON data. @see Item::enum_const_item_cache
2822 };
2823 
2824 /**
2825  A helper class to give in a functor to Item::walk(). Use as e.g.:
2826 
2827  bool result = WalkItem(root_item, enum_walk::POSTFIX, [](Item *item) { ... });
2828 
2829  TODO: Make Item::walk() just take in a functor in the first place, instead of
2830  a pointer-to-member and an opaque argument.
2831  */
2832 template <class T>
2833 inline bool WalkItem(Item *item, enum_walk walk, T &&functor) {
2834  return item->walk(&Item::walk_helper_thunk<T>, walk,
2835  reinterpret_cast<uchar *>(&functor));
2836 }
2837 
2838 class sp_head;
2839 
2840 class Item_basic_constant : public Item {
2842 
2843  public:
2845  explicit Item_basic_constant(const POS &pos) : Item(pos), used_table_map(0) {}
2846 
2847  /// @todo add implementation of basic_const_item
2848  /// and remove from subclasses as appropriate.
2849 
2851  table_map used_tables() const override { return used_table_map; }
2852  bool check_function_as_value_generator(uchar *) override { return false; }
2853  /* to prevent drop fixed flag (no need parent cleanup call) */
2854  void cleanup() override {
2855  /*
2856  Restore the original field name as it might not have been allocated
2857  in the statement memory. If the name is auto generated, it must be
2858  done again between subsequent executions of a prepared statement.
2859  */
2861  }
2862  bool basic_const_item() const override { return true; }
2863  void set_str_value(String *str) { str_value = *str; }
2864 };
2865 
2866 /*****************************************************************************
2867  The class is a base class for representation of stored routine variables in
2868  the Item-hierarchy. There are the following kinds of SP-vars:
2869  - local variables (Item_splocal);
2870  - CASE expression (Item_case_expr);
2871 *****************************************************************************/
2872 
2873 class Item_sp_variable : public Item {
2874  protected:
2875  /*
2876  THD, which is stored in fix_fields() and is used in this_item() to avoid
2877  current_thd use.
2878  */
2880 
2881  public:
2883 
2884  public:
2885 #ifndef DBUG_OFF
2886  /*
2887  Routine to which this Item_splocal belongs. Used for checking if correct
2888  runtime context is used for variable handling.
2889  */
2891 #endif
2892 
2893  public:
2894  Item_sp_variable(const Name_string sp_var_name);
2895 
2896  public:
2897  bool fix_fields(THD *thd, Item **) override;
2898 
2899  double val_real() override;
2900  longlong val_int() override;
2901  String *val_str(String *sp) override;
2902  my_decimal *val_decimal(my_decimal *decimal_value) override;
2903  bool val_json(Json_wrapper *result) override;
2904  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
2905  bool get_time(MYSQL_TIME *ltime) override;
2906  bool is_null() override;
2907 
2908  public:
2909  inline void make_field(Send_field *field) override;
2910  inline bool send(Protocol *protocol, String *str) override;
2911 
2912  protected:
2914  Field *field, bool no_conversions) override;
2915 };
2916 
2917 /*****************************************************************************
2918  Item_sp_variable inline implementation.
2919 *****************************************************************************/
2920 
2922  Item *it = this_item();
2924  it->make_field(field);
2925 }
2926 
2928  Field *field, bool no_conversions) {
2929  return this_item()->save_in_field(field, no_conversions);
2930 }
2931 
2933  return this_item()->send(protocol, str);
2934 }
2935 
2936 /*****************************************************************************
2937  A reference to local SP variable (incl. reference to SP parameter), used in
2938  runtime.
2939 *****************************************************************************/
2940 
2942  private Settable_routine_parameter {
2944 
2947 
2948  public:
2949  /*
2950  If this variable is a parameter in LIMIT clause.
2951  Used only during NAME_CONST substitution, to not append
2952  NAME_CONST to the resulting query and thus not break
2953  the slave.
2954  */
2956  /*
2957  Position of this reference to SP variable in the statement (the
2958  statement itself is in sp_instr_stmt::m_query).
2959  This is valid only for references to SP variables in statements,
2960  excluding DECLARE CURSOR statement. It is used to replace references to SP
2961  variables with NAME_CONST calls when putting statements into the binary
2962  log.
2963  Value of 0 means that this object doesn't corresponding to reference to
2964  SP variable in query text.
2965  */
2967  /*
2968  Byte length of SP variable name in the statement (see pos_in_query).
2969  The value of this field may differ from the name_length value because
2970  name_length contains byte length of UTF8-encoded item name, but
2971  the query string (see sp_instr_stmt::m_query) is currently stored with
2972  a charset from the SET NAMES statement.
2973  */
2975 
2976  Item_splocal(const Name_string sp_var_name, uint sp_var_idx,
2977  enum_field_types sp_var_type, uint pos_in_q = 0,
2978  uint len_in_q = 0);
2979 
2980  bool is_splocal() const override { return true; }
2981 
2982  Item *this_item() override;
2983  const Item *this_item() const override;
2984  Item **this_item_addr(THD *thd, Item **) override;
2985 
2986  void print(const THD *thd, String *str,
2987  enum_query_type query_type) const override;
2988 
2989  public:
2990  inline uint get_var_idx() const { return m_var_idx; }
2991 
2992  inline enum Type type() const override { return m_type; }
2993  inline Item_result result_type() const override { return m_result_type; }
2994  bool val_json(Json_wrapper *result) override;
2995 
2996  private:
2997  bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
2998 
2999  public:
3001  return this;
3002  }
3003 };
3004 
3005 /*****************************************************************************
3006  A reference to case expression in SP, used in runtime.
3007 *****************************************************************************/
3008 
3010  public:
3011  Item_case_expr(uint case_expr_id);
3012 
3013  public:
3014  Item *this_item() override;
3015  const Item *this_item() const override;
3016  Item **this_item_addr(THD *thd, Item **) override;
3017 
3018  Type type() const override { return this_item()->type(); }
3019  Item_result result_type() const override {
3020  return this_item()->result_type();
3021  }
3022 
3023  public:
3024  /*
3025  NOTE: print() is intended to be used from views and for debug.
3026  Item_case_expr can not occur in views, so here it is only for debug
3027  purposes.
3028  */
3029  void print(const THD *thd, String *str,
3030  enum_query_type query_type) const override;
3031 
3032  private:
3034 };
3035 
3036 /*
3037  NAME_CONST(given_name, const_value).
3038  This 'function' has all properties of the supplied const_value (which is
3039  assumed to be a literal constant), and the name given_name.
3040 
3041  This is used to replace references to SP variables when we write PROCEDURE
3042  statements into the binary log.
3043 
3044  TODO
3045  Together with Item_splocal and Item::this_item() we can actually extract
3046  common a base of this class and Item_splocal. Maybe it is possible to
3047  extract a common base with class Item_ref, too.
3048 */
3049 
3050 class Item_name_const final : public Item {
3051  typedef Item super;
3052 
3056 
3057  public:
3058  Item_name_const(const POS &pos, Item *name_arg, Item *val);
3059 
3060  bool itemize(Parse_context *pc, Item **res) override;
3061  bool fix_fields(THD *, Item **) override;
3062 
3063  enum Type type() const override;
3064  double val_real() override;
3065  longlong val_int() override;
3066  String *val_str(String *sp) override;
3067  my_decimal *val_decimal(my_decimal *) override;
3068  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3069  bool get_time(MYSQL_TIME *ltime) override;
3070  bool is_null() override;
3071  void print(const THD *thd, String *str,
3072  enum_query_type query_type) const override;
3073 
3074  Item_result result_type() const override { return value_item->result_type(); }
3075 
3076  bool send(Protocol *protocol, String *str) override {
3077  return value_item->send(protocol, str);
3078  }
3079 
3080  bool cache_const_expr_analyzer(uchar **) override {
3081  // Item_name_const always wraps a literal, so there is no need to cache it.
3082  return false;
3083  }
3084 
3085  protected:
3087  bool no_conversions) override {
3088  return value_item->save_in_field(field, no_conversions);
3089  }
3090 };
3091 
3093  Item **items, uint nitems, uint flags);
3094 bool agg_item_set_converter(DTCollation &coll, const char *fname, Item **args,
3095  uint nargs, uint flags, int item_sep);
3096 bool agg_item_charsets(DTCollation &c, const char *name, Item **items,
3097  uint nitems, uint flags, int item_sep);
3099  const char *name, Item **items,
3100  uint nitems, int item_sep = 1) {
3103  return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3104 }
3106  Item **items, uint nitems,
3107  int item_sep = 1) {
3110  return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3111 }
3113  DTCollation &c, const char *name, Item **items, uint nitems,
3114  int item_sep = 1) {
3117  return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3118 }
3119 
3122 
3123  public:
3124  Item_num() { collation.set_numeric(); } /* Remove gcc warning */
3125  explicit Item_num(const POS &pos) : super(pos) { collation.set_numeric(); }
3126 
3127  virtual Item_num *neg() = 0;
3128  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3129  bool check_partition_func_processor(uchar *) override { return false; }
3130 };
3131 
3132 #define NO_CACHED_FIELD_INDEX ((uint)(-1))
3133 
3134 class Item_ident : public Item {
3135  typedef Item super;
3136 
3137  protected:
3138  /*
3139  We have to store initial values of db_name, table_name and field_name
3140  to be able to restore them during cleanup() because they can be
3141  updated during fix_fields() to values from Field object and life-time
3142  of those is shorter than life-time of Item_field.
3143  */
3144  const char *orig_db_name;
3145  const char *orig_table_name;
3146  const char *orig_field_name;
3147  bool m_alias_of_expr; ///< if this Item's name is alias of SELECT expression
3148 
3149  public:
3150  /**
3151  For regularly resolved column references, 'context' points to a name
3152  resolution context object belonging to the query block which simply
3153  contains the reference. To further clarify, in
3154  SELECT (SELECT t.a) FROM t;
3155  t.a is an Item_ident whose 'context' belongs to the subquery
3156  (context->select_lex == that of the subquery).
3157  For column references that are part of a generated column expression,
3158  'context' points to a temporary name resolution context object during
3159  resolving, but is set to nullptr after resolving is done. Note that
3160  Item_ident::local_column() depends on that.
3161  */
3163  const char *db_name;
3164  const char *table_name;
3165  const char *field_name;
3166 
3167  /*
3168  Cached value of index for this field in table->field array, used by prep.
3169  stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX
3170  if index value is not known.
3171  */
3173  /*
3174  Cached pointer to table which contains this field, used for the same reason
3175  by prep. stmt. too in case then we have not-fully qualified field.
3176  0 - means no cached value.
3177  @todo Notice that this is usually the same as Item_field::table_ref.
3178  cached_table should be replaced by table_ref ASAP.
3179  */
3182 
3183  Item_ident(Name_resolution_context *context_arg, const char *db_name_arg,
3184  const char *table_name_arg, const char *field_name_arg)
3185  : orig_db_name(db_name_arg),
3186  orig_table_name(table_name_arg),
3187  orig_field_name(field_name_arg),
3189  context(context_arg),
3190  db_name(db_name_arg),
3191  table_name(table_name_arg),
3192  field_name(field_name_arg),
3194  cached_table(NULL),
3195  depended_from(NULL) {
3196  item_name.set(field_name_arg);
3197  }
3198 
3199  Item_ident(const POS &pos, const char *db_name_arg,
3200  const char *table_name_arg, const char *field_name_arg)
3201  : super(pos),
3202  orig_db_name(db_name_arg),
3203  orig_table_name(table_name_arg),
3204  orig_field_name(field_name_arg),
3206  db_name(db_name_arg),
3207  table_name(table_name_arg),
3208  field_name(field_name_arg),
3210  cached_table(NULL),
3211  depended_from(NULL) {
3212  item_name.set(field_name_arg);
3213  }
3214 
3215  /// Constructor used by Item_field & Item_*_ref (see Item comment)
3216 
3218  : Item(thd, item),
3219  orig_db_name(item->orig_db_name),
3223  context(item->context),
3224  db_name(item->db_name),
3225  table_name(item->table_name),
3226  field_name(item->field_name),
3228  cached_table(item->cached_table),
3229  depended_from(item->depended_from) {}
3230 
3231  bool itemize(Parse_context *pc, Item **res) override;
3232 
3233  const char *full_name() const override;
3234  void fix_after_pullout(SELECT_LEX *parent_select,
3235  SELECT_LEX *removed_select) override;
3236  void cleanup() override;
3237  bool aggregate_check_distinct(uchar *arg) override;
3238  bool aggregate_check_group(uchar *arg) override;
3239  Bool3 local_column(const SELECT_LEX *sl) const override;
3240 
3241  void print(const THD *thd, String *str,
3242  enum_query_type query_type) const override {
3243  print(thd, str, query_type, db_name, table_name);
3244  }
3245 
3246  /**
3247  Assign the argument to table_name. Argument passed as uchar* to
3248  match requirement of Item::walk.
3249 
3250  @param tn new table_name (should be pointer to const char)
3251  @return true - to signal that walk should continue to sub items.
3252  */
3253  bool set_table_name(uchar *tn) override final {
3254  table_name = pointer_cast<const char *>(tn);
3255  return true;
3256  }
3257 
3258  protected:
3259  /**
3260  Function to print column name for a table
3261 
3262  To print a column for a permanent table (picks up database and table from
3263  Item_ident object):
3264 
3265  item->print(str, qt)
3266 
3267  To print a column for a temporary table:
3268 
3269  item->print(str, qt, specific_db, specific_table)
3270 
3271  Items of temporary table fields have empty/NULL values of table_name and
3272  db_name. To print column names in a 3D form (`database`.`table`.`column`),
3273  this function prints db_name_arg and table_name_arg parameters instead of
3274  this->db_name and this->table_name respectively.
3275 
3276  @param thd Thread handle.
3277  @param [out] str Output string buffer.
3278  @param query_type Bitmap to control printing details.
3279  @param db_name_arg String to output as a column database name.
3280  @param table_name_arg String to output as a column table name.
3281  */
3282  void print(const THD *thd, String *str, enum_query_type query_type,
3283  const char *db_name_arg, const char *table_name_arg) const;
3284 
3285  public:
3286  bool change_context_processor(uchar *cntx) override {
3287  context = reinterpret_cast<Name_resolution_context *>(cntx);
3288  return false;
3289  }
3290 
3291  /// @returns true if this Item's name is alias of SELECT expression
3292  bool is_alias_of_expr() const { return m_alias_of_expr; }
3293  /// Marks that this Item's name is alias of SELECT expression
3295 
3296  bool walk(Item_processor processor, enum_walk walk, uchar *arg) override {
3297  /*
3298  Item_ident processors like aggregate_check*() use
3299  enum_walk::PREFIX|enum_walk::POSTFIX and depend on the processor being
3300  called twice then.
3301  */
3302  return ((walk & enum_walk::PREFIX) && (this->*processor)(arg)) ||
3303  ((walk & enum_walk::POSTFIX) && (this->*processor)(arg));
3304  }
3305 
3306  /**
3307  @returns true if a part of this Item's full name (name or table name) is
3308  an alias.
3309  */
3310  virtual bool alias_name_used() const { return m_alias_of_expr; }
3311  friend bool insert_fields(THD *thd, Name_resolution_context *context,
3312  const char *db_name, const char *table_name,
3313  List_iterator<Item> *it, bool any_privileges);
3314  bool is_strong_side_column_not_in_fd(uchar *arg) override;
3315  bool is_column_not_in_fd(uchar *arg) override;
3316 };
3317 
3319  public:
3321  const char *db_name;
3322  const char *table_name;
3323 
3324  Item_ident_for_show(Field *par_field, const char *db_arg,
3325  const char *table_name_arg)
3326  : field(par_field), db_name(db_arg), table_name(table_name_arg) {}
3327 
3328  enum Type type() const override { return FIELD_ITEM; }
3329  virtual bool fix_fields(THD *thd, Item **ref) override;
3330  double val_real() override { return field->val_real(); }
3331  longlong val_int() override { return field->val_int(); }
3332  String *val_str(String *str) override { return field->val_str(str); }
3334  return field->val_decimal(dec);
3335  }
3336  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
3337  return field->get_date(ltime, fuzzydate);
3338  }
3339  bool get_time(MYSQL_TIME *ltime) override { return field->get_time(ltime); }
3340  void make_field(Send_field *tmp_field) override;
3341  const CHARSET_INFO *charset_for_protocol() const override {
3342  return field->charset_for_protocol();
3343  }
3344 };
3345 
3346 class COND_EQUAL;
3347 class Item_equal;
3348 
3349 class Item_field : public Item_ident {
3351 
3352  protected:
3353  void set_field(Field *field);
3355  bool no_conversions) override;
3356 
3357  public:
3358  /**
3359  Table containing this resolved field. This is required e.g for calculation
3360  of table map. Notice that for the following types of "tables",
3361  no TABLE_LIST object is assigned and hence table_ref is NULL:
3362  - Temporary tables assigned by join optimizer for sorting and aggregation.
3363  - Stored procedure dummy tables.
3364  For fields referencing such tables, table number is always 0, and other
3365  uses of table_ref is not needed.
3366  */
3368  /// Source field
3370  /**
3371  Item's original field. Used to compare fields in Item_field::eq() in order
3372  to get proper result when field is transformed by tmp table.
3373  */
3375  /// Result field
3379  /*
3380  if any_privileges set to true then here real effective privileges will
3381  be stored
3382  */
3384  /* field need any privileges (for VIEW creation) */
3386  /*
3387  if this field is used in a context where covering prefix keys
3388  are supported.
3389  */
3390  bool can_use_prefix_key{false};
3391 
3392  Item_field(Name_resolution_context *context_arg, const char *db_arg,
3393  const char *table_name_arg, const char *field_name_arg);
3394  Item_field(const POS &pos, const char *db_arg, const char *table_name_arg,
3395  const char *field_name_arg);
3396 
3397  /*
3398  Constructor needed to process subquery with temporary tables (see Item).
3399  Notice that it will have no name resolution context.
3400  */
3401  Item_field(THD *thd, Item_field *item);
3402  /*
3403  Ensures that field, table, and database names will live as long as
3404  Item_field (this is important in prepared statements).
3405  */
3406  Item_field(THD *thd, Name_resolution_context *context_arg, Field *field);
3407  /*
3408  If this constructor is used, fix_fields() won't work, because
3409  db_name, table_name and column_name are unknown. It's necessary to call
3410  reset_field() before fix_fields() for all fields created this way.
3411  */
3413 
3414  bool itemize(Parse_context *pc, Item **res) override;
3415 
3416  enum Type type() const override { return FIELD_ITEM; }
3417  bool eq(const Item *item, bool binary_cmp) const override;
3418  double val_real() override;
3419  longlong val_int() override;
3420  longlong val_time_temporal() override;
3421  longlong val_date_temporal() override;
3422  my_decimal *val_decimal(my_decimal *) override;
3423  String *val_str(String *) override;
3424  bool val_json(Json_wrapper *result) override;
3425  bool send(Protocol *protocol, String *str_arg) override;
3426  void reset_field(Field *f);
3427  bool fix_fields(THD *, Item **) override;
3428  void make_field(Send_field *tmp_field) override;
3429  void save_org_in_field(Field *field) override;
3430  table_map used_tables() const override;
3431  enum Item_result result_type() const override { return field->result_type(); }
3434  }
3435  Item_result cast_to_int_type() const override {
3436  return field->cast_to_int_type();
3437  }
3440  }
3441  longlong val_int_endpoint(bool left_endp, bool *incl_endp) override;
3442  Field *get_tmp_table_field() override { return result_field; }
3443  Field *tmp_table_field(TABLE *) override { return result_field; }
3444  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3445  bool get_time(MYSQL_TIME *ltime) override;
3446  bool get_timeval(struct timeval *tm, int *warnings) override;
3447  bool is_null() override {
3448  // NOTE: May return true even if maybe_null is not set!
3449  // This can happen if the underlying TABLE did not have a NULL row
3450  // at set_field() time (ie., table->is_null_row() was false),
3451  // but does now.
3452  return field->is_null();
3453  }
3454  Item *get_tmp_table_item(THD *thd) override;
3455  bool collect_item_field_processor(uchar *arg) override;
3456  bool add_field_to_set_processor(uchar *arg) override;
3457  bool add_field_to_cond_set_processor(uchar *) override;
3458  bool remove_column_from_bitmap(uchar *arg) override;
3459  bool find_item_in_field_list_processor(uchar *arg) override;
3460  bool find_field_processor(uchar *arg) override {
3461  return pointer_cast<Field *>(arg) == field;
3462  }
3463  bool check_function_as_value_generator(uchar *args) override;
3464  bool mark_field_in_map(uchar *arg) override {
3465  auto mark_field = pointer_cast<Mark_field *>(arg);
3466  bool rc = Item::mark_field_in_map(mark_field, field);
3467  if (result_field && result_field != field)
3468  rc |= Item::mark_field_in_map(mark_field, result_field);
3469  return rc;
3470  }
3471  bool used_tables_for_level(uchar *arg) override;
3472  bool check_column_privileges(uchar *arg) override;
3473  bool check_partition_func_processor(uchar *) override { return false; }
3474  void cleanup() override;
3475  Item_equal *find_item_equal(COND_EQUAL *cond_equal);
3476  bool subst_argument_checker(uchar **arg) override;
3477  Item *equal_fields_propagator(uchar *arg) override;
3478  bool set_no_const_sub(uchar *) override;
3479  Item *replace_equal_field(uchar *) override;
3481  Item_field *field_for_view_update() override { return this; }
3482  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3483  int fix_outer_field(THD *thd, Field **field, Item **reference);
3484  Item *update_value_transformer(uchar *select_arg) override;
3485  void print(const THD *thd, String *str,
3486  enum_query_type query_type) const override;
3487  bool is_outer_field() const override {
3488  DBUG_ASSERT(fixed);
3490  }
3493  return field->get_geometry_type();
3494  }
3495  const CHARSET_INFO *charset_for_protocol(void) const override {
3496  return field->charset_for_protocol();
3497  }
3498 
3499 #ifndef DBUG_OFF
3500  void dbug_print() const {
3501  fprintf(DBUG_FILE, "<field ");
3502  if (field) {
3503  fprintf(DBUG_FILE, "'%s.%s': ", field->table->alias, field->field_name);
3504  field->dbug_print();
3505  } else
3506  fprintf(DBUG_FILE, "NULL");
3507 
3508  fprintf(DBUG_FILE, ", result_field: ");
3509  if (result_field) {
3510  fprintf(DBUG_FILE, "'%s.%s': ", result_field->table->alias,
3513  } else
3514  fprintf(DBUG_FILE, "NULL");
3515  fprintf(DBUG_FILE, ">\n");
3516  }
3517 #endif
3518 
3519  float get_filtering_effect(THD *thd, table_map filter_for_table,
3520  table_map read_tables,
3521  const MY_BITMAP *fields_to_ignore,
3522  double rows_in_table) override;
3523 
3524  /**
3525  Returns the probability for the predicate "col OP <val>" to be
3526  true for a row in the case where no index statistics or range
3527  estimates are available for 'col'.
3528 
3529  The probability depends on the number of rows in the table: it is by
3530  default 'default_filter', but never lower than 1/max_distinct_values
3531  (e.g. number of rows in the table, or the number of distinct values
3532  possible for the datatype if the field provides that kind of
3533  information).
3534 
3535  @param max_distinct_values The maximum number of distinct values,
3536  typically the number of rows in the table
3537  @param default_filter The default filter for the predicate
3538 
3539  @return the estimated filtering effect for this predicate
3540  */
3541 
3542  float get_cond_filter_default_probability(double max_distinct_values,
3543  float default_filter) const;
3544 
3545  friend class Item_default_value;
3546  friend class Item_insert_value;
3547  friend class SELECT_LEX_UNIT;
3548 
3549  /**
3550  @note that field->table->alias_name_used is reliable only if
3551  thd->lex->need_correct_ident() is true.
3552  */
3553  bool alias_name_used() const override {
3554  return m_alias_of_expr ||
3555  // maybe the qualifying table was given an alias ("t1 AS foo"):
3557  }
3558 
3559  bool repoint_const_outer_ref(uchar *arg) override;
3560  Field *get_orig_field() override { return orig_field; }
3561  void set_orig_field(Field *orig_field_arg) override {
3562  if (orig_field_arg) orig_field = orig_field_arg;
3563  }
3564  bool returns_array() const override { return field && field->is_array(); }
3565 
3566  void set_can_use_prefix_key() override { can_use_prefix_key = true; }
3567 
3568  bool replace_field_processor(uchar *arg) override;
3569  bool strip_db_table_name_processor(uchar *) override;
3570 };
3571 
3574 
3575  void init() {
3576  maybe_null = true;
3577  null_value = true;
3579  max_length = 0;
3580  fixed = true;
3582  }
3583 
3584  protected:
3586  bool no_conversions) override;
3587 
3588  public:
3590  init();
3591  item_name = NAME_STRING("NULL");
3592  }
3593  explicit Item_null(const POS &pos) : super(pos) {
3594  init();
3595  item_name = NAME_STRING("NULL");
3596  }
3597 
3598  Item_null(const Name_string &name_par) {
3599  init();
3600  item_name = name_par;
3601  }
3602 
3603  enum Type type() const override { return NULL_ITEM; }
3604  bool eq(const Item *item, bool binary_cmp) const override;
3605  double val_real() override;
3606  longlong val_int() override;
3607  longlong val_time_temporal() override { return val_int(); }
3608  longlong val_date_temporal() override { return val_int(); }
3609  String *val_str(String *str) override;
3610  my_decimal *val_decimal(my_decimal *) override;
3611  bool get_date(MYSQL_TIME *, my_time_flags_t) override { return true; }
3612  bool get_time(MYSQL_TIME *) override { return true; }
3613  bool val_json(Json_wrapper *wr) override;
3614  bool send(Protocol *protocol, String *str) override;
3615  enum Item_result result_type() const override { return STRING_RESULT; }
3616  Item *clone_item() const override { return new Item_null(item_name); }
3617  bool is_null() override { return true; }
3618 
3619  void print(const THD *, String *str,
3620  enum_query_type query_type) const override {
3621  str->append(query_type == QT_NORMALIZED_FORMAT ? "?" : "NULL");
3622  }
3623 
3624  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3625  bool check_partition_func_processor(uchar *) override { return false; }
3626 };
3627 
3628 /**
3629  An item representing NULL values for use with ROLLUP.
3630 
3631  When grouping WITH ROLLUP, Item_null_result items are created to
3632  represent NULL values in the grouping columns of the ROLLUP rows. To
3633  avoid type problems during execution, these objects are created with
3634  the same field and result types as the fields of the columns they
3635  belong to.
3636  */
3638  /** Result type for this NULL value */
3640 
3641  public:
3645  set_data_type(fld_type);
3646  }
3647  void set_result_field(Field *field) override { result_field = field; }
3648  bool is_result_field() const override { return result_field != nullptr; }
3649  Field *get_result_field() const override { return result_field; }
3650  void save_in_result_field(bool no_conversions) override {
3651  save_in_field(result_field, no_conversions);
3652  }
3653  bool check_partition_func_processor(uchar *) override { return true; }
3654  Item_result result_type() const override { return res_type; }
3658  func_arg->banned_function_name = "NULL";
3659  // This should not happen as SELECT statements are not allowed.
3660  DBUG_ASSERT(false);
3661  return true;
3662  }
3663  enum Type type() const override { return NULL_RESULT_ITEM; }
3664 };
3665 
3666 /// Placeholder ('?') of prepared statement.
3668  typedef Item super;
3669 
3670  protected:
3672  bool no_conversions) override;
3673 
3674  public:
3684  } state;
3685 
3686  /*
3687  A buffer for string and long data values. Historically all allocated
3688  values returned from val_str() were treated as eligible to
3689  modification. I. e. in some cases Item_func_concat can append it's
3690  second argument to return value of the first one. Because of that we
3691  can't return the original buffer holding string data from val_str(),
3692  and have to have one buffer for data and another just pointing to
3693  the data. This is the latter one and it's returned from val_str().
3694  Can not be declared inside the union as it's not a POD type.
3695  */
3698  union {
3700  double real;
3701  /*
3702  Character sets conversion info for string values.
3703  Character sets of client and connection defined at bind time are used
3704  for all conversions, even if one of them is later changed (i.e.
3705  between subsequent calls to mysql_stmt_execute).
3706  */
3707  struct CONVERSION_INFO {
3710  /*
3711  This points at character set of connection if conversion
3712  to it is required (i. e. if placeholder typecode is not BLOB).
3713  Otherwise it's equal to character_set_client (to simplify
3714  check in convert_str_value()).
3715  */
3717  } cs_info;
3719  } value;
3720 
3721  /* Cached values for virtual methods to save us one switch. */
3724 
3725  /*
3726  data_type() is used when this item is used in a temporary table.
3727  This is NOT placeholder metadata sent to client, as this value
3728  is assigned after sending metadata (in setup_one_conversion_function).
3729  For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both
3730  in result set and placeholders metadata, no matter what type you will
3731  supply for this placeholder in mysql_stmt_execute.
3732  */
3733 
3734  /*
3735  Offset of placeholder inside statement text. Used to create
3736  no-placeholders version of this statement for the binary log.
3737  */
3739 
3740  Item_param(const POS &pos, MEM_ROOT *root, uint pos_in_query_arg);
3741 
3742  bool itemize(Parse_context *pc, Item **item) override;
3743 
3744  enum Item_result result_type() const override { return item_result_type; }
3745  enum Type type() const override { return item_type; }
3746 
3747  double val_real() override;
3748  longlong val_int() override;
3749  my_decimal *val_decimal(my_decimal *) override;
3750  String *val_str(String *) override;
3751  bool get_time(MYSQL_TIME *tm) override;
3752  bool get_date(MYSQL_TIME *tm, my_time_flags_t fuzzydate) override;
3753 
3754  void set_null();
3755  void set_int(longlong i, uint32 max_length_arg);
3756  void set_double(double i);
3757  void set_decimal(const char *str, ulong length);
3758  void set_decimal(const my_decimal *dv);
3759  bool set_str(const char *str, size_t length);
3760  bool set_longdata(const char *str, ulong length);
3762  uint32 max_length_arg);
3763  bool set_from_user_var(THD *thd, const user_var_entry *entry);
3764  void reset();
3765  /*
3766  Assign placeholder value from bind data.
3767  */
3769 
3770  const String *query_val_str(const THD *thd, String *str) const;
3771 
3772  bool convert_str_value();
3773 
3774  /*
3775  Parameter is treated as constant during execution, thus it will not be
3776  evaluated during preparation.
3777  */
3778  table_map used_tables() const override {
3779  return state != NO_VALUE ? 0 : INNER_TABLE_BIT;
3780  }
3781  void print(const THD *thd, String *str,
3782  enum_query_type query_type) const override;
3783  bool is_null() override {
3785  return state == NULL_VALUE;
3786  }
3787  bool basic_const_item() const override {
3788  if (state == NO_VALUE || state == TIME_VALUE) return false;
3789  return true;
3790  }
3791 
3792  /*
3793  This method is used to make a copy of a basic constant item when
3794  propagating constants in the optimizer. The reason to create a new
3795  item and not use the existing one is not precisely known (2005/04/16).
3796  Probably we are trying to preserve tree structure of items, in other
3797  words, avoid pointing at one item from two different nodes of the tree.
3798  Return a new basic constant item if parameter value is a basic
3799  constant, assert otherwise. This method is called only if
3800  basic_const_item returned true.
3801  */
3802  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3803  Item *clone_item() const override;
3804  /*
3805  Implement by-value equality evaluation if parameter value
3806  is set and is a basic constant (integer, real or string).
3807  Otherwise return false.
3808  */
3809  bool eq(const Item *item, bool binary_cmp) const override;
3810  /** Item is a argument to a limit clause. */
3813  bool is_non_const_over_literals(uchar *) override { return true; }
3814  /**
3815  This should be called after any modification done to this Item, to
3816  propagate the said modification to all its clones.
3817  */
3818  void sync_clones();
3819  bool add_clone(Item_param *i) { return m_clones.push_back(i); }
3820 
3821  private:
3823  return this;
3824  }
3825 
3826  bool set_value(THD *, sp_rcontext *, Item **it) override;
3827 
3828  void set_out_param_info(Send_field *info) override;
3829 
3830  public:
3831  const Send_field *get_out_param_info() const override;
3832 
3833  void make_field(Send_field *field) override;
3834 
3838  func_arg->err_code = func_arg->get_unnamed_function_error_code();
3839  return true;
3840  }
3841 
3842  private:
3844  /**
3845  If a query expression's text QT, containing a parameter, is internally
3846  duplicated and parsed twice (@see reparse_common_table_expression), the
3847  first parsing will create an Item_param I, and the re-parsing, which
3848  parses a forged "(QT)" parse-this-CTE type of statement, will create an
3849  Item_param J. J should not exist:
3850  - from the point of view of logging: it is not in the original query so it
3851  should not be substituted in the query written to logs (in insert_params()
3852  if with_log is true).
3853  - from the POV of the user:
3854  * user provides one single value for I, not one for I and one for J.
3855  * user expects mysql_stmt_param_count() to return 1, not 2 (count is
3856  sent by the server in send_prep_stmt()).
3857  That is why J is part neither of LEX::param_list, nor of param_array; it
3858  is considered an inferior clone of I; I::m_clones contains J.
3859  The connection between I and J is made once, by comparing their
3860  byte position in the statement, in Item_param::itemize().
3861  J gets its value from I: @see Item_param::sync_clones.
3862  */
3864 };
3865 
3866 class Item_int : public Item_num {
3867  typedef Item_num super;
3868 
3869  public:
3872  : value((longlong)i) {
3874  max_length = length;
3875  fixed = true;
3876  }
3878  : super(pos), value((longlong)i) {
3880  max_length = length;
3881  fixed = true;
3882  }
3885  max_length = length;
3886  fixed = true;
3887  }
3889  : value((longlong)i) {
3891  max_length = length;
3892  fixed = true;
3893  unsigned_flag = true;
3894  }
3895  Item_int(const Item_int *item_arg) {
3896  set_data_type(item_arg->data_type());
3897  value = item_arg->value;
3898  item_name = item_arg->item_name;
3899  max_length = item_arg->max_length;
3900  fixed = true;
3901  }
3902  Item_int(const Name_string &name_arg, longlong i, uint length) : value(i) {
3904  max_length = length;
3905  item_name = name_arg;
3906  fixed = true;
3907  }
3908  Item_int(const POS &pos, const Name_string &name_arg, longlong i, uint length)
3909  : super(pos), value(i) {
3911  max_length = length;
3912  item_name = name_arg;
3913  fixed = true;
3914  }
3915  Item_int(const char *str_arg, uint length) {
3917  init(str_arg, length);
3918  }
3919  Item_int(const POS &pos, const char *str_arg, uint length) : super(pos) {
3921  init(str_arg, length);
3922  }
3923 
3924  Item_int(const POS &pos, const LEX_STRING &num, int dummy_error = 0)
3925  : Item_int(pos, num, my_strtoll10(num.str, NULL, &dummy_error),
3926  static_cast<uint>(num.length)) {}
3927 
3928  private:
3929  void init(const char *str_arg, uint length);
3930 
3931  protected:
3933  bool no_conversions) override;
3934 
3935  public:
3936  enum Type type() const override { return INT_ITEM; }
3937  enum Item_result result_type() const override { return INT_RESULT; }
3938  longlong val_int() override {
3939  DBUG_ASSERT(fixed);
3940  return value;
3941  }
3942  double val_real() override {
3943  DBUG_ASSERT(fixed);
3944  return static_cast<double>(value);
3945  }
3946  my_decimal *val_decimal(my_decimal *) override;
3947  String *val_str(String *) override;
3948  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
3949  return get_date_from_int(ltime, fuzzydate);
3950  }
3951  bool get_time(MYSQL_TIME *ltime) override { return get_time_from_int(ltime); }
3952  Item *clone_item() const override { return new Item_int(this); }
3953  void print(const THD *thd, String *str,
3954  enum_query_type query_type) const override;
3955  Item_num *neg() override {
3956  value = -value;
3957  return this;
3958  }
3959  uint decimal_precision() const override {
3960  return (uint)(max_length - (value < 0));
3961  }
3962  bool eq(const Item *, bool) const override;
3963  bool check_partition_func_processor(uchar *) override { return false; }
3964  bool check_function_as_value_generator(uchar *) override { return false; }
3965 };
3966 
3967 /**
3968  Item_int with value==0 and length==1
3969 */
3970 class Item_int_0 final : public Item_int {
3971  public:
3972  Item_int_0() : Item_int(NAME_STRING("0"), 0, 1) {}
3973  explicit Item_int_0(const POS &pos) : Item_int(pos, NAME_STRING("0"), 0, 1) {}
3974 };
3975 
3976 /*
3977  Item_temporal is used to store numeric representation
3978  of time/date/datetime values for queries like:
3979 
3980  WHERE datetime_column NOT IN
3981  ('2006-04-25 10:00:00','2006-04-25 10:02:00', ...);
3982 
3983  and for SHOW/INFORMATION_SCHEMA purposes (see sql_show.cc)
3984 
3985  TS-TODO: Can't we use Item_time_literal, Item_date_literal,
3986  TS-TODO: and Item_datetime_literal for this purpose?
3987 */
3988 class Item_temporal final : public Item_int {
3989  protected:
3991  bool no_conversions) override;
3992 
3993  public:
3995  DBUG_ASSERT(is_temporal_type(field_type_arg));
3996  set_data_type(field_type_arg);
3997  }
3998  Item_temporal(enum_field_types field_type_arg, const Name_string &name_arg,
3999  longlong i, uint length)
4000  : Item_int(i) {
4001  DBUG_ASSERT(is_temporal_type(field_type_arg));
4002  set_data_type(field_type_arg);
4003  max_length = length;
4004  item_name = name_arg;
4005  fixed = true;
4006  }
4007  Item *clone_item() const override {
4008  return new Item_temporal(data_type(), value);
4009  }
4010  longlong val_time_temporal() override { return val_int(); }
4011  longlong val_date_temporal() override { return val_int(); }
4013  DBUG_ASSERT(0);
4014  return false;
4015  }
4016  bool get_time(MYSQL_TIME *) override {
4017  DBUG_ASSERT(0);
4018  return false;
4019  }
4020 };
4021 
4022 class Item_uint : public Item_int {
4023  protected:
4025  bool no_conversions) override;
4026 
4027  public:
4028  Item_uint(const char *str_arg, uint length) : Item_int(str_arg, length) {
4029  unsigned_flag = 1;
4030  }
4031  Item_uint(const POS &pos, const char *str_arg, uint length)
4032  : Item_int(pos, str_arg, length) {
4033  unsigned_flag = 1;
4034  }
4035 
4038  : Item_int(name_arg, i, length) {
4039  unsigned_flag = true;
4040  }
4041  double val_real() override {
4042  DBUG_ASSERT(fixed);
4043  return ulonglong2double(static_cast<ulonglong>(value));
4044  }
4045  String *val_str(String *) override;
4046 
4047  Item *clone_item() const override {
4048  return new Item_uint(item_name, value, max_length);
4049  }
4050  void print(const THD *thd, String *str,
4051  enum_query_type query_type) const override;
4052  Item_num *neg() override;
4053  uint decimal_precision() const override { return max_length; }
4054 };
4055 
4056 /* decimal (fixed point) constant */
4057 class Item_decimal : public Item_num {
4058  typedef Item_num super;
4059 
4060  protected:
4063  bool no_conversions) override;
4064 
4065  public:
4066  Item_decimal(const POS &pos, const char *str_arg, uint length,
4067  const CHARSET_INFO *charset);
4068  Item_decimal(const Name_string &name_arg, const my_decimal *val_arg,
4069  uint decimal_par, uint length);
4070  Item_decimal(my_decimal *value_par);
4071  Item_decimal(longlong val, bool unsig);
4072  Item_decimal(double val);
4073  Item_decimal(const uchar *bin, int precision, int scale);
4074 
4075  enum Type type() const override { return DECIMAL_ITEM; }
4076  enum Item_result result_type() const override { return DECIMAL_RESULT; }
4077  longlong val_int() override;
4078  double val_real() override;
4079  String *val_str(String *) override;
4081  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4082  return get_date_from_decimal(ltime, fuzzydate);
4083  }
4084  bool get_time(MYSQL_TIME *ltime) override {
4085  return get_time_from_decimal(ltime);
4086  }
4087  Item *clone_item() const override {
4089  }
4090  void print(const THD *thd, String *str,
4091  enum_query_type query_type) const override;
4092  Item_num *neg() override {
4095  return this;
4096  }
4097  uint decimal_precision() const override { return decimal_value.precision(); }
4098  bool eq(const Item *, bool binary_cmp) const override;
4099  void set_decimal_value(const my_decimal *value_par);
4100  bool check_partition_func_processor(uchar *) override { return false; }
4101 };
4102 
4103 class Item_float : public Item_num {
4104  typedef Item_num super;
4105 
4107 
4108  public:
4109  double value;
4110  // Item_real() :value(0) {}
4111  Item_float(const char *str_arg, uint length) { init(str_arg, length); }
4112  Item_float(const POS &pos, const char *str_arg, uint length) : super(pos) {
4113  init(str_arg, length);
4114  }
4115 
4116  Item_float(const Name_string name_arg, double val_arg, uint decimal_par,
4117  uint length)
4118  : value(val_arg) {
4119  presentation = name_arg;
4120  item_name = name_arg;
4122  decimals = (uint8)decimal_par;
4123  max_length = length;
4124  fixed = 1;
4125  }
4126  Item_float(const POS &pos, const Name_string name_arg, double val_arg,
4127  uint decimal_par, uint length)
4128  : super(pos), value(val_arg) {
4129  presentation = name_arg;
4130  item_name = name_arg;
4132  decimals = (uint8)decimal_par;
4133  max_length = length;
4134  fixed = 1;
4135  }
4136 
4137  Item_float(double value_par, uint decimal_par) : value(value_par) {
4139  decimals = (uint8)decimal_par;
4140  fixed = 1;
4141  }
4142 
4143  private:
4144  void init(const char *str_arg, uint length);
4145 
4146  protected:
4148  bool no_conversions) override;
4149 
4150  public:
4151  enum Type type() const override { return REAL_ITEM; }
4152  double val_real() override {
4153  DBUG_ASSERT(fixed);
4154  return value;
4155  }
4156  longlong val_int() override {
4157  DBUG_ASSERT(fixed == 1);
4158  if (value <= (double)LLONG_MIN) {
4159  return LLONG_MIN;
4160  } else if (value >= (double)(ulonglong)LLONG_MAX) {
4161  return LLONG_MAX;
4162  }
4163  return (longlong)rint(value);
4164  }
4165  String *val_str(String *) override;
4166  my_decimal *val_decimal(my_decimal *) override;
4167  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4168  return get_date_from_real(ltime, fuzzydate);
4169  }
4170  bool get_time(MYSQL_TIME *ltime) override {
4171  return get_time_from_real(ltime);
4172  }
4173  Item *clone_item() const override {
4174  return new Item_float(item_name, value, decimals, max_length);
4175  }
4176  Item_num *neg() override {
4177  value = -value;
4178  return this;
4179  }
4180  void print(const THD *thd, String *str,
4181  enum_query_type query_type) const override;
4182  bool eq(const Item *, bool binary_cmp) const override;
4183 };
4184 
4185 class Item_func_pi : public Item_float {
4187 
4188  public:
4190  : Item_float(pos, null_name_string, M_PI, 6, 8),
4191  func_name(NAME_STRING("pi()")) {}
4192 
4193  void print(const THD *, String *str, enum_query_type) const override {
4194  str->append(func_name);
4195  }
4196 
4197  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4198 };
4199 
4202 
4203  protected:
4204  explicit Item_string(const POS &pos) : super(pos), m_cs_specified(false) {
4206  }
4207 
4208  void init(const char *str, size_t length, const CHARSET_INFO *cs,
4209  Derivation dv, uint repertoire) {
4212  collation.set(cs, dv, repertoire);
4213  /*
4214  We have to have a different max_length than 'length' here to
4215  ensure that we get the right length if we do use the item
4216  to create a new table. In this case max_length must be the maximum
4217  number of chars for a string of this type because we in Create_field::
4218  divide the max_length with mbmaxlen).
4219  */
4220  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4221  item_name.copy(str, length, cs);
4223  // it is constant => can be used without fix_fields (and frequently used)
4224  fixed = 1;
4225  /*
4226  Check if the string has any character that can't be
4227  interpreted using the relevant charset.
4228  */
4229  check_well_formed_result(&str_value, false, false);
4230  }
4232  bool no_conversions) override;
4233 
4234  public:
4235  /* Create from a string, set name from the string itself. */
4236  Item_string(const char *str, size_t length, const CHARSET_INFO *cs,
4238  uint repertoire = MY_REPERTOIRE_UNICODE30)
4239  : m_cs_specified(false) {
4240  init(str, length, cs, dv, repertoire);
4241  }
4242  Item_string(const POS &pos, const char *str, size_t length,
4244  uint repertoire = MY_REPERTOIRE_UNICODE30)
4245  : super(pos), m_cs_specified(false) {
4246  init(str, length, cs, dv, repertoire);
4247  }
4248 
4249  /* Just create an item and do not fill string representation */
4251  : m_cs_specified(false) {
4252  collation.set(cs, dv);
4254  max_length = 0;
4256  fixed = 1;
4257  }
4258 
4259  /* Create from the given name and string. */
4260  Item_string(const Name_string name_par, const char *str, size_t length,
4262  uint repertoire = MY_REPERTOIRE_UNICODE30)
4263  : m_cs_specified(false) {
4265  collation.set(cs, dv, repertoire);
4267  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4268  item_name = name_par;
4270  // it is constant => can be used without fix_fields (and frequently used)
4271  fixed = 1;
4272  }
4273  Item_string(const POS &pos, const Name_string name_par, const char *str,
4274  size_t length, const CHARSET_INFO *cs,
4276  uint repertoire = MY_REPERTOIRE_UNICODE30)
4277  : super(pos), m_cs_specified(false) {
4279  collation.set(cs, dv, repertoire);
4281  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4282  item_name = name_par;
4284  // it is constant => can be used without fix_fields (and frequently used)
4285  fixed = 1;
4286  }
4287 
4288  /* Create from the given name and string. */
4289  Item_string(const POS &pos, const Name_string name_par,
4290  const LEX_CSTRING &literal, const CHARSET_INFO *cs,
4292  uint repertoire = MY_REPERTOIRE_UNICODE30)
4293  : super(pos), m_cs_specified(false) {
4294  str_value.set_or_copy_aligned(literal.str ? literal.str : "",
4295  literal.str ? literal.length : 0, cs);
4296  collation.set(cs, dv, repertoire);
4298  max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4299  item_name = name_par;
4301  // it is constant => can be used without fix_fields (and frequently used)
4302  fixed = 1;
4303  }
4304 
4305  /*
4306  This is used in stored procedures to avoid memory leaks and
4307  does a deep copy of its argument.
4308  */
4309  void set_str_with_copy(const char *str_arg, uint length_arg) {
4310  str_value.copy(str_arg, length_arg, collation.collation);
4311  max_length = static_cast<uint32>(str_value.numchars() *
4313  }
4317  }
4318  enum Type type() const override { return STRING_ITEM; }
4319  double val_real() override;
4320  longlong val_int() override;
4321  String *val_str(String *) override {
4322  DBUG_ASSERT(fixed == 1);
4323  return &str_value;
4324  }
4325  my_decimal *val_decimal(my_decimal *) override;
4326  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4327  return get_date_from_string(ltime, fuzzydate);
4328  }
4329  bool get_time(MYSQL_TIME *ltime) override {
4330  return get_time_from_string(ltime);
4331  }
4332  enum Item_result result_type() const override { return STRING_RESULT; }
4333  bool eq(const Item *item, bool binary_cmp) const override;
4334  Item *clone_item() const override {
4335  return new Item_string(static_cast<Name_string>(item_name), str_value.ptr(),
4337  }
4338  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4339  Item *charset_converter(THD *thd, const CHARSET_INFO *tocs, bool lossless);
4340  inline void append(char *str, size_t length) {
4341  str_value.append(str, length);
4342  max_length = static_cast<uint32>(str_value.numchars() *
4344  }
4345  void print(const THD *thd, String *str,
4346  enum_query_type query_type) const override;
4347  bool check_partition_func_processor(uchar *) override { return false; }
4348 
4349  /**
4350  Return true if character-set-introducer was explicitly specified in the
4351  original query for this item (text literal).
4352 
4353  This operation is to be called from Item_string::print(). The idea is
4354  that when a query is generated (re-constructed) from the Item-tree,
4355  character-set-introducers should appear only for those literals, where
4356  they were explicitly specified by the user. Otherwise, that may lead to
4357  loss collation information (character set introducers implies default
4358  collation for the literal).
4359 
4360  Basically, that makes sense only for views and hopefully will be gone
4361  one day when we start using original query as a view definition.
4362 
4363  @return This operation returns the value of m_cs_specified attribute.
4364  @retval true if character set introducer was explicitly specified in
4365  the original query.
4366  @retval false otherwise.
4367  */
4368  inline bool is_cs_specified() const { return m_cs_specified; }
4369 
4370  /**
4371  Set the value of m_cs_specified attribute.
4372 
4373  m_cs_specified attribute shows whether character-set-introducer was
4374  explicitly specified in the original query for this text literal or
4375  not. The attribute makes sense (is used) only for views.
4376 
4377  This operation is to be called from the parser during parsing an input
4378  query.
4379  */
4380  inline void set_cs_specified(bool cs_specified) {
4381  m_cs_specified = cs_specified;
4382  }
4383 
4385 
4386  private:
4388 };
4389 
4391  const char *cptr, const char *end);
4392 double double_from_string_with_check(const CHARSET_INFO *cs, const char *cptr,
4393  const char *end);
4394 
4397 
4398  public:
4399  Item_static_string_func(const Name_string &name_par, const char *str,
4400  size_t length, const CHARSET_INFO *cs,
4402  : Item_string(null_name_string, str, length, cs, dv),
4403  func_name(name_par) {}
4404  Item_static_string_func(const POS &pos, const Name_string &name_par,
4405  const char *str, size_t length,
4406  const CHARSET_INFO *cs,
4408  : Item_string(pos, null_name_string, str, length, cs, dv),
4409  func_name(name_par) {}
4410 
4411  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4412 
4413  void print(const THD *, String *str, enum_query_type) const override {
4414  str->append(func_name);
4415  }
4416 
4417  bool check_partition_func_processor(uchar *) override { return true; }
4421  func_arg->banned_function_name = func_name.ptr();
4422  return true;
4423  }
4424 };
4425 
4426 /* for show tables */
4428  public:
4430  const CHARSET_INFO *cs = NULL)
4431  : Item_string(name, NullS, 0, cs) {
4432  max_length = static_cast<uint32>(length);
4433  }
4434 };
4435 
4437  public:
4438  Item_blob(const char *name, size_t length)
4440  &my_charset_bin) {
4442  }
4443  enum Type type() const override { return TYPE_HOLDER; }
4447  func_arg->err_code = func_arg->get_unnamed_function_error_code();
4448  return true;
4449  }
4450 };
4451 
4452 /**
4453  Item_empty_string -- is a utility class to put an item into List<Item>
4454  which is then used in protocol.send_result_set_metadata() when sending SHOW
4455  output to the client.
4456 */
4457 
4459  public:
4460  Item_empty_string(const char *header, size_t length,
4461  const CHARSET_INFO *cs = NULL)
4462  : Item_partition_func_safe_string(Name_string(header, strlen(header)), 0,
4463  cs ? cs : &my_charset_utf8_general_ci) {
4464  max_length = static_cast<uint32>(length * collation.collation->mbmaxlen);
4465  }
4466  void make_field(Send_field *field) override;
4467 };
4468 
4469 class Item_return_int : public Item_int {
4470  public:
4471  Item_return_int(const char *name_arg, uint length,
4472  enum_field_types field_type_arg, longlong value_arg = 0)
4473  : Item_int(Name_string(name_arg, name_arg ? strlen(name_arg) : 0),
4474  value_arg, length) {
4475  set_data_type(field_type_arg);
4476  unsigned_flag = true;
4477  }
4478 };
4479 
4482 
4483  protected:
4485  bool no_conversions) override;
4486 
4487  public:
4488  Item_hex_string();
4489  explicit Item_hex_string(const POS &pos) : super(pos) {
4491  }
4492 
4493  Item_hex_string(const char *str, uint str_length);
4494  Item_hex_string(const POS &pos, const LEX_STRING &literal);
4495 
4496  enum Type type() const override { return VARBIN_ITEM; }
4497  double val_real() override {
4498  DBUG_ASSERT(fixed);
4499  return (double)(ulonglong)Item_hex_string::val_int();
4500  }
4501  longlong val_int() override;
4502  Item *clone_item() const override {
4503  return new Item_hex_string(str_value.ptr(), max_length);
4504  }
4505  String *val_str(String *) override {
4506  DBUG_ASSERT(fixed);
4507  return &str_value;
4508  }
4509  my_decimal *val_decimal(my_decimal *) override;
4510  bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4511  return get_date_from_string(ltime, fuzzydate);
4512  }
4513  bool get_time(MYSQL_TIME *ltime) override {
4514  return get_time_from_string(ltime);
4515  }
4516  Item_result result_type() const override { return STRING_RESULT; }
4518  return INT_RESULT;
4519  }
4520  Item_result cast_to_int_type() const override { return INT_RESULT; }
4521  void print(const THD *thd, String *str,
4522  enum_query_type query_type) const override;
4523  bool eq(const Item *item, bool binary_cmp) const override;
4524  Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4525  bool check_partition_func_processor(uchar *) override { return false; }
4526  static LEX_CSTRING make_hex_str(const char *str, size_t str_length);
4527 
4528  private:
4529  void hex_string_init(const char *str, uint str_length);
4530 };
4531 
4534 
4535  public:
4536  Item_bin_string(const char *str, size_t str_length) {
4537  bin_string_init(str, str_length);
4538  }
4539  Item_bin_string(const POS &pos, const LEX_STRING &literal) : super(pos) {
4540  bin_string_init(literal.str, literal.length);
4541  }
4542 
4543  static LEX_CSTRING make_bin_str(const char *str, size_t str_length);
4544 
4545  private:
4546  void bin_string_init(const char *str, size_t str_length);
4547 };
4548 
4549 /**
4550  Item with result field.
4551 
4552  It adds to an Item a "result_field" Field member. This is for an item which
4553  may have a result (e.g. Item_func), and may store this result into a field;
4554  usually this field is a column of an internal temporary table. So the
4555  function may be evaluated by save_in_field(), storing result into
4556  result_field in tmp table. Then this result can be copied from tmp table to
4557  a following tmp table (e.g. GROUP BY table then ORDER BY table), or to a row
4558  buffer and back, as we want to avoid multiple evaluations of the Item, first
4559  because of performance, second because that evaluation may have side
4560  effects, e.g. SLEEP, GET_LOCK, RAND, window functions doing
4561  accumulations...
4562  Item_field and Item_ref also have a "result_field" for a similar goal.
4563  Literals don't need such "result_field" as their value is readily
4564  available.
4565 */
4566 class Item_result_field : public Item {
4567  public:
4568  Field *result_field; /* Save result here */
4570  explicit Item_result_field(const POS &pos) : Item(pos), result_field(0) {}
4571 
4572  // Constructor used for Item_sum/Item_cond_and/or (see Item comment)
4574  : Item(thd, item), result_field(item->result_field) {}
4575  ~Item_result_field() override {} /* Required with gcc 2.95 */
4576  Field *get_tmp_table_field() override { return result_field; }
4577  Field *tmp_table_field(TABLE *) override { return result_field; }
4578  table_map used_tables() const override { return 1; }
4579 
4580  /**
4581  Resolve type-related information for this item, such as result field type,
4582  maximum size, precision, signedness, character set and collation.
4583  Also check compatibility of argument types and return error when applicable.
4584  Also adjust nullability when applicable.
4585 
4586  @param thd thread handler
4587  @returns false if success, true if error
4588  */
4589  virtual bool resolve_type(THD *thd) = 0;
4590 
4591  void set_result_field(Field *field) override { result_field = field; }
4592  bool is_result_field() const override { return true; }
4593  Field *get_result_field() const override { return result_field; }
4594  void save_in_result_field(bool no_conversions) override {
4595  DBUG_ENTER("Item_result_field::save_in_result_field");
4596  save_in_field(result_field, no_conversions);
4598  }
4599 
4600  void cleanup() override;
4601  /*
4602  This method is used for debug purposes to print the name of an
4603  item to the debug log. The second use of this method is as
4604  a helper function of print() and error messages, where it is
4605  applicable. To suit both goals it should return a meaningful,
4606  distinguishable and syntactically correct string. This method
4607  should not be used for runtime type identification, use enum
4608  {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
4609  instead.
4610  Added here, to the parent class of both Item_func and Item_sum.
4611  */
4612  virtual const char *func_name() const = 0;
4613  bool check_function_as_value_generator(uchar *) override { return false; }
4614  bool mark_field_in_map(uchar *arg) override {
4615  bool rc = Item::mark_field_in_map(arg);
4616  if (result_field) // most likely result_field will be read too
4617  rc |= Item::mark_field_in_map(pointer_cast<Mark_field *>(arg),
4618  result_field);
4619  return rc;
4620  }
4621 
4623  if (realval < LLONG_MIN || realval > LLONG_MAX) {
4625  return error_int();
4626  }
4627  // Rounding error, llrint() may return LLONG_MIN.
4628  const longlong retval = realval == LLONG_MAX ? LLONG_MAX : llrint(realval);
4629  return retval;
4630  }
4631 
4632  void raise_numeric_overflow(const char *type_name);
4633 
4635  raise_numeric_overflow("DOUBLE");
4636  return 0.0;
4637  }
4638 
4640  raise_numeric_overflow(unsigned_flag ? "BIGINT UNSIGNED" : "BIGINT");
4641  return 0;
4642  }
4643 
4645  raise_numeric_overflow(unsigned_flag ? "DECIMAL UNSIGNED" : "DECIMAL");
4646  return E_DEC_OVERFLOW;
4647  }
4648 };
4649 
4650 class Item_ref : public Item_ident {
4651  protected:
4652  void set_properties();
4654  bool no_conversions) override;
4655 
4656  public:
4658  Field *result_field; /* Save result here */
4660 
4661  private:
4662  /**
4663  'ref' can be set (to non-NULL) in the constructor or afterwards.
4664  The second case means that we are doing resolution, possibly pointing
4665  'ref' to a non-permanent Item. To not have 'ref' become dangling at the
4666  end of execution, and to start clean for the resolution of the next
4667  execution, 'ref' must be restored to NULL. rollback_item_tree_changes()
4668  does not handle restoration of Item** values, so we need this dedicated
4669  Boolean.
4670  */
4671  const bool chop_ref;
4672 
4673  public: