1 #ifndef ITEM_INCLUDED
2 #define ITEM_INCLUDED
3 
4 /* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
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 
33 #include <memory>
34 #include <new>
35 #include <string>
36 
37 #include "decimal.h"
38 #include "field_types.h"  // enum_field_types
39 #include "lex_string.h"
40 #include "m_ctype.h"
41 #include "m_string.h"
42 #include "memory_debugging.h"
43 #include "my_alloc.h"
44 #include "my_bitmap.h"
45 #include "my_compiler.h"
46 #include "my_dbug.h"
47 #include "my_double2ulonglong.h"
48 #include "my_inttypes.h"
49 #include "my_sys.h"
50 #include "my_table_map.h"
51 #include "my_time.h"
52 #include "mysql/udf_registration_types.h"
53 #include "mysql_com.h"
54 #include "mysql_time.h"
55 #include "mysqld_error.h"
56 #include "sql/enum_query_type.h"
57 #include "sql/field.h"  // Derivation
58 #include "sql/mem_root_array.h"
59 #include "sql/my_decimal.h"            // my_decimal
60 #include "sql/parse_tree_node_base.h"  // Parse_tree_node
61 #include "sql/sql_array.h"             // Bounds_checked_array
62 #include "sql/sql_const.h"
63 #include "sql/sql_list.h"
64 #include "sql/table.h"
65 #include "sql/table_trigger_field_support.h"  // Table_trigger_field_support
66 #include "sql/thr_malloc.h"
67 #include "sql/trigger_def.h"  // enum_trigger_variable_type
68 #include "sql_string.h"
69 #include "template_utils.h"
70 
71 class Item;
72 class Item_field;
73 class Item_singlerow_subselect;
74 class Item_sum;
75 class Json_wrapper;
76 class Protocol;
77 class SELECT_LEX;
78 class Security_context;
79 class THD;
80 class user_var_entry;
81 struct TYPELIB;
82 
83 typedef Bounds_checked_array<Item *> Ref_item_array;
84 
85 void item_init(void); /* Init item functions */
86 
87 /**
88   Default condition filtering (selectivity) values used by
89   get_filtering_effect() and friends when better estimates
90   (statistics) are not available for a predicate.
91 */
92 /**
93   For predicates that are always satisfied. Must be 1.0 or the filter
94   calculation logic will break down.
95 */
96 #define COND_FILTER_ALLPASS 1.0f
97 /// Filtering effect for equalities: col1 = col2
98 #define COND_FILTER_EQUALITY 0.1f
99 /// Filtering effect for inequalities: col1 > col2
100 #define COND_FILTER_INEQUALITY 0.3333f
101 /// Filtering effect for between: col1 BETWEEN a AND b
102 #define COND_FILTER_BETWEEN 0.1111f
103 /**
104    Value is out-of-date, will need recalculation.
105    This is used by post-greedy-search logic which changes the access method and
106   thus makes obsolete the filtering value calculated by best_access_path(). For
107   example, test_if_skip_sort_order().
108 */
109 #define COND_FILTER_STALE -1.0f
110 /**
111    A special subcase of the above:
112    - if this is table/index/range scan, and
113    - rows_fetched is how many rows we will examine, and
114    - rows_fetched is less than the number of rows in the table (as determined
115    by test_if_cheaper_ordering() and test_if_skip_sort_order()).
116    Unlike the ordinary case where rows_fetched:
117    - is set by calculate_scan_cost(), and
118    - is how many rows pass the constant condition (so, less than we will
119    examine), and
120    - the actual rows_fetched to show in EXPLAIN is the number of rows in the
121    table (== rows which we will examine), and
122    - the constant condition's effect has to be moved to filter_effect for
123    EXPLAIN.
124 */
125 #define COND_FILTER_STALE_NO_CONST -2.0f
126 
char_to_byte_length_safe(uint32 char_length_arg,uint32 mbmaxlen_arg)127 static inline uint32 char_to_byte_length_safe(uint32 char_length_arg,
128                                               uint32 mbmaxlen_arg) {
129   ulonglong tmp = ((ulonglong)char_length_arg) * mbmaxlen_arg;
130   return (tmp > UINT_MAX32) ? (uint32)UINT_MAX32 : (uint32)tmp;
131 }
132 
numeric_context_result_type(enum_field_types data_type,Item_result result_type,uint8 decimals)133 inline Item_result numeric_context_result_type(enum_field_types data_type,
134                                                Item_result result_type,
135                                                uint8 decimals) {
136   if (is_temporal_type(real_type_to_type(data_type)))
137     return decimals ? DECIMAL_RESULT : INT_RESULT;
138   if (result_type == STRING_RESULT) return REAL_RESULT;
139   return result_type;
140 }
141 
142 /*
143    "Declared Type Collation"
144    A combination of collation and its derivation.
145 
146   Flags for collation aggregation modes:
147   MY_COLL_ALLOW_SUPERSET_CONV  - allow conversion to a superset
148   MY_COLL_ALLOW_COERCIBLE_CONV - allow conversion of a coercible value
149                                  (i.e. constant).
150   MY_COLL_ALLOW_CONV           - allow any kind of conversion
151                                  (combination of the above two)
152   MY_COLL_ALLOW_NUMERIC_CONV   - if all items were numbers, convert to
153                                  @@character_set_connection
154   MY_COLL_DISALLOW_NONE        - don't allow return DERIVATION_NONE
155                                  (e.g. when aggregating for comparison)
156   MY_COLL_CMP_CONV             - combination of MY_COLL_ALLOW_CONV
157                                  and MY_COLL_DISALLOW_NONE
158 */
159 
160 #define MY_COLL_ALLOW_SUPERSET_CONV 1
161 #define MY_COLL_ALLOW_COERCIBLE_CONV 2
162 #define MY_COLL_DISALLOW_NONE 4
163 #define MY_COLL_ALLOW_NUMERIC_CONV 8
164 
165 #define MY_COLL_ALLOW_CONV \
166   (MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV)
167 #define MY_COLL_CMP_CONV (MY_COLL_ALLOW_CONV | MY_COLL_DISALLOW_NONE)
168 
169 class DTCollation {
170  public:
171   const CHARSET_INFO *collation;
172   Derivation derivation{DERIVATION_NONE};
173   uint repertoire;
174 
set_repertoire_from_charset(const CHARSET_INFO * cs)175   void set_repertoire_from_charset(const CHARSET_INFO *cs) {
176     repertoire = cs->state & MY_CS_PUREASCII ? MY_REPERTOIRE_ASCII
177                                              : MY_REPERTOIRE_UNICODE30;
178   }
DTCollation()179   DTCollation() {
180     collation = &my_charset_bin;
181     derivation = DERIVATION_NONE;
182     repertoire = MY_REPERTOIRE_UNICODE30;
183   }
DTCollation(const CHARSET_INFO * collation_arg,Derivation derivation_arg)184   DTCollation(const CHARSET_INFO *collation_arg, Derivation derivation_arg) {
185     collation = collation_arg;
186     derivation = derivation_arg;
187     set_repertoire_from_charset(collation_arg);
188   }
set(const DTCollation & dt)189   void set(const DTCollation &dt) {
190     collation = dt.collation;
191     derivation = dt.derivation;
192     repertoire = dt.repertoire;
193   }
set(const CHARSET_INFO * collation_arg,Derivation derivation_arg)194   void set(const CHARSET_INFO *collation_arg, Derivation derivation_arg) {
195     collation = collation_arg;
196     derivation = derivation_arg;
197     set_repertoire_from_charset(collation_arg);
198   }
set(const CHARSET_INFO * collation_arg,Derivation derivation_arg,uint repertoire_arg)199   void set(const CHARSET_INFO *collation_arg, Derivation derivation_arg,
200            uint repertoire_arg) {
201     collation = collation_arg;
202     derivation = derivation_arg;
203     repertoire = repertoire_arg;
204   }
set_numeric()205   void set_numeric() {
206     collation = &my_charset_numeric;
207     derivation = DERIVATION_NUMERIC;
208     repertoire = MY_REPERTOIRE_NUMERIC;
209   }
set(const CHARSET_INFO * collation_arg)210   void set(const CHARSET_INFO *collation_arg) {
211     collation = collation_arg;
212     set_repertoire_from_charset(collation_arg);
213   }
set(Derivation derivation_arg)214   void set(Derivation derivation_arg) { derivation = derivation_arg; }
set_repertoire(uint repertoire_arg)215   void set_repertoire(uint repertoire_arg) { repertoire = repertoire_arg; }
216   bool aggregate(DTCollation &dt, uint flags = 0);
217   bool set(DTCollation &dt1, DTCollation &dt2, uint flags = 0) {
218     set(dt1);
219     return aggregate(dt2, flags);
220   }
derivation_name()221   const char *derivation_name() const {
222     switch (derivation) {
223       case DERIVATION_NUMERIC:
224         return "NUMERIC";
225       case DERIVATION_IGNORABLE:
226         return "IGNORABLE";
227       case DERIVATION_COERCIBLE:
228         return "COERCIBLE";
229       case DERIVATION_IMPLICIT:
230         return "IMPLICIT";
231       case DERIVATION_SYSCONST:
232         return "SYSCONST";
233       case DERIVATION_EXPLICIT:
234         return "EXPLICIT";
235       case DERIVATION_NONE:
236         return "NONE";
237       default:
238         return "UNKNOWN";
239     }
240   }
241 };
242 
243 /**
244   Class used as argument to Item::walk() together with mark_field_in_map()
245 */
246 class Mark_field {
247  public:
Mark_field(TABLE * table,enum_mark_columns mark)248   Mark_field(TABLE *table, enum_mark_columns mark) : table(table), mark(mark) {}
Mark_field(enum_mark_columns mark)249   Mark_field(enum_mark_columns mark) : table(nullptr), mark(mark) {}
250 
251   /**
252      If == NULL, update map of any table.
253      If <> NULL, update map of only this table.
254   */
255   TABLE *const table;
256   /// How to mark the map.
257   const enum_mark_columns mark;
258 };
259 
260 /**
261   Class used as argument to Item::walk() together with used_tables_for_level()
262 */
263 class Used_tables {
264  public:
Used_tables(SELECT_LEX * select)265   explicit Used_tables(SELECT_LEX *select) : select(select), used_tables(0) {}
266 
267   SELECT_LEX *const select;  ///< Level for which data is accumulated
268   table_map used_tables;     ///< Accumulated used tables data
269 };
270 
271 /*************************************************************************/
272 
273 /**
274   Storage for name strings.
275   Enpowers Simple_cstring with allocation routines from the sql_strmake family.
276 
277   This class must stay as small as possible as we often
278   pass it into functions using call-by-value evaluation.
279 
280   Don't add new members or virual methods into this class!
281 */
282 class Name_string : public Simple_cstring {
283  private:
set_or_copy(const char * str,size_t length,bool is_null_terminated)284   void set_or_copy(const char *str, size_t length, bool is_null_terminated) {
285     if (is_null_terminated)
286       set(str, length);
287     else
288       copy(str, length);
289   }
290 
291  public:
Name_string()292   Name_string() : Simple_cstring() {}
293   /*
294     Please do NOT add constructor Name_string(const char *str) !
295     It will involve hidden strlen() call, which can affect
296     performance negatively. Use Name_string(str, len) instead.
297   */
Name_string(const char * str,size_t length)298   Name_string(const char *str, size_t length) : Simple_cstring(str, length) {}
Name_string(const LEX_STRING str)299   Name_string(const LEX_STRING str) : Simple_cstring(str) {}
Name_string(const LEX_CSTRING str)300   Name_string(const LEX_CSTRING str) : Simple_cstring(str) {}
Name_string(const char * str,size_t length,bool is_null_terminated)301   Name_string(const char *str, size_t length, bool is_null_terminated)
302       : Simple_cstring() {
303     set_or_copy(str, length, is_null_terminated);
304   }
Name_string(const LEX_STRING str,bool is_null_terminated)305   Name_string(const LEX_STRING str, bool is_null_terminated)
306       : Simple_cstring() {
307     set_or_copy(str.str, str.length, is_null_terminated);
308   }
309   /**
310     Allocate space using sql_strmake() or sql_strmake_with_convert().
311   */
312   void copy(const char *str, size_t length, const CHARSET_INFO *cs);
313   /**
314     Variants for copy(), for various argument combinations.
315   */
copy(const char * str,size_t length)316   void copy(const char *str, size_t length) {
317     copy(str, length, system_charset_info);
318   }
copy(const char * str)319   void copy(const char *str) {
320     copy(str, (str ? strlen(str) : 0), system_charset_info);
321   }
copy(const LEX_STRING lex)322   void copy(const LEX_STRING lex) { copy(lex.str, lex.length); }
copy(const LEX_STRING * lex)323   void copy(const LEX_STRING *lex) { copy(lex->str, lex->length); }
copy(const Name_string str)324   void copy(const Name_string str) { copy(str.ptr(), str.length()); }
325   /**
326     Compare name to another name in C string, case insensitively.
327   */
eq(const char * str)328   bool eq(const char *str) const {
329     DBUG_ASSERT(str && ptr());
330     return my_strcasecmp(system_charset_info, ptr(), str) == 0;
331   }
eq_safe(const char * str)332   bool eq_safe(const char *str) const { return is_set() && str && eq(str); }
333   /**
334     Compare name to another name in Name_string, case insensitively.
335   */
eq(const Name_string name)336   bool eq(const Name_string name) const { return eq(name.ptr()); }
eq_safe(const Name_string name)337   bool eq_safe(const Name_string name) const {
338     return is_set() && name.is_set() && eq(name);
339   }
340 };
341 
342 #define NAME_STRING(x) Name_string(STRING_WITH_LEN(x))
343 
344 extern const Name_string null_name_string;
345 
346 /**
347   Storage for Item names.
348   Adds "autogenerated" flag and warning functionality to Name_string.
349 */
350 class Item_name_string : public Name_string {
351  private:
352   bool m_is_autogenerated; /* indicates if name of this Item
353                               was autogenerated or set by user */
354  public:
Item_name_string()355   Item_name_string() : Name_string(), m_is_autogenerated(true) {}
Item_name_string(const Name_string name)356   Item_name_string(const Name_string name)
357       : Name_string(name), m_is_autogenerated(true) {}
358   /**
359     Set m_is_autogenerated flag to the given value.
360   */
set_autogenerated(bool is_autogenerated)361   void set_autogenerated(bool is_autogenerated) {
362     m_is_autogenerated = is_autogenerated;
363   }
364   /**
365     Return the auto-generated flag.
366   */
is_autogenerated()367   bool is_autogenerated() const { return m_is_autogenerated; }
368   using Name_string::copy;
369   /**
370     Copy name together with autogenerated flag.
371     Produce a warning if name was cut.
372   */
373   void copy(const char *str_arg, size_t length_arg, const CHARSET_INFO *cs_arg,
374             bool is_autogenerated_arg);
375 };
376 
377 /*
378   Instances of Name_resolution_context store the information necesary for
379   name resolution of Items and other context analysis of a query made in
380   fix_fields().
381 
382   This structure is a part of SELECT_LEX, a pointer to this structure is
383   assigned when an item is created (which happens mostly during  parsing
384   (sql_yacc.yy)), but the structure itself will be initialized after parsing
385   is complete
386 
387   TODO: move subquery of INSERT ... SELECT and CREATE ... SELECT to
388   separate SELECT_LEX which allow to remove tricks of changing this
389   structure before and after INSERT/CREATE and its SELECT to make correct
390   field name resolution.
391 */
392 struct Name_resolution_context {
393   /*
394     The name resolution context to search in when an Item cannot be
395     resolved in this context (the context of an outer select)
396   */
397   Name_resolution_context *outer_context;
398   /// Link to next name res context with the same query block as the base
399   Name_resolution_context *next_context;
400 
401   /*
402     List of tables used to resolve the items of this context.  Usually these
403     are tables from the FROM clause of SELECT statement.  The exceptions are
404     INSERT ... SELECT and CREATE ... SELECT statements, where SELECT
405     subquery is not moved to a separate SELECT_LEX.  For these types of
406     statements we have to change this member dynamically to ensure correct
407     name resolution of different parts of the statement.
408   */
409   TABLE_LIST *table_list;
410   /*
411     In most cases the two table references below replace 'table_list' above
412     for the purpose of name resolution. The first and last name resolution
413     table references allow us to search only in a sub-tree of the nested
414     join tree in a FROM clause. This is needed for NATURAL JOIN, JOIN ... USING
415     and JOIN ... ON.
416   */
417   TABLE_LIST *first_name_resolution_table;
418   /*
419     Last table to search in the list of leaf table references that begins
420     with first_name_resolution_table.
421   */
422   TABLE_LIST *last_name_resolution_table;
423 
424   /*
425     SELECT_LEX item belong to, in case of merged VIEW it can differ from
426     SELECT_LEX where item was created, so we can't use table_list/field_list
427     from there
428   */
429   SELECT_LEX *select_lex;
430 
431   /*
432     Processor of errors caused during Item name resolving, now used only to
433     hide underlying tables in errors about views (i.e. it substitute some
434     errors for views)
435   */
436   bool view_error_handler;
437   TABLE_LIST *view_error_handler_arg;
438 
439   /**
440     When true, items are resolved in this context against
441     SELECT_LEX::item_list, SELECT_lex::group_list and
442     this->table_list. If false, items are resolved only against
443     this->table_list.
444 
445     @see SELECT_LEX::item_list, SELECT_LEX::group_list
446   */
447   bool resolve_in_select_list;
448 
449   /*
450     Security context of this name resolution context. It's used for views
451     and is non-zero only if the view is defined with SQL SECURITY DEFINER.
452   */
453   Security_context *security_ctx;
454 
Name_resolution_contextName_resolution_context455   Name_resolution_context()
456       : outer_context(nullptr),
457         next_context(nullptr),
458         table_list(nullptr),
459         select_lex(nullptr),
460         view_error_handler_arg(nullptr),
461         security_ctx(nullptr) {
462     DBUG_PRINT("outer_field", ("creating ctx %p", this));
463   }
464 
initName_resolution_context465   void init() {
466     resolve_in_select_list = false;
467     view_error_handler = false;
468     first_name_resolution_table = nullptr;
469     last_name_resolution_table = nullptr;
470   }
471 
resolve_in_table_list_onlyName_resolution_context472   void resolve_in_table_list_only(TABLE_LIST *tables) {
473     table_list = first_name_resolution_table = tables;
474     resolve_in_select_list = false;
475   }
476 };
477 
478 /**
479   Struct used to pass around arguments to/from
480   check_function_as_value_generator
481 */
482 struct Check_function_as_value_generator_parameters {
Check_function_as_value_generator_parametersCheck_function_as_value_generator_parameters483   Check_function_as_value_generator_parameters(
484       int default_error_code, Value_generator_source val_gen_src)
485       : err_code(default_error_code), source(val_gen_src) {}
486   /// the order of the column in table
487   int col_index{-1};
488   /// the error code found during check(if any)
489   int err_code;
490   /*
491     If it is a generated column, default expression or check constraint
492     expresion value generator.
493   */
494   Value_generator_source source;
495   /// the name of the function which is not allowed
496   const char *banned_function_name{nullptr};
497 
498   /// Return the correct error code, based on whether or not if we are checking
499   /// for disallowed functions in generated column expressions, in default
500   /// value expressions or in check constraint expression.
get_unnamed_function_error_codeCheck_function_as_value_generator_parameters501   int get_unnamed_function_error_code() const {
502     return ((source == VGS_GENERATED_COLUMN)
503                 ? ER_GENERATED_COLUMN_FUNCTION_IS_NOT_ALLOWED
504                 : (source == VGS_DEFAULT_EXPRESSION)
505                       ? ER_DEFAULT_VAL_GENERATED_FUNCTION_IS_NOT_ALLOWED
506                       : ER_CHECK_CONSTRAINT_FUNCTION_IS_NOT_ALLOWED);
507   }
508 };
509 /*
510   Store and restore the current state of a name resolution context.
511 */
512 
513 class Name_resolution_context_state {
514  private:
515   TABLE_LIST *save_table_list;
516   TABLE_LIST *save_first_name_resolution_table;
517   TABLE_LIST *save_next_name_resolution_table;
518   bool save_resolve_in_select_list;
519   TABLE_LIST *save_next_local;
520 
521  public:
522   /* Save the state of a name resolution context. */
save_state(Name_resolution_context * context,TABLE_LIST * table_list)523   void save_state(Name_resolution_context *context, TABLE_LIST *table_list) {
524     save_table_list = context->table_list;
525     save_first_name_resolution_table = context->first_name_resolution_table;
526     save_resolve_in_select_list = context->resolve_in_select_list;
527     save_next_local = table_list->next_local;
528     save_next_name_resolution_table = table_list->next_name_resolution_table;
529   }
530 
531   /* Restore a name resolution context from saved state. */
restore_state(Name_resolution_context * context,TABLE_LIST * table_list)532   void restore_state(Name_resolution_context *context, TABLE_LIST *table_list) {
533     table_list->next_local = save_next_local;
534     table_list->next_name_resolution_table = save_next_name_resolution_table;
535     context->table_list = save_table_list;
536     context->first_name_resolution_table = save_first_name_resolution_table;
537     context->resolve_in_select_list = save_resolve_in_select_list;
538   }
539 
update_next_local(TABLE_LIST * table_list)540   void update_next_local(TABLE_LIST *table_list) {
541     save_next_local = table_list;
542   }
543 
get_first_name_resolution_table()544   TABLE_LIST *get_first_name_resolution_table() {
545     return save_first_name_resolution_table;
546   }
547 };
548 
549 /*
550   This enum is used to report information about monotonicity of function
551   represented by Item* tree.
552   Monotonicity is defined only for Item* trees that represent table
553   partitioning expressions (i.e. have no subselects/user vars/PS parameters
554   etc etc). An Item* tree is assumed to have the same monotonicity properties
555   as its correspoinding function F:
556 
557   [signed] longlong F(field1, field2, ...) {
558     put values of field_i into table record buffer;
559     return item->val_int();
560   }
561 
562   NOTE
563   At the moment function monotonicity is not well defined (and so may be
564   incorrect) for Item trees with parameters/return types that are different
565   from INT_RESULT, may be NULL, or are unsigned.
566   It will be possible to address this issue once the related partitioning bugs
567   (BUG#16002, BUG#15447, BUG#13436) are fixed.
568 
569   The NOT_NULL enums are used in TO_DAYS, since TO_DAYS('2001-00-00') returns
570   NULL which puts those rows into the NULL partition, but
571   '2000-12-31' < '2001-00-00' < '2001-01-01'. So special handling is needed
572   for this (see Bug#20577).
573 */
574 
575 typedef enum monotonicity_info {
576   NON_MONOTONIC,        /* none of the below holds */
577   MONOTONIC_INCREASING, /* F() is unary and (x < y) => (F(x) <= F(y)) */
578   MONOTONIC_INCREASING_NOT_NULL, /* But only for valid/real x and y */
579   MONOTONIC_STRICT_INCREASING, /* F() is unary and (x < y) => (F(x) <  F(y)) */
580   MONOTONIC_STRICT_INCREASING_NOT_NULL /* But only for valid/real x and y */
581 } enum_monotonicity_info;
582 
583 /**
584    A type for SQL-like 3-valued Booleans: true/false/unknown.
585 */
586 class Bool3 {
587  public:
588   /// @returns an instance set to "FALSE"
false3()589   static const Bool3 false3() { return Bool3(v_FALSE); }
590   /// @returns an instance set to "UNKNOWN"
unknown3()591   static const Bool3 unknown3() { return Bool3(v_UNKNOWN); }
592   /// @returns an instance set to "TRUE"
true3()593   static const Bool3 true3() { return Bool3(v_TRUE); }
594 
is_true()595   bool is_true() const { return m_val == v_TRUE; }
is_unknown()596   bool is_unknown() const { return m_val == v_UNKNOWN; }
is_false()597   bool is_false() const { return m_val == v_FALSE; }
598 
599  private:
600   enum value { v_FALSE, v_UNKNOWN, v_TRUE };
601   /// This is private; instead, use false3()/etc.
Bool3(value v)602   Bool3(value v) : m_val(v) {}
603 
604   value m_val;
605   /*
606     No operator to convert Bool3 to bool (or int) - intentionally: how
607     would you map unknown3 to true/false?
608     It is because we want to block such conversions that Bool3 is a class
609     instead of a plain enum.
610   */
611 };
612 
613 /*************************************************************************/
614 
615 class sp_rcontext;
616 
617 class Settable_routine_parameter {
618  public:
619   /*
620     Set required privileges for accessing the parameter.
621 
622     SYNOPSIS
623       set_required_privilege()
624         rw        if 'rw' is true then we are going to read and set the
625                   parameter, so SELECT and UPDATE privileges might be
626                   required, otherwise we only reading it and SELECT
627                   privilege might be required.
628   */
Settable_routine_parameter()629   Settable_routine_parameter() {}
~Settable_routine_parameter()630   virtual ~Settable_routine_parameter() {}
set_required_privilege(bool rw MY_ATTRIBUTE ((unused)))631   virtual void set_required_privilege(bool rw MY_ATTRIBUTE((unused))) {}
632 
633   /*
634     Set parameter value.
635 
636     SYNOPSIS
637       set_value()
638         thd       thread handle
639         ctx       context to which parameter belongs (if it is local
640                   variable).
641         it        item which represents new value
642 
643     RETURN
644       false if parameter value has been set,
645       true if error has occurred.
646   */
647   virtual bool set_value(THD *thd, sp_rcontext *ctx, Item **it) = 0;
648 
set_out_param_info(Send_field * info MY_ATTRIBUTE ((unused)))649   virtual void set_out_param_info(Send_field *info MY_ATTRIBUTE((unused))) {}
650 
get_out_param_info()651   virtual const Send_field *get_out_param_info() const { return nullptr; }
652 };
653 
654 /*
655   Analyzer function
656     SYNOPSIS
657       argp   in/out IN:  Analysis parameter
658                     OUT: Parameter to be passed to the transformer
659 
660     RETURN
661       true   Invoke the transformer
662       false  Don't do it
663 
664 */
665 typedef bool (Item::*Item_analyzer)(uchar **argp);
666 
667 /**
668   Type for transformers used by Item::transform and Item::compile
669   @param arg  Argument used by the transformer. Really a typeless pointer
670               in spite of the uchar type (historical reasons). The
671               transformer needs to cast this to the desired pointer type
672   @returns    The transformed item
673 */
674 typedef Item *(Item::*Item_transformer)(uchar *arg);
675 typedef void (*Cond_traverser)(const Item *item, void *arg);
676 
677 /**
678   Re-usable shortcut, when it does not make sense to do copy objects of a
679   class named "myclass"; add this to a private section of the class. The
680   implementations are intentionally not created, so if someone tries to use
681   them like in "myclass A= B" there will be a linker error.
682 */
683 #define FORBID_COPY_CTOR_AND_ASSIGN_OP(myclass) \
684   myclass(myclass const &);                     \
685   void operator=(myclass const &)
686 
687 /**
688   Utility mixin class to be able to walk() only parts of item trees.
689 
690   Used with PREFIX+POSTFIX walk: in the prefix call of the Item
691   processor, we process the item X, may decide that its children should not
692   be processed (just like if they didn't exist): processor calls stop_at(X)
693   for that. Then walk() goes to a child Y; the processor tests is_stopped(Y)
694   which returns true, so processor sees that it must not do any processing
695   and returns immediately. Finally, the postfix call to the processor on X
696   tests is_stopped(X) which returns "true" and understands that the
697   not-to-be-processed children have been skipped so calls restart(). Thus,
698   any sibling of X, any part of the Item tree not under X, can then be
699   processed.
700 */
701 class Item_tree_walker {
702  protected:
Item_tree_walker()703   Item_tree_walker() : stopped_at_item(nullptr) {}
~Item_tree_walker()704   ~Item_tree_walker() { DBUG_ASSERT(!stopped_at_item); }
705 
706   /// Stops walking children of this item
stop_at(const Item * i)707   void stop_at(const Item *i) {
708     DBUG_ASSERT(!stopped_at_item);
709     stopped_at_item = i;
710   }
711 
712   /**
713    @returns if we are stopped. If item 'i' is where we stopped, restarts the
714    walk for next items.
715    */
is_stopped(const Item * i)716   bool is_stopped(const Item *i) {
717     if (stopped_at_item) {
718       /*
719        Walking was disabled for a tree part rooted a one ancestor of 'i' or
720        rooted at 'i'.
721        */
722       if (stopped_at_item == i) {
723         /*
724          Walking was disabled for the tree part rooted at 'i'; we have now just
725          returned back to this root (POSTFIX call), left the tree part:
726          enable the walk again, for other tree parts.
727          */
728         stopped_at_item = nullptr;
729       }
730       // No further processing to do for this item:
731       return true;
732     }
733     return false;
734   }
735 
736  private:
737   const Item *stopped_at_item;
738   FORBID_COPY_CTOR_AND_ASSIGN_OP(Item_tree_walker);
739 };
740 
741 class Item : public Parse_tree_node {
742   typedef Parse_tree_node super;
743 
744   friend class udf_handler;
is_expensive_processor(uchar *)745   virtual bool is_expensive_processor(uchar *) { return false; }
746 
747  protected:
748   /**
749      Sets the result value of the function an empty string, using the current
750      character set. No memory is allocated.
751      @retval A pointer to the str_value member.
752    */
make_empty_result()753   String *make_empty_result() {
754     str_value.set("", 0, collation.collation);
755     return &str_value;
756   }
757 
758  public:
759   Item(const Item &) = delete;
760   void operator=(Item &) = delete;
new(size_t size)761   static void *operator new(size_t size) noexcept {
762     return (*THR_MALLOC)->Alloc(size);
763   }
764   static void *operator new(size_t size, MEM_ROOT *mem_root,
765                             const std::nothrow_t &arg MY_ATTRIBUTE((unused)) =
766                                 std::nothrow) noexcept {
767     return mem_root->Alloc(size);
768   }
769 
delete(void * ptr MY_ATTRIBUTE ((unused)),size_t size MY_ATTRIBUTE ((unused)))770   static void operator delete(void *ptr MY_ATTRIBUTE((unused)),
771                               size_t size MY_ATTRIBUTE((unused))) {
772     TRASH(ptr, size);
773   }
delete(void *,MEM_ROOT *,const std::nothrow_t &)774   static void operator delete(void *, MEM_ROOT *,
775                               const std::nothrow_t &) noexcept {}
776 
777   enum Type {
778     INVALID_ITEM = 0,
779     FIELD_ITEM,
780     FUNC_ITEM,
781     SUM_FUNC_ITEM,
782     STRING_ITEM,
783     INT_ITEM,
784     REAL_ITEM,
785     NULL_ITEM,
786     VARBIN_ITEM,
787     COPY_STR_ITEM,
788     FIELD_AVG_ITEM,
789     DEFAULT_VALUE_ITEM,
790     PROC_ITEM,
791     COND_ITEM,
792     REF_ITEM,
793     FIELD_STD_ITEM,
794     FIELD_VARIANCE_ITEM,
795     INSERT_VALUE_ITEM,
796     SUBSELECT_ITEM,
797     ROW_ITEM,
798     CACHE_ITEM,
799     TYPE_HOLDER,
800     PARAM_ITEM,
801     TRIGGER_FIELD_ITEM,
802     DECIMAL_ITEM,
803     XPATH_NODESET,
804     XPATH_NODESET_CMP,
805     VIEW_FIXER_ITEM,
806     FIELD_BIT_ITEM,
807     VALUES_COLUMN_ITEM
808   };
809 
810   enum cond_result { COND_UNDEF, COND_OK, COND_TRUE, COND_FALSE };
811 
812   enum traverse_order { POSTFIX, PREFIX };
813 
814   /// How to cache constant JSON data
815   enum enum_const_item_cache {
816     /// Don't cache
817     CACHE_NONE = 0,
818     /// Source data is a JSON string, parse and cache result
819     CACHE_JSON_VALUE,
820     /// Source data is SQL scalar, convert and cache result
821     CACHE_JSON_ATOM
822   };
823 
824   enum Bool_test  ///< Modifier for result transformation
825   { BOOL_IS_TRUE = 0x00,
826     BOOL_IS_FALSE = 0x01,
827     BOOL_IS_UNKNOWN = 0x02,
828     BOOL_NOT_TRUE = 0x03,
829     BOOL_NOT_FALSE = 0x04,
830     BOOL_NOT_UNKNOWN = 0x05,
831     BOOL_IDENTITY = 0x06,
832     BOOL_NEGATED = 0x07,
833     BOOL_ALWAYS_TRUE = 0x08,
834     BOOL_ALWAYS_FALSE = 0x09,
835   };
836 
837   /**
838     Provide data type for a user or system variable, based on the type of
839     the item that is assigned to the variable.
840 
841     @note MYSQL_TYPE_VARCHAR is returned for all string types, but must be
842           further adjusted based on maximum string length by the caller.
843 
844     @param src_type  Source type that variable's type is derived from
845   */
type_for_variable(enum_field_types src_type)846   static enum_field_types type_for_variable(enum_field_types src_type) {
847     switch (src_type) {
848       case MYSQL_TYPE_TINY:
849       case MYSQL_TYPE_SHORT:
850       case MYSQL_TYPE_INT24:
851       case MYSQL_TYPE_LONG:
852       case MYSQL_TYPE_LONGLONG:
853         return MYSQL_TYPE_LONGLONG;
854       case MYSQL_TYPE_DECIMAL:
855       case MYSQL_TYPE_NEWDECIMAL:
856         return MYSQL_TYPE_NEWDECIMAL;
857       case MYSQL_TYPE_FLOAT:
858       case MYSQL_TYPE_DOUBLE:
859         return MYSQL_TYPE_DOUBLE;
860       case MYSQL_TYPE_VARCHAR:
861       case MYSQL_TYPE_VAR_STRING:
862       case MYSQL_TYPE_STRING:
863         return MYSQL_TYPE_VARCHAR;
864       case MYSQL_TYPE_YEAR:
865         return MYSQL_TYPE_LONGLONG;
866       case MYSQL_TYPE_TIMESTAMP:
867       case MYSQL_TYPE_DATE:
868       case MYSQL_TYPE_TIME:
869       case MYSQL_TYPE_DATETIME:
870       case MYSQL_TYPE_NEWDATE:
871       case MYSQL_TYPE_BIT:
872       case MYSQL_TYPE_TIMESTAMP2:
873       case MYSQL_TYPE_DATETIME2:
874       case MYSQL_TYPE_TIME2:
875       case MYSQL_TYPE_JSON:
876       case MYSQL_TYPE_ENUM:
877       case MYSQL_TYPE_SET:
878       case MYSQL_TYPE_GEOMETRY:
879       case MYSQL_TYPE_NULL:
880       case MYSQL_TYPE_TINY_BLOB:
881       case MYSQL_TYPE_BLOB:
882       case MYSQL_TYPE_MEDIUM_BLOB:
883       case MYSQL_TYPE_LONG_BLOB:
884         return MYSQL_TYPE_VARCHAR;
885       default:
886         DBUG_ASSERT(false);
887         return MYSQL_TYPE_NULL;
888     }
889   }
890 
891   /// Item constructor for general use.
892   Item();
893 
894   /**
895     Constructor used by Item_field, Item_ref & aggregate functions.
896     Used for duplicating lists in processing queries with temporary tables.
897 
898     Also used for Item_cond_and/Item_cond_or for creating top AND/OR structure
899     of WHERE clause to protect it of optimisation changes in prepared statements
900   */
901   Item(THD *thd, const Item *item);
902 
903   /**
904     Parse-time context-independent constructor.
905 
906     This constructor and caller constructors of child classes must not
907     access/change thd->lex (including thd->lex->current_select(),
908     thd->m_parser_state etc structures).
909 
910     If we need to finalize the construction of the object, then we move
911     all context-sensitive code to the itemize() virtual function.
912 
913     The POS parameter marks this constructor and other context-independent
914     constructors of child classes for easy recognition/separation from other
915     (context-dependent) constructors.
916   */
917   explicit Item(const POS &);
918 
~Item()919   virtual ~Item() override {
920 #ifdef EXTRA_DEBUG
921     item_name.set(0);
922 #endif
923   } /*lint -e1509 */
924 
925  private:
926   /*
927     Hide the contextualize*() functions: call/override the itemize()
928     in Item class tree instead.
929   */
contextualize(Parse_context *)930   bool contextualize(Parse_context *) override {
931     DBUG_ASSERT(0);
932     return true;
933   }
934 
935  protected:
936   /**
937     Helper function to skip itemize() for grammar-allocated items
938 
939     @param [out] res    pointer to "this"
940 
941     @retval true        can skip itemize()
942     @retval false       can't skip: the item is allocated directly by the parser
943   */
skip_itemize(Item ** res)944   bool skip_itemize(Item **res) {
945     *res = this;
946     return !is_parser_item;
947   }
948 
949   /*
950     Checks if the function should return binary result based on the items
951     provided as parameter.
952     Function should only be used by Item_bit_func*
953 
954     @param      a item to check
955     @param      b item to check, may be nullptr
956 
957     @returns true if binary result.
958    */
959   static bool bit_func_returns_binary(const Item *a, const Item *b);
960 
961  public:
962   /**
963     The same as contextualize() but with additional parameter
964 
965     This function finalize the construction of Item objects (see the Item(POS)
966     constructor): we can access/change parser contexts from the itemize()
967     function.
968 
969     @param        pc    current parse context
970     @param  [out] res   pointer to "this" or to a newly allocated
971                         replacement object to use in the Item tree instead
972 
973     @retval false       success
974     @retval true        syntax/OOM/etc error
975   */
976   virtual bool itemize(Parse_context *pc, Item **res);
977 
978   void rename(char *new_name);
979   void init_make_field(Send_field *tmp_field, enum enum_field_types type);
980   virtual void cleanup();
981   virtual void make_field(Send_field *field);
982   virtual Field *make_string_field(TABLE *table) const;
983   virtual bool fix_fields(THD *, Item **);
984   /**
985     Fix after tables have been moved from one select_lex level to the parent
986     level, e.g by semijoin conversion.
987     Basically re-calculate all attributes dependent on the tables.
988 
989     @param parent_select  select_lex that tables are moved to.
990     @param removed_select select_lex that tables are moved away from,
991                           child of parent_select.
992   */
fix_after_pullout(SELECT_LEX * parent_select MY_ATTRIBUTE ((unused)),SELECT_LEX * removed_select MY_ATTRIBUTE ((unused)))993   virtual void fix_after_pullout(
994       SELECT_LEX *parent_select MY_ATTRIBUTE((unused)),
995       SELECT_LEX *removed_select MY_ATTRIBUTE((unused))) {}
996   /*
997     should be used in case where we are sure that we do not need
998     complete fix_fields() procedure.
999   */
quick_fix_field()1000   inline void quick_fix_field() { fixed = true; }
set_can_use_prefix_key()1001   virtual void set_can_use_prefix_key() {}
1002 
1003  protected:
1004   /**
1005     Helper function which does all of the work for
1006     save_in_field(Field*, bool), except some error checking common to
1007     all subclasses, which is performed by save_in_field() itself.
1008 
1009     Subclasses that need to specialize the behaviour of
1010     save_in_field(), should override this function instead of
1011     save_in_field().
1012 
1013     @param[in,out] field  the field to save the item into
1014     @param no_conversions whether or not to allow conversions of the value
1015 
1016     @return the status from saving into the field
1017       @retval TYPE_OK    item saved without any errors or warnings
1018       @retval != TYPE_OK there were errors or warnings when saving the item
1019   */
1020   virtual type_conversion_status save_in_field_inner(Field *field,
1021                                                      bool no_conversions);
1022 
1023  public:
1024   /**
1025     Save the item into a field but do not emit any warnings.
1026 
1027     @param field         field to save the item into
1028     @param no_conversions whether or not to allow conversions of the value
1029 
1030     @return the status from saving into the field
1031       @retval TYPE_OK    item saved without any issues
1032       @retval != TYPE_OK there were issues saving the item
1033   */
1034   type_conversion_status save_in_field_no_warnings(Field *field,
1035                                                    bool no_conversions);
1036   /**
1037     Save a temporal value in packed longlong format into a Field.
1038     Used in optimizer.
1039 
1040     Subclasses that need to specialize this function, should override
1041     save_in_field_inner().
1042 
1043     @param[in,out] field  the field to save the item into
1044     @param no_conversions whether or not to allow conversions of the value
1045 
1046     @return the status from saving into the field
1047       @retval TYPE_OK    item saved without any errors or warnings
1048       @retval != TYPE_OK there were errors or warnings when saving the item
1049   */
1050   type_conversion_status save_in_field(Field *field, bool no_conversions);
1051 
save_org_in_field(Field * field)1052   virtual void save_org_in_field(Field *field) { save_in_field(field, true); }
1053 
1054   virtual bool send(Protocol *protocol, String *str);
1055   bool evaluate(THD *thd, String *str);
1056   virtual bool eq(const Item *, bool binary_cmp) const;
result_type()1057   virtual Item_result result_type() const { return REAL_RESULT; }
1058   /**
1059     Result type when an item appear in a numeric context.
1060     See Field::numeric_context_result_type() for more comments.
1061   */
numeric_context_result_type()1062   virtual enum Item_result numeric_context_result_type() const {
1063     return ::numeric_context_result_type(data_type(), result_type(), decimals);
1064   }
1065   /**
1066     Similar to result_type() but makes DATE, DATETIME, TIMESTAMP
1067     pretend to be numbers rather than strings.
1068   */
temporal_with_date_as_number_result_type()1069   inline enum Item_result temporal_with_date_as_number_result_type() const {
1070     return is_temporal_with_date() ? (decimals ? DECIMAL_RESULT : INT_RESULT)
1071                                    : result_type();
1072   }
1073 
1074   /// Retrieve the derived data type of the Item.
data_type()1075   inline enum_field_types data_type() const {
1076     return static_cast<enum_field_types>(m_data_type);
1077   }
1078 
1079   /**
1080     Set the data type of the current Item. It is however recommended to
1081     use one of the type-specific setters if possible.
1082 
1083     @param data_type The data type of this Item.
1084   */
set_data_type(enum_field_types data_type)1085   inline void set_data_type(enum_field_types data_type) {
1086     m_data_type = static_cast<uint8>(data_type);
1087   }
1088 
set_data_type_bool()1089   inline void set_data_type_bool() {
1090     set_data_type(MYSQL_TYPE_LONG);
1091     collation.set_numeric();
1092     max_length = 1;
1093   }
1094 
1095   /**
1096     Set the data type of the Item to be longlong.
1097     Maximum display width is set to be the maximum of a 64-bit integer,
1098     but it may be adjusted later. The unsigned property is not affected.
1099   */
set_data_type_longlong()1100   inline void set_data_type_longlong() {
1101     set_data_type(MYSQL_TYPE_LONGLONG);
1102     collation.set_numeric();
1103     fix_char_length(21);
1104   }
1105 
1106   /**
1107     Set the data type of the Item to be decimal.
1108     The unsigned property must have been set before calling this function.
1109 
1110     @param precision Number of digits of precision
1111     @param dec       Number of digits after decimal point.
1112   */
set_data_type_decimal(uint8 precision,uint8 dec)1113   inline void set_data_type_decimal(uint8 precision, uint8 dec) {
1114     set_data_type(MYSQL_TYPE_NEWDECIMAL);
1115     collation.set_numeric();
1116     decimals = dec;
1117     fix_char_length(my_decimal_precision_to_length_no_truncation(
1118         precision, dec, unsigned_flag));
1119   }
1120 
1121   /// Set the data type of the Item to be double precision floating point.
set_data_type_double()1122   inline void set_data_type_double() {
1123     set_data_type(MYSQL_TYPE_DOUBLE);
1124     decimals = DECIMAL_NOT_SPECIFIED;
1125     max_length = float_length(decimals);
1126     collation.set_numeric();
1127   }
1128 
1129   /// Set the data type of the Item to be single precision floating point.
set_data_type_float()1130   inline void set_data_type_float() {
1131     set_data_type(MYSQL_TYPE_FLOAT);
1132     decimals = DECIMAL_NOT_SPECIFIED;
1133     max_length = float_length(decimals);
1134     collation.set_numeric();
1135   }
1136 
1137   /// Initialize an Item to be of VARCHAR type, other properties undetermined.
set_data_type_string_init()1138   inline void set_data_type_string_init() {
1139     set_data_type(MYSQL_TYPE_VARCHAR);
1140     decimals = DECIMAL_NOT_SPECIFIED;
1141   }
1142 
1143   /**
1144     Set the Item to be variable length string. Actual type is determined from
1145     maximum string size. Collation must have been set before calling function.
1146 
1147     @param max_l  Maximum number of characters in string
1148   */
set_data_type_string(uint32 max_l)1149   inline void set_data_type_string(uint32 max_l) {
1150     max_length = max_l * collation.collation->mbmaxlen;
1151     if (max_length < 65536)
1152       set_data_type(MYSQL_TYPE_VARCHAR);
1153     else if (max_length < 16777216)
1154       set_data_type(MYSQL_TYPE_MEDIUM_BLOB);
1155     else
1156       set_data_type(MYSQL_TYPE_LONG_BLOB);
1157   }
1158 
1159   /**
1160     Set the Item to be variable length string. Like function above, but with
1161     larger string length precision.
1162 
1163     @param max_char_length_arg  Maximum number of characters in string
1164   */
set_data_type_string(ulonglong max_char_length_arg)1165   inline void set_data_type_string(ulonglong max_char_length_arg) {
1166     ulonglong max_result_length =
1167         max_char_length_arg * collation.collation->mbmaxlen;
1168     if (max_result_length >= MAX_BLOB_WIDTH) {
1169       max_result_length = MAX_BLOB_WIDTH;
1170       maybe_null = true;
1171     }
1172     set_data_type_string(
1173         uint32(max_result_length / collation.collation->mbmaxlen));
1174   }
1175 
1176   /**
1177     Set the Item to be variable length string. Like function above, but will
1178     also set character set and collation.
1179 
1180     @param max_l  Maximum number of characters in string
1181     @param cs     Pointer to character set and collation struct
1182   */
set_data_type_string(ulonglong max_l,const CHARSET_INFO * cs)1183   inline void set_data_type_string(ulonglong max_l, const CHARSET_INFO *cs) {
1184     collation.collation = cs;
1185     set_data_type_string(max_l);
1186   }
1187 
1188   /**
1189     Set the Item to be variable length string. Like function above, but will
1190     also set full collation information.
1191 
1192     @param max_l  Maximum number of characters in string
1193     @param coll   Ref to collation data, including derivation and repertoire
1194   */
set_data_type_string(uint32 max_l,const DTCollation & coll)1195   inline void set_data_type_string(uint32 max_l, const DTCollation &coll) {
1196     collation.set(coll);
1197     set_data_type_string(max_l);
1198   }
1199 
1200   /**
1201     Set the Item to be fixed length string. Collation must have been set
1202     before calling function.
1203 
1204     @param max_l Number of characters in string
1205   */
set_data_type_char(uint32 max_l)1206   inline void set_data_type_char(uint32 max_l) {
1207     max_length = max_l * collation.collation->mbmaxlen;
1208     DBUG_ASSERT(max_length < 65536);
1209     set_data_type(MYSQL_TYPE_STRING);
1210   }
1211 
1212   /**
1213     Set the Item to be fixed length string. Like function above, but will
1214     also set character set and collation.
1215 
1216     @param max_l  Maximum number of characters in string
1217     @param cs     Pointer to character set and collation struct
1218   */
set_data_type_char(uint32 max_l,const CHARSET_INFO * cs)1219   inline void set_data_type_char(uint32 max_l, const CHARSET_INFO *cs) {
1220     collation.collation = cs;
1221     set_data_type_char(max_l);
1222   }
1223 
1224   /**
1225     Set the Item to be of BLOB type.
1226 
1227     @param max_l Maximum number of bytes in data type
1228   */
set_data_type_blob(uint32 max_l)1229   inline void set_data_type_blob(uint32 max_l) {
1230     set_data_type(MYSQL_TYPE_LONG_BLOB);
1231     max_length = max_l;
1232   }
1233 
1234   /// Set all type properties for Item of DATE type.
set_data_type_date()1235   inline void set_data_type_date() {
1236     set_data_type(MYSQL_TYPE_DATE);
1237     collation.set_numeric();
1238     decimals = 0;
1239     max_length = MAX_DATE_WIDTH;
1240   }
1241 
1242   /**
1243     Set all type properties for Item of TIME type.
1244 
1245     @param fsp Fractional seconds precision
1246   */
set_data_type_time(uint8 fsp)1247   inline void set_data_type_time(uint8 fsp) {
1248     set_data_type(MYSQL_TYPE_TIME);
1249     collation.set_numeric();
1250     decimals = fsp;
1251     max_length = MAX_TIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1252   }
1253 
1254   /**
1255     Set all properties for Item of DATETIME type.
1256 
1257     @param fsp Fractional seconds precision
1258   */
set_data_type_datetime(uint8 fsp)1259   inline void set_data_type_datetime(uint8 fsp) {
1260     set_data_type(MYSQL_TYPE_DATETIME);
1261     collation.set_numeric();
1262     decimals = fsp;
1263     max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1264   }
1265 
1266   /**
1267     Set all properties for Item of TIMESTAMP type.
1268 
1269     @param fsp Fractional seconds precision
1270   */
set_data_type_timestamp(uint8 fsp)1271   inline void set_data_type_timestamp(uint8 fsp) {
1272     set_data_type(MYSQL_TYPE_TIMESTAMP);
1273     collation.set_numeric();
1274     decimals = fsp;
1275     max_length = MAX_DATETIME_WIDTH + fsp + (fsp > 0 ? 1 : 0);
1276   }
1277 
1278   /**
1279     Set the data type of the Item to be JSON.
1280   */
set_data_type_json()1281   void set_data_type_json() {
1282     set_data_type(MYSQL_TYPE_JSON);
1283     collation.set(&my_charset_utf8mb4_bin, DERIVATION_IMPLICIT);
1284     decimals = DECIMAL_NOT_SPECIFIED;
1285     max_length = MAX_BLOB_WIDTH;
1286   }
1287 
1288   /**
1289     Set the data type of the Item to be YEAR.
1290   */
set_data_type_year()1291   void set_data_type_year() {
1292     set_data_type(MYSQL_TYPE_YEAR);
1293     collation.set_numeric();
1294     max_length = 4;
1295   }
1296 
1297   /**
1298     Set the Item to be of GEOMETRY type.
1299   */
set_data_type_geometry()1300   inline void set_data_type_geometry() {
1301     set_data_type(MYSQL_TYPE_GEOMETRY);
1302     decimals = DECIMAL_NOT_SPECIFIED;
1303     max_length = MAX_BLOB_WIDTH;
1304   }
1305 
1306   /**
1307     Set type information of Item from "result" information.
1308     For String types, type is set based on maximum string size.
1309     For other types, the associated type with the largest precision is set.
1310 
1311     @param result Either Integer, Decimal, Double or String
1312     @param length Maximum string size, used only for String result.
1313   */
set_data_type_from_result(Item_result result,uint32 length)1314   void set_data_type_from_result(Item_result result, uint32 length) {
1315     switch (result) {
1316       case INT_RESULT:
1317         set_data_type(MYSQL_TYPE_LONGLONG);
1318         break;
1319       case DECIMAL_RESULT:
1320         set_data_type(MYSQL_TYPE_NEWDECIMAL);
1321         break;
1322       case REAL_RESULT:
1323         set_data_type(MYSQL_TYPE_DOUBLE);
1324         break;
1325       case STRING_RESULT:
1326         set_data_type_string(length);
1327         break;
1328       case ROW_RESULT:
1329       case INVALID_RESULT:
1330       default:
1331         DBUG_ASSERT(false);
1332         break;
1333     }
1334   }
1335 
1336   /**
1337     Set data type properties of the item from the properties of another item.
1338 
1339     @param item Item to set data type properties from.
1340   */
set_data_type_from_item(Item * item)1341   inline void set_data_type_from_item(Item *item) {
1342     set_data_type(item->data_type());
1343     collation = item->collation;
1344     max_length = item->max_length;
1345     decimals = item->decimals;
1346     unsigned_flag = item->unsigned_flag;
1347   }
1348 
1349   /**
1350     Determine correct string field type, based on string length
1351 
1352     @param max_bytes Maximum string size, in number of bytes
1353   */
string_field_type(uint32 max_bytes)1354   static enum_field_types string_field_type(uint32 max_bytes) {
1355     if (max_bytes >= 16777216)
1356       return MYSQL_TYPE_LONG_BLOB;
1357     else if (max_bytes >= 65536)
1358       return MYSQL_TYPE_MEDIUM_BLOB;
1359     else
1360       return MYSQL_TYPE_VARCHAR;
1361   }
1362 
cast_to_int_type()1363   virtual Item_result cast_to_int_type() const { return result_type(); }
1364   virtual enum Type type() const = 0;
1365 
1366   void aggregate_type(Bounds_checked_array<Item *> items);
1367 
1368   /*
1369     Return information about function monotonicity. See comment for
1370     enum_monotonicity_info for details. This function can only be called
1371     after fix_fields() call.
1372   */
get_monotonicity_info()1373   virtual enum_monotonicity_info get_monotonicity_info() const {
1374     return NON_MONOTONIC;
1375   }
1376 
1377   /*
1378     Convert "func_arg $CMP$ const" half-interval into "FUNC(func_arg) $CMP2$
1379     const2"
1380 
1381     SYNOPSIS
1382       val_int_endpoint()
1383         left_endp  false  <=> The interval is "x < const" or "x <= const"
1384                    true   <=> The interval is "x > const" or "x >= const"
1385 
1386         incl_endp  IN   false <=> the comparison is '<' or '>'
1387                         true  <=> the comparison is '<=' or '>='
1388                    OUT  The same but for the "F(x) $CMP$ F(const)" comparison
1389 
1390     DESCRIPTION
1391       This function is defined only for unary monotonic functions. The caller
1392       supplies the source half-interval
1393 
1394          x $CMP$ const
1395 
1396       The value of const is supplied implicitly as the value this item's
1397       argument, the form of $CMP$ comparison is specified through the
1398       function's arguments. The calle returns the result interval
1399 
1400          F(x) $CMP2$ F(const)
1401 
1402       passing back F(const) as the return value, and the form of $CMP2$
1403       through the out parameter. NULL values are assumed to be comparable and
1404       be less than any non-NULL values.
1405 
1406     RETURN
1407       The output range bound, which equal to the value of val_int()
1408         - If the value of the function is NULL then the bound is the
1409           smallest possible value of LLONG_MIN
1410   */
val_int_endpoint(bool left_endp MY_ATTRIBUTE ((unused)),bool * incl_endp MY_ATTRIBUTE ((unused)))1411   virtual longlong val_int_endpoint(bool left_endp MY_ATTRIBUTE((unused)),
1412                                     bool *incl_endp MY_ATTRIBUTE((unused))) {
1413     DBUG_ASSERT(0);
1414     return 0;
1415   }
1416 
1417   /* valXXX methods must return NULL or 0 or 0.0 if null_value is set. */
1418   /*
1419     Return double precision floating point representation of item.
1420 
1421     SYNOPSIS
1422       val_real()
1423 
1424     RETURN
1425       In case of NULL value return 0.0 and set null_value flag to true.
1426       If value is not null null_value flag will be reset to false.
1427   */
1428   virtual double val_real() = 0;
1429   /*
1430     Return integer representation of item.
1431 
1432     SYNOPSIS
1433       val_int()
1434 
1435     RETURN
1436       In case of NULL value return 0 and set null_value flag to true.
1437       If value is not null null_value flag will be reset to false.
1438   */
1439   virtual longlong val_int() = 0;
1440   /**
1441     Return date value of item in packed longlong format.
1442   */
1443   virtual longlong val_date_temporal();
1444   /**
1445     Return time value of item in packed longlong format.
1446   */
1447   virtual longlong val_time_temporal();
1448   /**
1449     Return date or time value of item in packed longlong format,
1450     depending on item field type.
1451   */
val_temporal_by_field_type()1452   longlong val_temporal_by_field_type() {
1453     if (data_type() == MYSQL_TYPE_TIME) return val_time_temporal();
1454     DBUG_ASSERT(is_temporal_with_date());
1455     return val_date_temporal();
1456   }
1457   /**
1458     Get date or time value in packed longlong format.
1459     Before conversion from MYSQL_TIME to packed format,
1460     the MYSQL_TIME value is rounded to "dec" fractional digits.
1461   */
1462   longlong val_temporal_with_round(enum_field_types type, uint8 dec);
1463 
1464   /*
1465     This is just a shortcut to avoid the cast. You should still use
1466     unsigned_flag to check the sign of the item.
1467   */
val_uint()1468   inline ulonglong val_uint() { return (ulonglong)val_int(); }
1469   /*
1470     Return string representation of this item object.
1471 
1472     SYNOPSIS
1473       val_str()
1474       str   an allocated buffer this or any nested Item object can use to
1475             store return value of this method.
1476 
1477     NOTE
1478       Buffer passed via argument  should only be used if the item itself
1479       doesn't have an own String buffer. In case when the item maintains
1480       it's own string buffer, it's preferable to return it instead to
1481       minimize number of mallocs/memcpys.
1482       The caller of this method can modify returned string, but only in case
1483       when it was allocated on heap, (is_alloced() is true).  This allows
1484       the caller to efficiently use a buffer allocated by a child without
1485       having to allocate a buffer of it's own. The buffer, given to
1486       val_str() as argument, belongs to the caller and is later used by the
1487       caller at it's own choosing.
1488       A few implications from the above:
1489       - unless you return a string object which only points to your buffer
1490         but doesn't manages it you should be ready that it will be
1491         modified.
1492       - even for not allocated strings (is_alloced() == false) the caller
1493         can change charset (see Item_func_{typecast/binary}. XXX: is this
1494         a bug?
1495       - still you should try to minimize data copying and return internal
1496         object whenever possible.
1497 
1498     RETURN
1499       In case of NULL value or error, return error_str() as this function will
1500       check if the return value may be null, and it will either set null_value
1501       to true and return nullptr or to false and it will return empty string.
1502       If value is not null set null_value flag to false before returning it.
1503   */
1504   virtual String *val_str(String *str) = 0;
1505 
1506   /*
1507     Returns string representation of this item in ASCII format.
1508 
1509     SYNOPSIS
1510       val_str_ascii()
1511       str - similar to val_str();
1512 
1513     NOTE
1514       This method is introduced for performance optimization purposes.
1515 
1516       1. val_str() result of some Items in string context
1517       depends on @@character_set_results.
1518       @@character_set_results can be set to a "real multibyte" character
1519       set like UCS2, UTF16, UTF32. (We'll use only UTF32 in the examples
1520       below for convenience.)
1521 
1522       So the default string result of such functions
1523       in these circumstances is real multi-byte character set, like UTF32.
1524 
1525       For example, all numbers in string context
1526       return result in @@character_set_results:
1527 
1528       SELECT CONCAT(20010101); -> UTF32
1529 
1530       We do sprintf() first (to get ASCII representation)
1531       and then convert to UTF32;
1532 
1533       So these kind "data sources" can use ASCII representation
1534       internally, but return multi-byte data only because
1535       @@character_set_results wants so.
1536       Therefore, conversion from ASCII to UTF32 is applied internally.
1537 
1538 
1539       2. Some other functions need in fact ASCII input.
1540 
1541       For example,
1542         inet_aton(), GeometryFromText(), Convert_TZ(), GET_FORMAT().
1543 
1544       Similar, fields of certain type, like DATE, TIME,
1545       when you insert string data into them, expect in fact ASCII input.
1546       If they get non-ASCII input, for example UTF32, they
1547       convert input from UTF32 to ASCII, and then use ASCII
1548       representation to do further processing.
1549 
1550 
1551       3. Now imagine we pass result of a data source of the first type
1552          to a data destination of the second type.
1553 
1554       What happens:
1555         a. data source converts data from ASCII to UTF32, because
1556            @@character_set_results wants so and passes the result to
1557            data destination.
1558         b. data destination gets UTF32 string.
1559         c. data destination converts UTF32 string to ASCII,
1560            because it needs ASCII representation to be able to handle data
1561            correctly.
1562 
1563       As a result we get two steps of unnecessary conversion:
1564       From ASCII to UTF32, then from UTF32 to ASCII.
1565 
1566       A better way to handle these situations is to pass ASCII
1567       representation directly from the source to the destination.
1568 
1569       This is why val_str_ascii() introduced.
1570 
1571     RETURN
1572       Similar to val_str()
1573   */
1574   virtual String *val_str_ascii(String *str);
1575 
1576   /*
1577     Return decimal representation of item with fixed point.
1578 
1579     SYNOPSIS
1580       val_decimal()
1581       decimal_buffer  buffer which can be used by Item for returning value
1582                       (but can be not)
1583 
1584     NOTE
1585       Returned value should not be changed if it is not the same which was
1586       passed via argument.
1587 
1588     RETURN
1589       Return pointer on my_decimal (it can be other then passed via argument)
1590         if value is not NULL (null_value flag will be reset to false).
1591       In case of NULL value it return 0 pointer and set null_value flag
1592         to true.
1593   */
1594   virtual my_decimal *val_decimal(my_decimal *decimal_buffer) = 0;
1595   /*
1596     Return boolean value of item.
1597 
1598     RETURN
1599       false value is false or NULL
1600       true value is true (not equal to 0)
1601   */
1602   virtual bool val_bool();
1603 
1604   /**
1605     Get a JSON value from an Item.
1606 
1607     All subclasses that can return a JSON value, should override this
1608     function. The function in the base class is not expected to be
1609     called. If it is called, it most likely means that some subclass
1610     is missing an override of val_json().
1611 
1612     @param[in,out] result The resulting Json_wrapper.
1613 
1614     @return false if successful, true on failure
1615   */
1616   /* purecov: begin deadcode */
val_json(Json_wrapper * result MY_ATTRIBUTE ((unused)))1617   virtual bool val_json(Json_wrapper *result MY_ATTRIBUTE((unused))) {
1618     DBUG_ASSERT(false);
1619     my_error(ER_NOT_SUPPORTED_YET, MYF(0), "item type for JSON");
1620     return error_json();
1621   }
1622   /* purecov: end */
1623 
1624   /**
1625     Calculate the filter contribution that is relevant for table
1626     'filter_for_table' for this item.
1627 
1628     @param thd               Thread handler
1629     @param filter_for_table  The table we are calculating filter effect for
1630     @param read_tables       Tables earlier in the join sequence.
1631                              Predicates for table 'filter_for_table' that
1632                              rely on values from these tables can be part of
1633                              the filter effect.
1634     @param fields_to_ignore  Fields in 'filter_for_table' that should not
1635                              be part of the filter calculation. The filtering
1636                              effect of these fields is already part of the
1637                              calculation somehow (e.g. because there is a
1638                              predicate "col = <const>", and the optimizer
1639                              has decided to do ref access on 'col').
1640     @param rows_in_table     The number of rows in table 'filter_for_table'
1641 
1642     @return                  the filtering effect (between 0 and 1) this
1643                              Item contributes with.
1644   */
get_filtering_effect(THD * thd MY_ATTRIBUTE ((unused)),table_map filter_for_table MY_ATTRIBUTE ((unused)),table_map read_tables MY_ATTRIBUTE ((unused)),const MY_BITMAP * fields_to_ignore MY_ATTRIBUTE ((unused)),double rows_in_table MY_ATTRIBUTE ((unused)))1645   virtual float get_filtering_effect(
1646       THD *thd MY_ATTRIBUTE((unused)),
1647       table_map filter_for_table MY_ATTRIBUTE((unused)),
1648       table_map read_tables MY_ATTRIBUTE((unused)),
1649       const MY_BITMAP *fields_to_ignore MY_ATTRIBUTE((unused)),
1650       double rows_in_table MY_ATTRIBUTE((unused))) {
1651     // Filtering effect cannot be calculated for a table already read.
1652     DBUG_ASSERT((read_tables & filter_for_table) == 0);
1653     return COND_FILTER_ALLPASS;
1654   }
1655 
1656   /**
1657     Get the value to return from val_json() in case of errors.
1658 
1659     @see Item::error_bool
1660 
1661     @return The value val_json() should return, which is true.
1662   */
error_json()1663   bool error_json() {
1664     null_value = maybe_null;
1665     return true;
1666   }
1667 
1668   /**
1669     Convert a non-temporal type to date
1670   */
1671   bool get_date_from_non_temporal(MYSQL_TIME *ltime, my_time_flags_t fuzzydate);
1672 
1673   /**
1674     Convert a non-temporal type to time
1675   */
1676   bool get_time_from_non_temporal(MYSQL_TIME *ltime);
1677 
1678  protected:
1679   /* Helper functions, see item_sum.cc */
1680   String *val_string_from_real(String *str);
1681   String *val_string_from_int(String *str);
1682   String *val_string_from_decimal(String *str);
1683   String *val_string_from_date(String *str);
1684   String *val_string_from_datetime(String *str);
1685   String *val_string_from_time(String *str);
1686   my_decimal *val_decimal_from_real(my_decimal *decimal_value);
1687   my_decimal *val_decimal_from_int(my_decimal *decimal_value);
1688   my_decimal *val_decimal_from_string(my_decimal *decimal_value);
1689   my_decimal *val_decimal_from_date(my_decimal *decimal_value);
1690   my_decimal *val_decimal_from_time(my_decimal *decimal_value);
1691   longlong val_int_from_decimal();
1692   longlong val_int_from_date();
1693   longlong val_int_from_time();
1694   longlong val_int_from_datetime();
1695   longlong val_int_from_string();
1696   double val_real_from_decimal();
1697   double val_real_from_string();
1698 
1699   /**
1700     Get the value to return from val_bool() in case of errors.
1701 
1702     This function is called from val_bool() when an error has occurred
1703     and we need to return something to abort evaluation of the
1704     item. The expected pattern in val_bool() is
1705 
1706       if (@<error condition@>)
1707       {
1708         my_error(...)
1709         return error_bool();
1710       }
1711 
1712     @return The value val_bool() should return.
1713   */
error_bool()1714   bool error_bool() {
1715     null_value = maybe_null;
1716     return false;
1717   }
1718 
1719   /**
1720     Get the value to return from val_int() in case of errors.
1721 
1722     @see Item::error_bool
1723 
1724     @return The value val_int() should return.
1725   */
error_int()1726   int error_int() {
1727     null_value = maybe_null;
1728     return 0;
1729   }
1730 
1731   /**
1732     Get the value to return from val_real() in case of errors.
1733 
1734     @see Item::error_bool
1735 
1736     @return The value val_real() should return.
1737   */
error_real()1738   double error_real() {
1739     null_value = maybe_null;
1740     return 0.0;
1741   }
1742 
1743   /**
1744     Get the value to return from val_str() in case of errors.
1745 
1746     @see Item::error_bool
1747 
1748     @return The value val_str() should return.
1749   */
error_str()1750   String *error_str() {
1751     null_value = maybe_null;
1752     return null_value ? nullptr : make_empty_result();
1753   }
1754 
1755   /**
1756     Gets the value to return from val_str() when returning a NULL value.
1757     @return The value val_str() should return.
1758   */
null_return_str()1759   String *null_return_str() {
1760     DBUG_ASSERT(maybe_null);
1761     null_value = true;
1762     return nullptr;
1763   }
1764 
1765   /**
1766     Convert val_str() to date in MYSQL_TIME
1767   */
1768   bool get_date_from_string(MYSQL_TIME *ltime, my_time_flags_t flags);
1769   /**
1770     Convert val_real() to date in MYSQL_TIME
1771   */
1772   bool get_date_from_real(MYSQL_TIME *ltime, my_time_flags_t flags);
1773   /**
1774     Convert val_decimal() to date in MYSQL_TIME
1775   */
1776   bool get_date_from_decimal(MYSQL_TIME *ltime, my_time_flags_t flags);
1777   /**
1778     Convert val_int() to date in MYSQL_TIME
1779   */
1780   bool get_date_from_int(MYSQL_TIME *ltime, my_time_flags_t flags);
1781   /**
1782     Convert get_time() from time to date in MYSQL_TIME
1783   */
1784   bool get_date_from_time(MYSQL_TIME *ltime);
1785 
1786   /**
1787     Convert a numeric type to date
1788   */
1789   bool get_date_from_numeric(MYSQL_TIME *ltime, my_time_flags_t fuzzydate);
1790 
1791   /**
1792     Convert val_str() to time in MYSQL_TIME
1793   */
1794   bool get_time_from_string(MYSQL_TIME *ltime);
1795   /**
1796     Convert val_real() to time in MYSQL_TIME
1797   */
1798   bool get_time_from_real(MYSQL_TIME *ltime);
1799   /**
1800     Convert val_decimal() to time in MYSQL_TIME
1801   */
1802   bool get_time_from_decimal(MYSQL_TIME *ltime);
1803   /**
1804     Convert val_int() to time in MYSQL_TIME
1805   */
1806   bool get_time_from_int(MYSQL_TIME *ltime);
1807   /**
1808     Convert date to time
1809   */
1810   bool get_time_from_date(MYSQL_TIME *ltime);
1811   /**
1812     Convert datetime to time
1813   */
1814   bool get_time_from_datetime(MYSQL_TIME *ltime);
1815 
1816   /**
1817     Convert a numeric type to time
1818   */
1819   bool get_time_from_numeric(MYSQL_TIME *ltime);
1820 
1821  public:
1822   type_conversion_status save_time_in_field(Field *field);
1823   type_conversion_status save_date_in_field(Field *field);
1824   type_conversion_status save_str_value_in_field(Field *field, String *result);
1825 
1826   /**
1827     If this Item is being materialized into a temporary table, returns the
1828     field that is being materialized into. (Typically, this is the
1829     “result_field” members for items that have one.)
1830    */
get_tmp_table_field()1831   virtual Field *get_tmp_table_field() {
1832     DBUG_TRACE;
1833     return nullptr;
1834   }
1835   /* This is also used to create fields in CREATE ... SELECT: */
tmp_table_field(TABLE *)1836   virtual Field *tmp_table_field(TABLE *) { return nullptr; }
full_name()1837   virtual const char *full_name() const {
1838     return item_name.is_set() ? item_name.ptr() : "???";
1839   }
1840 
1841   /* bit map of tables used by item */
used_tables()1842   virtual table_map used_tables() const { return (table_map)0L; }
1843 
1844   /*
1845     Return table map of tables that can't be NULL tables (tables that are
1846     used in a context where if they would contain a NULL row generated
1847     by a LEFT or RIGHT join, the item would not be true).
1848     This expression is used on WHERE item to determinate if a LEFT JOIN can be
1849     converted to a normal join.
1850     Generally this function should return used_tables() if the function
1851     would return null if any of the arguments are null
1852     As this is only used in the beginning of optimization, the value don't
1853     have to be updated in update_used_tables()
1854   */
not_null_tables()1855   virtual table_map not_null_tables() const { return used_tables(); }
1856 
1857   /**
1858     Returns true if this is a simple constant item like an integer, not
1859     a constant expression. Used in the optimizer to propagate basic constants.
1860     It is assumed that val_xxx() does not modify the item's state for
1861     such items. It is also assumed that val_str() can be called with nullptr
1862     as argument as val_str() will return an internally cached const string.
1863   */
basic_const_item()1864   virtual bool basic_const_item() const { return false; }
1865   /**
1866     @return cloned item if it is constant
1867       @retval nullptr  if this is not const
1868   */
clone_item()1869   virtual Item *clone_item() const { return nullptr; }
eq_cmp_result()1870   virtual cond_result eq_cmp_result() const { return COND_OK; }
float_length(uint decimals_par)1871   inline uint float_length(uint decimals_par) const {
1872     return decimals != DECIMAL_NOT_SPECIFIED ? (DBL_DIG + 2 + decimals_par)
1873                                              : DBL_DIG + 8;
1874   }
1875   virtual uint decimal_precision() const;
decimal_int_part()1876   inline int decimal_int_part() const {
1877     return my_decimal_int_part(decimal_precision(), decimals);
1878   }
1879   /**
1880     TIME precision of the item: 0..6
1881   */
1882   virtual uint time_precision();
1883   /**
1884     DATETIME precision of the item: 0..6
1885   */
1886   virtual uint datetime_precision();
1887   /**
1888     Returns true if item is constant, regardless of query evaluation state.
1889     An expression is constant if it:
1890     - refers no tables.
1891     - refers no subqueries that refers any tables.
1892     - refers no non-deterministic functions.
1893     - refers no statement parameters.
1894     - contains no group expression under rollup
1895   */
const_item()1896   bool const_item() const { return (used_tables() == 0); }
1897   /**
1898     Returns true if item is constant during one query execution.
1899     If const_for_execution() is true but const_item() is false, value is
1900     not available before tables have been locked and parameters have been
1901     assigned values. This applies to
1902     - statement parameters
1903     - non-dependent subqueries
1904     - deterministic stored functions that contain SQL code.
1905     For items where the default implementation of used_tables() and
1906     const_item() are effective, const_item() will always return true.
1907   */
const_for_execution()1908   bool const_for_execution() const {
1909     return !(used_tables() & ~INNER_TABLE_BIT);
1910   }
1911 
1912   /**
1913     Return true if this is a const item that may be evaluated in
1914     the current phase of statement processing.
1915     - No evaluation is performed when analyzing a view, otherwise:
1916     - Items that have the const_item() property can always be evaluated.
1917     - Items that have the const_for_execution() property can be evaluated when
1918       tables are locked (ie during optimization or execution).
1919 
1920     This function should be used in the following circumstances:
1921     - during preparation to check whether an item can be permanently transformed
1922     - to check that an item is constant in functions that may be used in both
1923       the preparation and optimization phases.
1924 
1925     This function should not be used by code that is called during optimization
1926     and/or execution only. Use const_for_execution() in this case.
1927   */
1928   bool may_evaluate_const(const THD *thd) const;
1929 
1930   /**
1931     This method is used for to:
1932       - to generate a view definition query (SELECT-statement);
1933       - to generate a SQL-query for EXPLAIN EXTENDED;
1934       - to generate a SQL-query to be shown in INFORMATION_SCHEMA;
1935       - to generate a SQL-query that looks like a prepared statement for
1936     query_rewrite
1937       - debug.
1938 
1939     For more information about view definition query, INFORMATION_SCHEMA
1940     query and why they should be generated from the Item-tree, @see
1941     mysql_register_view().
1942   */
print(const THD *,String * str,enum_query_type)1943   virtual void print(const THD *, String *str, enum_query_type) const {
1944     str->append(full_name());
1945   }
1946 
1947   void print_item_w_name(const THD *thd, String *,
1948                          enum_query_type query_type) const;
1949   /**
1950      Prints the item when it's part of ORDER BY and GROUP BY.
1951      @param  thd            Thread handle
1952      @param  str            String to print to
1953      @param  query_type     How to format the item
1954      @param  used_alias     Whether item was referenced with alias.
1955   */
1956   void print_for_order(const THD *thd, String *str, enum_query_type query_type,
1957                        bool used_alias) const;
1958 
1959   /**
1960     Updates used tables, not null tables information and accumulates
1961     properties up the item tree, cf. used_tables_cache, not_null_tables_cache
1962     and m_accum_properties.
1963   */
update_used_tables()1964   virtual void update_used_tables() {}
1965 
split_sum_func(THD *,Ref_item_array,List<Item> &)1966   virtual void split_sum_func(THD *, Ref_item_array, List<Item> &) {}
1967   /* Called for items that really have to be split */
1968   void split_sum_func2(THD *thd, Ref_item_array ref_item_array,
1969                        List<Item> &fields, Item **ref, bool skip_registered);
1970   virtual bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) = 0;
1971   virtual bool get_time(MYSQL_TIME *ltime) = 0;
1972   /**
1973     Get timestamp in "struct timeval" format.
1974     @retval  false on success
1975     @retval  true  on error
1976   */
1977   virtual bool get_timeval(struct timeval *tm, int *warnings);
1978   /**
1979     The method allows to determine nullness of a complex expression
1980     without fully evaluating it, instead of calling val*() then
1981     checking null_value. Used in Item_func_isnull/Item_func_isnotnull
1982     and Item_sum_count/Item_sum_count_distinct.
1983     Any new item which can be NULL must implement this method.
1984   */
is_null()1985   virtual bool is_null() { return false; }
1986 
1987   /// Make sure the null_value member has a correct value.
1988   bool update_null_value();
1989 
1990   /**
1991     Apply the IS TRUE truth property, meaning that an UNKNOWN result and a
1992     FALSE result are treated the same.
1993 
1994     This property is applied e.g to all conditions in WHERE, HAVING and ON
1995     clauses, and is recursively applied to operands of AND, OR
1996     operators. Some items (currently AND and subquery predicates) may enable
1997     special optimizations when they have this property.
1998    */
apply_is_true()1999   virtual void apply_is_true() {}
2000   /*
2001     set field of temporary table for Item which can be switched on temporary
2002     table during query processing (grouping and so on). @see
2003     Item_result_field.
2004   */
set_result_field(Field *)2005   virtual void set_result_field(Field *) {}
is_result_field()2006   virtual bool is_result_field() const { return false; }
get_result_field()2007   virtual Field *get_result_field() const { return nullptr; }
is_bool_func()2008   virtual bool is_bool_func() const { return false; }
2009   /*
2010     Set value of aggregate function in case of no rows for grouping were found.
2011     Also used for subqueries with outer references in SELECT list.
2012   */
no_rows_in_result()2013   virtual void no_rows_in_result() {}
copy_or_same(THD *)2014   virtual Item *copy_or_same(THD *) { return this; }
copy_andor_structure(THD *)2015   virtual Item *copy_andor_structure(THD *) { return this; }
real_item()2016   virtual Item *real_item() { return this; }
substitutional_item()2017   virtual Item *substitutional_item() {
2018     return runtime_item ? real_item() : this;
2019   }
set_runtime_created()2020   virtual void set_runtime_created() { runtime_item = true; }
2021 
2022   /**
2023     If an Item is materialized in a temporary table, a different Item may have
2024     to be used in the part of the query that runs after the materialization.
2025     For instance, if the Item was an Item_field, the new Item_field needs to
2026     point into the temporary table instead of the original one, but if, on the
2027     other hand, the Item was a literal constant, it can be reused as-is.
2028     This function encapsulates these policies for the different kinds of Items.
2029     See also get_tmp_table_field().
2030 
2031     TODO: Document how aggregate functions (Item_sum) are handled.
2032    */
get_tmp_table_item(THD * thd)2033   virtual Item *get_tmp_table_item(THD *thd) { return copy_or_same(thd); }
2034 
2035   static const CHARSET_INFO *default_charset();
compare_collation()2036   virtual const CHARSET_INFO *compare_collation() const { return nullptr; }
2037 
2038   /*
2039     For backward compatibility, to make numeric
2040     data types return "binary" charset in client-side metadata.
2041   */
charset_for_protocol()2042   virtual const CHARSET_INFO *charset_for_protocol() const {
2043     return result_type() == STRING_RESULT ? collation.collation
2044                                           : &my_charset_bin;
2045   }
2046 
2047   /**
2048     Traverses a tree of Items in prefix and/or postfix order.
2049     Optionally walks into subqueries.
2050 
2051     @param processor   processor function to be invoked per item
2052                        returns true to abort traversal, false to continue
2053     @param walk        controls how to traverse the item tree
2054                        enum_walk::PREFIX:  call processor before invoking
2055     children enum_walk::POSTFIX: call processor after invoking children
2056                        enum_walk::SUBQUERY go down into subqueries
2057                        walk values are bit-coded and may be combined.
2058                        Omitting both enum_walk::PREFIX and enum_walk::POSTFIX
2059                        is undefined behaviour.
2060     @param arg         Optional pointer to a walk-specific object
2061 
2062     @retval      false walk succeeded
2063     @retval      true  walk aborted
2064                        by agreement, an error may have been reported
2065   */
2066 
walk(Item_processor processor,enum_walk walk MY_ATTRIBUTE ((unused)),uchar * arg)2067   virtual bool walk(Item_processor processor,
2068                     enum_walk walk MY_ATTRIBUTE((unused)), uchar *arg) {
2069     return (this->*processor)(arg);
2070   }
2071 
2072   /** @see WalkItem */
2073   template <class T>
walk_helper_thunk(uchar * arg)2074   bool walk_helper_thunk(uchar *arg) {
2075     return (*reinterpret_cast<T *>(arg))(this);
2076   }
2077 
2078   /**
2079     Perform a generic transformation of the Item tree, by adding zero or
2080     more additional Item objects to it.
2081 
2082     @param transformer  Transformer function
2083     @param[in,out] arg  Pointer to struct used by transformer function
2084 
2085     @returns Returned item tree after transformation, NULL if error
2086 
2087     Transformation is performed as follows:
2088 
2089     @code
2090     transform()
2091     {
2092       transform children if any;
2093       return this->*some_transformer(...);
2094     }
2095     @endcode
2096 
2097     Note that unlike Item::compile(), transform() does not support an analyzer
2098     function, ie. all children are unconditionally invoked.
2099 
2100     @todo Let compile() handle all transformations during optimization, and
2101           let transform() handle transformations during preparation only.
2102           Then there would be no need to call change_item_tree() during
2103           transformation.
2104   */
2105   virtual Item *transform(Item_transformer transformer, uchar *arg);
2106 
2107   /**
2108     Perform a generic "compilation" of the Item tree, ie transform the Item tree
2109     by adding zero or more Item objects to it.
2110 
2111     @param analyzer      Analyzer function, see details section
2112     @param[in,out] arg_p Pointer to struct used by analyzer function
2113     @param transformer   Transformer function, see details section
2114     @param[in,out] arg_t Pointer to struct used by transformer function
2115 
2116     @returns Returned item tree after transformation, NULL if error
2117 
2118     The process of this transformation is assumed to be as follows:
2119 
2120     @code
2121     compile()
2122     {
2123       if (this->*some_analyzer(...))
2124       {
2125         compile children if any;
2126         return this->*some_transformer(...);
2127       }
2128       else
2129         return this;
2130     }
2131     @endcode
2132 
2133     i.e. analysis is performed top-down while transformation is done
2134     bottom-up. If no transformation is applied, the item is returned unchanged.
2135     A transformation error is indicated by returning a NULL pointer. Notice
2136     that the analyzer function should never cause an error.
2137 
2138     The function is supposed to be used during the optimization stage of
2139     query execution. All new allocations are recorded using
2140     THD::change_item_tree() so that they can be rolled back after execution.
2141 
2142     @todo Pass THD to compile() function, thus no need to use current_thd.
2143   */
compile(Item_analyzer analyzer,uchar ** arg_p,Item_transformer transformer,uchar * arg_t)2144   virtual Item *compile(Item_analyzer analyzer, uchar **arg_p,
2145                         Item_transformer transformer, uchar *arg_t) {
2146     if ((this->*analyzer)(arg_p)) return ((this->*transformer)(arg_t));
2147     return this;
2148   }
2149 
traverse_cond(Cond_traverser traverser,void * arg,traverse_order)2150   virtual void traverse_cond(Cond_traverser traverser, void *arg,
2151                              traverse_order) {
2152     (*traverser)(this, arg);
2153   }
2154 
2155   /*
2156     This is used to get the most recent version of any function in
2157     an item tree. The version is the version where a MySQL function
2158     was introduced in. So any function which is added should use
2159     this function and set the int_arg to maximum of the input data
2160     and their own version info.
2161   */
intro_version(uchar *)2162   virtual bool intro_version(uchar *) { return false; }
2163 
2164   /// cleanup() item if it is resolved ('fixed').
cleanup_processor(uchar *)2165   bool cleanup_processor(uchar *) {
2166     if (fixed) cleanup();
2167     return false;
2168   }
2169 
collect_item_field_processor(uchar *)2170   virtual bool collect_item_field_processor(uchar *) { return false; }
2171 
2172   class Collect_item_fields : public Item_tree_walker {
2173    public:
2174     List<Item_field> *m_item_fields;
Collect_item_fields(List<Item_field> * fields)2175     Collect_item_fields(List<Item_field> *fields) : m_item_fields(fields) {}
2176     FORBID_COPY_CTOR_AND_ASSIGN_OP(Collect_item_fields);
2177 
2178     friend class Item_sum;
2179     friend class Item_field;
2180   };
2181 
2182   class Collect_item_fields_or_view_refs : public Item_tree_walker {
2183    public:
2184     List<Item> *m_item_fields_or_view_refs;
2185     SELECT_LEX *m_transformed_block;
Collect_item_fields_or_view_refs(List<Item> * fields_or_vr,SELECT_LEX * transformed_block)2186     Collect_item_fields_or_view_refs(List<Item> *fields_or_vr,
2187                                      SELECT_LEX *transformed_block)
2188         : m_item_fields_or_view_refs(fields_or_vr),
2189           m_transformed_block(transformed_block) {}
2190     FORBID_COPY_CTOR_AND_ASSIGN_OP(Collect_item_fields_or_view_refs);
2191 
2192     friend class Item_sum;
2193     friend class Item_field;
2194     friend class Item_view_ref;
2195   };
2196 
collect_item_field_or_view_ref_processor(uchar *)2197   virtual bool collect_item_field_or_view_ref_processor(uchar *) {
2198     return false;
2199   }
2200 
2201   /**
2202     Item::walk function. Set bit in table->tmp_set for all fields in
2203     table 'arg' that are referred to by the Item.
2204   */
add_field_to_set_processor(uchar *)2205   virtual bool add_field_to_set_processor(uchar *) { return false; }
2206 
2207   /// A processor to handle the select lex visitor framework.
2208   virtual bool visitor_processor(uchar *arg);
2209 
2210   /**
2211     Item::walk function. Set bit in table->cond_set for all fields of
2212     all tables that are referred to by the Item.
2213   */
add_field_to_cond_set_processor(uchar *)2214   virtual bool add_field_to_cond_set_processor(uchar *) { return false; }
2215 
2216   /**
2217      Visitor interface for removing all column expressions (Item_field) in
2218      this expression tree from a bitmap. @see walk()
2219 
2220      @param arg  A MY_BITMAP* cast to unsigned char*, where the bits represent
2221                  Field::field_index values.
2222    */
remove_column_from_bitmap(uchar * arg MY_ATTRIBUTE ((unused)))2223   virtual bool remove_column_from_bitmap(uchar *arg MY_ATTRIBUTE((unused))) {
2224     return false;
2225   }
find_item_in_field_list_processor(uchar *)2226   virtual bool find_item_in_field_list_processor(uchar *) { return false; }
change_context_processor(uchar *)2227   virtual bool change_context_processor(uchar *) { return false; }
find_item_processor(uchar * arg)2228   virtual bool find_item_processor(uchar *arg) { return this == (void *)arg; }
is_non_const_over_literals(uchar *)2229   virtual bool is_non_const_over_literals(uchar *) {
2230     return !basic_const_item();
2231   }
2232   /// Is this an Item_field which references the given Field argument?
find_field_processor(uchar *)2233   virtual bool find_field_processor(uchar *) { return false; }
2234   /// Wrap incompatible arguments in CAST nodes to the expected data types
cast_incompatible_args(uchar *)2235   virtual bool cast_incompatible_args(uchar *) { return false; }
2236   /**
2237     Mark underlying field in read or write map of a table.
2238 
2239     @param arg        Mark_field object
2240   */
mark_field_in_map(uchar * arg MY_ATTRIBUTE ((unused)))2241   virtual bool mark_field_in_map(uchar *arg MY_ATTRIBUTE((unused))) {
2242     return false;
2243   }
2244   /**
2245     @returns true if the expression contains a reference to
2246     an expression of the SELECT list of the given query block.
2247     @param arg   query block to search in.
2248   */
references_select_expr_of(uchar * arg MY_ATTRIBUTE ((unused)))2249   virtual bool references_select_expr_of(uchar *arg MY_ATTRIBUTE((unused))) {
2250     return false;
2251   }
2252 
2253   /// Traverse the item tree and replace fields that are outside of reach with
2254   /// fields that are within reach. This is used by hash join when it detects
2255   /// that a join condition refers to a field that is outside of reach, due to
2256   /// equality propagation. See
2257   /// Item_func::ensure_multi_equality_fields_are_available_walker for more
2258   /// details.
ensure_multi_equality_fields_are_available_walker(uchar *)2259   virtual bool ensure_multi_equality_fields_are_available_walker(uchar *) {
2260     return false;
2261   }
2262 
2263  protected:
2264   /**
2265     Helper function for mark_field_in_map(uchar *arg).
2266 
2267     @param mark_field Mark_field object
2268     @param field      Field to be marked for read/write
2269   */
mark_field_in_map(Mark_field * mark_field,Field * field)2270   static inline bool mark_field_in_map(Mark_field *mark_field, Field *field) {
2271     TABLE *table = mark_field->table;
2272     if (table != nullptr && table != field->table) return false;
2273 
2274     table = field->table;
2275     table->mark_column_used(field, mark_field->mark);
2276 
2277     return false;
2278   }
2279 
2280  public:
2281   /**
2282     Reset execution state for such window function types
2283     as determined by arg
2284 
2285     @param arg   pointing to a bool which, if true, says to reset state
2286                  for framing window function, else for non-framing
2287   */
reset_wf_state(uchar * arg MY_ATTRIBUTE ((unused)))2288   virtual bool reset_wf_state(uchar *arg MY_ATTRIBUTE((unused))) {
2289     return false;
2290   }
2291 
2292   /**
2293     Return used table information for the specified query block (level).
2294     For a field that is resolved from this query block, return the table number.
2295     For a field that is resolved from a query block outer to the specified one,
2296     return OUTER_REF_TABLE_BIT
2297 
2298     @param[in,out] arg pointer to an instance of class Used_tables, which is
2299                        constructed with the query block as argument.
2300                        The used tables information is accumulated in the field
2301                        used_tables in this class.
2302 
2303     @note This function is used to update used tables information after
2304           merging a query block (a subquery) with its parent.
2305   */
used_tables_for_level(uchar * arg MY_ATTRIBUTE ((unused)))2306   virtual bool used_tables_for_level(uchar *arg MY_ATTRIBUTE((unused))) {
2307     return false;
2308   }
2309   /**
2310     Check privileges.
2311 
2312     @param thd   thread handle
2313   */
check_column_privileges(uchar * thd MY_ATTRIBUTE ((unused)))2314   virtual bool check_column_privileges(uchar *thd MY_ATTRIBUTE((unused))) {
2315     return false;
2316   }
inform_item_in_cond_of_tab(uchar *)2317   virtual bool inform_item_in_cond_of_tab(uchar *) { return false; }
2318 
2319   struct Cleanup_after_removal_context {
2320     /**
2321       Pointer to Cleanup_after_removal_context containing from which
2322       select the walk started, i.e., the SELECT_LEX that contained the clause
2323       that was removed.
2324     */
2325     SELECT_LEX *m_root;
2326 
Cleanup_after_removal_contextCleanup_after_removal_context2327     Cleanup_after_removal_context(SELECT_LEX *root) : m_root(root) {}
2328   };
2329   /**
2330      Clean up after removing the item from the item tree.
2331 
2332      @param arg pointer to a Cleanup_after_removal_context object
2333   */
clean_up_after_removal(uchar * arg MY_ATTRIBUTE ((unused)))2334   virtual bool clean_up_after_removal(uchar *arg MY_ATTRIBUTE((unused))) {
2335     return false;
2336   }
2337 
2338   /**
2339     Propagate components that use referenced columns from derived tables.
2340     Some columns from derived tables may be determined to be unused, but
2341     may actually reference other columns that are used. This function will
2342     return true for such columns when called with Item::walk(), which then
2343     means that this column can also be marked as used.
2344     @see also SELECT_LEX::delete_unused_merged_columns().
2345   */
propagate_derived_used(uchar *)2346   bool propagate_derived_used(uchar *) { return is_derived_used(); }
2347 
2348   /**
2349     Called by Item::walk() to set all the referenced items' derived_used flag.
2350   */
propagate_set_derived_used(uchar *)2351   bool propagate_set_derived_used(uchar *) {
2352     set_derived_used();
2353     return false;
2354   }
2355 
2356   /// @see Distinct_check::check_query()
aggregate_check_distinct(uchar *)2357   virtual bool aggregate_check_distinct(uchar *) { return false; }
2358   /// @see Group_check::check_query()
aggregate_check_group(uchar *)2359   virtual bool aggregate_check_group(uchar *) { return false; }
2360   /// @see Group_check::analyze_conjunct()
is_strong_side_column_not_in_fd(uchar *)2361   virtual bool is_strong_side_column_not_in_fd(uchar *) { return false; }
2362   /// @see Group_check::is_in_fd_of_underlying()
is_column_not_in_fd(uchar *)2363   virtual bool is_column_not_in_fd(uchar *) { return false; }
local_column(const SELECT_LEX *)2364   virtual Bool3 local_column(const SELECT_LEX *) const {
2365     return Bool3::false3();
2366   }
2367 
2368   /// argument used by walk method collect_scalar_subqueries ("css")
2369   struct Collect_scalar_subquery_info : public Item_tree_walker {
2370     enum Location { L_SELECT = 1, L_WHERE = 2, L_HAVING = 4, L_JOIN_COND = 8 };
2371     struct Css_info {
2372       int8 m_location{0};  ///< set of locations
2373       /// the scalar subquery
2374       Item_singlerow_subselect *item{nullptr};
2375       /// Where did we find item above? Used when m_location == L_JOIN_COND,
2376       /// nullptr for other locations.
2377       Item *m_join_condition{nullptr};
2378     };
2379 
2380     /// accumulated all scalar subqueries found
2381     std::vector<Css_info> list;
2382     /// we are currently looking at this kind of clause, cf. enum Location
2383     int8 m_location;
2384     Item *m_join_condition_context{nullptr};
Collect_scalar_subquery_infoCollect_scalar_subquery_info2385     Collect_scalar_subquery_info() {}
2386     friend class Item_sum;
2387     friend class Item_singlerow_subselect;
2388   };
2389 
collect_scalar_subqueries(uchar *)2390   virtual bool collect_scalar_subqueries(uchar *) { return false; }
collect_grouped_aggregates(uchar *)2391   virtual bool collect_grouped_aggregates(uchar *) { return false; }
collect_subqueries(uchar *)2392   virtual bool collect_subqueries(uchar *) { return false; }
update_depended_from(uchar *)2393   virtual bool update_depended_from(uchar *) { return false; }
2394   /**
2395     Check if an aggregate is referenced from within the GROUP BY
2396     clause of the query block in which it is aggregated. Such
2397     references will be rejected.
2398     @see Item_ref::fix_fields()
2399     @retval true   if this is an aggregate which is referenced from
2400                    the GROUP BY clause of the aggregating query block
2401     @retval false  otherwise
2402   */
has_aggregate_ref_in_group_by(uchar *)2403   virtual bool has_aggregate_ref_in_group_by(uchar *) { return false; }
2404 
2405   virtual bool cache_const_expr_analyzer(uchar **cache_item);
2406   Item *cache_const_expr_transformer(uchar *item);
2407 
equality_substitution_analyzer(uchar **)2408   virtual bool equality_substitution_analyzer(uchar **) { return false; }
2409 
equality_substitution_transformer(uchar *)2410   virtual Item *equality_substitution_transformer(uchar *) { return this; }
2411 
2412   /**
2413     Check if a partition function is allowed.
2414 
2415     @return whether a partition function is not accepted
2416 
2417     @details
2418     check_partition_func_processor is used to check if a partition function
2419     uses an allowed function. An allowed function will always ensure that
2420     X=Y guarantees that also part_function(X)=part_function(Y) where X is
2421     a set of partition fields and so is Y. The problems comes mainly from
2422     character sets where two equal strings can be quite unequal. E.g. the
2423     german character for double s is equal to 2 s.
2424 
2425     The default is that an item is not allowed
2426     in a partition function. Allowed functions
2427     can never depend on server version, they cannot depend on anything
2428     related to the environment. They can also only depend on a set of
2429     fields in the table itself. They cannot depend on other tables and
2430     cannot contain any queries and cannot contain udf's or similar.
2431     If a new Item class is defined and it inherits from a class that is
2432     allowed in a partition function then it is very important to consider
2433     whether this should be inherited to the new class. If not the function
2434     below should be defined in the new Item class.
2435 
2436     The general behaviour is that most integer functions are allowed.
2437     If the partition function contains any multi-byte collations then
2438     the function check_part_func_fields will report an error on the
2439     partition function independent of what functions are used. So the
2440     only character sets allowed are single character collation and
2441     even for those only a limited set of functions are allowed. The
2442     problem with multi-byte collations is that almost every string
2443     function has the ability to change things such that two strings
2444     that are equal will not be equal after manipulated by a string
2445     function. E.g. two strings one contains a double s, there is a
2446     special german character that is equal to two s. Now assume a
2447     string function removes one character at this place, then in
2448     one the double s will be removed and in the other there will
2449     still be one s remaining and the strings are no longer equal
2450     and thus the partition function will not sort equal strings into
2451     the same partitions.
2452 
2453     So the check if a partition function is valid is two steps. First
2454     check that the field types are valid, next check that the partition
2455     function is valid. The current set of partition functions valid
2456     assumes that there are no multi-byte collations amongst the partition
2457     fields.
2458   */
check_partition_func_processor(uchar *)2459   virtual bool check_partition_func_processor(uchar *) { return true; }
subst_argument_checker(uchar ** arg)2460   virtual bool subst_argument_checker(uchar **arg) {
2461     if (*arg) *arg = nullptr;
2462     return true;
2463   }
explain_subquery_checker(uchar **)2464   virtual bool explain_subquery_checker(uchar **) { return true; }
explain_subquery_propagator(uchar *)2465   virtual Item *explain_subquery_propagator(uchar *) { return this; }
2466 
equal_fields_propagator(uchar *)2467   virtual Item *equal_fields_propagator(uchar *) { return this; }
2468   // Mark the item to not be part of substitution.
disable_constant_propagation(uchar *)2469   virtual bool disable_constant_propagation(uchar *) { return false; }
replace_equal_field(uchar *)2470   virtual Item *replace_equal_field(uchar *) { return this; }
2471   /*
2472     Check if an expression value has allowed arguments, like DATE/DATETIME
2473     for date functions. Also used by partitioning code to reject
2474     timezone-dependent expressions in a (sub)partitioning function.
2475   */
check_valid_arguments_processor(uchar *)2476   virtual bool check_valid_arguments_processor(uchar *) { return false; }
2477 
2478   /**
2479     Check if this item is allowed for a virtual column or inside a
2480     default expression. Should be overridden in child classes.
2481 
2482     @param[in,out] args  Due to the limitation of Item::walk()
2483     it is declared as a pointer to uchar, underneath there's a actually a
2484     structure of type Check_function_as_value_generator_parameters.
2485     It is used mainly in Item_field.
2486 
2487     @returns true if function is not accepted
2488    */
2489   virtual bool check_function_as_value_generator(uchar *args);
2490 
2491   /**
2492     Check if a generated expression depends on DEFAULT function with
2493     specific column name as argument.
2494 
2495     @param[in] args Name of column used as DEFAULT function argument.
2496 
2497     @returns false if the function is not DEFAULT(args), otherwise true.
2498   */
check_gcol_depend_default_processor(uchar * args MY_ATTRIBUTE ((unused)))2499   virtual bool check_gcol_depend_default_processor(
2500       uchar *args MY_ATTRIBUTE((unused))) {
2501     return false;
2502   }
2503 
2504   /*
2505     For SP local variable returns pointer to Item representing its
2506     current value and pointer to current Item otherwise.
2507   */
this_item()2508   virtual Item *this_item() { return this; }
this_item()2509   virtual const Item *this_item() const { return this; }
2510 
2511   /*
2512     For SP local variable returns address of pointer to Item representing its
2513     current value and pointer passed via parameter otherwise.
2514   */
this_item_addr(THD *,Item ** addr_arg)2515   virtual Item **this_item_addr(THD *, Item **addr_arg) { return addr_arg; }
2516 
2517   // Row emulation
cols()2518   virtual uint cols() const { return 1; }
element_index(uint)2519   virtual Item *element_index(uint) { return this; }
addr(uint)2520   virtual Item **addr(uint) { return nullptr; }
2521   virtual bool check_cols(uint c);
2522   // It is not row => null inside is impossible
null_inside()2523   virtual bool null_inside() { return false; }
2524   // used in row subselects to get value of elements
bring_value()2525   virtual void bring_value() {}
2526 
2527   Field *tmp_table_field_from_field_type(TABLE *table, bool fixed_length) const;
field_for_view_update()2528   virtual Item_field *field_for_view_update() { return nullptr; }
2529   /**
2530     Informs an item that it is wrapped in a truth test, in case it wants to
2531     transforms itself to implement this test by itself.
2532     @param thd   Thread handle
2533     @param test  Truth test
2534   */
truth_transformer(THD * thd MY_ATTRIBUTE ((unused)),Bool_test test MY_ATTRIBUTE ((unused)))2535   virtual Item *truth_transformer(THD *thd MY_ATTRIBUTE((unused)),
2536                                   Bool_test test MY_ATTRIBUTE((unused))) {
2537     return nullptr;
2538   }
update_value_transformer(uchar *)2539   virtual Item *update_value_transformer(uchar *) { return this; }
2540 
2541   struct Item_replacement {
2542     SELECT_LEX *m_trans_block;  ///< Transformed query block
2543     SELECT_LEX *m_curr_block;   ///< Transformed query block or a contained
2544     ///< subquery. Pushed when diving into
2545     ///< subqueries.
Item_replacementItem_replacement2546     Item_replacement(SELECT_LEX *transformed_block, SELECT_LEX *current_block)
2547         : m_trans_block(transformed_block), m_curr_block(current_block) {}
2548   };
2549   struct Item_field_replacement : Item_replacement {
2550     Field *m_target;           ///< The field to be replaced
2551     Item_field *m_item;        ///< The replacement field
2552     bool m_keep_alias{false};  ///< Needed for SELECT list alias preservation
Item_field_replacementItem_field_replacement2553     Item_field_replacement(Field *target, Item_field *item, SELECT_LEX *select,
2554                            bool keep)
2555         : Item_replacement(select, select),
2556           m_target(target),
2557           m_item(item),
2558           m_keep_alias(keep) {}
2559   };
2560 
2561   struct Item_view_ref_replacement : Item_replacement {
2562     Item *m_target;  ///< The item identifying the view_ref to be replaced
2563     Field *m_field;  ///< The replacement field
2564     ///< subquery. Pushed when diving into
2565     ///< subqueries.
Item_view_ref_replacementItem_view_ref_replacement2566     Item_view_ref_replacement(Item *target, Field *field, SELECT_LEX *select)
2567         : Item_replacement(select, select), m_target(target), m_field(field) {}
2568   };
2569 
2570   struct Aggregate_replacement {
2571     Item_sum *m_target;
2572     Item_field *m_replacement;
Aggregate_replacementAggregate_replacement2573     Aggregate_replacement(Item_sum *target, Item_field *replacement)
2574         : m_target(target), m_replacement(replacement) {}
2575   };
2576 
2577   /**
2578     When walking the item tree seeing an Item_singlerow_subselect matching
2579     a target, replace it with a substitute field used when transforming
2580     scalar subqueries into derived tables. Cf.
2581     SELECT_LEX::transform_scalar_subqueries_to_join_with_derived.
2582   */
replace_scalar_subquery(uchar *)2583   virtual Item *replace_scalar_subquery(uchar *) { return this; }
2584 
2585   /**
2586     Transform processor used by SELECT_LEX::transform_grouped_to_derived
2587     to replace fields which used to be at the transformed query block
2588     with corresponding fields in the new derived table containing the grouping
2589     operation of the original transformed query block.
2590   */
replace_item_field(uchar *)2591   virtual Item *replace_item_field(uchar *) { return this; }
replace_item_view_ref(uchar *)2592   virtual Item *replace_item_view_ref(uchar *) { return this; }
replace_aggregate(uchar *)2593   virtual Item *replace_aggregate(uchar *) { return this; }
update_context(uchar *)2594   virtual bool update_context(uchar *) { return false; }
2595 
2596   struct Aggregate_ref_update {
2597     Item_sum *m_target;
2598     SELECT_LEX *m_owner;
Aggregate_ref_updateAggregate_ref_update2599     Aggregate_ref_update(Item_sum *target, SELECT_LEX *owner)
2600         : m_target(target), m_owner(owner) {}
2601   };
2602 
2603   /**
2604     A walker processor overridden by Item_aggregate_ref, q.v.
2605   */
update_aggr_refs(uchar *)2606   virtual bool update_aggr_refs(uchar *) { return false; }
2607 
2608   virtual Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs);
delete_self()2609   void delete_self() {
2610     cleanup();
2611     delete this;
2612   }
2613 
2614   /** @return whether the item is local to a stored procedure */
is_splocal()2615   virtual bool is_splocal() const { return false; }
2616 
2617   /*
2618     Return Settable_routine_parameter interface of the Item.  Return 0
2619     if this Item is not Settable_routine_parameter.
2620   */
get_settable_routine_parameter()2621   virtual Settable_routine_parameter *get_settable_routine_parameter() {
2622     return nullptr;
2623   }
is_temporal_with_date()2624   inline bool is_temporal_with_date() const {
2625     return is_temporal_type_with_date(real_type_to_type(data_type()));
2626   }
is_temporal_with_date_and_time()2627   inline bool is_temporal_with_date_and_time() const {
2628     return is_temporal_type_with_date_and_time(real_type_to_type(data_type()));
2629   }
is_temporal_with_time()2630   inline bool is_temporal_with_time() const {
2631     return is_temporal_type_with_time(real_type_to_type(data_type()));
2632   }
is_temporal()2633   inline bool is_temporal() const {
2634     return is_temporal_type(real_type_to_type(data_type()));
2635   }
2636   /**
2637     Check whether this and the given item has compatible comparison context.
2638     Used by the equality propagation. See Item_field::equal_fields_propagator.
2639 
2640     @return
2641       true  if the context is the same or if fields could be
2642             compared as DATETIME values by the Arg_comparator.
2643       false otherwise.
2644   */
has_compatible_context(Item * item)2645   inline bool has_compatible_context(Item *item) const {
2646     /* Same context. */
2647     if (cmp_context == INVALID_RESULT || item->cmp_context == cmp_context)
2648       return true;
2649     /* DATETIME comparison context. */
2650     if (is_temporal_with_date())
2651       return item->is_temporal_with_date() ||
2652              item->cmp_context == STRING_RESULT;
2653     if (item->is_temporal_with_date())
2654       return is_temporal_with_date() || cmp_context == STRING_RESULT;
2655     return false;
2656   }
get_geometry_type()2657   virtual Field::geometry_type get_geometry_type() const {
2658     return Field::GEOM_GEOMETRY;
2659   }
2660   String *check_well_formed_result(String *str, bool send_error, bool truncate);
2661   bool eq_by_collation(Item *item, bool binary_cmp, const CHARSET_INFO *cs);
2662 
2663   /*
2664     Test whether an expression is expensive to compute. Used during
2665     optimization to avoid computing expensive expressions during this
2666     phase. Also used to force temp tables when sorting on expensive
2667     functions.
2668     TODO:
2669     Normally we should have a method:
2670       cost Item::execution_cost(),
2671     where 'cost' is either 'double' or some structure of various cost
2672     parameters.
2673   */
is_expensive()2674   virtual bool is_expensive() {
2675     if (is_expensive_cache < 0)
2676       is_expensive_cache =
2677           walk(&Item::is_expensive_processor, enum_walk::POSTFIX, nullptr);
2678     return is_expensive_cache;
2679   }
2680 
2681   /**
2682     @return maximum number of characters that this Item can store
2683     If Item is of string or blob type, return max string length in bytes
2684     divided by bytes per character, otherwise return max_length.
2685     @todo - check if collation for other types should have mbmaxlen = 1
2686   */
max_char_length()2687   uint32 max_char_length() const {
2688     /*
2689       Length of e.g. 5.5e5 in an expression such as GREATEST(5.5e5, '5') is 5
2690       (length of that string) although length of the actual value is 6.
2691       Return MAX_DOUBLE_STR_LENGTH to prevent truncation of data without having
2692       to evaluate the value of the item.
2693     */
2694     uint32 max_len =
2695         data_type() == MYSQL_TYPE_DOUBLE ? MAX_DOUBLE_STR_LENGTH : max_length;
2696     if (result_type() == STRING_RESULT)
2697       return max_len / collation.collation->mbmaxlen;
2698     return max_len;
2699   }
2700 
fix_char_length(uint32 max_char_length_arg)2701   inline void fix_char_length(uint32 max_char_length_arg) {
2702     max_length = char_to_byte_length_safe(max_char_length_arg,
2703                                           collation.collation->mbmaxlen);
2704   }
2705 
2706   /*
2707     Return true if the item points to a column of an outer-joined table.
2708   */
is_outer_field()2709   virtual bool is_outer_field() const {
2710     DBUG_ASSERT(fixed);
2711     return false;
2712   }
2713 
2714   /**
2715      Check if an item either is a blob field, or will be represented as a BLOB
2716      field if a field is created based on this item.
2717 
2718      @retval true  If a field based on this item will be a BLOB field,
2719      @retval false Otherwise.
2720   */
2721   bool is_blob_field() const;
2722 
2723  protected:
2724   /// Set accumulated properties for an Item
set_accum_properties(const Item * item)2725   void set_accum_properties(const Item *item) {
2726     m_accum_properties = item->m_accum_properties;
2727   }
2728 
2729   /// Add more accumulated properties to an Item
add_accum_properties(const Item * item)2730   void add_accum_properties(const Item *item) {
2731     m_accum_properties |= item->m_accum_properties;
2732   }
2733 
2734   /// Set the "has subquery" property
set_subquery()2735   void set_subquery() { m_accum_properties |= PROP_SUBQUERY; }
2736 
2737   /// Set the "has stored program" property
set_stored_program()2738   void set_stored_program() { m_accum_properties |= PROP_STORED_PROGRAM; }
2739 
2740  public:
2741   /// @return true if this item or any of its decendents contains a subquery.
has_subquery()2742   bool has_subquery() const { return m_accum_properties & PROP_SUBQUERY; }
2743 
2744   /// @return true if this item or any of its decendents refers a stored func.
has_stored_program()2745   bool has_stored_program() const {
2746     return m_accum_properties & PROP_STORED_PROGRAM;
2747   }
2748 
2749   /// @return true if this item or any of its decendents is an aggregated func.
has_aggregation()2750   bool has_aggregation() const { return m_accum_properties & PROP_AGGREGATION; }
2751 
2752   /// Set the "has aggregation" property
set_aggregation()2753   void set_aggregation() { m_accum_properties |= PROP_AGGREGATION; }
2754 
2755   /// Reset the "has aggregation" property
reset_aggregation()2756   void reset_aggregation() { m_accum_properties &= ~PROP_AGGREGATION; }
2757 
2758   /// @return true if this item or any of its decendents is a window func.
has_wf()2759   bool has_wf() const { return m_accum_properties & PROP_WINDOW_FUNCTION; }
2760 
2761   /// Set the "has window function" property
set_wf()2762   void set_wf() { m_accum_properties |= PROP_WINDOW_FUNCTION; }
2763 
2764   /**
2765     @return true if this item or any of its decendents within the same query
2766     has a reference to a ROLLUP expression
2767   */
has_rollup_expr()2768   bool has_rollup_expr() const { return m_accum_properties & PROP_ROLLUP_EXPR; }
2769 
2770   /// Set the property: this item (tree) contains a reference to a ROLLUP expr
set_rollup_expr()2771   void set_rollup_expr() { m_accum_properties |= PROP_ROLLUP_EXPR; }
2772 
2773   /**
2774     @return true if this item or any of underlying items is a GROUPING function
2775    */
has_grouping_func()2776   bool has_grouping_func() const {
2777     return m_accum_properties & PROP_GROUPING_FUNC;
2778   }
2779 
2780   /// Set the property: this item is a call to GROUPING
set_grouping_func()2781   void set_grouping_func() { m_accum_properties |= PROP_GROUPING_FUNC; }
2782 
2783   /// Whether this Item was created by the IN->EXISTS subquery transformation
created_by_in2exists()2784   virtual bool created_by_in2exists() const { return false; }
2785 
2786   // @return true if an expression in select list of derived table is used
is_derived_used()2787   bool is_derived_used() const { return derived_used; }
2788 
mark_subqueries_optimized_away()2789   void mark_subqueries_optimized_away() {
2790     if (has_subquery())
2791       walk(&Item::subq_opt_away_processor, enum_walk::POSTFIX, nullptr);
2792   }
2793 
2794   /**
2795     Analyzer function for GC substitution. @see substitute_gc()
2796   */
gc_subst_analyzer(uchar **)2797   virtual bool gc_subst_analyzer(uchar **) { return false; }
2798   /**
2799     Transformer function for GC substitution. @see substitute_gc()
2800   */
gc_subst_transformer(uchar *)2801   virtual Item *gc_subst_transformer(uchar *) { return this; }
2802 
2803   /**
2804     A processor that replaces any Fields with a Create_field_wrapper. This
2805     will allow us to resolve functions during CREATE TABLE, where we only have
2806     Create_field available and not Field. Used for functional index
2807     implementation.
2808   */
replace_field_processor(uchar *)2809   virtual bool replace_field_processor(uchar *) { return false; }
2810   /**
2811     Check if this item is of a type that is eligible for GC
2812     substitution. All items that belong to subclasses of Item_func are
2813     eligible for substitution. @see substitute_gc()
2814   */
can_be_substituted_for_gc()2815   bool can_be_substituted_for_gc() const {
2816     const Type t = type();
2817     return t == FUNC_ITEM || t == COND_ITEM;
2818   }
2819 
2820   void aggregate_decimal_properties(Item **item, uint nitems);
2821   void aggregate_float_properties(Item **item, uint nitems);
2822   void aggregate_char_length(Item **args, uint nitems);
2823   void aggregate_temporal_properties(Item **item, uint nitems);
2824   bool aggregate_string_properties(const char *name, Item **item, uint nitems);
2825   void aggregate_num_type(Item_result result_type, Item **item, uint nitems);
2826 
2827   /**
2828     This function applies only to Item_field objects referred to by an Item_ref
2829     object that has been marked as a const_item.
2830 
2831     @param arg  Keep track of whether an Item_ref refers to an Item_field.
2832   */
repoint_const_outer_ref(uchar * arg MY_ATTRIBUTE ((unused)))2833   virtual bool repoint_const_outer_ref(uchar *arg MY_ATTRIBUTE((unused))) {
2834     return false;
2835   }
get_orig_field()2836   virtual const Field *get_orig_field() { return nullptr; }
set_orig_field(const Field *)2837   virtual void set_orig_field(const Field *) {}
strip_db_table_name_processor(uchar *)2838   virtual bool strip_db_table_name_processor(uchar *) { return false; }
2839 
2840  private:
subq_opt_away_processor(uchar *)2841   virtual bool subq_opt_away_processor(uchar *) { return false; }
2842 
2843   // Set an expression from select list of derived table as used.
set_derived_used()2844   void set_derived_used() { derived_used = true; }
2845 
2846  public:  // Start of data fields
2847   /**
2848     Intrusive list pointer for free list. If not null, points to the next
2849     Item on some Query_arena's free list. For instance, stored procedures
2850     have their own Query_arena's.
2851 
2852     @see Query_arena::free_list
2853   */
2854   Item *next_free;
2855 
2856  protected:
2857   /// str_values's main purpose is to cache the value in save_in_field
2858   String str_value;
2859 
2860  public:
2861   /**
2862     Character set and collation properties assigned for this Item.
2863     Used if Item represents a character string expression.
2864   */
2865   DTCollation collation;
2866   Item_name_string item_name;  ///< Name from query
2867   Item_name_string orig_name;  ///< Original item name (if it was renamed)
2868   /**
2869     Maximum length of result of evaluating this item, in number of bytes.
2870     - For character or blob data types, max char length multiplied by max
2871       character size (collation.mbmaxlen).
2872     - For decimal type, it is the precision in digits plus sign (unless
2873       unsigned) plus decimal point (unless it has zero decimals).
2874     - For other numeric types, the default or specific display length.
2875     - For date/time types, the display length (10 for DATE, 10 + optional FSP
2876       for TIME, 19 + optional fsp for datetime/timestamp).
2877     - For bit, the number of bits.
2878     - For enum, the string length of the widest enum element.
2879     - For set, the sum of the string length of each set element plus separators.
2880     - For geometry, the maximum size of a BLOB (it's underlying storage type).
2881     - For json, the maximum size of a BLOB (it's underlying storage type).
2882   */
2883   uint32 max_length;  ///< Maximum length, in bytes
2884   enum item_marker    ///< Values for member 'marker'
2885   { MARKER_NONE = 0,
2886     /// When contextualization or itemization adds an implicit comparison '0<>'
2887     /// (see make_condition()), to record that this Item_func_ne was created for
2888     /// this purpose; this value is tested during resolution.
2889     MARKER_IMPLICIT_NE_ZERO = 1,
2890     /// When doing constant propagation (e.g. change_cond_ref_to_const(), to
2891     /// remember that we have already processed the item.
2892     MARKER_CONST_PROPAG = 2,
2893     /// When creating an internal temporary table: says how to store BIT fields.
2894     MARKER_BIT = 4,
2895     /// When analyzing functional dependencies for only_full_group_by (says
2896     /// whether a nullable column can be treated at not nullable).
2897     MARKER_FUNC_DEP_NOT_NULL = 5,
2898     /// When we change DISTINCT to GROUP BY: used for book-keeping of
2899     /// fields.
2900     MARKER_DISTINCT_GROUP = 6,
2901     /// When pushing index conditions: it says whether a condition uses only
2902     /// indexed columns.
2903     MARKER_ICP_COND_USES_INDEX_ONLY = 10 };
2904   /**
2905     This member has several successive meanings, depending on the phase we're
2906     in (@see item_marker).
2907     The important property is that a phase must have a value (or few values)
2908     which is reserved for this phase. If it wants to set "marked", it assigns
2909     the value; it it wants to test if it is marked, it tests marker !=
2910     value. If the value has been assigned and the phase wants to cancel it can
2911     set marker to MARKER_NONE, which is a magic number which no phase
2912     reserves.
2913     A phase can expect 'marker' to be MARKER_NONE at the start of execution of
2914     a normal statement, at the start of preparation of a PS, and at the start
2915     of execution of a PS.
2916     A phase should not expect marker's value to survive after the phase's
2917     end - as a following phase may change it.
2918   */
2919   item_marker marker;
2920   Item_result cmp_context;  ///< Comparison context
2921  private:
2922   const bool is_parser_item;  ///< true if allocated directly by parser
2923   /*
2924     If this item was created in runtime memroot, it cannot be used for
2925     substitution in subquery transformation process
2926   */
2927   bool runtime_item;
2928   int8 is_expensive_cache;  ///< Cache of result of is_expensive()
2929   uint8 m_data_type;        ///< Data type assigned to Item
2930  public:
2931   bool fixed;  ///< True if item has been resolved
2932   /**
2933     Number of decimals in result when evaluating this item
2934     - For integer type, always zero.
2935     - For decimal type, number of decimals.
2936     - For float type, it may be DECIMAL_NOT_SPECIFIED
2937     - For time, datetime and timestamp, number of decimals in fractional second
2938     - For string types, may be decimals of cast source or DECIMAL_NOT_SPECIFIED
2939   */
2940   uint8 decimals;
2941   /**
2942     True if this item may be null.
2943 
2944     For items that represent rows, it is true if one of the columns
2945     may be null.
2946 
2947     For items that represent scalar or row subqueries, it is true if
2948     one of the returned columns could be null, or if the subquery
2949     could return zero rows.
2950 
2951     It is worth noting that this information is correct only until
2952     equality propagation has been run by the optimization phase.
2953     Indeed, consider:
2954      select * from t1, t2,t3 where t1.pk=t2.a and t1.pk+1...
2955     the '+' is not nullable as t1.pk is not nullable;
2956     but if the optimizer chooses plan is t2-t3-t1, then, due to equality
2957     propagation it will replace t1.pk in '+' with t2.a (as t2 is before t1
2958     in plan), making the '+' capable of returning NULL when t2.a is NULL.
2959   */
2960   bool maybe_null;
2961   bool null_value;  ///< True if item is null
2962   bool unsigned_flag;
2963   bool m_is_window_function;  ///< True if item represents window func
2964   /**
2965     True if item is a top most element in the expression being
2966     evaluated for a check constraint.
2967   */
2968   bool m_in_check_constraint_exec_ctx{false};
2969 
2970  private:
2971   /**
2972     True if this is an expression from the select list of a derived table
2973     which is actually used by outer query.
2974   */
2975   bool derived_used;
2976 
2977  protected:
2978   /**
2979     Set of properties that are calculated by accumulation from underlying items.
2980     Computed by constructors and fix_fields() and updated by
2981     update_used_tables(). The properties are accumulated up to the root of the
2982     current item tree, except they are not accumulated across subqueries and
2983     functions.
2984   */
2985   static constexpr uint8 PROP_SUBQUERY = 0x01;
2986   static constexpr uint8 PROP_STORED_PROGRAM = 0x02;
2987   static constexpr uint8 PROP_AGGREGATION = 0x04;
2988   static constexpr uint8 PROP_WINDOW_FUNCTION = 0x08;
2989   /**
2990     Set if the item or one or more of the underlying items contains a
2991     ROLLUP expression. The rolled up expression itself is not so marked.
2992   */
2993   static constexpr uint8 PROP_ROLLUP_EXPR = 0x10;
2994   /**
2995     Set if the item or one or more of the underlying items is a GROUPING
2996     function.
2997   */
2998   static constexpr uint8 PROP_GROUPING_FUNC = 0x20;
2999   uint8 m_accum_properties;
3000 
3001  public:
3002   /**
3003      Noop in Item for items that are not subclasses of Item_ident.
3004      Overridden in Item_ident where it sets the
3005      table_name member. Signture matches the requirement of
3006      Item::walk.
3007 
3008      @return true - to signal that walk should continue to sub items.
3009    */
set_table_name(uchar *)3010   virtual bool set_table_name(uchar *) { return true; }
3011 
3012   /**
3013     Check if this expression can be used for partial update of a given
3014     JSON column.
3015 
3016     For example, the expression `JSON_REPLACE(col, '$.foo', 'bar')`
3017     can be used to partially update the column `foo`.
3018 
3019     @param field  the JSON column that is being updated
3020     @return true if this expression can be used for partial update,
3021       false otherwise
3022   */
supports_partial_update(const Field_json * field MY_ATTRIBUTE ((unused)))3023   virtual bool supports_partial_update(
3024       const Field_json *field MY_ATTRIBUTE((unused))) const {
3025     return false;
3026   }
3027 
3028   /**
3029     Whether the item returns array of its data type
3030   */
returns_array()3031   virtual bool returns_array() const { return false; }
3032 
3033   /**
3034    A helper funciton to ensure proper usage of CAST(.. AS .. ARRAY)
3035   */
allow_array_cast()3036   virtual void allow_array_cast() {}
3037 };
3038 
3039 /**
3040   Descriptor of what and how to cache for
3041   Item::cache_const_expr_transformer/analyzer.
3042 
3043 */
3044 
3045 struct cache_const_expr_arg {
3046   /// Path from the expression's top to the current item in item tree
3047   /// used to track parent of current item for caching JSON data
3048   List<Item> stack;
3049   /// Item to cache. Used as a binary flag, but kept as Item* for assertion
3050   Item *cache_item{nullptr};
3051   /// How to cache JSON data. @see Item::enum_const_item_cache
3052   Item::enum_const_item_cache cache_arg{Item::CACHE_NONE};
3053 };
3054 
3055 /**
3056   A helper class to give in a functor to Item::walk(). Use as e.g.:
3057 
3058   bool result = WalkItem(root_item, enum_walk::POSTFIX, [](Item *item) { ... });
3059 
3060   TODO: Make Item::walk() just take in a functor in the first place, instead of
3061   a pointer-to-member and an opaque argument.
3062  */
3063 template <class T>
WalkItem(Item * item,enum_walk walk,T && functor)3064 inline bool WalkItem(Item *item, enum_walk walk, T &&functor) {
3065   return item->walk(&Item::walk_helper_thunk<T>, walk,
3066                     reinterpret_cast<uchar *>(&functor));
3067 }
3068 
3069 class sp_head;
3070 
3071 class Item_basic_constant : public Item {
3072   table_map used_table_map;
3073 
3074  public:
Item_basic_constant()3075   Item_basic_constant() : Item(), used_table_map(0) {}
Item_basic_constant(const POS & pos)3076   explicit Item_basic_constant(const POS &pos) : Item(pos), used_table_map(0) {}
3077 
3078   /// @todo add implementation of basic_const_item
3079   ///       and remove from subclasses as appropriate.
3080 
set_used_tables(table_map map)3081   void set_used_tables(table_map map) { used_table_map = map; }
used_tables()3082   table_map used_tables() const override { return used_table_map; }
check_function_as_value_generator(uchar *)3083   bool check_function_as_value_generator(uchar *) override { return false; }
3084   /* to prevent drop fixed flag (no need parent cleanup call) */
cleanup()3085   void cleanup() override {
3086     /*
3087       Restore the original field name as it might not have been allocated
3088       in the statement memory. If the name is auto generated, it must be
3089       done again between subsequent executions of a prepared statement.
3090     */
3091     if (orig_name.is_set()) item_name = orig_name;
3092   }
basic_const_item()3093   bool basic_const_item() const override { return true; }
set_str_value(String * str)3094   void set_str_value(String *str) { str_value = *str; }
3095 };
3096 
3097 /*****************************************************************************
3098   The class is a base class for representation of stored routine variables in
3099   the Item-hierarchy. There are the following kinds of SP-vars:
3100     - local variables (Item_splocal);
3101     - CASE expression (Item_case_expr);
3102 *****************************************************************************/
3103 
3104 class Item_sp_variable : public Item {
3105  protected:
3106   /*
3107     THD, which is stored in fix_fields() and is used in this_item() to avoid
3108     current_thd use.
3109   */
3110   THD *m_thd;
3111 
3112  public:
3113   Name_string m_name;
3114 
3115  public:
3116 #ifndef DBUG_OFF
3117   /*
3118     Routine to which this Item_splocal belongs. Used for checking if correct
3119     runtime context is used for variable handling.
3120   */
3121   sp_head *m_sp;
3122 #endif
3123 
3124  public:
3125   Item_sp_variable(const Name_string sp_var_name);
3126 
3127  public:
3128   bool fix_fields(THD *thd, Item **) override;
3129 
3130   double val_real() override;
3131   longlong val_int() override;
3132   String *val_str(String *sp) override;
3133   my_decimal *val_decimal(my_decimal *decimal_value) override;
3134   bool val_json(Json_wrapper *result) override;
3135   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3136   bool get_time(MYSQL_TIME *ltime) override;
3137   bool is_null() override;
3138 
3139  public:
3140   inline void make_field(Send_field *field) override;
send(Protocol * protocol,String * str)3141   bool send(Protocol *protocol, String *str) override {
3142     // Need to override send() in case this_item() is an Item_field with a
3143     // ZEROFILL attribute.
3144     return this_item()->send(protocol, str);
3145   }
3146 
3147  protected:
3148   inline type_conversion_status save_in_field_inner(
3149       Field *field, bool no_conversions) override;
3150 };
3151 
3152 /*****************************************************************************
3153   Item_sp_variable inline implementation.
3154 *****************************************************************************/
3155 
make_field(Send_field * field)3156 inline void Item_sp_variable::make_field(Send_field *field) {
3157   Item *it = this_item();
3158   it->item_name.copy(item_name.is_set() ? item_name : m_name);
3159   it->make_field(field);
3160 }
3161 
save_in_field_inner(Field * field,bool no_conversions)3162 inline type_conversion_status Item_sp_variable::save_in_field_inner(
3163     Field *field, bool no_conversions) {
3164   return this_item()->save_in_field(field, no_conversions);
3165 }
3166 
3167 /*****************************************************************************
3168   A reference to local SP variable (incl. reference to SP parameter), used in
3169   runtime.
3170 *****************************************************************************/
3171 
3172 class Item_splocal final : public Item_sp_variable,
3173                            private Settable_routine_parameter {
3174   uint m_var_idx;
3175 
3176   Type m_type;
3177   Item_result m_result_type;
3178 
3179  public:
3180   /*
3181     If this variable is a parameter in LIMIT clause.
3182     Used only during NAME_CONST substitution, to not append
3183     NAME_CONST to the resulting query and thus not break
3184     the slave.
3185   */
3186   bool limit_clause_param;
3187   /*
3188     Position of this reference to SP variable in the statement (the
3189     statement itself is in sp_instr_stmt::m_query).
3190     This is valid only for references to SP variables in statements,
3191     excluding DECLARE CURSOR statement. It is used to replace references to SP
3192     variables with NAME_CONST calls when putting statements into the binary
3193     log.
3194     Value of 0 means that this object doesn't corresponding to reference to
3195     SP variable in query text.
3196   */
3197   uint pos_in_query;
3198   /*
3199     Byte length of SP variable name in the statement (see pos_in_query).
3200     The value of this field may differ from the name_length value because
3201     name_length contains byte length of UTF8-encoded item name, but
3202     the query string (see sp_instr_stmt::m_query) is currently stored with
3203     a charset from the SET NAMES statement.
3204   */
3205   uint len_in_query;
3206 
3207   Item_splocal(const Name_string sp_var_name, uint sp_var_idx,
3208                enum_field_types sp_var_type, uint pos_in_q = 0,
3209                uint len_in_q = 0);
3210 
is_splocal()3211   bool is_splocal() const override { return true; }
3212 
3213   Item *this_item() override;
3214   const Item *this_item() const override;
3215   Item **this_item_addr(THD *thd, Item **) override;
3216 
3217   void print(const THD *thd, String *str,
3218              enum_query_type query_type) const override;
3219 
3220  public:
get_var_idx()3221   inline uint get_var_idx() const { return m_var_idx; }
3222 
type()3223   inline enum Type type() const override { return m_type; }
result_type()3224   inline Item_result result_type() const override { return m_result_type; }
3225   bool val_json(Json_wrapper *result) override;
3226 
3227  private:
3228   bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
3229 
3230  public:
get_settable_routine_parameter()3231   Settable_routine_parameter *get_settable_routine_parameter() override {
3232     return this;
3233   }
3234 };
3235 
3236 /*****************************************************************************
3237   A reference to case expression in SP, used in runtime.
3238 *****************************************************************************/
3239 
3240 class Item_case_expr final : public Item_sp_variable {
3241  public:
3242   Item_case_expr(uint case_expr_id);
3243 
3244  public:
3245   Item *this_item() override;
3246   const Item *this_item() const override;
3247   Item **this_item_addr(THD *thd, Item **) override;
3248 
type()3249   Type type() const override { return this_item()->type(); }
result_type()3250   Item_result result_type() const override {
3251     return this_item()->result_type();
3252   }
3253 
3254  public:
3255   /*
3256     NOTE: print() is intended to be used from views and for debug.
3257     Item_case_expr can not occur in views, so here it is only for debug
3258     purposes.
3259   */
3260   void print(const THD *thd, String *str,
3261              enum_query_type query_type) const override;
3262 
3263  private:
3264   uint m_case_expr_id;
3265 };
3266 
3267 /*
3268   NAME_CONST(given_name, const_value).
3269   This 'function' has all properties of the supplied const_value (which is
3270   assumed to be a literal constant), and the name given_name.
3271 
3272   This is used to replace references to SP variables when we write PROCEDURE
3273   statements into the binary log.
3274 
3275   TODO
3276     Together with Item_splocal and Item::this_item() we can actually extract
3277     common a base of this class and Item_splocal. Maybe it is possible to
3278     extract a common base with class Item_ref, too.
3279 */
3280 
3281 class Item_name_const final : public Item {
3282   typedef Item super;
3283 
3284   Item *value_item;
3285   Item *name_item;
3286   bool valid_args;
3287 
3288  public:
3289   Item_name_const(const POS &pos, Item *name_arg, Item *val);
3290 
3291   bool itemize(Parse_context *pc, Item **res) override;
3292   bool fix_fields(THD *, Item **) override;
3293 
3294   enum Type type() const override;
3295   double val_real() override;
3296   longlong val_int() override;
3297   String *val_str(String *sp) override;
3298   my_decimal *val_decimal(my_decimal *) override;
3299   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3300   bool get_time(MYSQL_TIME *ltime) override;
3301   bool is_null() override;
3302   void print(const THD *thd, String *str,
3303              enum_query_type query_type) const override;
3304 
result_type()3305   Item_result result_type() const override { return value_item->result_type(); }
3306 
cache_const_expr_analyzer(uchar **)3307   bool cache_const_expr_analyzer(uchar **) override {
3308     // Item_name_const always wraps a literal, so there is no need to cache it.
3309     return false;
3310   }
3311 
3312  protected:
save_in_field_inner(Field * field,bool no_conversions)3313   type_conversion_status save_in_field_inner(Field *field,
3314                                              bool no_conversions) override {
3315     return value_item->save_in_field(field, no_conversions);
3316   }
3317 };
3318 
3319 bool agg_item_collations_for_comparison(DTCollation &c, const char *name,
3320                                         Item **items, uint nitems, uint flags);
3321 bool agg_item_set_converter(DTCollation &coll, const char *fname, Item **args,
3322                             uint nargs, uint flags, int item_sep);
3323 bool agg_item_charsets(DTCollation &c, const char *name, Item **items,
3324                        uint nitems, uint flags, int item_sep);
3325 inline bool agg_item_charsets_for_string_result(DTCollation &c,
3326                                                 const char *name, Item **items,
3327                                                 uint nitems, int item_sep = 1) {
3328   uint flags = MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV |
3329                MY_COLL_ALLOW_NUMERIC_CONV;
3330   return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3331 }
3332 inline bool agg_item_charsets_for_comparison(DTCollation &c, const char *name,
3333                                              Item **items, uint nitems,
3334                                              int item_sep = 1) {
3335   uint flags = MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV |
3336                MY_COLL_DISALLOW_NONE;
3337   return agg_item_charsets(c, name, items, nitems, flags, item_sep);
3338 }
3339 
3340 class Item_num : public Item_basic_constant {
3341   typedef Item_basic_constant super;
3342 
3343  public:
Item_num()3344   Item_num() { collation.set_numeric(); }
Item_num(const POS & pos)3345   explicit Item_num(const POS &pos) : super(pos) { collation.set_numeric(); }
3346 
3347   virtual Item_num *neg() = 0;
3348   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
check_partition_func_processor(uchar *)3349   bool check_partition_func_processor(uchar *) override { return false; }
3350 };
3351 
3352 #define NO_CACHED_FIELD_INDEX ((uint)(-1))
3353 
3354 class Item_ident : public Item {
3355   typedef Item super;
3356 
3357  protected:
3358   /*
3359     We have to store initial values of db_name, table_name and field_name
3360     to be able to restore them during cleanup() because they can be
3361     updated during fix_fields() to values from Field object and life-time
3362     of those is shorter than life-time of Item_field.
3363   */
3364   const char *orig_db_name;
3365   const char *orig_table_name;
3366   const char *orig_field_name;
3367   bool m_alias_of_expr;  ///< if this Item's name is alias of SELECT expression
3368 
3369  public:
3370   /**
3371     For regularly resolved column references, 'context' points to a name
3372     resolution context object belonging to the query block which simply
3373     contains the reference. To further clarify, in
3374     SELECT (SELECT t.a) FROM t;
3375     t.a is an Item_ident whose 'context' belongs to the subquery
3376     (context->select_lex == that of the subquery).
3377     For column references that are part of a generated column expression,
3378     'context' points to a temporary name resolution context object during
3379     resolving, but is set to nullptr after resolving is done. Note that
3380     Item_ident::local_column() depends on that.
3381   */
3382   Name_resolution_context *context;
3383   const char *db_name;
3384   const char *table_name;
3385   const char *field_name;
3386 
3387   /*
3388     Cached value of index for this field in table->field array, used by prep.
3389     stmts for speeding up their re-execution. Holds NO_CACHED_FIELD_INDEX
3390     if index value is not known.
3391   */
3392   uint cached_field_index;
3393   /*
3394     Cached pointer to table which contains this field, used for the same reason
3395     by prep. stmt. too in case then we have not-fully qualified field.
3396     0 - means no cached value.
3397     @todo Notice that this is usually the same as Item_field::table_ref.
3398           cached_table should be replaced by table_ref ASAP.
3399   */
3400   TABLE_LIST *cached_table;
3401   SELECT_LEX *depended_from;
3402 
Item_ident(Name_resolution_context * context_arg,const char * db_name_arg,const char * table_name_arg,const char * field_name_arg)3403   Item_ident(Name_resolution_context *context_arg, const char *db_name_arg,
3404              const char *table_name_arg, const char *field_name_arg)
3405       : orig_db_name(db_name_arg),
3406         orig_table_name(table_name_arg),
3407         orig_field_name(field_name_arg),
3408         m_alias_of_expr(false),
3409         context(context_arg),
3410         db_name(db_name_arg),
3411         table_name(table_name_arg),
3412         field_name(field_name_arg),
3413         cached_field_index(NO_CACHED_FIELD_INDEX),
3414         cached_table(nullptr),
3415         depended_from(nullptr) {
3416     item_name.set(field_name_arg);
3417   }
3418 
Item_ident(const POS & pos,const char * db_name_arg,const char * table_name_arg,const char * field_name_arg)3419   Item_ident(const POS &pos, const char *db_name_arg,
3420              const char *table_name_arg, const char *field_name_arg)
3421       : super(pos),
3422         orig_db_name(db_name_arg),
3423         orig_table_name(table_name_arg),
3424         orig_field_name(field_name_arg),
3425         m_alias_of_expr(false),
3426         db_name(db_name_arg),
3427         table_name(table_name_arg),
3428         field_name(field_name_arg),
3429         cached_field_index(NO_CACHED_FIELD_INDEX),
3430         cached_table(nullptr),
3431         depended_from(nullptr) {
3432     item_name.set(field_name_arg);
3433   }
3434 
3435   /// Constructor used by Item_field & Item_*_ref (see Item comment)
3436 
Item_ident(THD * thd,Item_ident * item)3437   Item_ident(THD *thd, Item_ident *item)
3438       : Item(thd, item),
3439         orig_db_name(item->orig_db_name),
3440         orig_table_name(item->orig_table_name),
3441         orig_field_name(item->orig_field_name),
3442         m_alias_of_expr(item->m_alias_of_expr),
3443         context(item->context),
3444         db_name(item->db_name),
3445         table_name(item->table_name),
3446         field_name(item->field_name),
3447         cached_field_index(item->cached_field_index),
3448         cached_table(item->cached_table),
3449         depended_from(item->depended_from) {}
3450 
3451   bool itemize(Parse_context *pc, Item **res) override;
3452 
3453   const char *full_name() const override;
3454   void fix_after_pullout(SELECT_LEX *parent_select,
3455                          SELECT_LEX *removed_select) override;
3456   void cleanup() override;
3457   bool aggregate_check_distinct(uchar *arg) override;
3458   bool aggregate_check_group(uchar *arg) override;
3459   Bool3 local_column(const SELECT_LEX *sl) const override;
3460 
print(const THD * thd,String * str,enum_query_type query_type)3461   void print(const THD *thd, String *str,
3462              enum_query_type query_type) const override {
3463     print(thd, str, query_type, db_name, table_name);
3464   }
3465 
3466   /**
3467      Assign the argument to table_name. Argument passed as uchar* to
3468      match requirement of Item::walk.
3469 
3470      @param tn new table_name (should be pointer to const char)
3471      @return true - to signal that walk should continue to sub items.
3472    */
set_table_name(uchar * tn)3473   bool set_table_name(uchar *tn) override final {
3474     table_name = pointer_cast<const char *>(tn);
3475     return true;
3476   }
3477 
3478   ///< Used for permanent transformations so we can re-bind. Remove after
3479   ///< WL#6570.
set_orig_names()3480   void set_orig_names() {
3481     orig_field_name = field_name;
3482     orig_table_name = table_name;
3483   }
3484 
3485  protected:
3486   /**
3487     Function to print column name for a table
3488 
3489     To print a column for a permanent table (picks up database and table from
3490     Item_ident object):
3491 
3492        item->print(str, qt)
3493 
3494     To print a column for a temporary table:
3495 
3496        item->print(str, qt, specific_db, specific_table)
3497 
3498     Items of temporary table fields have empty/NULL values of table_name and
3499     db_name. To print column names in a 3D form (`database`.`table`.`column`),
3500     this function prints db_name_arg and table_name_arg parameters instead of
3501     this->db_name and this->table_name respectively.
3502 
3503     @param       thd            Thread handle.
3504     @param [out] str            Output string buffer.
3505     @param       query_type     Bitmap to control printing details.
3506     @param       db_name_arg    String to output as a column database name.
3507     @param       table_name_arg String to output as a column table name.
3508   */
3509   void print(const THD *thd, String *str, enum_query_type query_type,
3510              const char *db_name_arg, const char *table_name_arg) const;
3511 
3512  public:
3513   ///< Argument object to change_context_processor
3514   struct Change_context {
3515     Name_resolution_context *m_context;
3516     bool m_permanent{false};  // Can be removed with WL#6570
3517     Change_context(Name_resolution_context *context, bool permanent = false)
m_contextChange_context3518         : m_context(context), m_permanent(permanent) {}
3519   };
change_context_processor(uchar * arg)3520   bool change_context_processor(uchar *arg) override {
3521     context = reinterpret_cast<Change_context *>(arg)->m_context;
3522     return false;
3523   }
3524 
3525   /// @returns true if this Item's name is alias of SELECT expression
is_alias_of_expr()3526   bool is_alias_of_expr() const { return m_alias_of_expr; }
3527   /// Marks that this Item's name is alias of SELECT expression
set_alias_of_expr()3528   void set_alias_of_expr() { m_alias_of_expr = true; }
3529 
walk(Item_processor processor,enum_walk walk,uchar * arg)3530   bool walk(Item_processor processor, enum_walk walk, uchar *arg) override {
3531     /*
3532       Item_ident processors like aggregate_check*() use
3533       enum_walk::PREFIX|enum_walk::POSTFIX and depend on the processor being
3534       called twice then.
3535     */
3536     return ((walk & enum_walk::PREFIX) && (this->*processor)(arg)) ||
3537            ((walk & enum_walk::POSTFIX) && (this->*processor)(arg));
3538   }
3539 
3540   /**
3541     Argument structure for walk processor Item::update_depended_from
3542   */
3543   struct Depended_change {
3544     SELECT_LEX *old_depended_from;  // the transformed query block
3545     SELECT_LEX *new_depended_from;  // the new derived table for grouping
3546   };
3547 
3548   bool update_depended_from(uchar *) override;
3549 
3550   /**
3551      @returns true if a part of this Item's full name (name or table name) is
3552      an alias.
3553   */
alias_name_used()3554   virtual bool alias_name_used() const { return m_alias_of_expr; }
3555   friend bool insert_fields(THD *thd, Name_resolution_context *context,
3556                             const char *db_name, const char *table_name,
3557                             List_iterator<Item> *it, bool any_privileges);
3558   bool is_strong_side_column_not_in_fd(uchar *arg) override;
3559   bool is_column_not_in_fd(uchar *arg) override;
3560 };
3561 
3562 class Item_ident_for_show final : public Item {
3563  public:
3564   Field *field;
3565   const char *db_name;
3566   const char *table_name;
3567 
Item_ident_for_show(Field * par_field,const char * db_arg,const char * table_name_arg)3568   Item_ident_for_show(Field *par_field, const char *db_arg,
3569                       const char *table_name_arg)
3570       : field(par_field), db_name(db_arg), table_name(table_name_arg) {}
3571 
type()3572   enum Type type() const override { return FIELD_ITEM; }
3573   virtual bool fix_fields(THD *thd, Item **ref) override;
val_real()3574   double val_real() override { return field->val_real(); }
val_int()3575   longlong val_int() override { return field->val_int(); }
val_str(String * str)3576   String *val_str(String *str) override { return field->val_str(str); }
val_decimal(my_decimal * dec)3577   my_decimal *val_decimal(my_decimal *dec) override {
3578     return field->val_decimal(dec);
3579   }
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)3580   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
3581     return field->get_date(ltime, fuzzydate);
3582   }
get_time(MYSQL_TIME * ltime)3583   bool get_time(MYSQL_TIME *ltime) override { return field->get_time(ltime); }
3584   void make_field(Send_field *tmp_field) override;
charset_for_protocol()3585   const CHARSET_INFO *charset_for_protocol() const override {
3586     return field->charset_for_protocol();
3587   }
3588 };
3589 
3590 class COND_EQUAL;
3591 class Item_equal;
3592 
3593 class Item_field : public Item_ident {
3594   typedef Item_ident super;
3595 
3596  protected:
3597   void set_field(Field *field);
3598   type_conversion_status save_in_field_inner(Field *field,
3599                                              bool no_conversions) override;
3600 
3601  public:
3602   /**
3603     Table containing this resolved field. This is required e.g for calculation
3604     of table map. Notice that for the following types of "tables",
3605     no TABLE_LIST object is assigned and hence table_ref is NULL:
3606      - Temporary tables assigned by join optimizer for sorting and aggregation.
3607      - Stored procedure dummy tables.
3608     For fields referencing such tables, table number is always 0, and other
3609     uses of table_ref is not needed.
3610   */
3611   TABLE_LIST *table_ref;
3612   /// Source field
3613   Field *field;
3614 
3615  private:
3616   /**
3617     Item's original field. Used to compare fields in Item_field::eq() in order
3618     to get proper result when field is transformed by tmp table.
3619   */
3620   const Field *orig_field;
3621   /// Result field
3622   Field *result_field{nullptr};
3623 
3624  public:
set_item_equal_all_join_nests(Item_equal * item_equal)3625   void set_item_equal_all_join_nests(Item_equal *item_equal) {
3626     if (item_equal != nullptr) {
3627       item_equal_all_join_nests = item_equal;
3628     }
3629   }
3630 
3631   Item_equal *item_equal;
3632 
3633   // A list of fields that are considered "equal" to this field. E.g., a query
3634   // on the form "a JOIN b ON a.i = b.i JOIN c ON b.i = c.i" would consider
3635   // a.i, b.i and c.i equal due to equality propagation. This is the same as
3636   // "item_equal" above, except that "item_equal" will only contain fields from
3637   // the same join nest. This is used by hash join and BKA when they need to
3638   // undo multi-equality propagation done by the optimizer. (The optimizer may
3639   // generate join conditions that references unreachable fields for said
3640   // iterators.) The split is done because NDB expects the list to only
3641   // contain fields from the same join nest.
3642   Item_equal *item_equal_all_join_nests{nullptr};
3643   /// If true, the optimizer's constant propagation will not replace this item
3644   /// with an equal constant.
3645   bool no_constant_propagation{false};
3646   /*
3647     if any_privileges set to true then here real effective privileges will
3648     be stored
3649   */
3650   uint have_privileges;
3651   /* field need any privileges (for VIEW creation) */
3652   bool any_privileges;
3653   /*
3654     if this field is used in a context where covering prefix keys
3655     are supported.
3656   */
3657   bool can_use_prefix_key{false};
3658 
3659   Item_field(Name_resolution_context *context_arg, const char *db_arg,
3660              const char *table_name_arg, const char *field_name_arg);
3661   Item_field(const POS &pos, const char *db_arg, const char *table_name_arg,
3662              const char *field_name_arg);
3663 
3664   /*
3665     Constructor needed to process subquery with temporary tables (see Item).
3666     Notice that it will have no name resolution context.
3667   */
3668   Item_field(THD *thd, Item_field *item);
3669   /*
3670     Ensures that field, table, and database names will live as long as
3671     Item_field (this is important in prepared statements).
3672   */
3673   Item_field(THD *thd, Name_resolution_context *context_arg, Field *field);
3674   /*
3675     If this constructor is used, fix_fields() won't work, because
3676     db_name, table_name and column_name are unknown.
3677   */
3678   Item_field(Field *field);
3679 
3680   bool itemize(Parse_context *pc, Item **res) override;
3681 
type()3682   enum Type type() const override { return FIELD_ITEM; }
3683   bool eq(const Item *item, bool binary_cmp) const override;
3684   double val_real() override;
3685   longlong val_int() override;
3686   longlong val_time_temporal() override;
3687   longlong val_date_temporal() override;
3688   my_decimal *val_decimal(my_decimal *) override;
3689   String *val_str(String *) override;
3690   bool val_json(Json_wrapper *result) override;
3691   bool send(Protocol *protocol, String *str_arg) override;
3692   void reset_field(Field *f);
3693   bool fix_fields(THD *, Item **) override;
3694   void make_field(Send_field *tmp_field) override;
3695   void save_org_in_field(Field *field) override;
3696   table_map used_tables() const override;
result_type()3697   enum Item_result result_type() const override { return field->result_type(); }
numeric_context_result_type()3698   enum Item_result numeric_context_result_type() const override {
3699     return field->numeric_context_result_type();
3700   }
cast_to_int_type()3701   Item_result cast_to_int_type() const override {
3702     return field->cast_to_int_type();
3703   }
get_monotonicity_info()3704   enum_monotonicity_info get_monotonicity_info() const override {
3705     return MONOTONIC_STRICT_INCREASING;
3706   }
3707   longlong val_int_endpoint(bool left_endp, bool *incl_endp) override;
set_result_field(Field * field_arg)3708   void set_result_field(Field *field_arg) override { result_field = field_arg; }
get_tmp_table_field()3709   Field *get_tmp_table_field() override { return result_field; }
tmp_table_field(TABLE *)3710   Field *tmp_table_field(TABLE *) override { return result_field; }
3711   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
3712   bool get_time(MYSQL_TIME *ltime) override;
3713   bool get_timeval(struct timeval *tm, int *warnings) override;
is_null()3714   bool is_null() override {
3715     // NOTE: May return true even if maybe_null is not set!
3716     // This can happen if the underlying TABLE did not have a NULL row
3717     // at set_field() time (ie., table->is_null_row() was false),
3718     // but does now.
3719     return field->is_null();
3720   }
3721   Item *get_tmp_table_item(THD *thd) override;
3722   bool collect_item_field_processor(uchar *arg) override;
3723   bool collect_item_field_or_view_ref_processor(uchar *arg) override;
3724   bool add_field_to_set_processor(uchar *arg) override;
3725   bool add_field_to_cond_set_processor(uchar *) override;
3726   bool remove_column_from_bitmap(uchar *arg) override;
3727   bool find_item_in_field_list_processor(uchar *arg) override;
find_field_processor(uchar * arg)3728   bool find_field_processor(uchar *arg) override {
3729     return pointer_cast<Field *>(arg) == field;
3730   }
3731   bool check_function_as_value_generator(uchar *args) override;
mark_field_in_map(uchar * arg)3732   bool mark_field_in_map(uchar *arg) override {
3733     auto mark_field = pointer_cast<Mark_field *>(arg);
3734     bool rc = Item::mark_field_in_map(mark_field, field);
3735     if (result_field && result_field != field)
3736       rc |= Item::mark_field_in_map(mark_field, result_field);
3737     return rc;
3738   }
3739   bool used_tables_for_level(uchar *arg) override;
3740   bool check_column_privileges(uchar *arg) override;
check_partition_func_processor(uchar *)3741   bool check_partition_func_processor(uchar *) override { return false; }
3742   void cleanup() override;
3743   Item_equal *find_item_equal(COND_EQUAL *cond_equal) const;
3744   bool subst_argument_checker(uchar **arg) override;
3745   Item *equal_fields_propagator(uchar *arg) override;
3746   Item *replace_item_field(uchar *) override;
3747   /// Argument to update_context
3748   struct Context_info {
3749     SELECT_LEX *old_block;
3750     SELECT_LEX *new_block;
3751   };
3752   bool update_context(uchar *) override;
disable_constant_propagation(uchar *)3753   bool disable_constant_propagation(uchar *) override {
3754     no_constant_propagation = true;
3755     return false;
3756   }
3757   Item *replace_equal_field(uchar *) override;
max_disp_length()3758   inline uint32 max_disp_length() { return field->max_display_length(); }
field_for_view_update()3759   Item_field *field_for_view_update() override { return this; }
3760   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
3761   int fix_outer_field(THD *thd, Field **field, Item **reference);
3762   Item *update_value_transformer(uchar *select_arg) override;
3763   void print(const THD *thd, String *str,
3764              enum_query_type query_type) const override;
is_outer_field()3765   bool is_outer_field() const override {
3766     DBUG_ASSERT(fixed);
3767     return table_ref->outer_join || table_ref->outer_join_nest();
3768   }
get_geometry_type()3769   Field::geometry_type get_geometry_type() const override {
3770     DBUG_ASSERT(data_type() == MYSQL_TYPE_GEOMETRY);
3771     return field->get_geometry_type();
3772   }
charset_for_protocol(void)3773   const CHARSET_INFO *charset_for_protocol(void) const override {
3774     return field->charset_for_protocol();
3775   }
3776 
3777 #ifndef DBUG_OFF
dbug_print()3778   void dbug_print() const {
3779     fprintf(DBUG_FILE, "<field ");
3780     if (field) {
3781       fprintf(DBUG_FILE, "'%s.%s': ", field->table->alias, field->field_name);
3782       field->dbug_print();
3783     } else
3784       fprintf(DBUG_FILE, "NULL");
3785 
3786     fprintf(DBUG_FILE, ", result_field: ");
3787     if (result_field) {
3788       fprintf(DBUG_FILE, "'%s.%s': ", result_field->table->alias,
3789               result_field->field_name);
3790       result_field->dbug_print();
3791     } else
3792       fprintf(DBUG_FILE, "NULL");
3793     fprintf(DBUG_FILE, ">\n");
3794   }
3795 #endif
3796 
3797   float get_filtering_effect(THD *thd, table_map filter_for_table,
3798                              table_map read_tables,
3799                              const MY_BITMAP *fields_to_ignore,
3800                              double rows_in_table) override;
3801 
3802   /**
3803     Returns the probability for the predicate "col OP <val>" to be
3804     true for a row in the case where no index statistics or range
3805     estimates are available for 'col'.
3806 
3807     The probability depends on the number of rows in the table: it is by
3808     default 'default_filter', but never lower than 1/max_distinct_values
3809     (e.g. number of rows in the table, or the number of distinct values
3810     possible for the datatype if the field provides that kind of
3811     information).
3812 
3813     @param max_distinct_values The maximum number of distinct values,
3814                                typically the number of rows in the table
3815     @param default_filter      The default filter for the predicate
3816 
3817     @return the estimated filtering effect for this predicate
3818   */
3819 
3820   float get_cond_filter_default_probability(double max_distinct_values,
3821                                             float default_filter) const;
3822 
3823   /**
3824      @note that field->table->alias_name_used is reliable only if
3825      thd->lex->need_correct_ident() is true.
3826   */
alias_name_used()3827   bool alias_name_used() const override {
3828     return m_alias_of_expr ||
3829            // maybe the qualifying table was given an alias ("t1 AS foo"):
3830            (field && field->table && field->table->alias_name_used);
3831   }
3832 
3833   bool repoint_const_outer_ref(uchar *arg) override;
get_orig_field()3834   const Field *get_orig_field() override { return orig_field; }
set_orig_field(const Field * orig_field_arg)3835   void set_orig_field(const Field *orig_field_arg) override {
3836     if (orig_field_arg) orig_field = orig_field_arg;
3837   }
returns_array()3838   bool returns_array() const override { return field && field->is_array(); }
3839 
set_can_use_prefix_key()3840   void set_can_use_prefix_key() override { can_use_prefix_key = true; }
3841 
3842   bool replace_field_processor(uchar *arg) override;
3843   bool strip_db_table_name_processor(uchar *) override;
3844 
3845   /**
3846     Checks if the current object represents an asterisk select list item
3847 
3848     @returns false if a regular column reference, true if an asterisk
3849              select list item.
3850   */
is_asterisk()3851   virtual bool is_asterisk() const { return false; }
3852 };
3853 
3854 /**
3855   Represents [schema.][table.]* in a select list
3856 
3857   Item_asterisk is used to insert placeholder objects for the special
3858   select list item * (asterisk) into AST.
3859   Those placeholder objects are to be substituted later with e.g. a list of real
3860   table columns by a resolver (@see setup_wild).
3861 
3862   @todo The parent class Item_field is redundant. Refactor setup_wild() to
3863         replace Item_field with a simpler one.
3864 */
3865 class Item_asterisk : public Item_field {
3866   typedef Item_field super;
3867 
3868  public:
3869   /**
3870     Constructor
3871 
3872     @param pos                  Location of the * (asterisk) lexeme.
3873     @param opt_schema_name      Schema name or nullptr.
3874     @param opt_table_name       Table name or nullptr.
3875   */
Item_asterisk(const POS & pos,const char * opt_schema_name,const char * opt_table_name)3876   Item_asterisk(const POS &pos, const char *opt_schema_name,
3877                 const char *opt_table_name)
3878       : super(pos, opt_schema_name, opt_table_name, "*") {}
3879 
3880   bool itemize(Parse_context *pc, Item **res) override;
fix_fields(THD *,Item **)3881   bool fix_fields(THD *, Item **) override {
3882     DBUG_ASSERT(false);  // should never happen: see setup_wild()
3883     return true;
3884   }
is_asterisk()3885   bool is_asterisk() const override { return true; }
3886 };
3887 
3888 // See if the provided item points to a reachable field (one that belongs to a
3889 // table within 'reachable_tables'). If not, go through the list of 'equal'
3890 // items in the item and see if we have a field that is reachable. If any such
3891 // field is found, create a new Item_field that points to this reachable field
3892 // and return it. If the provided item is already reachable, or if we cannot
3893 // find a reachable field, return the provided item unchanged. This is used when
3894 // creating a hash join iterator, where the join condition may point to a
3895 // non-reachable field due to multi-equality propagation during optimization.
3896 // (Ideally, the optimizer should not set up such condition in the first place.
3897 // This is difficult, if not impossible, to accomplish, given that the plan
3898 // created by the optimizer does not map 100% to the iterator executor.) Note
3899 // that if the field is not reachable, and we cannot find a reachable field, we
3900 // provided field is returned unchanged. The effect is that the hash join will
3901 // degrade into a nested loop.
3902 Item_field *FindEqualField(Item_field *item_field, table_map reachable_tables);
3903 
3904 class Item_null : public Item_basic_constant {
3905   typedef Item_basic_constant super;
3906 
init()3907   void init() {
3908     maybe_null = true;
3909     null_value = true;
3910     set_data_type(MYSQL_TYPE_NULL);
3911     max_length = 0;
3912     fixed = true;
3913     collation.set(&my_charset_bin, DERIVATION_IGNORABLE);
3914   }
3915 
3916  protected:
3917   type_conversion_status save_in_field_inner(Field *field,
3918                                              bool no_conversions) override;
3919 
3920  public:
Item_null()3921   Item_null() {
3922     init();
3923     item_name = NAME_STRING("NULL");
3924   }
Item_null(const POS & pos)3925   explicit Item_null(const POS &pos) : super(pos) {
3926     init();
3927     item_name = NAME_STRING("NULL");
3928   }
3929 
Item_null(const Name_string & name_par)3930   Item_null(const Name_string &name_par) {
3931     init();
3932     item_name = name_par;
3933   }
3934 
type()3935   enum Type type() const override { return NULL_ITEM; }
3936   bool eq(const Item *item, bool binary_cmp) const override;
3937   double val_real() override;
3938   longlong val_int() override;
val_time_temporal()3939   longlong val_time_temporal() override { return val_int(); }
val_date_temporal()3940   longlong val_date_temporal() override { return val_int(); }
3941   String *val_str(String *str) override;
3942   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME *,my_time_flags_t)3943   bool get_date(MYSQL_TIME *, my_time_flags_t) override { return true; }
get_time(MYSQL_TIME *)3944   bool get_time(MYSQL_TIME *) override { return true; }
3945   bool val_json(Json_wrapper *wr) override;
3946   bool send(Protocol *protocol, String *str) override;
result_type()3947   enum Item_result result_type() const override { return STRING_RESULT; }
clone_item()3948   Item *clone_item() const override { return new Item_null(item_name); }
is_null()3949   bool is_null() override { return true; }
3950 
print(const THD *,String * str,enum_query_type query_type)3951   void print(const THD *, String *str,
3952              enum_query_type query_type) const override {
3953     str->append(query_type == QT_NORMALIZED_FORMAT ? "?" : "NULL");
3954   }
3955 
3956   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
check_partition_func_processor(uchar *)3957   bool check_partition_func_processor(uchar *) override { return false; }
3958 };
3959 
3960 /// Placeholder ('?') of prepared statement.
3961 class Item_param final : public Item, private Settable_routine_parameter {
3962   typedef Item super;
3963 
3964  protected:
3965   type_conversion_status save_in_field_inner(Field *field,
3966                                              bool no_conversions) override;
3967 
3968  public:
3969   enum enum_item_param_state {
3970     NO_VALUE,
3971     NULL_VALUE,
3972     INT_VALUE,
3973     REAL_VALUE,
3974     STRING_VALUE,
3975     TIME_VALUE,
3976     LONG_DATA_VALUE,
3977     DECIMAL_VALUE
3978   } state;
3979 
3980   /*
3981     A buffer for string and long data values. Historically all allocated
3982     values returned from val_str() were treated as eligible to
3983     modification. I. e. in some cases Item_func_concat can append it's
3984     second argument to return value of the first one. Because of that we
3985     can't return the original buffer holding string data from val_str(),
3986     and have to have one buffer for data and another just pointing to
3987     the data. This is the latter one and it's returned from val_str().
3988     Can not be declared inside the union as it's not a POD type.
3989   */
3990   String str_value_ptr;
3991   my_decimal decimal_value;
3992   union {
3993     longlong integer;
3994     double real;
3995     /*
3996       Character sets conversion info for string values.
3997       Character sets of client and connection defined at bind time are used
3998       for all conversions, even if one of them is later changed (i.e.
3999       between subsequent calls to mysql_stmt_execute).
4000     */
4001     struct CONVERSION_INFO {
4002       const CHARSET_INFO *character_set_client;
4003       const CHARSET_INFO *character_set_of_placeholder;
4004       /*
4005         This points at character set of connection if conversion
4006         to it is required (i. e. if placeholder typecode is not BLOB).
4007         Otherwise it's equal to character_set_client (to simplify
4008         check in convert_str_value()).
4009       */
4010       const CHARSET_INFO *final_character_set_of_str_value;
4011     } cs_info;
4012     MYSQL_TIME time;
4013   } value;
4014 
4015   /* Cached values for virtual methods to save us one switch.  */
4016   enum Item_result item_result_type;
4017   enum Type item_type;
4018 
4019   /*
4020     data_type() is used when this item is used in a temporary table.
4021     This is NOT placeholder metadata sent to client, as this value
4022     is assigned after sending metadata (in setup_one_conversion_function).
4023     For example in case of 'SELECT ?' you'll get MYSQL_TYPE_STRING both
4024     in result set and placeholders metadata, no matter what type you will
4025     supply for this placeholder in mysql_stmt_execute.
4026   */
4027 
4028   /*
4029     Offset of placeholder inside statement text. Used to create
4030     no-placeholders version of this statement for the binary log.
4031   */
4032   uint pos_in_query;
4033 
4034   Item_param(const POS &pos, MEM_ROOT *root, uint pos_in_query_arg);
4035 
4036   bool itemize(Parse_context *pc, Item **item) override;
4037 
result_type()4038   enum Item_result result_type() const override { return item_result_type; }
type()4039   enum Type type() const override { return item_type; }
4040 
4041   double val_real() override;
4042   longlong val_int() override;
4043   my_decimal *val_decimal(my_decimal *) override;
4044   String *val_str(String *) override;
4045   bool get_time(MYSQL_TIME *tm) override;
4046   bool get_date(MYSQL_TIME *tm, my_time_flags_t fuzzydate) override;
4047 
4048   void set_null();
4049   void set_int(longlong i, uint32 max_length_arg);
4050   void set_double(double i);
4051   void set_decimal(const char *str, ulong length);
4052   void set_decimal(const my_decimal *dv);
4053   bool set_str(const char *str, size_t length);
4054   bool set_longdata(const char *str, ulong length);
4055   void set_time(MYSQL_TIME *tm, enum_mysql_timestamp_type type,
4056                 uint32 max_length_arg);
4057   bool set_from_user_var(THD *thd, const user_var_entry *entry);
4058   void reset();
4059   /*
4060     Assign placeholder value from bind data.
4061   */
4062   void (*set_param_func)(Item_param *param, uchar **pos, ulong len);
4063 
4064   const String *query_val_str(const THD *thd, String *str) const;
4065 
4066   bool convert_str_value();
4067 
4068   /*
4069     Parameter is treated as constant during execution, thus it will not be
4070     evaluated during preparation.
4071   */
used_tables()4072   table_map used_tables() const override {
4073     return state != NO_VALUE ? 0 : INNER_TABLE_BIT;
4074   }
4075   void print(const THD *thd, String *str,
4076              enum_query_type query_type) const override;
is_null()4077   bool is_null() override {
4078     DBUG_ASSERT(state != NO_VALUE);
4079     return state == NULL_VALUE;
4080   }
basic_const_item()4081   bool basic_const_item() const override {
4082     if (state == NO_VALUE || state == TIME_VALUE) return false;
4083     return true;
4084   }
4085 
4086   /*
4087     This method is used to make a copy of a basic constant item when
4088     propagating constants in the optimizer. The reason to create a new
4089     item and not use the existing one is not precisely known (2005/04/16).
4090     Probably we are trying to preserve tree structure of items, in other
4091     words, avoid pointing at one item from two different nodes of the tree.
4092     Return a new basic constant item if parameter value is a basic
4093     constant, assert otherwise. This method is called only if
4094     basic_const_item returned true.
4095   */
4096   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4097   Item *clone_item() const override;
4098   /*
4099     Implement by-value equality evaluation if parameter value
4100     is set and is a basic constant (integer, real or string).
4101     Otherwise return false.
4102   */
4103   bool eq(const Item *item, bool binary_cmp) const override;
4104   /** Item is a argument to a limit clause. */
4105   bool limit_clause_param;
4106   void set_param_type_and_swap_value(Item_param *from);
is_non_const_over_literals(uchar *)4107   bool is_non_const_over_literals(uchar *) override { return true; }
4108   /**
4109     This should be called after any modification done to this Item, to
4110     propagate the said modification to all its clones.
4111   */
4112   void sync_clones();
add_clone(Item_param * i)4113   bool add_clone(Item_param *i) { return m_clones.push_back(i); }
4114 
4115  private:
get_settable_routine_parameter()4116   Settable_routine_parameter *get_settable_routine_parameter() override {
4117     return this;
4118   }
4119 
4120   bool set_value(THD *, sp_rcontext *, Item **it) override;
4121 
4122   void set_out_param_info(Send_field *info) override;
4123 
4124  public:
4125   const Send_field *get_out_param_info() const override;
4126 
4127   void make_field(Send_field *field) override;
4128 
check_function_as_value_generator(uchar * args)4129   bool check_function_as_value_generator(uchar *args) override {
4130     Check_function_as_value_generator_parameters *func_arg =
4131         pointer_cast<Check_function_as_value_generator_parameters *>(args);
4132     func_arg->err_code = func_arg->get_unnamed_function_error_code();
4133     return true;
4134   }
4135 
4136  private:
4137   Send_field *m_out_param_info;
4138   /**
4139     If a query expression's text QT, containing a parameter, is internally
4140     duplicated and parsed twice (@see reparse_common_table_expression), the
4141     first parsing will create an Item_param I, and the re-parsing, which
4142     parses a forged "(QT)" parse-this-CTE type of statement, will create an
4143     Item_param J. J should not exist:
4144     - from the point of view of logging: it is not in the original query so it
4145     should not be substituted in the query written to logs (in insert_params()
4146     if with_log is true).
4147     - from the POV of the user:
4148         * user provides one single value for I, not one for I and one for J.
4149         * user expects mysql_stmt_param_count() to return 1, not 2 (count is
4150         sent by the server in send_prep_stmt()).
4151     That is why J is part neither of LEX::param_list, nor of param_array; it
4152     is considered an inferior clone of I; I::m_clones contains J.
4153     The connection between I and J is made once, by comparing their
4154     byte position in the statement, in Item_param::itemize().
4155     J gets its value from I: @see Item_param::sync_clones.
4156   */
4157   Mem_root_array<Item_param *> m_clones;
4158 };
4159 
4160 class Item_int : public Item_num {
4161   typedef Item_num super;
4162 
4163  public:
4164   longlong value;
4165   Item_int(int32 i, uint length = MY_INT32_NUM_DECIMAL_DIGITS)
4166       : value((longlong)i) {
4167     set_data_type(MYSQL_TYPE_LONGLONG);
4168     max_length = length;
4169     fixed = true;
4170   }
4171   Item_int(const POS &pos, int32 i, uint length = MY_INT32_NUM_DECIMAL_DIGITS)
super(pos)4172       : super(pos), value((longlong)i) {
4173     set_data_type(MYSQL_TYPE_LONGLONG);
4174     max_length = length;
4175     fixed = true;
4176   }
value(i)4177   Item_int(longlong i, uint length = MY_INT64_NUM_DECIMAL_DIGITS) : value(i) {
4178     set_data_type(MYSQL_TYPE_LONGLONG);
4179     max_length = length;
4180     fixed = true;
4181   }
4182   Item_int(ulonglong i, uint length = MY_INT64_NUM_DECIMAL_DIGITS)
4183       : value((longlong)i) {
4184     set_data_type(MYSQL_TYPE_LONGLONG);
4185     max_length = length;
4186     fixed = true;
4187     unsigned_flag = true;
4188   }
Item_int(const Item_int * item_arg)4189   Item_int(const Item_int *item_arg) {
4190     set_data_type(item_arg->data_type());
4191     value = item_arg->value;
4192     item_name = item_arg->item_name;
4193     max_length = item_arg->max_length;
4194     fixed = true;
4195   }
Item_int(const Name_string & name_arg,longlong i,uint length)4196   Item_int(const Name_string &name_arg, longlong i, uint length) : value(i) {
4197     set_data_type(MYSQL_TYPE_LONGLONG);
4198     max_length = length;
4199     item_name = name_arg;
4200     fixed = true;
4201   }
Item_int(const POS & pos,const Name_string & name_arg,longlong i,uint length)4202   Item_int(const POS &pos, const Name_string &name_arg, longlong i, uint length)
4203       : super(pos), value(i) {
4204     set_data_type(MYSQL_TYPE_LONGLONG);
4205     max_length = length;
4206     item_name = name_arg;
4207     fixed = true;
4208   }
Item_int(const char * str_arg,uint length)4209   Item_int(const char *str_arg, uint length) {
4210     set_data_type(MYSQL_TYPE_LONGLONG);
4211     init(str_arg, length);
4212   }
Item_int(const POS & pos,const char * str_arg,uint length)4213   Item_int(const POS &pos, const char *str_arg, uint length) : super(pos) {
4214     set_data_type(MYSQL_TYPE_LONGLONG);
4215     init(str_arg, length);
4216   }
4217 
4218   Item_int(const POS &pos, const LEX_STRING &num, int dummy_error = 0)
4219       : Item_int(pos, num, my_strtoll10(num.str, nullptr, &dummy_error),
4220                  static_cast<uint>(num.length)) {}
4221 
4222  private:
4223   void init(const char *str_arg, uint length);
4224 
4225  protected:
4226   type_conversion_status save_in_field_inner(Field *field,
4227                                              bool no_conversions) override;
4228 
4229  public:
type()4230   enum Type type() const override { return INT_ITEM; }
result_type()4231   enum Item_result result_type() const override { return INT_RESULT; }
val_int()4232   longlong val_int() override {
4233     DBUG_ASSERT(fixed);
4234     return value;
4235   }
val_real()4236   double val_real() override {
4237     DBUG_ASSERT(fixed);
4238     return static_cast<double>(value);
4239   }
4240   my_decimal *val_decimal(my_decimal *) override;
4241   String *val_str(String *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)4242   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4243     return get_date_from_int(ltime, fuzzydate);
4244   }
get_time(MYSQL_TIME * ltime)4245   bool get_time(MYSQL_TIME *ltime) override { return get_time_from_int(ltime); }
clone_item()4246   Item *clone_item() const override { return new Item_int(this); }
4247   void print(const THD *thd, String *str,
4248              enum_query_type query_type) const override;
neg()4249   Item_num *neg() override {
4250     value = -value;
4251     return this;
4252   }
decimal_precision()4253   uint decimal_precision() const override {
4254     return (uint)(max_length - (value < 0));
4255   }
4256   bool eq(const Item *, bool) const override;
check_partition_func_processor(uchar *)4257   bool check_partition_func_processor(uchar *) override { return false; }
check_function_as_value_generator(uchar *)4258   bool check_function_as_value_generator(uchar *) override { return false; }
4259 };
4260 
4261 /**
4262   Item_int with value==0 and length==1
4263 */
4264 class Item_int_0 final : public Item_int {
4265  public:
Item_int_0()4266   Item_int_0() : Item_int(NAME_STRING("0"), 0, 1) {}
Item_int_0(const POS & pos)4267   explicit Item_int_0(const POS &pos) : Item_int(pos, NAME_STRING("0"), 0, 1) {}
4268 };
4269 
4270 /*
4271   Item_temporal is used to store numeric representation
4272   of time/date/datetime values for queries like:
4273 
4274      WHERE datetime_column NOT IN
4275      ('2006-04-25 10:00:00','2006-04-25 10:02:00', ...);
4276 
4277   and for SHOW/INFORMATION_SCHEMA purposes (see sql_show.cc)
4278 
4279   TS-TODO: Can't we use Item_time_literal, Item_date_literal,
4280   TS-TODO: and Item_datetime_literal for this purpose?
4281 */
4282 class Item_temporal final : public Item_int {
4283  protected:
4284   type_conversion_status save_in_field_inner(Field *field,
4285                                              bool no_conversions) override;
4286 
4287  public:
Item_temporal(enum_field_types field_type_arg,longlong i)4288   Item_temporal(enum_field_types field_type_arg, longlong i) : Item_int(i) {
4289     DBUG_ASSERT(is_temporal_type(field_type_arg));
4290     set_data_type(field_type_arg);
4291   }
Item_temporal(enum_field_types field_type_arg,const Name_string & name_arg,longlong i,uint length)4292   Item_temporal(enum_field_types field_type_arg, const Name_string &name_arg,
4293                 longlong i, uint length)
4294       : Item_int(i) {
4295     DBUG_ASSERT(is_temporal_type(field_type_arg));
4296     set_data_type(field_type_arg);
4297     max_length = length;
4298     item_name = name_arg;
4299     fixed = true;
4300   }
clone_item()4301   Item *clone_item() const override {
4302     return new Item_temporal(data_type(), value);
4303   }
val_time_temporal()4304   longlong val_time_temporal() override { return val_int(); }
val_date_temporal()4305   longlong val_date_temporal() override { return val_int(); }
get_date(MYSQL_TIME *,my_time_flags_t)4306   bool get_date(MYSQL_TIME *, my_time_flags_t) override {
4307     DBUG_ASSERT(0);
4308     return false;
4309   }
get_time(MYSQL_TIME *)4310   bool get_time(MYSQL_TIME *) override {
4311     DBUG_ASSERT(0);
4312     return false;
4313   }
4314 };
4315 
4316 class Item_uint : public Item_int {
4317  protected:
4318   type_conversion_status save_in_field_inner(Field *field,
4319                                              bool no_conversions) override;
4320 
4321  public:
Item_uint(const char * str_arg,uint length)4322   Item_uint(const char *str_arg, uint length) : Item_int(str_arg, length) {
4323     unsigned_flag = true;
4324   }
Item_uint(const POS & pos,const char * str_arg,uint length)4325   Item_uint(const POS &pos, const char *str_arg, uint length)
4326       : Item_int(pos, str_arg, length) {
4327     unsigned_flag = true;
4328   }
4329 
Item_uint(ulonglong i)4330   Item_uint(ulonglong i) : Item_int(i, 10) {}
Item_uint(const Name_string & name_arg,longlong i,uint length)4331   Item_uint(const Name_string &name_arg, longlong i, uint length)
4332       : Item_int(name_arg, i, length) {
4333     unsigned_flag = true;
4334   }
val_real()4335   double val_real() override {
4336     DBUG_ASSERT(fixed);
4337     return ulonglong2double(static_cast<ulonglong>(value));
4338   }
4339   String *val_str(String *) override;
4340 
clone_item()4341   Item *clone_item() const override {
4342     return new Item_uint(item_name, value, max_length);
4343   }
4344   void print(const THD *thd, String *str,
4345              enum_query_type query_type) const override;
4346   Item_num *neg() override;
decimal_precision()4347   uint decimal_precision() const override { return max_length; }
4348 };
4349 
4350 /* decimal (fixed point) constant */
4351 class Item_decimal : public Item_num {
4352   typedef Item_num super;
4353 
4354  protected:
4355   my_decimal decimal_value;
4356   type_conversion_status save_in_field_inner(Field *field,
4357                                              bool no_conversions) override;
4358 
4359  public:
4360   Item_decimal(const POS &pos, const char *str_arg, uint length,
4361                const CHARSET_INFO *charset);
4362   Item_decimal(const Name_string &name_arg, const my_decimal *val_arg,
4363                uint decimal_par, uint length);
4364   Item_decimal(my_decimal *value_par);
4365   Item_decimal(longlong val, bool unsig);
4366   Item_decimal(double val);
4367   Item_decimal(const uchar *bin, int precision, int scale);
4368 
type()4369   enum Type type() const override { return DECIMAL_ITEM; }
result_type()4370   enum Item_result result_type() const override { return DECIMAL_RESULT; }
4371   longlong val_int() override;
4372   double val_real() override;
4373   String *val_str(String *) override;
val_decimal(my_decimal *)4374   my_decimal *val_decimal(my_decimal *) override { return &decimal_value; }
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)4375   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4376     return get_date_from_decimal(ltime, fuzzydate);
4377   }
get_time(MYSQL_TIME * ltime)4378   bool get_time(MYSQL_TIME *ltime) override {
4379     return get_time_from_decimal(ltime);
4380   }
clone_item()4381   Item *clone_item() const override {
4382     return new Item_decimal(item_name, &decimal_value, decimals, max_length);
4383   }
4384   void print(const THD *thd, String *str,
4385              enum_query_type query_type) const override;
neg()4386   Item_num *neg() override {
4387     my_decimal_neg(&decimal_value);
4388     unsigned_flag = !decimal_value.sign();
4389     return this;
4390   }
decimal_precision()4391   uint decimal_precision() const override { return decimal_value.precision(); }
4392   bool eq(const Item *, bool binary_cmp) const override;
4393   void set_decimal_value(const my_decimal *value_par);
check_partition_func_processor(uchar *)4394   bool check_partition_func_processor(uchar *) override { return false; }
4395 };
4396 
4397 class Item_float : public Item_num {
4398   typedef Item_num super;
4399 
4400   Name_string presentation;
4401 
4402  public:
4403   double value;
4404   // Item_real() :value(0) {}
Item_float(const char * str_arg,uint length)4405   Item_float(const char *str_arg, uint length) { init(str_arg, length); }
Item_float(const POS & pos,const char * str_arg,uint length)4406   Item_float(const POS &pos, const char *str_arg, uint length) : super(pos) {
4407     init(str_arg, length);
4408   }
4409 
Item_float(const Name_string name_arg,double val_arg,uint decimal_par,uint length)4410   Item_float(const Name_string name_arg, double val_arg, uint decimal_par,
4411              uint length)
4412       : value(val_arg) {
4413     presentation = name_arg;
4414     item_name = name_arg;
4415     set_data_type(MYSQL_TYPE_DOUBLE);
4416     decimals = (uint8)decimal_par;
4417     max_length = length;
4418     fixed = true;
4419   }
Item_float(const POS & pos,const Name_string name_arg,double val_arg,uint decimal_par,uint length)4420   Item_float(const POS &pos, const Name_string name_arg, double val_arg,
4421              uint decimal_par, uint length)
4422       : super(pos), value(val_arg) {
4423     presentation = name_arg;
4424     item_name = name_arg;
4425     set_data_type(MYSQL_TYPE_DOUBLE);
4426     decimals = (uint8)decimal_par;
4427     max_length = length;
4428     fixed = true;
4429   }
4430 
Item_float(double value_par,uint decimal_par)4431   Item_float(double value_par, uint decimal_par) : value(value_par) {
4432     set_data_type(MYSQL_TYPE_DOUBLE);
4433     decimals = (uint8)decimal_par;
4434     max_length = float_length(decimal_par);
4435     fixed = true;
4436   }
4437 
4438  private:
4439   void init(const char *str_arg, uint length);
4440 
4441  protected:
4442   type_conversion_status save_in_field_inner(Field *field,
4443                                              bool no_conversions) override;
4444 
4445  public:
type()4446   enum Type type() const override { return REAL_ITEM; }
val_real()4447   double val_real() override {
4448     DBUG_ASSERT(fixed);
4449     return value;
4450   }
val_int()4451   longlong val_int() override {
4452     DBUG_ASSERT(fixed == 1);
4453     if (value <= (double)LLONG_MIN) {
4454       return LLONG_MIN;
4455     } else if (value > LLONG_MAX_DOUBLE) {
4456       return LLONG_MAX;
4457     }
4458     return (longlong)rint(value);
4459   }
4460   String *val_str(String *) override;
4461   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)4462   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4463     return get_date_from_real(ltime, fuzzydate);
4464   }
get_time(MYSQL_TIME * ltime)4465   bool get_time(MYSQL_TIME *ltime) override {
4466     return get_time_from_real(ltime);
4467   }
clone_item()4468   Item *clone_item() const override {
4469     return new Item_float(item_name, value, decimals, max_length);
4470   }
neg()4471   Item_num *neg() override {
4472     value = -value;
4473     return this;
4474   }
4475   void print(const THD *thd, String *str,
4476              enum_query_type query_type) const override;
4477   bool eq(const Item *, bool binary_cmp) const override;
4478 };
4479 
4480 class Item_func_pi : public Item_float {
4481   const Name_string func_name;
4482 
4483  public:
Item_func_pi(const POS & pos)4484   Item_func_pi(const POS &pos)
4485       : Item_float(pos, null_name_string, M_PI, 6, 8),
4486         func_name(NAME_STRING("pi()")) {}
4487 
print(const THD *,String * str,enum_query_type)4488   void print(const THD *, String *str, enum_query_type) const override {
4489     str->append(func_name);
4490   }
4491 
4492   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4493 };
4494 
4495 class Item_string : public Item_basic_constant {
4496   typedef Item_basic_constant super;
4497 
4498  protected:
Item_string(const POS & pos)4499   explicit Item_string(const POS &pos) : super(pos), m_cs_specified(false) {
4500     set_data_type(MYSQL_TYPE_VARCHAR);
4501   }
4502 
init(const char * str,size_t length,const CHARSET_INFO * cs,Derivation dv,uint repertoire)4503   void init(const char *str, size_t length, const CHARSET_INFO *cs,
4504             Derivation dv, uint repertoire) {
4505     set_data_type(MYSQL_TYPE_VARCHAR);
4506     str_value.set_or_copy_aligned(str, length, cs);
4507     collation.set(cs, dv, repertoire);
4508     /*
4509       We have to have a different max_length than 'length' here to
4510       ensure that we get the right length if we do use the item
4511       to create a new table. In this case max_length must be the maximum
4512       number of chars for a string of this type because we in Create_field::
4513       divide the max_length with mbmaxlen).
4514     */
4515     max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4516     item_name.copy(str, length, cs);
4517     decimals = DECIMAL_NOT_SPECIFIED;
4518     // it is constant => can be used without fix_fields (and frequently used)
4519     fixed = true;
4520     /*
4521       Check if the string has any character that can't be
4522       interpreted using the relevant charset.
4523     */
4524     check_well_formed_result(&str_value, false, false);
4525   }
4526   type_conversion_status save_in_field_inner(Field *field,
4527                                              bool no_conversions) override;
4528 
4529  public:
4530   /* Create from a string, set name from the string itself. */
4531   Item_string(const char *str, size_t length, const CHARSET_INFO *cs,
4532               Derivation dv = DERIVATION_COERCIBLE,
4533               uint repertoire = MY_REPERTOIRE_UNICODE30)
m_cs_specified(false)4534       : m_cs_specified(false) {
4535     init(str, length, cs, dv, repertoire);
4536   }
4537   Item_string(const POS &pos, const char *str, size_t length,
4538               const CHARSET_INFO *cs, Derivation dv = DERIVATION_COERCIBLE,
4539               uint repertoire = MY_REPERTOIRE_UNICODE30)
super(pos)4540       : super(pos), m_cs_specified(false) {
4541     init(str, length, cs, dv, repertoire);
4542   }
4543 
4544   /* Just create an item and do not fill string representation */
4545   Item_string(const CHARSET_INFO *cs, Derivation dv = DERIVATION_COERCIBLE)
m_cs_specified(false)4546       : m_cs_specified(false) {
4547     collation.set(cs, dv);
4548     set_data_type(MYSQL_TYPE_VARCHAR);
4549     max_length = 0;
4550     decimals = DECIMAL_NOT_SPECIFIED;
4551     fixed = true;
4552   }
4553 
4554   /* Create from the given name and string. */
4555   Item_string(const Name_string name_par, const char *str, size_t length,
4556               const CHARSET_INFO *cs, Derivation dv = DERIVATION_COERCIBLE,
4557               uint repertoire = MY_REPERTOIRE_UNICODE30)
m_cs_specified(false)4558       : m_cs_specified(false) {
4559     str_value.set_or_copy_aligned(str, length, cs);
4560     collation.set(cs, dv, repertoire);
4561     set_data_type(MYSQL_TYPE_VARCHAR);
4562     max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4563     item_name = name_par;
4564     decimals = DECIMAL_NOT_SPECIFIED;
4565     // it is constant => can be used without fix_fields (and frequently used)
4566     fixed = true;
4567   }
4568   Item_string(const POS &pos, const Name_string name_par, const char *str,
4569               size_t length, const CHARSET_INFO *cs,
4570               Derivation dv = DERIVATION_COERCIBLE,
4571               uint repertoire = MY_REPERTOIRE_UNICODE30)
super(pos)4572       : super(pos), m_cs_specified(false) {
4573     str_value.set_or_copy_aligned(str, length, cs);
4574     collation.set(cs, dv, repertoire);
4575     set_data_type(MYSQL_TYPE_VARCHAR);
4576     max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4577     item_name = name_par;
4578     decimals = DECIMAL_NOT_SPECIFIED;
4579     // it is constant => can be used without fix_fields (and frequently used)
4580     fixed = true;
4581   }
4582 
4583   /* Create from the given name and string. */
4584   Item_string(const POS &pos, const Name_string name_par,
4585               const LEX_CSTRING &literal, const CHARSET_INFO *cs,
4586               Derivation dv = DERIVATION_COERCIBLE,
4587               uint repertoire = MY_REPERTOIRE_UNICODE30)
super(pos)4588       : super(pos), m_cs_specified(false) {
4589     str_value.set_or_copy_aligned(literal.str ? literal.str : "",
4590                                   literal.str ? literal.length : 0, cs);
4591     collation.set(cs, dv, repertoire);
4592     set_data_type(MYSQL_TYPE_VARCHAR);
4593     max_length = static_cast<uint32>(str_value.numchars() * cs->mbmaxlen);
4594     item_name = name_par;
4595     decimals = DECIMAL_NOT_SPECIFIED;
4596     // it is constant => can be used without fix_fields (and frequently used)
4597     fixed = true;
4598   }
4599 
4600   /*
4601     This is used in stored procedures to avoid memory leaks and
4602     does a deep copy of its argument.
4603   */
set_str_with_copy(const char * str_arg,uint length_arg)4604   void set_str_with_copy(const char *str_arg, uint length_arg) {
4605     str_value.copy(str_arg, length_arg, collation.collation);
4606     max_length = static_cast<uint32>(str_value.numchars() *
4607                                      collation.collation->mbmaxlen);
4608   }
set_repertoire_from_value()4609   void set_repertoire_from_value() {
4610     collation.repertoire = my_string_repertoire(
4611         str_value.charset(), str_value.ptr(), str_value.length());
4612   }
type()4613   enum Type type() const override { return STRING_ITEM; }
4614   double val_real() override;
4615   longlong val_int() override;
val_str(String *)4616   String *val_str(String *) override {
4617     DBUG_ASSERT(fixed == 1);
4618     return &str_value;
4619   }
4620   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)4621   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4622     return get_date_from_string(ltime, fuzzydate);
4623   }
get_time(MYSQL_TIME * ltime)4624   bool get_time(MYSQL_TIME *ltime) override {
4625     return get_time_from_string(ltime);
4626   }
result_type()4627   enum Item_result result_type() const override { return STRING_RESULT; }
4628   bool eq(const Item *item, bool binary_cmp) const override;
clone_item()4629   Item *clone_item() const override {
4630     return new Item_string(static_cast<Name_string>(item_name), str_value.ptr(),
4631                            str_value.length(), collation.collation);
4632   }
4633   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4634   Item *charset_converter(THD *thd, const CHARSET_INFO *tocs, bool lossless);
append(char * str,size_t length)4635   inline void append(char *str, size_t length) {
4636     str_value.append(str, length);
4637     max_length = static_cast<uint32>(str_value.numchars() *
4638                                      collation.collation->mbmaxlen);
4639   }
4640   void print(const THD *thd, String *str,
4641              enum_query_type query_type) const override;
check_partition_func_processor(uchar *)4642   bool check_partition_func_processor(uchar *) override { return false; }
4643 
4644   /**
4645     Return true if character-set-introducer was explicitly specified in the
4646     original query for this item (text literal).
4647 
4648     This operation is to be called from Item_string::print(). The idea is
4649     that when a query is generated (re-constructed) from the Item-tree,
4650     character-set-introducers should appear only for those literals, where
4651     they were explicitly specified by the user. Otherwise, that may lead to
4652     loss collation information (character set introducers implies default
4653     collation for the literal).
4654 
4655     Basically, that makes sense only for views and hopefully will be gone
4656     one day when we start using original query as a view definition.
4657 
4658     @return This operation returns the value of m_cs_specified attribute.
4659       @retval true if character set introducer was explicitly specified in
4660       the original query.
4661       @retval false otherwise.
4662   */
is_cs_specified()4663   inline bool is_cs_specified() const { return m_cs_specified; }
4664 
4665   /**
4666     Set the value of m_cs_specified attribute.
4667 
4668     m_cs_specified attribute shows whether character-set-introducer was
4669     explicitly specified in the original query for this text literal or
4670     not. The attribute makes sense (is used) only for views.
4671 
4672     This operation is to be called from the parser during parsing an input
4673     query.
4674   */
set_cs_specified(bool cs_specified)4675   inline void set_cs_specified(bool cs_specified) {
4676     m_cs_specified = cs_specified;
4677   }
4678 
mark_result_as_const()4679   void mark_result_as_const() { str_value.mark_as_const(); }
4680 
4681  private:
4682   bool m_cs_specified;
4683 };
4684 
4685 longlong longlong_from_string_with_check(const CHARSET_INFO *cs,
4686                                          const char *cptr, const char *end);
4687 double double_from_string_with_check(const CHARSET_INFO *cs, const char *cptr,
4688                                      const char *end);
4689 
4690 class Item_static_string_func : public Item_string {
4691   const Name_string func_name;
4692 
4693  public:
4694   Item_static_string_func(const Name_string &name_par, const char *str,
4695                           size_t length, const CHARSET_INFO *cs,
4696                           Derivation dv = DERIVATION_COERCIBLE)
Item_string(null_name_string,str,length,cs,dv)4697       : Item_string(null_name_string, str, length, cs, dv),
4698         func_name(name_par) {}
4699   Item_static_string_func(const POS &pos, const Name_string &name_par,
4700                           const char *str, size_t length,
4701                           const CHARSET_INFO *cs,
4702                           Derivation dv = DERIVATION_COERCIBLE)
Item_string(pos,null_name_string,str,length,cs,dv)4703       : Item_string(pos, null_name_string, str, length, cs, dv),
4704         func_name(name_par) {}
4705 
4706   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
4707 
print(const THD *,String * str,enum_query_type)4708   void print(const THD *, String *str, enum_query_type) const override {
4709     str->append(func_name);
4710   }
4711 
check_partition_func_processor(uchar *)4712   bool check_partition_func_processor(uchar *) override { return true; }
check_function_as_value_generator(uchar * args)4713   bool check_function_as_value_generator(uchar *args) override {
4714     Check_function_as_value_generator_parameters *func_arg =
4715         pointer_cast<Check_function_as_value_generator_parameters *>(args);
4716     func_arg->banned_function_name = func_name.ptr();
4717     return true;
4718   }
4719 };
4720 
4721 /* for show tables */
4722 class Item_partition_func_safe_string : public Item_string {
4723  public:
4724   Item_partition_func_safe_string(const Name_string name, size_t length,
4725                                   const CHARSET_INFO *cs = nullptr)
4726       : Item_string(name, NullS, 0, cs) {
4727     max_length = static_cast<uint32>(length);
4728   }
4729 };
4730 
4731 class Item_blob final : public Item_partition_func_safe_string {
4732  public:
Item_blob(const char * name,size_t length)4733   Item_blob(const char *name, size_t length)
4734       : Item_partition_func_safe_string(Name_string(name, strlen(name)), length,
4735                                         &my_charset_bin) {
4736     set_data_type(MYSQL_TYPE_BLOB);
4737   }
type()4738   enum Type type() const override { return TYPE_HOLDER; }
check_function_as_value_generator(uchar * args)4739   bool check_function_as_value_generator(uchar *args) override {
4740     Check_function_as_value_generator_parameters *func_arg =
4741         pointer_cast<Check_function_as_value_generator_parameters *>(args);
4742     func_arg->err_code = func_arg->get_unnamed_function_error_code();
4743     return true;
4744   }
4745 };
4746 
4747 /**
4748   Item_empty_string -- is a utility class to put an item into List<Item>
4749   which is then used in protocol.send_result_set_metadata() when sending SHOW
4750   output to the client.
4751 */
4752 
4753 class Item_empty_string : public Item_partition_func_safe_string {
4754  public:
4755   Item_empty_string(const char *header, size_t length,
4756                     const CHARSET_INFO *cs = nullptr)
Name_string(header,strlen (header))4757       : Item_partition_func_safe_string(Name_string(header, strlen(header)), 0,
4758                                         cs ? cs : &my_charset_utf8_general_ci) {
4759     max_length = static_cast<uint32>(length * collation.collation->mbmaxlen);
4760   }
4761   void make_field(Send_field *field) override;
4762 };
4763 
4764 class Item_return_int : public Item_int {
4765  public:
4766   Item_return_int(const char *name_arg, uint length,
4767                   enum_field_types field_type_arg, longlong value_arg = 0)
4768       : Item_int(Name_string(name_arg, name_arg ? strlen(name_arg) : 0),
4769                  value_arg, length) {
4770     set_data_type(field_type_arg);
4771     unsigned_flag = true;
4772   }
4773 };
4774 
4775 class Item_hex_string : public Item_basic_constant {
4776   typedef Item_basic_constant super;
4777 
4778  protected:
4779   type_conversion_status save_in_field_inner(Field *field,
4780                                              bool no_conversions) override;
4781 
4782  public:
4783   Item_hex_string();
Item_hex_string(const POS & pos)4784   explicit Item_hex_string(const POS &pos) : super(pos) {
4785     set_data_type(MYSQL_TYPE_VARCHAR);
4786   }
4787 
4788   Item_hex_string(const char *str, uint str_length);
4789   Item_hex_string(const POS &pos, const LEX_STRING &literal);
4790 
type()4791   enum Type type() const override { return VARBIN_ITEM; }
val_real()4792   double val_real() override {
4793     DBUG_ASSERT(fixed);
4794     return (double)(ulonglong)Item_hex_string::val_int();
4795   }
4796   longlong val_int() override;
clone_item()4797   Item *clone_item() const override {
4798     return new Item_hex_string(str_value.ptr(), max_length);
4799   }
val_str(String *)4800   String *val_str(String *) override {
4801     DBUG_ASSERT(fixed);
4802     return &str_value;
4803   }
4804   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)4805   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
4806     return get_date_from_string(ltime, fuzzydate);
4807   }
get_time(MYSQL_TIME * ltime)4808   bool get_time(MYSQL_TIME *ltime) override {
4809     return get_time_from_string(ltime);
4810   }
result_type()4811   Item_result result_type() const override { return STRING_RESULT; }
numeric_context_result_type()4812   Item_result numeric_context_result_type() const override {
4813     return INT_RESULT;
4814   }
cast_to_int_type()4815   Item_result cast_to_int_type() const override { return INT_RESULT; }
4816   void print(const THD *thd, String *str,
4817              enum_query_type query_type) const override;
4818   bool eq(const Item *item, bool binary_cmp) const override;
4819   Item *safe_charset_converter(THD *thd, const CHARSET_INFO *tocs) override;
check_partition_func_processor(uchar *)4820   bool check_partition_func_processor(uchar *) override { return false; }
4821   static LEX_CSTRING make_hex_str(const char *str, size_t str_length);
4822 
4823  private:
4824   void hex_string_init(const char *str, uint str_length);
4825 };
4826 
4827 class Item_bin_string final : public Item_hex_string {
4828   typedef Item_hex_string super;
4829 
4830  public:
Item_bin_string(const char * str,size_t str_length)4831   Item_bin_string(const char *str, size_t str_length) {
4832     bin_string_init(str, str_length);
4833   }
Item_bin_string(const POS & pos,const LEX_STRING & literal)4834   Item_bin_string(const POS &pos, const LEX_STRING &literal) : super(pos) {
4835     bin_string_init(literal.str, literal.length);
4836   }
4837 
4838   static LEX_CSTRING make_bin_str(const char *str, size_t str_length);
4839 
4840  private:
4841   void bin_string_init(const char *str, size_t str_length);
4842 };
4843 
4844 /**
4845   Item with result field.
4846 
4847   It adds to an Item a "result_field" Field member. This is for an item which
4848   may have a result (e.g. Item_func), and may store this result into a field;
4849   usually this field is a column of an internal temporary table. So the
4850   function may be evaluated by save_in_field(), storing result into
4851   result_field in tmp table. Then this result can be copied from tmp table to
4852   a following tmp table (e.g. GROUP BY table then ORDER BY table), or to a row
4853   buffer and back, as we want to avoid multiple evaluations of the Item, first
4854   because of performance, second because that evaluation may have side
4855   effects, e.g. SLEEP, GET_LOCK, RAND, window functions doing
4856   accumulations...
4857   Item_field and Item_ref also have a "result_field" for a similar goal.
4858   Literals don't need such "result_field" as their value is readily
4859   available.
4860 */
4861 class Item_result_field : public Item {
4862  protected:
4863   Field *result_field{nullptr}; /* Save result here */
4864  public:
4865   Item_result_field() = default;
Item_result_field(const POS & pos)4866   explicit Item_result_field(const POS &pos) : Item(pos) {}
4867 
4868   // Constructor used for Item_sum/Item_cond_and/or (see Item comment)
Item_result_field(THD * thd,const Item_result_field * item)4869   Item_result_field(THD *thd, const Item_result_field *item)
4870       : Item(thd, item), result_field(item->result_field) {}
get_tmp_table_field()4871   Field *get_tmp_table_field() override { return result_field; }
tmp_table_field(TABLE *)4872   Field *tmp_table_field(TABLE *) override { return result_field; }
used_tables()4873   table_map used_tables() const override { return 1; }
4874 
4875   /**
4876     Resolve type-related information for this item, such as result field type,
4877     maximum size, precision, signedness, character set and collation.
4878     Also check compatibility of argument types and return error when applicable.
4879     Also adjust nullability when applicable.
4880 
4881     @param thd    thread handler
4882     @returns      false if success, true if error
4883   */
4884   virtual bool resolve_type(THD *thd) = 0;
4885 
set_result_field(Field * field)4886   void set_result_field(Field *field) override { result_field = field; }
is_result_field()4887   bool is_result_field() const override { return true; }
get_result_field()4888   Field *get_result_field() const override { return result_field; }
4889 
4890   void cleanup() override;
4891   /*
4892     This method is used for debug purposes to print the name of an
4893     item to the debug log. The second use of this method is as
4894     a helper function of print() and error messages, where it is
4895     applicable. To suit both goals it should return a meaningful,
4896     distinguishable and syntactically correct string. This method
4897     should not be used for runtime type identification, use enum
4898     {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
4899     instead.
4900     Added here, to the parent class of both Item_func and Item_sum.
4901   */
4902   virtual const char *func_name() const = 0;
check_function_as_value_generator(uchar *)4903   bool check_function_as_value_generator(uchar *) override { return false; }
mark_field_in_map(uchar * arg)4904   bool mark_field_in_map(uchar *arg) override {
4905     bool rc = Item::mark_field_in_map(arg);
4906     if (result_field)  // most likely result_field will be read too
4907       rc |= Item::mark_field_in_map(pointer_cast<Mark_field *>(arg),
4908                                     result_field);
4909     return rc;
4910   }
4911 
llrint_with_overflow_check(double realval)4912   longlong llrint_with_overflow_check(double realval) {
4913     if (realval < LLONG_MIN || realval > LLONG_MAX_DOUBLE) {
4914       raise_integer_overflow();
4915       return error_int();
4916     }
4917     return llrint(realval);
4918   }
4919 
4920   void raise_numeric_overflow(const char *type_name);
4921 
raise_float_overflow()4922   double raise_float_overflow() {
4923     raise_numeric_overflow("DOUBLE");
4924     return 0.0;
4925   }
4926 
raise_integer_overflow()4927   longlong raise_integer_overflow() {
4928     raise_numeric_overflow(unsigned_flag ? "BIGINT UNSIGNED" : "BIGINT");
4929     return 0;
4930   }
4931 
raise_decimal_overflow()4932   int raise_decimal_overflow() {
4933     raise_numeric_overflow(unsigned_flag ? "DECIMAL UNSIGNED" : "DECIMAL");
4934     return E_DEC_OVERFLOW;
4935   }
4936 };
4937 
4938 class Item_ref : public Item_ident {
4939  protected:
4940   void set_properties();
4941   type_conversion_status save_in_field_inner(Field *field,
4942                                              bool no_conversions) override;
4943 
4944  public:
4945   enum Ref_Type { REF, VIEW_REF, OUTER_REF, AGGREGATE_REF };
4946 
4947  private:
4948   Field *result_field{nullptr}; /* Save result here */
4949  public:
4950   Item **ref;
4951 
4952  private:
4953   /**
4954     'ref' can be set (to non-NULL) in the constructor or afterwards.
4955     The second case means that we are doing resolution, possibly pointing
4956     'ref' to a non-permanent Item. To not have 'ref' become dangling at the
4957     end of execution, and to start clean for the resolution of the next
4958     execution, 'ref' must be restored to NULL. rollback_item_tree_changes()
4959     does not handle restoration of Item** values, so we need this dedicated
4960     Boolean.
4961   */
4962   const bool chop_ref;
4963 
4964  public:
Item_ref(Name_resolution_context * context_arg,const char * db_arg,const char * table_name_arg,const char * field_name_arg)4965   Item_ref(Name_resolution_context *context_arg, const char *db_arg,
4966            const char *table_name_arg, const char *field_name_arg)
4967       : Item_ident(context_arg, db_arg, table_name_arg, field_name_arg),
4968         ref(nullptr),
4969         chop_ref(!ref) {}
Item_ref(const POS & pos,const char * db_arg,const char * table_name_arg,const char * field_name_arg)4970   Item_ref(const POS &pos, const char *db_arg, const char *table_name_arg,
4971            const char *field_name_arg)
4972       : Item_ident(pos, db_arg, table_name_arg, field_name_arg),
4973         ref(nullptr),
4974         chop_ref(!ref) {}
4975 
4976   /*
4977     This constructor is used in two scenarios:
4978     A) *item = NULL
4979       No initialization is performed, fix_fields() call will be necessary.
4980 
4981     B) *item points to an Item this Item_ref will refer to. This is
4982       used for GROUP BY. fix_fields() will not be called in this case,
4983       so we call set_properties to make this item "fixed". set_properties
4984       performs a subset of action Item_ref::fix_fields does, and this subset
4985       is enough for Item_ref's used in GROUP BY.
4986 
4987     TODO we probably fix a superset of problems like in BUG#6658. Check this
4988          with Bar, and if we have a more broader set of problems like this.
4989   */
4990   Item_ref(Name_resolution_context *context_arg, Item **item,
4991            const char *table_name_arg, const char *field_name_arg,
4992            bool alias_of_expr_arg = false);
4993 
4994   /* Constructor need to process subselect with temporary tables (see Item) */
Item_ref(THD * thd,Item_ref * item)4995   Item_ref(THD *thd, Item_ref *item)
4996       : Item_ident(thd, item),
4997         result_field(item->result_field),
4998         ref(item->ref),
4999         chop_ref(!ref) {}
type()5000   enum Type type() const override { return REF_ITEM; }
eq(const Item * item,bool binary_cmp)5001   bool eq(const Item *item, bool binary_cmp) const override {
5002     const Item *it = const_cast<Item *>(item)->real_item();
5003     return ref && (*ref)->eq(it, binary_cmp);
5004   }
5005   double val_real() override;
5006   longlong val_int() override;
5007   longlong val_time_temporal() override;
5008   longlong val_date_temporal() override;
5009   my_decimal *val_decimal(my_decimal *) override;
5010   bool val_bool() override;
5011   String *val_str(String *tmp) override;
5012   bool val_json(Json_wrapper *result) override;
5013   bool is_null() override;
5014   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
5015   bool send(Protocol *prot, String *tmp) override;
5016   void make_field(Send_field *field) override;
5017   bool fix_fields(THD *, Item **) override;
5018   void fix_after_pullout(SELECT_LEX *parent_select,
5019                          SELECT_LEX *removed_select) override;
5020   void save_org_in_field(Field *field) override;
result_type()5021   Item_result result_type() const override { return (*ref)->result_type(); }
get_tmp_table_field()5022   Field *get_tmp_table_field() override {
5023     return result_field ? result_field : (*ref)->get_tmp_table_field();
5024   }
5025   Item *get_tmp_table_item(THD *thd) override;
used_tables()5026   table_map used_tables() const override {
5027     if (depended_from != nullptr) return OUTER_REF_TABLE_BIT;
5028     const table_map map = (*ref)->used_tables();
5029     if (map != 0) return map;
5030     // rollup constant: ensure it is non-constant by returning RAND_TABLE_BIT
5031     if (has_rollup_expr()) return RAND_TABLE_BIT;
5032     return 0;
5033   }
update_used_tables()5034   void update_used_tables() override {
5035     if (!depended_from) (*ref)->update_used_tables();
5036     /*
5037       Reset all flags except rollup, since we do not mark the rollup expression
5038       itself.
5039     */
5040     m_accum_properties &= PROP_ROLLUP_EXPR;
5041     add_accum_properties(*ref);
5042   }
5043 
not_null_tables()5044   table_map not_null_tables() const override {
5045     /*
5046       It can happen that our 'depended_from' member is set but the
5047       'depended_from' member of the referenced item is not (example: if a
5048       field in a subquery belongs to an outer merged view), so we first test
5049       ours:
5050     */
5051     return depended_from ? OUTER_REF_TABLE_BIT : (*ref)->not_null_tables();
5052   }
set_result_field(Field * field)5053   void set_result_field(Field *field) override { result_field = field; }
is_result_field()5054   bool is_result_field() const override { return true; }
get_result_field()5055   Field *get_result_field() const override { return result_field; }
real_item()5056   Item *real_item() override { return ref ? (*ref)->real_item() : this; }
walk(Item_processor processor,enum_walk walk,uchar * arg)5057   bool walk(Item_processor processor, enum_walk walk, uchar *arg) override {
5058     return ((walk & enum_walk::PREFIX) && (this->*processor)(arg)) ||
5059            // For having clauses 'ref' will consistently =NULL.
5060            (ref != nullptr ? (*ref)->walk(processor, walk, arg) : false) ||
5061            ((walk & enum_walk::POSTFIX) && (this->*processor)(arg));
5062   }
5063   Item *transform(Item_transformer, uchar *arg) override;
5064   Item *compile(Item_analyzer analyzer, uchar **arg_p,
5065                 Item_transformer transformer, uchar *arg_t) override;
explain_subquery_checker(uchar **)5066   bool explain_subquery_checker(uchar **) override {
5067     /*
5068       Always return false: we don't need to go deeper into referenced
5069       expression tree since we have to mark aliased subqueries at
5070       their original places (select list, derived tables), not by
5071       references from other expression (order by etc).
5072     */
5073     return false;
5074   }
5075   void print(const THD *thd, String *str,
5076              enum_query_type query_type) const override;
5077   void cleanup() override;
field_for_view_update()5078   Item_field *field_for_view_update() override {
5079     return (*ref)->field_for_view_update();
5080   }
ref_type()5081   virtual Ref_Type ref_type() const { return REF; }
5082 
5083   // Row emulation: forwarding of ROW-related calls to ref
cols()5084   uint cols() const override {
5085     return ref && result_type() == ROW_RESULT ? (*ref)->cols() : 1;
5086   }
element_index(uint i)5087   Item *element_index(uint i) override {
5088     return ref && result_type() == ROW_RESULT ? (*ref)->element_index(i) : this;
5089   }
addr(uint i)5090   Item **addr(uint i) override {
5091     return ref && result_type() == ROW_RESULT ? (*ref)->addr(i) : nullptr;
5092   }
check_cols(uint c)5093   bool check_cols(uint c) override {
5094     return ref && result_type() == ROW_RESULT ? (*ref)->check_cols(c)
5095                                               : Item::check_cols(c);
5096   }
null_inside()5097   bool null_inside() override {
5098     return ref && result_type() == ROW_RESULT ? (*ref)->null_inside() : false;
5099   }
bring_value()5100   void bring_value() override {
5101     if (ref && result_type() == ROW_RESULT) (*ref)->bring_value();
5102   }
get_time(MYSQL_TIME * ltime)5103   bool get_time(MYSQL_TIME *ltime) override {
5104     DBUG_ASSERT(fixed);
5105     return (*ref)->get_time(ltime);
5106   }
5107 
5108   /**
5109     @todo Consider re-implementing this for Item_view_ref, as it
5110           may return NULL even if it wraps a constant value, if one the
5111           inner side of an outer join.
5112   */
basic_const_item()5113   bool basic_const_item() const override {
5114     return ref && (*ref)->basic_const_item();
5115   }
is_outer_field()5116   bool is_outer_field() const override {
5117     DBUG_ASSERT(fixed);
5118     DBUG_ASSERT(ref);
5119     return (*ref)->is_outer_field();
5120   }
5121 
created_by_in2exists()5122   bool created_by_in2exists() const override {
5123     return (*ref)->created_by_in2exists();
5124   }
5125 
5126   bool repoint_const_outer_ref(uchar *arg) override;
5127   bool references_select_expr_of(uchar *arg) override;
is_non_const_over_literals(uchar *)5128   bool is_non_const_over_literals(uchar *) override { return true; }
check_function_as_value_generator(uchar * args)5129   bool check_function_as_value_generator(uchar *args) override {
5130     Check_function_as_value_generator_parameters *func_arg =
5131         pointer_cast<Check_function_as_value_generator_parameters *>(args);
5132     func_arg->err_code = func_arg->get_unnamed_function_error_code();
5133     return true;
5134   }
cast_to_int_type()5135   Item_result cast_to_int_type() const override {
5136     return (*ref)->cast_to_int_type();
5137   }
5138 };
5139 
5140 /**
5141   Class for fields from derived tables and views.
5142   The same as Item_ref, but call fix_fields() of reference if
5143   not called yet.
5144 */
5145 class Item_view_ref final : public Item_ref {
5146   typedef Item_ref super;
5147 
5148  public:
Item_view_ref(Name_resolution_context * context_arg,Item ** item,const char * alias_name_arg,const char * table_name_arg,const char * field_name_arg,TABLE_LIST * tl)5149   Item_view_ref(Name_resolution_context *context_arg, Item **item,
5150                 const char *alias_name_arg, const char *table_name_arg,
5151                 const char *field_name_arg, TABLE_LIST *tl)
5152       : Item_ref(context_arg, item, alias_name_arg, field_name_arg),
5153         first_inner_table(nullptr) {
5154     orig_table_name = table_name_arg;
5155     cached_table = tl;
5156     if (cached_table->is_inner_table_of_outer_join()) {
5157       maybe_null = true;
5158       first_inner_table = cached_table->any_outer_leaf_table();
5159       // @todo delete this when WL#6570 is implemented
5160       (*ref)->maybe_null = true;
5161     }
5162   }
5163 
5164   /*
5165     We share one underlying Item_field, so we have to disable
5166     build_equal_items_for_cond().
5167     TODO: Implement multiple equality optimization for views.
5168   */
subst_argument_checker(uchar **)5169   bool subst_argument_checker(uchar **) override { return false; }
5170 
5171   bool fix_fields(THD *, Item **) override;
5172 
5173   /**
5174     Takes into account whether an Item in a derived table / view is part of an
5175     inner table of an outer join.
5176 
5177     1) If the field is an outer reference, return OUTER_TABLE_REF_BIT.
5178     2) Else
5179        2a) If the field is const_for_execution and the field is used in the
5180            inner part of an outer join, return the inner tables of the outer
5181            join. (A 'const' field that depends on the inner table of an outer
5182            join shouldn't be interpreted as const.)
5183        2b) Else return the used_tables info of the underlying field.
5184 
5185     @note The call to const_for_execution has been replaced by
5186           "!(inner_map & ~INNER_TABLE_BIT)" to avoid multiple and recursive
5187           calls to used_tables. This can create a problem when Views are
5188           created using other views
5189 */
used_tables()5190   table_map used_tables() const override {
5191     if (depended_from != nullptr) return OUTER_REF_TABLE_BIT;
5192 
5193     table_map inner_map = (*ref)->used_tables();
5194     return !(inner_map & ~INNER_TABLE_BIT) && first_inner_table != nullptr
5195                ? (*ref)->real_item()->type() == FIELD_ITEM
5196                      ? down_cast<Item_field *>((*ref)->real_item())
5197                            ->table_ref->map()
5198                      : first_inner_table->map()
5199                : inner_map;
5200   }
5201 
5202   bool eq(const Item *item, bool) const override;
get_tmp_table_item(THD * thd)5203   Item *get_tmp_table_item(THD *thd) override {
5204     DBUG_TRACE;
5205     Item *item = Item_ref::get_tmp_table_item(thd);
5206     item->item_name = item_name;
5207     return item;
5208   }
ref_type()5209   Ref_Type ref_type() const override { return VIEW_REF; }
5210 
5211   bool check_column_privileges(uchar *arg) override;
mark_field_in_map(uchar * arg)5212   bool mark_field_in_map(uchar *arg) override {
5213     /*
5214       If this referenced column is marked as used, flag underlying
5215       selected item from a derived table/view as used.
5216     */
5217     auto mark_field = (Mark_field *)arg;
5218     if (mark_field->mark != MARK_COLUMNS_NONE)
5219       // Set the same flag for all the objects that *ref depends on.
5220       (*ref)->walk(&Item::propagate_set_derived_used,
5221                    enum_walk::SUBQUERY_POSTFIX, nullptr);
5222     return get_result_field()
5223                ? Item::mark_field_in_map(mark_field, get_result_field())
5224                : false;
5225   }
5226   longlong val_int() override;
5227   double val_real() override;
5228   my_decimal *val_decimal(my_decimal *dec) override;
5229   String *val_str(String *str) override;
5230   bool val_bool() override;
5231   bool val_json(Json_wrapper *wr) override;
5232   bool is_null() override;
5233   bool send(Protocol *prot, String *tmp) override;
5234   bool change_context_processor(uchar *arg) override;
5235   bool collect_item_field_or_view_ref_processor(uchar *arg) override;
5236   Item *replace_item_view_ref(uchar *arg) override;
5237 
5238  protected:
5239   type_conversion_status save_in_field_inner(Field *field,
5240                                              bool no_conversions) override;
5241 
5242  private:
5243   /// @return true if item is from a null-extended row from an outer join
has_null_row()5244   bool has_null_row() const {
5245     return first_inner_table && first_inner_table->table->has_null_row();
5246   }
5247 
5248   /**
5249     If this column belongs to a view that is an inner table of an outer join,
5250     then this field points to the first leaf table of the view, otherwise NULL.
5251   */
5252   TABLE_LIST *first_inner_table;
5253 };
5254 
5255 /*
5256   Class for outer fields.
5257   An object of this class is created when the select where the outer field was
5258   resolved is a grouping one. After it has been fixed the ref field will point
5259   to an Item_ref object which will be used to access the field.
5260   The ref field may also point to an Item_field instance.
5261   See also comments of the Item_field::fix_outer_field() function.
5262 */
5263 
5264 class Item_outer_ref final : public Item_ref {
5265   typedef Item_ref super;
5266 
5267  private:
5268   /**
5269      Qualifying query of this outer ref (i.e. query block which owns FROM of
5270      table which this Item references).
5271   */
5272   SELECT_LEX *qualifying;
5273 
5274  public:
5275   Item *outer_ref;
5276   /* The aggregate function under which this outer ref is used, if any. */
5277   Item_sum *in_sum_func;
5278   /*
5279     true <=> that the outer_ref is already present in the select list
5280     of the outer select.
5281   */
5282   bool found_in_select_list;
Item_outer_ref(Name_resolution_context * context_arg,Item_ident * ident_arg,SELECT_LEX * qualifying)5283   Item_outer_ref(Name_resolution_context *context_arg, Item_ident *ident_arg,
5284                  SELECT_LEX *qualifying)
5285       : Item_ref(context_arg, nullptr, ident_arg->table_name,
5286                  ident_arg->field_name, false),
5287         qualifying(qualifying),
5288         outer_ref(ident_arg),
5289         in_sum_func(nullptr),
5290         found_in_select_list(false) {
5291     ref = &outer_ref;
5292     set_properties();
5293     fixed = false;
5294   }
Item_outer_ref(Name_resolution_context * context_arg,Item ** item,const char * table_name_arg,const char * field_name_arg,bool alias_of_expr_arg,SELECT_LEX * qualifying)5295   Item_outer_ref(Name_resolution_context *context_arg, Item **item,
5296                  const char *table_name_arg, const char *field_name_arg,
5297                  bool alias_of_expr_arg, SELECT_LEX *qualifying)
5298       : Item_ref(context_arg, item, table_name_arg, field_name_arg,
5299                  alias_of_expr_arg),
5300         qualifying(qualifying),
5301         outer_ref(nullptr),
5302         in_sum_func(nullptr),
5303         found_in_select_list(true) {}
5304   bool fix_fields(THD *, Item **) override;
5305   void fix_after_pullout(SELECT_LEX *parent_select,
5306                          SELECT_LEX *removed_select) override;
used_tables()5307   table_map used_tables() const override {
5308     return (*ref)->used_tables() == 0 ? 0 : OUTER_REF_TABLE_BIT;
5309   }
not_null_tables()5310   table_map not_null_tables() const override { return 0; }
5311 
ref_type()5312   Ref_Type ref_type() const override { return OUTER_REF; }
5313 };
5314 
5315 class Item_in_subselect;
5316 
5317 /*
5318   An object of this class is like Item_ref, and
5319   sets owner->was_null=true if it has returned a NULL value from any
5320   val_XXX() function. This allows to inject an Item_ref_null_helper
5321   object into subquery and then check if the subquery has produced a row
5322   with NULL value.
5323 */
5324 
5325 class Item_ref_null_helper final : public Item_ref {
5326   typedef Item_ref super;
5327 
5328  protected:
5329   Item_in_subselect *owner;
5330 
5331  public:
Item_ref_null_helper(Name_resolution_context * context_arg,Item_in_subselect * master,Item ** item,const char * table_name_arg,const char * field_name_arg)5332   Item_ref_null_helper(Name_resolution_context *context_arg,
5333                        Item_in_subselect *master, Item **item,
5334                        const char *table_name_arg, const char *field_name_arg)
5335       : super(context_arg, item, table_name_arg, field_name_arg),
5336         owner(master) {}
5337   double val_real() override;
5338   longlong val_int() override;
5339   longlong val_time_temporal() override;
5340   longlong val_date_temporal() override;
5341   String *val_str(String *s) override;
5342   my_decimal *val_decimal(my_decimal *) override;
5343   bool val_bool() override;
5344   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
5345   void print(const THD *thd, String *str,
5346              enum_query_type query_type) const override;
5347   /*
5348     we add RAND_TABLE_BIT to prevent moving this item from HAVING to WHERE
5349   */
used_tables()5350   table_map used_tables() const override {
5351     return (depended_from ? OUTER_REF_TABLE_BIT
5352                           : (*ref)->used_tables() | RAND_TABLE_BIT);
5353   }
5354 };
5355 
5356 /*
5357   The following class is used to optimize comparing of bigint columns.
5358   We need to save the original item ('ref') to be able to call
5359   ref->save_in_field(). This is used to create index search keys.
5360 
5361   An instance of Item_int_with_ref may have signed or unsigned integer value.
5362 
5363 */
5364 
5365 class Item_int_with_ref : public Item_int {
5366  protected:
5367   Item *ref;
save_in_field_inner(Field * field,bool no_conversions)5368   type_conversion_status save_in_field_inner(Field *field,
5369                                              bool no_conversions) override {
5370     return ref->save_in_field(field, no_conversions);
5371   }
5372 
5373  public:
Item_int_with_ref(enum_field_types field_type,longlong i,Item * ref_arg,bool unsigned_arg)5374   Item_int_with_ref(enum_field_types field_type, longlong i, Item *ref_arg,
5375                     bool unsigned_arg)
5376       : Item_int(i), ref(ref_arg) {
5377     set_data_type(field_type);
5378     unsigned_flag = unsigned_arg;
5379   }
5380   Item *clone_item() const override;
real_item()5381   Item *real_item() override { return ref; }
5382 };
5383 
5384 /*
5385   Similar to Item_int_with_ref, but to optimize comparing of temporal columns.
5386 */
5387 class Item_temporal_with_ref : public Item_int_with_ref {
5388  public:
Item_temporal_with_ref(enum_field_types field_type_arg,uint8 decimals_arg,longlong i,Item * ref_arg,bool unsigned_arg)5389   Item_temporal_with_ref(enum_field_types field_type_arg, uint8 decimals_arg,
5390                          longlong i, Item *ref_arg, bool unsigned_arg)
5391       : Item_int_with_ref(field_type_arg, i, ref_arg, unsigned_arg) {
5392     decimals = decimals_arg;
5393   }
5394   void print(const THD *thd, String *str,
5395              enum_query_type query_type) const override;
get_date(MYSQL_TIME *,my_time_flags_t)5396   bool get_date(MYSQL_TIME *, my_time_flags_t) override {
5397     DBUG_ASSERT(0);
5398     return true;
5399   }
get_time(MYSQL_TIME *)5400   bool get_time(MYSQL_TIME *) override {
5401     DBUG_ASSERT(0);
5402     return true;
5403   }
5404 };
5405 
5406 /*
5407   Item_datetime_with_ref is used to optimize queries like:
5408     SELECT ... FROM t1 WHERE date_or_datetime_column = 20110101101010;
5409   The numeric constant is replaced to Item_datetime_with_ref
5410   by convert_constant_item().
5411 */
5412 class Item_datetime_with_ref final : public Item_temporal_with_ref {
5413  public:
5414   /**
5415     Constructor for Item_datetime_with_ref.
5416     @param    field_type_arg Data type: MYSQL_TYPE_DATE or MYSQL_TYPE_DATETIME
5417     @param    decimals_arg   Number of fractional digits.
5418     @param    i              Temporal value in packed format.
5419     @param    ref_arg        Pointer to the original numeric Item.
5420   */
Item_datetime_with_ref(enum_field_types field_type_arg,uint8 decimals_arg,longlong i,Item * ref_arg)5421   Item_datetime_with_ref(enum_field_types field_type_arg, uint8 decimals_arg,
5422                          longlong i, Item *ref_arg)
5423       : Item_temporal_with_ref(field_type_arg, decimals_arg, i, ref_arg, true) {
5424   }
5425   Item *clone_item() const override;
val_date_temporal()5426   longlong val_date_temporal() override { return val_int(); }
val_time_temporal()5427   longlong val_time_temporal() override {
5428     DBUG_ASSERT(0);
5429     return val_int();
5430   }
5431 };
5432 
5433 /*
5434   Item_time_with_ref is used to optimize queries like:
5435     SELECT ... FROM t1 WHERE time_column = 20110101101010;
5436   The numeric constant is replaced to Item_time_with_ref
5437   by convert_constant_item().
5438 */
5439 class Item_time_with_ref final : public Item_temporal_with_ref {
5440  public:
5441   /**
5442     Constructor for Item_time_with_ref.
5443     @param    decimals_arg   Number of fractional digits.
5444     @param    i              Temporal value in packed format.
5445     @param    ref_arg        Pointer to the original numeric Item.
5446   */
Item_time_with_ref(uint8 decimals_arg,longlong i,Item * ref_arg)5447   Item_time_with_ref(uint8 decimals_arg, longlong i, Item *ref_arg)
5448       : Item_temporal_with_ref(MYSQL_TYPE_TIME, decimals_arg, i, ref_arg,
5449                                false) {}
5450   Item *clone_item() const override;
val_time_temporal()5451   longlong val_time_temporal() override { return val_int(); }
val_date_temporal()5452   longlong val_date_temporal() override {
5453     DBUG_ASSERT(0);
5454     return val_int();
5455   }
5456 };
5457 
5458 /**
5459   Base class to implement typed value caching Item classes
5460 
5461   Item_copy_ classes are very similar to the corresponding Item_
5462   classes (e.g. Item_copy_int is similar to Item_int) but they add
5463   the following additional functionality to Item_ :
5464     1. Nullability
5465     2. Possibility to store the value not only on instantiation time,
5466        but also later.
5467   Item_copy_ classes are a functionality subset of Item_cache_
5468   classes, as e.g. they don't support comparisons with the original Item
5469   as Item_cache_ classes do.
5470   Item_copy_ classes are used in GROUP BY calculation.
5471   TODO: Item_copy should be made an abstract interface and Item_copy_
5472   classes should inherit both the respective Item_ class and the interface.
5473   Ideally we should drop Item_copy_ classes altogether and merge
5474   their functionality to Item_cache_ (and these should be made to inherit
5475   from Item_).
5476 */
5477 
5478 class Item_copy : public Item {
5479  protected:
5480   /** The original item that is copied */
5481   Item *item;
5482 
5483   /**
5484     Stores the result type of the original item, so it can be returned
5485     without calling the original item's method
5486   */
5487   Item_result cached_result_type;
5488 
5489   /**
5490     Constructor of the Item_copy class
5491 
5492     stores metadata information about the original class as well as a
5493     pointer to it.
5494   */
Item_copy(Item * i)5495   Item_copy(Item *i) {
5496     item = i;
5497     null_value = maybe_null = item->maybe_null;
5498     decimals = item->decimals;
5499     max_length = item->max_length;
5500     item_name = item->item_name;
5501     set_data_type(item->data_type());
5502     cached_result_type = item->result_type();
5503     unsigned_flag = item->unsigned_flag;
5504     fixed = item->fixed;
5505     collation.set(item->collation);
5506   }
5507 
5508   virtual type_conversion_status save_in_field_inner(
5509       Field *field, bool no_conversions) override = 0;
5510 
5511  public:
5512   /**
5513     Factory method to create the appropriate subclass dependent on the type of
5514     the original item.
5515 
5516     @param item      the original item.
5517   */
5518   static Item_copy *create(Item *item);
5519 
5520   /**
5521     Update the cache with the value of the original item
5522 
5523     This is the method that updates the cached value.
5524     It must be explicitly called by the user of this class to store the value
5525     of the orginal item in the cache.
5526     @returns false if OK, true on error.
5527   */
5528   virtual bool copy(const THD *thd) = 0;
5529 
get_item()5530   virtual Item *get_item() { return item; }
5531   /** All of the subclasses should have the same type tag */
type()5532   enum Type type() const override { return COPY_STR_ITEM; }
result_type()5533   enum Item_result result_type() const override { return cached_result_type; }
5534 
make_field(Send_field * field)5535   void make_field(Send_field *field) override { item->make_field(field); }
5536 
5537   /*
5538     The likely reason for used_tables() to return 1 is that Item_copy
5539     represents a field in a temporary table used for group expressions,
5540     and such tables are represented with table map = 1.
5541   */
used_tables()5542   table_map used_tables() const override { return 1; }
5543 
is_null()5544   bool is_null() override { return null_value; }
5545 
no_rows_in_result()5546   void no_rows_in_result() override { item->no_rows_in_result(); }
5547 
5548   /*
5549     Override the methods below as pure virtual to make sure all the
5550     sub-classes implement them.
5551   */
5552 
5553   virtual String *val_str(String *) override = 0;
5554   virtual my_decimal *val_decimal(my_decimal *) override = 0;
5555   virtual double val_real() override = 0;
5556   virtual longlong val_int() override = 0;
5557   virtual bool get_date(MYSQL_TIME *ltime,
5558                         my_time_flags_t fuzzydate) override = 0;
5559   virtual bool get_time(MYSQL_TIME *ltime) override = 0;
5560   /* purecov: begin deadcode */
val_json(Json_wrapper *)5561   bool val_json(Json_wrapper *) override {
5562     DBUG_ASSERT(false);
5563     my_error(ER_NOT_SUPPORTED_YET, MYF(0), "item type for JSON");
5564     return error_json();
5565   }
5566   /* purecov: end */
check_function_as_value_generator(uchar * args)5567   bool check_function_as_value_generator(uchar *args) override {
5568     Check_function_as_value_generator_parameters *func_arg =
5569         pointer_cast<Check_function_as_value_generator_parameters *>(args);
5570     func_arg->banned_function_name = "values";
5571     return true;
5572   }
5573 };
5574 
5575 /**
5576  Implementation of a string cache.
5577 
5578  Uses Item::str_value for storage
5579 */
5580 class Item_copy_string final : public Item_copy {
5581  protected:
5582   type_conversion_status save_in_field_inner(Field *field,
5583                                              bool no_conversions) override;
5584 
5585  public:
Item_copy_string(Item * item_arg)5586   Item_copy_string(Item *item_arg) : Item_copy(item_arg) {}
5587 
5588   String *val_str(String *) override;
5589   my_decimal *val_decimal(my_decimal *) override;
5590   double val_real() override;
5591   longlong val_int() override;
5592   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
5593   bool get_time(MYSQL_TIME *ltime) override;
5594   bool copy(const THD *thd) override;
5595 };
5596 
5597 class Item_copy_json final : public Item_copy {
5598   Json_wrapper *m_value;
5599 
5600  protected:
5601   type_conversion_status save_in_field_inner(Field *field,
5602                                              bool no_conversions) override;
5603 
5604  public:
5605   explicit Item_copy_json(Item *item);
5606   virtual ~Item_copy_json() override;
5607   bool copy(const THD *thd) override;
5608   bool val_json(Json_wrapper *) override;
5609   String *val_str(String *) override;
5610   my_decimal *val_decimal(my_decimal *) override;
5611   double val_real() override;
5612   longlong val_int() override;
5613   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
5614   bool get_time(MYSQL_TIME *ltime) override;
5615 };
5616 
5617 class Item_copy_int : public Item_copy {
5618  protected:
5619   longlong cached_value;
5620   type_conversion_status save_in_field_inner(Field *field,
5621                                              bool no_conversions) override;
5622 
5623  public:
Item_copy_int(Item * i)5624   Item_copy_int(Item *i) : Item_copy(i) {}
5625 
5626   String *val_str(String *) override;
5627   my_decimal *val_decimal(my_decimal *) override;
val_real()5628   double val_real() override { return null_value ? 0.0 : (double)cached_value; }
val_int()5629   longlong val_int() override { return null_value ? 0LL : cached_value; }
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)5630   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
5631     return get_date_from_int(ltime, fuzzydate);
5632   }
get_time(MYSQL_TIME * ltime)5633   bool get_time(MYSQL_TIME *ltime) override { return get_time_from_int(ltime); }
5634   bool copy(const THD *thd) override;
5635 };
5636 
5637 class Item_copy_uint final : public Item_copy_int {
5638  public:
Item_copy_uint(Item * item_arg)5639   Item_copy_uint(Item *item_arg) : Item_copy_int(item_arg) {
5640     unsigned_flag = true;
5641   }
5642 
5643   String *val_str(String *) override;
val_real()5644   double val_real() override {
5645     return null_value ? 0.0 : (double)(ulonglong)cached_value;
5646   }
5647 };
5648 
5649 class Item_copy_float final : public Item_copy {
5650  protected:
5651   double cached_value;
5652   type_conversion_status save_in_field_inner(Field *field,
5653                                              bool no_conversions) override;
5654 
5655  public:
Item_copy_float(Item * i)5656   Item_copy_float(Item *i) : Item_copy(i) {}
5657 
5658   String *val_str(String *) override;
5659   my_decimal *val_decimal(my_decimal *) override;
val_real()5660   double val_real() override { return null_value ? 0.0 : cached_value; }
val_int()5661   longlong val_int() override { return (longlong)rint(val_real()); }
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)5662   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
5663     return get_date_from_real(ltime, fuzzydate);
5664   }
get_time(MYSQL_TIME * ltime)5665   bool get_time(MYSQL_TIME *ltime) override {
5666     return get_time_from_real(ltime);
5667   }
5668   bool copy(const THD *thd) override;
5669 };
5670 
5671 class Item_copy_decimal final : public Item_copy {
5672  protected:
5673   my_decimal cached_value;
5674   type_conversion_status save_in_field_inner(Field *field,
5675                                              bool no_conversions) override;
5676 
5677  public:
Item_copy_decimal(Item * i)5678   Item_copy_decimal(Item *i) : Item_copy(i) {}
5679 
5680   String *val_str(String *) override;
val_decimal(my_decimal *)5681   my_decimal *val_decimal(my_decimal *) override {
5682     return null_value ? nullptr : &cached_value;
5683   }
5684   double val_real() override;
5685   longlong val_int() override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)5686   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
5687     return get_date_from_decimal(ltime, fuzzydate);
5688   }
get_time(MYSQL_TIME * ltime)5689   bool get_time(MYSQL_TIME *ltime) override {
5690     return get_time_from_decimal(ltime);
5691   }
5692   bool copy(const THD *thd) override;
5693 };
5694 
5695 class Item_cache;
5696 
5697 /**
5698   This is used for segregating rows in groups (e.g. GROUP BY, windows), to
5699   detect boundaries of groups.
5700   It caches a value, which is representative of the group, and can compare it
5701   to another row, and update its value when entering a new group.
5702 */
5703 class Cached_item {
5704  protected:
5705   Item *item;  ///< The item whose value to cache.
5706  public:
5707   bool null_value;
Cached_item(Item * i)5708   Cached_item(Item *i) : item(i), null_value(false) {}
5709   /**
5710     If cached value is different from item's, returns true and updates
5711     cached value with item's.
5712   */
5713   virtual bool cmp() = 0;
5714   virtual ~Cached_item(); /*line -e1509 */
get_item()5715   Item *get_item() { return item; }
copy_to_Item_cache(Item_cache * i_c MY_ATTRIBUTE ((unused)))5716   virtual void copy_to_Item_cache(Item_cache *i_c MY_ATTRIBUTE((unused))) {
5717     DBUG_ASSERT(false); /* purecov: inspected */
5718   }
5719 };
5720 
5721 class Cached_item_str : public Cached_item {
5722   uint32 value_max_length;
5723   String value, tmp_value;
5724 
5725  public:
5726   Cached_item_str(THD *thd, Item *arg);
5727   bool cmp() override;
5728   ~Cached_item_str() override;  // Deallocate String:s
5729   void copy_to_Item_cache(Item_cache *i_c) override;
5730 };
5731 
5732 /// Cached_item subclass for JSON values.
5733 class Cached_item_json : public Cached_item {
5734   Json_wrapper *m_value;  ///< The cached JSON value.
5735  public:
5736   explicit Cached_item_json(Item *item);
5737   ~Cached_item_json() override;
5738   bool cmp() override;
5739   void copy_to_Item_cache(Item_cache *i_c) override;
5740 };
5741 
5742 class Cached_item_real : public Cached_item {
5743   double value;
5744 
5745  public:
Cached_item_real(Item * item_par)5746   Cached_item_real(Item *item_par) : Cached_item(item_par), value(0.0) {}
5747   bool cmp() override;
5748   void copy_to_Item_cache(Item_cache *i_c) override;
5749 };
5750 
5751 class Cached_item_int : public Cached_item {
5752   longlong value;
5753 
5754  public:
Cached_item_int(Item * item_par)5755   Cached_item_int(Item *item_par) : Cached_item(item_par), value(0) {}
5756   bool cmp() override;
5757   void copy_to_Item_cache(Item_cache *i_c) override;
5758 };
5759 
5760 class Cached_item_temporal : public Cached_item {
5761   longlong value;
5762 
5763  public:
Cached_item_temporal(Item * item_par)5764   Cached_item_temporal(Item *item_par) : Cached_item(item_par), value(0) {}
5765   bool cmp() override;
5766   void copy_to_Item_cache(Item_cache *i_c) override;
5767 };
5768 
5769 class Cached_item_decimal : public Cached_item {
5770   my_decimal value;
5771 
5772  public:
5773   Cached_item_decimal(Item *item_par);
5774   bool cmp() override;
5775   void copy_to_Item_cache(Item_cache *i_c) override;
5776 };
5777 
5778 class Item_default_value final : public Item_field {
5779   typedef Item_field super;
5780 
5781  protected:
5782   type_conversion_status save_in_field_inner(Field *field,
5783                                              bool no_conversions) override;
5784 
5785  public:
5786   Item *arg;
5787   Item_default_value(const POS &pos, Item *a = nullptr)
super(pos,nullptr,nullptr,nullptr)5788       : super(pos, nullptr, nullptr, nullptr), arg(a) {}
5789   bool itemize(Parse_context *pc, Item **res) override;
type()5790   enum Type type() const override { return DEFAULT_VALUE_ITEM; }
5791   bool eq(const Item *item, bool binary_cmp) const override;
5792   bool fix_fields(THD *, Item **) override;
5793   void print(const THD *thd, String *str,
5794              enum_query_type query_type) const override;
used_tables()5795   table_map used_tables() const override { return 0; }
get_tmp_table_item(THD * thd)5796   Item *get_tmp_table_item(THD *thd) override { return copy_or_same(thd); }
5797 
walk(Item_processor processor,enum_walk walk,uchar * args)5798   bool walk(Item_processor processor, enum_walk walk, uchar *args) override {
5799     return ((walk & enum_walk::PREFIX) && (this->*processor)(args)) ||
5800            (arg && arg->walk(processor, walk, args)) ||
5801            ((walk & enum_walk::POSTFIX) && (this->*processor)(args));
5802   }
5803 
check_gcol_depend_default_processor(uchar * args)5804   bool check_gcol_depend_default_processor(uchar *args) override {
5805     return !my_strcasecmp(system_charset_info, field_name,
5806                           reinterpret_cast<char *>(args));
5807   }
5808 
5809   Item *transform(Item_transformer transformer, uchar *args) override;
5810 };
5811 
5812 /*
5813   Item_insert_value -- an implementation of VALUES() function.
5814   You can use the VALUES(col_name) function in the UPDATE clause
5815   to refer to column values from the INSERT portion of the INSERT
5816   ... UPDATE statement. In other words, VALUES(col_name) in the
5817   UPDATE clause refers to the value of col_name that would be
5818   inserted, had no duplicate-key conflict occurred.
5819   In all other places this function returns NULL.
5820 */
5821 
5822 class Item_insert_value final : public Item_field {
5823  protected:
save_in_field_inner(Field * field_arg,bool no_conversions)5824   type_conversion_status save_in_field_inner(Field *field_arg,
5825                                              bool no_conversions) override {
5826     return Item_field::save_in_field_inner(field_arg, no_conversions);
5827   }
5828 
5829  public:
5830   Item *arg;
5831 
5832   /**
5833     Constructs an Item_insert_value that represents a call to the deprecated
5834     VALUES function.
5835   */
Item_insert_value(const POS & pos,Item * a)5836   Item_insert_value(const POS &pos, Item *a)
5837       : Item_field(pos, nullptr, nullptr, nullptr),
5838         arg(a),
5839         m_is_values_function(true) {}
5840 
5841   /**
5842     Constructs an Item_insert_value that represents a derived table that wraps a
5843     table value constructor.
5844   */
Item_insert_value(Name_resolution_context * context_arg,Item * a)5845   Item_insert_value(Name_resolution_context *context_arg, Item *a)
5846       : Item_field(context_arg, nullptr, nullptr, nullptr),
5847         arg(a),
5848         m_is_values_function(false) {}
5849 
itemize(Parse_context * pc,Item ** res)5850   bool itemize(Parse_context *pc, Item **res) override {
5851     if (skip_itemize(res)) return false;
5852     return Item_field::itemize(pc, res) || arg->itemize(pc, &arg);
5853   }
5854 
type()5855   enum Type type() const override { return INSERT_VALUE_ITEM; }
5856   bool eq(const Item *item, bool binary_cmp) const override;
5857   bool fix_fields(THD *, Item **) override;
5858   void print(const THD *thd, String *str,
5859              enum_query_type query_type) const override;
5860   /*
5861    We use RAND_TABLE_BIT to prevent Item_insert_value from
5862    being treated as a constant and precalculated before execution
5863   */
used_tables()5864   table_map used_tables() const override { return RAND_TABLE_BIT; }
5865 
walk(Item_processor processor,enum_walk walk,uchar * args)5866   bool walk(Item_processor processor, enum_walk walk, uchar *args) override {
5867     return ((walk & enum_walk::PREFIX) && (this->*processor)(args)) ||
5868            arg->walk(processor, walk, args) ||
5869            ((walk & enum_walk::POSTFIX) && (this->*processor)(args));
5870   }
check_function_as_value_generator(uchar * args)5871   bool check_function_as_value_generator(uchar *args) override {
5872     Check_function_as_value_generator_parameters *func_arg =
5873         pointer_cast<Check_function_as_value_generator_parameters *>(args);
5874     func_arg->banned_function_name = "values";
5875     return true;
5876   }
5877 
5878  private:
5879   /**
5880     This flag is true if the item represents a call to the deprecated VALUES
5881     function. It is false if the item represents a derived table that wraps a
5882     table value constructor.
5883   */
5884   const bool m_is_values_function;
5885 };
5886 
5887 /**
5888   Represents NEW/OLD version of field of row which is
5889   changed/read in trigger.
5890 
5891   Note: For this item main part of actual binding to Field object happens
5892         not during fix_fields() call (like for Item_field) but right after
5893         parsing of trigger definition, when table is opened, with special
5894         setup_field() call. On fix_fields() stage we simply choose one of
5895         two Field instances representing either OLD or NEW version of this
5896         field.
5897 */
5898 class Item_trigger_field final : public Item_field,
5899                                  private Settable_routine_parameter {
5900  public:
5901   /* Is this item represents row from NEW or OLD row ? */
5902   enum_trigger_variable_type trigger_var_type;
5903   /* Next in list of all Item_trigger_field's in trigger */
5904   Item_trigger_field *next_trg_field;
5905   /*
5906     Next list of Item_trigger_field's in "sp_head::
5907     m_list_of_trig_fields_item_lists".
5908   */
5909   SQL_I_List<Item_trigger_field> *next_trig_field_list;
5910   /* Index of the field in the TABLE::field array */
5911   uint field_idx;
5912   /* Pointer to an instance of Table_trigger_field_support interface */
5913   Table_trigger_field_support *triggers;
5914 
Item_trigger_field(Name_resolution_context * context_arg,enum_trigger_variable_type trigger_var_type_arg,const char * field_name_arg,ulong priv,const bool ro)5915   Item_trigger_field(Name_resolution_context *context_arg,
5916                      enum_trigger_variable_type trigger_var_type_arg,
5917                      const char *field_name_arg, ulong priv, const bool ro)
5918       : Item_field(context_arg, (const char *)nullptr, (const char *)nullptr,
5919                    field_name_arg),
5920         trigger_var_type(trigger_var_type_arg),
5921         next_trig_field_list(nullptr),
5922         field_idx((uint)-1),
5923         original_privilege(priv),
5924         want_privilege(priv),
5925         table_grants(nullptr),
5926         read_only(ro) {}
Item_trigger_field(const POS & pos,enum_trigger_variable_type trigger_var_type_arg,const char * field_name_arg,ulong priv,const bool ro)5927   Item_trigger_field(const POS &pos,
5928                      enum_trigger_variable_type trigger_var_type_arg,
5929                      const char *field_name_arg, ulong priv, const bool ro)
5930       : Item_field(pos, nullptr, nullptr, field_name_arg),
5931         trigger_var_type(trigger_var_type_arg),
5932         field_idx((uint)-1),
5933         original_privilege(priv),
5934         want_privilege(priv),
5935         table_grants(nullptr),
5936         read_only(ro) {}
5937   void setup_field(Table_trigger_field_support *table_triggers,
5938                    GRANT_INFO *table_grant_info);
type()5939   enum Type type() const override { return TRIGGER_FIELD_ITEM; }
5940   bool eq(const Item *item, bool binary_cmp) const override;
5941   bool fix_fields(THD *, Item **) override;
5942   void print(const THD *thd, String *str,
5943              enum_query_type query_type) const override;
used_tables()5944   table_map used_tables() const override { return 0; }
get_tmp_table_field()5945   Field *get_tmp_table_field() override { return nullptr; }
copy_or_same(THD *)5946   Item *copy_or_same(THD *) override { return this; }
get_tmp_table_item(THD * thd)5947   Item *get_tmp_table_item(THD *thd) override { return copy_or_same(thd); }
5948   void cleanup() override;
5949   void set_required_privilege(bool rw) override;
5950 
check_function_as_value_generator(uchar * args)5951   bool check_function_as_value_generator(uchar *args) override {
5952     Check_function_as_value_generator_parameters *func_arg =
5953         pointer_cast<Check_function_as_value_generator_parameters *>(args);
5954     func_arg->err_code = func_arg->get_unnamed_function_error_code();
5955     return true;
5956   }
5957 
5958  private:
5959   bool set_value(THD *thd, sp_rcontext *ctx, Item **it) override;
5960 
5961  public:
get_settable_routine_parameter()5962   Settable_routine_parameter *get_settable_routine_parameter() override {
5963     return (read_only ? nullptr : this);
5964   }
5965 
set_value(THD * thd,Item ** it)5966   bool set_value(THD *thd, Item **it) {
5967     bool ret = set_value(thd, nullptr, it);
5968     if (!ret)
5969       bitmap_set_bit(triggers->get_subject_table()->fields_set_during_insert,
5970                      field_idx);
5971     return ret;
5972   }
5973 
5974  private:
5975   /*
5976     'want_privilege' holds privileges required to perform operation on
5977     this trigger field (SELECT_ACL if we are going to read it and
5978     UPDATE_ACL if we are going to update it).  It is initialized at
5979     parse time but can be updated later if this trigger field is used
5980     as OUT or INOUT parameter of stored routine (in this case
5981     set_required_privilege() is called to appropriately update
5982     want_privilege and cleanup() is responsible for restoring of
5983     original want_privilege once parameter's value is updated).
5984   */
5985   ulong original_privilege;
5986   ulong want_privilege;
5987   GRANT_INFO *table_grants;
5988   /*
5989     Trigger field is read-only unless it belongs to the NEW row in a
5990     BEFORE INSERT of BEFORE UPDATE trigger.
5991   */
5992   bool read_only;
5993 };
5994 
5995 class Item_cache : public Item_basic_constant {
5996  protected:
5997   Item *example;
5998   table_map used_table_map;
5999   /**
6000     Field that this object will get value from. This is used by
6001     index-based subquery engines to detect and remove the equality injected
6002     by IN->EXISTS transformation.
6003   */
6004   Field *cached_field;
6005   /*
6006     true <=> cache holds value of the last stored item (i.e actual value).
6007     store() stores item to be cached and sets this flag to false.
6008     On the first call of val_xxx function if this flag is set to false the
6009     cache_value() will be called to actually cache value of saved item.
6010     cache_value() will set this flag to true.
6011   */
6012   bool value_cached;
6013 
6014   friend bool has_rollup_result(Item *item);
6015 
6016  public:
Item_cache()6017   Item_cache()
6018       : example(nullptr),
6019         used_table_map(0),
6020         cached_field(nullptr),
6021         value_cached(false) {
6022     fixed = true;
6023     maybe_null = true;
6024     null_value = true;
6025   }
Item_cache(enum_field_types field_type_arg)6026   Item_cache(enum_field_types field_type_arg)
6027       : example(nullptr),
6028         used_table_map(0),
6029         cached_field(nullptr),
6030         value_cached(false) {
6031     set_data_type(field_type_arg);
6032     fixed = true;
6033     maybe_null = true;
6034     null_value = true;
6035   }
6036 
set_used_tables(table_map map)6037   void set_used_tables(table_map map) { used_table_map = map; }
6038 
fix_after_pullout(SELECT_LEX * parent_select,SELECT_LEX * removed_select)6039   void fix_after_pullout(SELECT_LEX *parent_select,
6040                          SELECT_LEX *removed_select) override {
6041     if (example == nullptr) return;
6042     example->fix_after_pullout(parent_select, removed_select);
6043     used_table_map = example->used_tables();
6044   }
6045 
allocate(uint)6046   virtual bool allocate(uint) { return false; }
setup(Item * item)6047   virtual bool setup(Item *item) {
6048     example = item;
6049     max_length = item->max_length;
6050     decimals = item->decimals;
6051     collation.set(item->collation);
6052     unsigned_flag = item->unsigned_flag;
6053     add_accum_properties(item);
6054     /*
6055       Cache object cannot be marked as aggregated, due to problems with
6056       repeated preparation calls.
6057       @todo - consider this in WL#6570.
6058     */
6059     reset_aggregation();
6060     if (item->type() == FIELD_ITEM) {
6061       cached_field = ((Item_field *)item)->field;
6062       if (((Item_field *)item)->table_ref)
6063         used_table_map = ((Item_field *)item)->table_ref->map();
6064     } else {
6065       used_table_map = item->used_tables();
6066     }
6067     return false;
6068   }
type()6069   enum Type type() const override { return CACHE_ITEM; }
6070   static Item_cache *get_cache(const Item *item);
6071   static Item_cache *get_cache(const Item *item, const Item_result type);
used_tables()6072   table_map used_tables() const override { return used_table_map; }
keep_array()6073   virtual void keep_array() {}
6074   void print(const THD *thd, String *str,
6075              enum_query_type query_type) const override;
eq_def(const Field * field)6076   bool eq_def(const Field *field) {
6077     return cached_field && cached_field->eq_def(field);
6078   }
eq(const Item * item,bool)6079   bool eq(const Item *item, bool) const override { return this == item; }
6080   /**
6081      Check if saved item has a non-NULL value.
6082      Will cache value of saved item if not already done.
6083      @return true if cached value is non-NULL.
6084    */
6085   bool has_value();
6086 
6087   /**
6088     If this item caches a field value, return pointer to underlying field.
6089 
6090     @return Pointer to field, or NULL if this is not a cache for a field value.
6091   */
field()6092   Field *field() { return cached_field; }
6093 
6094   /**
6095     Assigns to the cache the expression to be cached. Does not evaluate it.
6096     @param item  the expression to be cached
6097   */
6098   virtual void store(Item *item);
6099 
6100   /**
6101     Force an item to be null. Used for empty subqueries to avoid attempts to
6102     evaluate expressions which could have uninitialized columns due to
6103     bypassing the subquery exec.
6104   */
store_null()6105   void store_null() {
6106     DBUG_ASSERT(maybe_null);
6107     value_cached = true;
6108     null_value = true;
6109   }
6110 
6111   virtual bool cache_value() = 0;
store_and_cache(Item * item)6112   bool store_and_cache(Item *item) {
6113     store(item);
6114     return cache_value();
6115   }
basic_const_item()6116   bool basic_const_item() const override {
6117     return (example != nullptr && example->basic_const_item());
6118   }
6119   bool walk(Item_processor processor, enum_walk walk, uchar *arg) override;
clear()6120   virtual void clear() {
6121     null_value = true;
6122     value_cached = false;
6123   }
is_null()6124   bool is_null() override {
6125     return value_cached ? null_value : example->is_null();
6126   }
is_non_const_over_literals(uchar *)6127   bool is_non_const_over_literals(uchar *) override { return true; }
check_function_as_value_generator(uchar * args)6128   bool check_function_as_value_generator(uchar *args) override {
6129     Check_function_as_value_generator_parameters *func_arg =
6130         pointer_cast<Check_function_as_value_generator_parameters *>(args);
6131     func_arg->banned_function_name = "cached item";
6132     // This should not happen as SELECT statements are not allowed.
6133     DBUG_ASSERT(false);
6134     return true;
6135   }
result_type()6136   Item_result result_type() const override {
6137     if (!example) return INT_RESULT;
6138     return Field::result_merge_type(example->data_type());
6139   }
6140 };
6141 
6142 class Item_cache_int final : public Item_cache {
6143  protected:
6144   longlong value;
6145 
6146  public:
Item_cache_int()6147   Item_cache_int() : Item_cache(MYSQL_TYPE_LONGLONG), value(0) {}
Item_cache_int(enum_field_types field_type_arg)6148   Item_cache_int(enum_field_types field_type_arg)
6149       : Item_cache(field_type_arg), value(0) {}
6150 
6151   /**
6152     Unlike store(), this stores an explicitly provided value, not the one of
6153     'item'; however, NULLness is still taken from 'item'.
6154   */
6155   void store_value(Item *item, longlong val_arg);
6156   double val_real() override;
6157   longlong val_int() override;
val_time_temporal()6158   longlong val_time_temporal() override { return val_int(); }
val_date_temporal()6159   longlong val_date_temporal() override { return val_int(); }
6160   String *val_str(String *str) override;
6161   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6162   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
6163     return get_date_from_int(ltime, fuzzydate);
6164   }
get_time(MYSQL_TIME * ltime)6165   bool get_time(MYSQL_TIME *ltime) override { return get_time_from_int(ltime); }
result_type()6166   enum Item_result result_type() const override { return INT_RESULT; }
6167   bool cache_value() override;
6168 };
6169 
6170 class Item_cache_real final : public Item_cache {
6171   double value;
6172 
6173  public:
Item_cache_real()6174   Item_cache_real() : Item_cache(MYSQL_TYPE_DOUBLE), value(0) {}
6175 
6176   double val_real() override;
6177   longlong val_int() override;
6178   String *val_str(String *str) override;
6179   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6180   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
6181     return get_date_from_real(ltime, fuzzydate);
6182   }
get_time(MYSQL_TIME * ltime)6183   bool get_time(MYSQL_TIME *ltime) override {
6184     return get_time_from_real(ltime);
6185   }
result_type()6186   enum Item_result result_type() const override { return REAL_RESULT; }
6187   bool cache_value() override;
6188   void store_value(Item *expr, double value);
6189 };
6190 
6191 class Item_cache_decimal final : public Item_cache {
6192  protected:
6193   my_decimal decimal_value;
6194 
6195  public:
Item_cache_decimal()6196   Item_cache_decimal() : Item_cache(MYSQL_TYPE_NEWDECIMAL) {}
6197 
6198   double val_real() override;
6199   longlong val_int() override;
6200   String *val_str(String *str) override;
6201   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6202   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
6203     return get_date_from_decimal(ltime, fuzzydate);
6204   }
get_time(MYSQL_TIME * ltime)6205   bool get_time(MYSQL_TIME *ltime) override {
6206     return get_time_from_decimal(ltime);
6207   }
result_type()6208   enum Item_result result_type() const override { return DECIMAL_RESULT; }
6209   bool cache_value() override;
6210   void store_value(Item *expr, my_decimal *d);
6211 };
6212 
6213 class Item_cache_str final : public Item_cache {
6214   char buffer[STRING_BUFFER_USUAL_SIZE];
6215   String *value, value_buff;
6216   bool is_varbinary;
6217 
6218  protected:
6219   type_conversion_status save_in_field_inner(Field *field,
6220                                              bool no_conversions) override;
6221 
6222  public:
Item_cache_str(const Item * item)6223   Item_cache_str(const Item *item)
6224       : Item_cache(item->data_type()),
6225         value(nullptr),
6226         is_varbinary(item->type() == FIELD_ITEM &&
6227                      data_type() == MYSQL_TYPE_VARCHAR &&
6228                      !((const Item_field *)item)->field->has_charset()) {
6229     collation.set(item->collation);
6230   }
6231   double val_real() override;
6232   longlong val_int() override;
6233   String *val_str(String *) override;
6234   my_decimal *val_decimal(my_decimal *) override;
get_date(MYSQL_TIME * ltime,my_time_flags_t fuzzydate)6235   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override {
6236     return get_date_from_string(ltime, fuzzydate);
6237   }
get_time(MYSQL_TIME * ltime)6238   bool get_time(MYSQL_TIME *ltime) override {
6239     return get_time_from_string(ltime);
6240   }
result_type()6241   enum Item_result result_type() const override { return STRING_RESULT; }
charset()6242   const CHARSET_INFO *charset() const { return value->charset(); }
6243   bool cache_value() override;
6244   void store_value(Item *expr, String &s);
6245 };
6246 
6247 class Item_cache_row final : public Item_cache {
6248   Item_cache **values;
6249   uint item_count;
6250   bool save_array;
6251 
6252  public:
Item_cache_row()6253   Item_cache_row()
6254       : Item_cache(), values(nullptr), item_count(2), save_array(false) {}
6255 
6256   /**
6257     'allocate' is only used in Item_cache_row::setup()
6258   */
6259   bool allocate(uint num) override;
6260   /*
6261     'setup' is needed only by row => it not called by simple row subselect
6262     (only by IN subselect (in subselect optimizer))
6263   */
6264   bool setup(Item *item) override;
6265   void store(Item *item) override;
6266   void illegal_method_call(const char *) const MY_ATTRIBUTE((cold));
make_field(Send_field *)6267   void make_field(Send_field *) override { illegal_method_call("make_field"); }
val_real()6268   double val_real() override {
6269     illegal_method_call("val_real");
6270     return 0;
6271   }
val_int()6272   longlong val_int() override {
6273     illegal_method_call("val_int");
6274     return 0;
6275   }
val_str(String *)6276   String *val_str(String *) override {
6277     illegal_method_call("val_str");
6278     return nullptr;
6279   }
val_decimal(my_decimal *)6280   my_decimal *val_decimal(my_decimal *) override {
6281     illegal_method_call("val_decimal");
6282     return nullptr;
6283   }
get_date(MYSQL_TIME *,my_time_flags_t)6284   bool get_date(MYSQL_TIME *, my_time_flags_t) override {
6285     illegal_method_call("get_date");
6286     return true;
6287   }
get_time(MYSQL_TIME *)6288   bool get_time(MYSQL_TIME *) override {
6289     illegal_method_call("get_time");
6290     return true;
6291   }
6292 
result_type()6293   enum Item_result result_type() const override { return ROW_RESULT; }
6294 
cols()6295   uint cols() const override { return item_count; }
element_index(uint i)6296   Item *element_index(uint i) override { return values[i]; }
addr(uint i)6297   Item **addr(uint i) override { return (Item **)(values + i); }
6298   bool check_cols(uint c) override;
6299   bool null_inside() override;
6300   void bring_value() override;
keep_array()6301   void keep_array() override { save_array = true; }
cleanup()6302   void cleanup() override {
6303     DBUG_TRACE;
6304     Item_cache::cleanup();
6305     if (save_array)
6306       memset(values, 0, item_count * sizeof(Item **));
6307     else
6308       values = nullptr;
6309     return;
6310   }
6311   bool cache_value() override;
6312 };
6313 
6314 class Item_cache_datetime : public Item_cache {
6315   String cached_string;
6316 
6317  protected:
6318   longlong int_value;
6319   bool str_value_cached;
6320 
6321  public:
Item_cache_datetime(enum_field_types field_type_arg)6322   Item_cache_datetime(enum_field_types field_type_arg)
6323       : Item_cache(field_type_arg), int_value(0), str_value_cached(false) {
6324     cmp_context = STRING_RESULT;
6325   }
6326 
6327   void store_value(Item *item, longlong val_arg);
6328   void store(Item *item) override;
6329   double val_real() override;
6330   longlong val_int() override;
6331   longlong val_time_temporal() override;
6332   longlong val_date_temporal() override;
6333   String *val_str(String *str) override;
6334   my_decimal *val_decimal(my_decimal *) override;
6335   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
6336   bool get_time(MYSQL_TIME *ltime) override;
result_type()6337   enum Item_result result_type() const override { return STRING_RESULT; }
6338   /*
6339     In order to avoid INT <-> STRING conversion of a DATETIME value
6340     two cache_value functions are introduced. One (cache_value) caches STRING
6341     value, another (cache_value_int) - INT value. Thus this cache item
6342     completely relies on the ability of the underlying item to do the
6343     correct conversion.
6344   */
6345   bool cache_value_int();
6346   bool cache_value() override;
clear()6347   void clear() override {
6348     Item_cache::clear();
6349     str_value_cached = false;
6350   }
6351 };
6352 
6353 /// An item cache for values of type JSON.
6354 class Item_cache_json : public Item_cache {
6355   /// Cached value
6356   Json_wrapper *m_value;
6357   /// Whether the cached value is array and it is sorted
6358   bool m_is_sorted;
6359 
6360  public:
6361   Item_cache_json();
6362   ~Item_cache_json() override;
6363   bool cache_value() override;
6364   void store_value(Item *expr, Json_wrapper *wr);
6365   bool val_json(Json_wrapper *wr) override;
6366   longlong val_int() override;
6367   String *val_str(String *str) override;
result_type()6368   Item_result result_type() const override { return STRING_RESULT; }
6369 
6370   double val_real() override;
6371   my_decimal *val_decimal(my_decimal *val) override;
6372   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
6373   bool get_time(MYSQL_TIME *ltime) override;
6374   /// Sort cached data. Only arrays are affected.
6375   void sort();
6376   /// Returns true when cached value is array and it's sorted
is_sorted()6377   bool is_sorted() { return m_is_sorted; }
6378 };
6379 
6380 /**
6381   Interface for storing an aggregation of type and type specification of
6382   multiple Item objects.
6383 
6384   This is useful for cases where a field is an amalgamation of multiple types,
6385   such as in UNION where type conversions must be done to a common denominator.
6386 */
6387 class Item_aggregate_type : public Item {
6388  protected:
6389   TYPELIB *enum_set_typelib;
6390   Field::geometry_type geometry_type;
6391 
6392   void get_full_info(Item *item);
6393 
6394  public:
6395   Item_aggregate_type(THD *, Item *);
6396 
6397   double val_real() override = 0;
6398   longlong val_int() override = 0;
6399   my_decimal *val_decimal(my_decimal *) override = 0;
6400   String *val_str(String *) override = 0;
6401   bool get_date(MYSQL_TIME *, my_time_flags_t) override = 0;
6402   bool get_time(MYSQL_TIME *) override = 0;
6403 
6404   Item_result result_type() const override;
6405   bool join_types(THD *, Item *);
6406   Field *make_field_by_type(TABLE *table, bool strict);
6407   static uint32 display_length(Item *item);
get_geometry_type()6408   Field::geometry_type get_geometry_type() const override {
6409     return geometry_type;
6410   }
make_field(Send_field * field)6411   void make_field(Send_field *field) override {
6412     Item::make_field(field);
6413     // Item_type_holder is used for unions and effectively sends Fields
6414     field->field = true;
6415   }
check_function_as_value_generator(uchar * args)6416   bool check_function_as_value_generator(uchar *args) override {
6417     Check_function_as_value_generator_parameters *func_arg =
6418         pointer_cast<Check_function_as_value_generator_parameters *>(args);
6419     func_arg->err_code = func_arg->get_unnamed_function_error_code();
6420     return true;
6421   }
6422 };
6423 
6424 /**
6425   Item_type_holder stores an aggregation of name, type and type specification of
6426   UNIONS and derived tables.
6427 */
6428 class Item_type_holder final : public Item_aggregate_type {
6429   typedef Item_aggregate_type super;
6430 
6431  public:
6432   /// @todo Consider giving Item_type_holder objects default names from the item
6433   /// they are initialized by. This would ensure that
6434   /// SELECT_LEX_UNIT::get_unit_column_types() always contains named items.
Item_type_holder(THD * thd,Item * item)6435   Item_type_holder(THD *thd, Item *item) : super(thd, item) {}
6436 
type()6437   enum Type type() const override { return TYPE_HOLDER; }
6438 
6439   double val_real() override;
6440   longlong val_int() override;
6441   my_decimal *val_decimal(my_decimal *) override;
6442   String *val_str(String *) override;
6443   bool get_date(MYSQL_TIME *, my_time_flags_t) override;
6444   bool get_time(MYSQL_TIME *) override;
6445 };
6446 
6447 /**
6448   Reference item that encapsulates both the type and the contained items of a
6449   single column of a VALUES ROW query expression.
6450 
6451   During execution, the item that will be output for the current iteration is
6452   contained in m_value_ref. The type of the column and the referenced item may
6453   differ in cases where a column of a VALUES clause contains different types
6454   across different rows, and must therefore do type conversions to their common
6455   denominator (e.g. a column containing both 10 and "10", of which the types
6456   will be aggregated into VARCHAR).
6457 
6458   See the class comment for TableValueConstructorIterator for info on how
6459   Item_values_column is used as an indirection to iterate over the rows of a
6460   table value constructor (i.e. VALUES ROW expressions).
6461 */
6462 class Item_values_column final : public Item_aggregate_type {
6463   typedef Item_aggregate_type super;
6464 
6465  private:
6466   Item *m_value_ref{nullptr};
6467   /*
6468     Even if a table value constructor contains only constant values, we
6469     still need to identify individual rows within it. Set RAND_TABLE_BIT
6470     to ensure that all rows are scanned, and that the whole VALUES clause
6471     is never substituted with a const value or row.
6472   */
6473   table_map m_aggregated_used_tables{RAND_TABLE_BIT};
6474 
6475   type_conversion_status save_in_field_inner(Field *field,
6476                                              bool no_conversions) override;
6477 
6478  public:
6479   Item_values_column(THD *thd, Item *ref);
6480 
6481   bool eq(const Item *item, bool binary_cmp) const override;
6482   double val_real() override;
6483   longlong val_int() override;
6484   my_decimal *val_decimal(my_decimal *) override;
6485   bool val_bool() override;
6486   String *val_str(String *tmp) override;
6487   bool val_json(Json_wrapper *result) override;
6488   bool is_null() override;
6489   bool get_date(MYSQL_TIME *ltime, my_time_flags_t fuzzydate) override;
6490   bool get_time(MYSQL_TIME *ltime) override;
6491 
type()6492   enum Type type() const override { return VALUES_COLUMN_ITEM; }
set_value(Item * new_value)6493   void set_value(Item *new_value) { m_value_ref = new_value; }
used_tables()6494   table_map used_tables() const override { return m_aggregated_used_tables; }
6495   void add_used_tables(Item *value);
6496 };
6497 
6498 /// A class that represents a constant JSON value.
6499 class Item_json final : public Item_basic_constant {
6500   unique_ptr_destroy_only<Json_wrapper> m_value;
6501 
6502  public:
6503   Item_json(unique_ptr_destroy_only<Json_wrapper> value,
6504             const Item_name_string &name);
6505   ~Item_json() override;
type()6506   enum Type type() const override { return STRING_ITEM; }
6507   void print(const THD *, String *str, enum_query_type) const override;
6508   bool val_json(Json_wrapper *result) override;
result_type()6509   Item_result result_type() const override { return STRING_RESULT; }
6510   double val_real() override;
6511   longlong val_int() override;
6512   String *val_str(String *str) override;
6513   my_decimal *val_decimal(my_decimal *buf) override;
6514   bool get_date(MYSQL_TIME *ltime, my_time_flags_t) override;
6515   bool get_time(MYSQL_TIME *ltime) override;
6516   Item *clone_item() const override;
6517 };
6518 
6519 extern Cached_item *new_Cached_item(THD *thd, Item *item);
6520 extern Item_result item_cmp_type(Item_result a, Item_result b);
6521 extern bool resolve_const_item(THD *thd, Item **ref, Item *cmp_item);
6522 extern int stored_field_cmp_to_item(THD *thd, Field *field, Item *item);
6523 extern bool is_null_on_empty_table(THD *thd, Item_field *i);
6524 
6525 extern const String my_null_string;
6526 void convert_and_print(const String *from_str, String *to_str,
6527                        const CHARSET_INFO *to_cs);
6528 
6529 std::string ItemToString(const Item *item);
6530 
6531 #endif /* ITEM_INCLUDED */
6532